Acq: several interface improvements
[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('dojox.timing.doLater');
10 dojo.require('openils.acq.Lineitem');
11 dojo.require('openils.acq.PO');
12 dojo.require('openils.acq.Picklist');
13 dojo.require('openils.widget.AutoFieldWidget');
14 dojo.require('dojo.data.ItemFileReadStore');
15 dojo.require('openils.widget.ProgressDialog');
16 dojo.require('openils.PermaCrud');
17 dojo.require("openils.widget.PCrudAutocompleteBox");
18 dojo.require('dijit.form.ComboBox');
19 dojo.require('openils.CGI');
20
21 if (!localeStrings) {   /* we can do this because javascript doesn't have block scope */
22     dojo.requireLocalization('openils.acq', 'acq');
23     var localeStrings = dojo.i18n.getLocalization('openils.acq', 'acq');
24 }
25 const XUL_OPAC_WRAPPER = 'chrome://open_ils_staff_client/content/cat/opac.xul';
26 var li_exportable_attrs = ["issn", "isbn", "upc"];
27
28 var fundLabelFormat = [
29     '<span class="fund_${0}">${1} (${2})</span>', 'id', 'code', 'year'
30 ];
31 var fundSearchFormat = ['${0} (${1})', 'code', 'year'];
32
33 function nodeByName(name, context) {
34     return dojo.query('[name='+name+']', context)[0];
35 }
36
37 // for caching linked users.  e.g. lineitem_detail.receiver
38 var userCache = {};
39
40 var liDetailBatchFields = ['fund', 'owning_lib', 'location', 'collection_code', 'circ_modifier', 'cn_label'];
41 var liDetailFields = liDetailBatchFields.concat(['barcode', 'note']);
42 var fundStyles = {
43     "stop": "color: #c00; font-weight: bold;",
44     "warning": "color: #c93;"
45 };
46
47 function AcqLiTable() {
48
49     var self = this;
50     this.liCache = {};
51     this.plCache = {};
52     this.poCache = {};
53     this.relCache = {};
54     this.haveFundClass = {}
55     this.fundBalanceState = {};
56     this.realDfaCache = {};
57     this.virtDfaCounts = {};
58     this.virtDfaId = -1;
59     this.dfeOffset = 0;
60     this.claimEligibleLidByLi = {};
61     this.claimEligibleLid = {};
62     this.toggleState = false;
63     this.tbody = dojo.byId('acq-lit-tbody');
64     this.selectors = [];
65     this.noteAcks = {};
66     this.authtoken = openils.User.authtoken;
67     this.pcrud = new openils.PermaCrud();
68     this.rowTemplate = this.tbody.removeChild(dojo.byId('acq-lit-row'));
69     this.copyTbody = dojo.byId('acq-lit-li-details-tbody');
70     this.copyRow = this.copyTbody.removeChild(dojo.byId('acq-lit-li-details-row'));
71     this.copyBatchRow = dojo.byId('acq-lit-li-details-batch-row');
72     this.copyBatchWidgets = {};
73     this.liNotesTbody = dojo.byId('acq-lit-notes-tbody');
74     this.liNotesRow = this.liNotesTbody.removeChild(dojo.byId('acq-lit-notes-row'));
75     this.realCopiesTbody = dojo.byId('acq-lit-real-copies-tbody');
76     this.realCopiesRow = this.realCopiesTbody.removeChild(dojo.byId('acq-lit-real-copies-row'));
77     this._copy_fields_for_acqdf = ['owning_lib', 'location'];
78     this.skipInitialEligibilityCheck = false;
79     this.claimDialog = new ClaimDialogManager(
80         liClaimDialog, finalClaimDialog, this.claimEligibleLidByLi,
81         function(li) {    /* callback that fires when claims are made */
82             self.fetchClaimInfo(li.id(), /* force update */ true);
83         }
84     );
85     this.vlAgent = new VLAgent();
86
87     if (dojo.byId('acq-lit-apply-idents')) {
88         dojo.byId('acq-lit-apply-idents').onclick = function() {
89             self.applyOrderIdentValues();
90         };
91     }
92
93     this.focusLineitem = new openils.CGI().param('focus_li');
94
95     // capture the inline copy display wrapper and row template
96     this.inlineCopyContainer = 
97         this.tbody.removeChild(dojo.byId('acq-inline-copies-row'));
98     var tb = dojo.query(
99         '[name=acq-li-inline-copies-tbody]', this.inlineCopyContainer)[0];
100     this.inlineCopyTemplate = tb.removeChild(
101         dojo.query('[name=acq-li-inline-copies-template]', tb)[0]);
102     this.inlineNoCopies = tb.removeChild(
103         dojo.query('[name=acq-li-inline-copies-none]', tb)[0]);
104
105     // list of LI IDs that should be refreshed at next display time
106     this.inlineCopiesNeedingRefresh = []; 
107
108     dojo.byId("acq-lit-li-actions-selector").onchange = function() { 
109         self.applySelectedLiAction(this.options[this.selectedIndex].value);
110         this.selectedIndex = 0;
111     };
112
113     acqLitCreatePoSubmit.onClick = function() {
114         if (!self.createPoProviderSelector.attr("value") ||
115                 !self.createPoAgencySelector.attr("value")) {
116             alert(localeStrings.CREATE_PO_INVALID);
117             return false;
118         } else if (self._confirmPoPrepaySituation()) {
119             acqLitPoCreateDialog.hide();
120             self._createPO(acqLitPoCreateDialog.getValues());
121         } else {
122             return false;
123         }
124     }
125
126     acqLitSavePlButton.onClick = function() {
127         acqLitSavePlDialog.hide();
128         self._savePl(acqLitSavePlDialog.getValues());
129     }
130
131     acqLitCancelLiStateButton.onClick = function() {
132         acqLitChangeLiStateDialog.hide();
133     }
134     acqLitSaveLiStateButton.onClick = function() {
135         acqLitChangeLiStateDialog.hide();
136         self._updateLiState(acqLitChangeLiStateDialog.getValues(), acqLitChangeLiStateDialog.attr('state'));
137     }
138
139
140     dojo.byId('acq-lit-select-toggle').onclick = function(){self.toggleSelect()};
141     dojo.byId('acq-inline-copies-toggle').onclick = function(){self.toggleInlineCopies()};
142     dojo.byId('acq-lit-info-back-button').onclick = function(){self.show('list')};
143     dojo.byId('acq-lit-copies-back-button').onclick = function(){self.show('list')};
144     dojo.byId('acq-lit-notes-back-button').onclick = function(){self.show('list')};
145     dojo.byId('acq-lit-real-copies-back-button').onclick = function(){self.show('list')};
146
147     this.reset = function(keep_selectors) {
148         while(self.tbody.childNodes[0])
149             self.tbody.removeChild(self.tbody.childNodes[0]);
150         self.noteAcks = {};
151         self.relCache = {};
152
153         if (!keep_selectors)
154             self.selectors = [];
155     };
156     
157     this.setNext = function(handler) {
158         var link = dojo.byId('acq-lit-next');
159         if(handler) {
160             dojo.style(link, 'visibility', 'visible');
161             link.onclick = handler;
162         } else {
163             dojo.style(link, 'visibility', 'hidden');
164         }
165     };
166
167     this.setPrev = function(handler) {
168         var link = dojo.byId('acq-lit-prev');
169         if(handler) {
170             dojo.style(link, 'visibility', 'visible'); 
171             link.onclick = handler; 
172         } else {
173             dojo.style(link, 'visibility', 'hidden');
174         }
175     };
176
177     this.enableActionsDropdownOptions = function(mask) {
178         /* 'mask' is probably a minomer the way I'm using it, but it needs to
179          * be one of pl,po,ao,gs,vp, or fs. */
180         dojo.query("option", "acq-lit-li-actions-selector").forEach(
181             function(option) {
182                 var opt_mask = dojo.attr(option, "mask");
183
184                 /* For each <option> element, an empty or non-existent mask
185                  * attribute, a mask attribute of "*", or a mask attribute that
186                  * matches this method's argument should result in that
187                  * option's being enabled. */
188                 dojo.attr(
189                     option, "disabled", !(
190                         !opt_mask ||
191                         opt_mask == "*" ||
192                         opt_mask.search(mask) != -1
193                     )
194                 );
195             }
196         );
197     };
198
199     /*
200      * Ensures this.focusLineitem is in view and causes a brief 
201      * border around the lineitem to come to life then fade.
202      */
203     this.focusLi = function() {
204         if (!this.focusLineitem) return;
205
206         // set during addLineitem()
207         var node = dojo.byId('li-title-ref-' + this.focusLineitem);
208
209         // LI may not yet be rendered
210         if (!node) return; 
211
212         // prevent numerous re-focuses
213         this.focusLineitem = null; 
214         
215         // causes the full row to be visible
216         dijit.scrollIntoView(node);
217
218         // may as well..
219         dojo.query('[attr=title]', node)[0].focus();
220
221         dojo.require('dojox.fx');
222
223         setTimeout(
224             function() {
225                 dojox.fx.highlight({color : '#BB4433', node : node, duration : 2000}).play();
226             }, 
227         100);
228     };
229
230     this.show = function(div) {
231         openils.Util.hide('acq-lit-table-div');
232         openils.Util.hide('acq-lit-info-div');
233         openils.Util.hide('acq-lit-li-details');
234         openils.Util.hide('acq-lit-notes-div');
235         openils.Util.hide('acq-lit-real-copies-div');
236         openils.Util.hide('acq-lit-asset-creator');
237         switch(div) {
238             case 'list':
239                 openils.Util.show('acq-lit-table-div');
240                 this.focusLi();
241                 this.refreshInlineCopies();
242                 break;
243             case 'info':
244                 openils.Util.show('acq-lit-info-div');
245                 break;
246             case 'copies':
247                 openils.Util.show('acq-lit-li-details');
248                 break;
249             case 'real-copies':
250                 openils.Util.show('acq-lit-real-copies-div');
251                 break;
252             case 'notes':
253                 openils.Util.show('acq-lit-notes-div');
254                 break;
255             case 'asset-creator':
256                 openils.Util.show('acq-lit-asset-creator');
257                 break;
258             default:
259                 if(div) 
260                     openils.Util.show(div);
261         }
262     }
263
264     this.hide = function() {
265         this.show(null);
266     }
267
268     this.toggleSelect = function() {
269         if(self.toggleState) 
270             dojo.forEach(self.selectors, function(i){i.checked = false});
271         else 
272             dojo.forEach(self.selectors, function(i){i.checked = true});
273         self.toggleState = !self.toggleState;
274     };
275
276
277     this.getAll = function(callback, id_only) {
278         /* For some uses of the li table, we may not really know about "all"
279          * the lineitems that the user thinks we know about. If we're a paged
280          * picklist, for example, we only know about the lineitems we've
281          * displayed, but not necessarily all the lineitems on the picklist.
282          * So we reach out to pcrud to inform us.
283          */
284
285         var oncomplete = function(r) {
286             var id_list = openils.Util.readResponse(r);
287             if (id_only)
288                 callback(id_list);
289             else
290                 self.fetchLineitemsById(id_list, callback);
291         };
292
293         if (this.isPL) {
294             this.pcrud.search(
295                 "jub", {"picklist": this.isPL}, {
296                     "id_list": true,    /* sic, even if id_only */
297                     "async": true,
298                     "oncomplete": oncomplete
299                 }
300             );
301             return;
302         } else if (this.isPO) {
303             this.pcrud.search(
304                 "jub", {"purchase_order": this.isPO}, {
305                     "id_list": true,
306                     "async": true,
307                     "oncomplete": oncomplete
308                 }
309             );
310             return;
311         } else if (this.isUni && this.pager) {
312             this.pager.getAllLineitemIDs(oncomplete);
313             return;
314         }
315
316         /* If execution reaches this point, we don't need or can't perform
317          * any special tricks to find out the "real" list of "all" lineitems
318          * in this context, so we fall back to the old method.
319          */
320         callback(this.getSelected(true, null, id_only));
321     };
322
323     /** @param all If true, assume all are selected */
324     this.getSelected = function(
325         all,
326         callback /* If you want a "good" idea of "all" lineitems, you must
327         provide a callback that accepts an array parameter, rather than
328         relying on the return value of this method itself. */,
329         id_only
330     ) {
331         if (all && callback)
332             return this.getAll(callback, id_only);
333
334         var indices = {};   /* use to uniqify. needed in paging situations. */
335         dojo.forEach(this.selectors,
336             function(i) { 
337                 if(i.checked || all)
338                     indices[i.parentNode.parentNode.getAttribute('li')] = true;
339             }
340         );
341
342         var result = openils.Util.objectProperties(indices);
343
344         if (!id_only)
345             result = result.map(function(liId) { return self.liCache[liId]; });
346
347         if (callback)
348             callback(result);
349         else
350             return result;
351     };
352
353     this.setRowAttr = function(td, liWrapper, field, type) {
354         var val = liWrapper.findAttr(field, type || 'lineitem_marc_attr_definition') || '';
355         td.appendChild(document.createTextNode(val));
356     };
357
358     this.setClaimPolicyControl = function(li, row) {
359         if (!self._claimPolicyPickerLoading) {
360             self._claimPolicyPickerLoading = true;
361
362             new openils.widget.AutoFieldWidget({
363                 "parentNode": "acq-lit-li-claim-policy",
364                 "fmClass": "acqclp",
365                 "selfReference": true,
366                 "dijitArgs": {"required": true}
367             }).build(
368                 function(w) { self.claimPolicyPicker = w; }
369             );
370         }
371
372         /* dojox.timing.doLater() is the best thing ever. Resource not yet
373          * ready? Just repeat my whole method when it is. */
374         if (dojox.timing.doLater(self.claimPolicyPicker)) {
375             return;
376         } else {
377             if (!row)
378                 row = self._findLiRow(li);
379
380             if (li.claim_policy()) {
381                 /* This Dojo data dance is necessary to get a whole fieldmapper
382                  * object based on a claim policy ID, since we alreay have the
383                  * widget thing loaded with all that data, and can thereby
384                  * avoid another request to the server. */
385                 self.claimPolicyPicker.store.fetchItemByIdentity({
386                     "identity": li.claim_policy(),
387                     "onItem": function(a) {
388                         var policy = (new acqclp()).fromStoreItem(a);
389                         var span = nodeByName("claim_policy", row);
390                         var inner = nodeByName("claim_policy_name", row);
391
392                         openils.Util.show(span, "inline");
393                         inner.innerHTML = policy.name();
394                     },
395                     "onError": function(e) {
396                         console.error(e);
397                     }
398                 });
399             } else {
400                 openils.Util.hide(nodeByName("claim_policy", row));
401                 nodeByName("claim_policy_name", row).innerHTML = "";
402             }
403         }
404     };
405
406     this.fetchClaimInfo = function(liId, force, callback, row) {
407         this._fetchLineitem(
408             liId, function(full) {
409                 self.liCache[full.id()] = full;
410                 self.checkClaimEligibility(full, callback, row);
411             }, force
412         );
413     }
414
415     /**
416      * Inserts a single lineitem into the growing table of lineitems
417      * @param {Object} li The lineitem object to insert
418      */
419     this.addLineitem = function(li, skip_final_placement) {
420         this.liCache[li.id()] = li;
421
422         // insert the row right away so that final order isn't
423         // dependent on how long subsequent async request take
424         // for a given line item
425         var row = self.rowTemplate.cloneNode(true);
426         if (!skip_final_placement) {
427             self.tbody.appendChild(row);
428         }
429         self.selectors.push(dojo.query('[name=selectbox]', row)[0]);
430
431         // sort the lineitem notes on edit_time
432         if(!li.lineitem_notes()) li.lineitem_notes([]);
433
434         var liWrapper = new openils.acq.Lineitem({lineitem:li});
435         row.setAttribute('li', li.id());
436         var tds = dojo.query('[attr]', row);
437         dojo.forEach(tds, function(td) {self.setRowAttr(td, liWrapper, td.getAttribute('attr'), td.getAttribute('attr_type'));});
438         dojo.query('[name=source_label]', row)[0].appendChild(document.createTextNode(li.source_label()));
439
440         // so we can scroll to it later
441         dojo.query('[name=bib-info-cell]', row)[0].id = 'li-title-ref-' + li.id();
442
443         var identifier =
444             liWrapper.findAttr("isbn", "lineitem_marc_attr_definition") ||
445             liWrapper.findAttr("upc", "lineitem_marc_attr_definition");
446
447         // XXX media prefix for added content
448         if (identifier) {
449             nodeByName("jacket", row).setAttribute(
450                 "src", "/opac/extras/ac/jacket/small/" + identifier
451             );
452         }
453
454         nodeByName("liid", row).innerHTML += li.id();
455
456         if(li.eg_bib_id()) {
457             openils.Util.show(nodeByName('catalog', row), 'inline');
458             nodeByName("catalog_link", row).onclick = this.generateMakeRecTab(li.eg_bib_id());
459         } else {
460             openils.Util.show(nodeByName('link_to_catalog', row), 'inline');
461             nodeByName("link_to_catalog_link", row).onclick = function() { self.drawBibFinder(li) };
462         }
463
464         if (li.queued_record()) {
465             this.pcrud.retrieve('vqbr', li.queued_record(),
466                 {   async : true, 
467                     oncomplete : function(r) {
468                         var qrec = openils.Util.readResponse(r);
469                         openils.Util.show(nodeByName('queue', row), 'inline');
470                         var link = nodeByName("queue_link", row);
471                         link.onclick = function() { 
472                             // open a new tab to the vandelay queue for this record
473                             openils.XUL.newTabEasy(
474                                 oilsBasePath + '/vandelay/vandelay?qtype=bib&qid=' + qrec.queue()
475                             );
476                         }
477                     }
478                 }
479             );
480         }
481
482         nodeByName("worksheet_link", row).href =
483             oilsBasePath + "/acq/lineitem/worksheet/" + li.id() + 
484             '?source=' + encodeURIComponent(location.pathname + location.search)
485
486         nodeByName("show_requests_link", row).href =
487             oilsBasePath + "/acq/picklist/user_request?lineitem=" + li.id() + 
488             '?source=' + encodeURIComponent(location.pathname + location.search)
489
490         dojo.query('[attr=title]', row)[0].onclick = function() {self.drawInfo(li.id())};
491         dojo.query('[name=copieslink]', row)[0].onclick = function() {self.drawCopies(li.id())};
492         dojo.query('[name=noteslink]', row)[0].onclick = function() {self.drawLiNotes(li)};
493         dojo.query('[name=expand_inline_copies]', row)[0].onclick = 
494             function() {self.drawInlineCopies(li.id())};
495
496         this.drawOrderIdentSelector(li, row);
497
498         if (!this.skipInitialEligibilityCheck)
499             this.fetchClaimInfo(
500                 li.id(),
501                 false,
502                 function(full) { self.setClaimPolicyControl(full, row) },
503                 row
504             );
505
506         this.updateLiNotesCount(li, row);
507
508         // show which PO this lineitem is a member of
509         if(li.purchase_order() && !this.isPO) {
510             var po = 
511                 this.poCache[li.purchase_order()] =
512                 this.poCache[li.purchase_order()] ||
513                 fieldmapper.standardRequest(
514                     ['open-ils.acq', 'open-ils.acq.purchase_order.retrieve'],
515                     {params: [
516                         this.authtoken, li.purchase_order(), {
517                             "flesh_price_summary": true,
518                             "flesh_provider" : true,
519                             "flesh_lineitem_count": true
520                         }
521                     ]});
522             if(po && !this.isMeta) {
523                 openils.Util.show(nodeByName('po', row), 'inline');
524                 var link = nodeByName('po_link', row);
525                 link.setAttribute('href', oilsBasePath +
526                     '/acq/po/view/' + li.purchase_order() +
527                     '?focus_li=' + li.id() +
528                     '&source=' + encodeURIComponent(location.pathname + location.search)
529                 );
530                 link.innerHTML += po.name();
531
532                 openils.Util.show(nodeByName('pro', row), 'inline');
533                 link = nodeByName('pro_link', row);
534                 link.setAttribute('href', oilsBasePath + '/conify/global/acq/provider/' + po.provider().id())
535                 link.innerHTML += po.provider().code();
536             }
537         }
538
539         // show which picklist this lineitem is a member of
540         if(li.picklist() && (this.isPO || this.isMeta || this.isUni)) {
541             var pl = 
542                 this.plCache[li.picklist()] = 
543                 this.plCache[li.picklist()] || 
544                 fieldmapper.standardRequest(
545                     ['open-ils.acq', 'open-ils.acq.picklist.retrieve.authoritative'],
546                     {params: [this.authtoken, li.picklist()]});
547             if (pl) {
548                 if (pl.name() == "") {
549                     openils.Util.show(nodeByName("bib_origin", row), "inline");
550
551                 } else {
552
553                     openils.Util.show(nodeByName('pl', row), 'inline');
554                     var link = nodeByName('pl_link', row);
555                     link.setAttribute('href', oilsBasePath +
556                         '/acq/picklist/view/' + li.picklist() +
557                         '?focus_li=' + li.id() +
558                         '&source=' + encodeURIComponent(location.pathname + location.search)
559                     );
560                     link.innerHTML += pl.name();
561                 }
562             }
563         }
564
565         var countNode = nodeByName('count', row);
566         var count = li.item_count() || 0;
567         if (typeof(this._copy_count_cb) == "function") {
568             this._copy_count_cb(li.id(), count);
569         }
570         countNode.innerHTML = count;
571         countNode.id = 'acq-lit-copy-count-label-' + li.id();
572
573         // lineitem price
574         var priceInput = dojo.query('[name=price]', row)[0];
575         priceInput.value = li.estimated_unit_price() || '';
576         priceInput.onchange = function() { self.updateLiPrice(priceInput, li) };
577
578         // show either "mark received" or "unreceive" as appropriate
579         this.updateLiState(li, row);
580
581         if (skip_final_placement) {
582             return row;
583         }
584
585         // the last LI may be rendered after the call to show('list'),
586         // so make sure it's focused if necessary.
587         if (this.focusLineitem == li.id())
588             this.focusLi();
589     };
590
591     this._liCountClaims = function(li) {
592         var total = 0;
593         for (var i = 0; i < li.lineitem_details().length; i++)
594             total += li.lineitem_details()[i].claims().length;
595         return total;
596     };
597
598     this._findLiRow = function(li) {
599         return dojo.query('tr[li="' + li.id() + '"]', "acq-lit-tbody")[0];
600     };
601
602     this.reconsiderClaimControl = function(li, row) {
603         if (!row) row = this._findLiRow(li);
604         var option = nodeByName("action_manage_claims", row);
605         var eligible = this.claimEligibleLidByLi[li.id()].length;
606         var count = this._liCountClaims(li);
607
608         option.disabled = !(count || eligible);
609         option.innerHTML =
610             dojo.string.substitute(localeStrings.NUM_CLAIMS_EXISTING, [count]);
611         option.onclick = function() { self.claimDialog.show(li); };
612     };
613
614     this.clearEligibility = function(li) {
615         this.claimEligibleLidByLi[li.id()] = [];
616
617         if (li.lineitem_details()) {
618             li.lineitem_details().forEach(
619                 function(lid) { delete self.claimEligibleLid[lid.id()]; }
620             );
621         }
622
623         if (this.copyCache) {
624             var to_del = [];
625             for (var k in this.copyCache) {
626                 if (this.copyCache[k].lineitem() == li.id())
627                     to_del.push(k);
628             }
629             to_del.forEach(
630                 function(k) { delete self.claimEligibleLid[k]; }
631             );
632         }
633     };
634
635     this.applyOrderIdentValues = function() {
636         this._identValuesInFlight = 
637             openils.Util.objectProperties(this.liCache).length;
638         for (var liId in this.liCache) {
639             this._applyOrderIdentValue(this.liCache[liId]);
640         }
641     };
642
643     // returns true if request was sent
644     this._applyOrderIdentValue = function(li) {
645         var self = this;
646
647         console.log('applying ident value for lineitem ' + li.id());
648
649         // main row
650         var row = dojo.query('[li=' + li.id() + ']')[0];
651
652         // find the selected ident value
653         var typeSel = dojo.query('[name=order_ident_type]', row)[0];
654         var valueSel = dojo.query('[name=order_ident_value]', row)[0];
655         var name = typeSel.options[typeSel.selectedIndex].value;
656         var val = typeSel._cbox.attr('value');
657
658         console.log("selected ident is " + val);
659
660         // it differs from the existing ident value, update it
661         var oldIdent = self.getLiOrderIdent(li);
662         if (oldIdent && 
663             oldIdent.attr_name() == name &&
664             oldIdent.attr_value() == val) {
665                 console.log('selected ident attr matches existing attr');
666                 if (--this._identValuesInFlight == 0) 
667                     location.href = location.href;
668                 return false;
669         }
670
671         // see if the selected ident value is represented
672         // by an existing lineitem attr
673
674         var args = {};
675         typeSel._cbox.store.fetch({
676             query : {attr_value : val},
677             onItem : function(item) {                                                       
678                 console.log('found existing attr for ident value');
679                 args.source_attr_id = li.attributes().filter(
680                     function(attr) { return attr.id() == item.id[0] }
681                 )[0];
682             }                                                                      
683         }); 
684
685
686         if (!args.source_attr_id) {
687             // user entered new text in the combobox
688             // so we need to create a new attr
689             console.log('creating new ident attr');
690             args.lineitem_id = li.id();
691             args.attr_name = name;
692             args.attr_value = val;
693         }
694
695         fieldmapper.standardRequest(
696             ['open-ils.acq', 'open-ils.acq.lineitem.order_identifier.set'],
697             {   async : true,
698                 params : [openils.User.authtoken, args],
699                 oncomplete : function() {
700                     console.log('order_ident oncomplete');
701                     if (--self._identValuesInFlight == 0) 
702                         location.href = location.href;
703                 }
704             }
705         );
706
707         return true;
708     };
709
710     this.getLiOrderIdent = function(li) {
711         var attrs = li.attributes();
712         if (!attrs) return null;
713         return attrs.filter(
714             function(attr) {
715                 return (
716                     attr.attr_type() == 'lineitem_local_attr_definition' &&
717                     openils.Util.isTrue(attr.order_ident())
718                 );
719             }
720         )[0];
721     };
722
723     this.drawOrderIdentSelector = function(li, row) {
724         var self = this;
725         var typeSel = dojo.query('[name=order_ident_type]', row)[0];
726         var valueSel = dojo.query('[name=order_ident_value]', row)[0];
727
728         var attrs = li.attributes();
729
730         // limit to MARC attr defs
731         attrs = attrs.filter(
732             function(attr) {
733                 return (attr.attr_type() == 'lineitem_marc_attr_definition');
734             }
735         );
736
737         var identAttr = this.getLiOrderIdent(li);
738
739
740         // collect the values for each type of identifier
741         // find a reasonable default identifier type to render
742         
743         var values = {};
744         var typeSet = null;
745         dojo.forEach(['isbn', 'upc', 'issn'],
746             function(name) {
747
748                 // collect the values for this attr name
749                 values[name] =  attrs.filter(
750                     function(attr) {
751                         return (attr.attr_name() == name)
752                     }
753                 );
754
755                 // select a reasonable default name in the type-selector
756                 if (!typeSet) {
757                     var useMe = false;
758                     if (identAttr) {
759                         if (identAttr.attr_name() == name)
760                             useMe = true;
761                     } else if (values[name].length) {
762                         useMe = true;
763                     }
764
765                     if (useMe) {
766                         dojo.forEach(typeSel.options, function(opt) {
767                             if (opt.value == name) {
768                                 opt.selected = true;
769                                 typeSet = name;
770                             }
771                         });
772                     }
773                 }
774             }
775         );
776
777         function updateOrderIdent(box) {
778             console.log('updating order ident for box ' + box);
779         }
780
781         // replace the ident combobox with a new 
782         // one for the selected ident type 
783         function changeComboBox(sel) {
784             var name = sel.options[sel.selectedIndex].value;
785
786             var td = dojo.query('[name=order_ident_value]', row)[0];
787             if (td.childNodes[0]) 
788                 dojo.destroy(td.childNodes[0]);
789
790             var store = new dojo.data.ItemFileWriteStore({
791                 data : acqlia.toStoreData(values[name])
792             });
793
794             var cbox = new dijit.form.ComboBox(
795                 {   store : store,
796                     labelAttr : 'attr_value',
797                     searchAttr : 'attr_value'
798                 }, 
799                 dojo.create('div', {}, td)
800             );
801
802             cbox.startup();
803
804             // set the value for the cbox
805             if (values[name].length) {
806                 var orderIdent = self.getLiOrderIdent(li);
807
808                 if (orderIdent && orderIdent.attr_name() == name) {
809                     cbox.attr('value', orderIdent.attr_value());
810                 } else  {
811                     cbox.attr('value', values[name][0].attr_value());
812                 }
813             }
814
815             if (!self.orderIdentAllowed) 
816                 cbox.attr('disabled', true);
817
818             sel._cbox = cbox;
819             cbox._lineitem = li;
820             dojo.connect(cbox, 'onChange', updateOrderIdent);
821         }
822
823         changeComboBox(typeSel); // force the initial draw
824         typeSel.onchange = function() {changeComboBox(typeSel)};
825     };
826
827     this.testOrderIdentPerms = function(org, callback) {
828         var self = this;
829         new openils.User().getPermOrgList(
830             'ACQ_SET_LINEITEM_IDENTIFIER',
831             function(orgs) { 
832                 console.log('found orgs = ' + orgs);
833                 for (var i = 0; i < orgs.length; i++) {
834                     if (Number(orgs[i]) == Number(org)) {
835                         self.orderIdentAllowed = true;
836                         if (callback) callback();
837                         return;
838                     }
839                 }
840                 if (callback) callback();
841             }, 
842             true, true
843         );
844     };
845
846     this.checkClaimEligibility = function(li, callback, row) {
847         /* Assume always eligible, i.e. from this interface we don't care about
848          * claim eligibility any more. this is where the user would force a
849          * claime. */
850         this.clearEligibility(li);
851         this.claimEligibleLidByLi[li.id()] = li.lineitem_details().map(
852             function(lid) { return lid.id(); }
853         );
854         li.lineitem_details().forEach(
855             function(lid) { self.claimEligibleLid[lid.id()] = true; }
856         );
857         this.reconsiderClaimControl(li, row);
858         if (callback) callback(li);
859         /*
860         this.clearEligibility(li);
861         fieldmapper.standardRequest(
862             ["open-ils.acq", "open-ils.acq.claim.eligible.lineitem_detail"], {
863                 "params": [openils.User.authtoken, {"lineitem": li.id()}],
864                 "async": true,
865                 "onresponse": function(r) {
866                     if (r = openils.Util.readResponse(r)) {
867                         self.claimEligibleLidByLi[li.id()].push(
868                             r.lineitem_detail()
869                         );
870                         self.claimEligibleLid[r.lineitem_detail()] = true;
871                     }
872                 },
873                 "oncomplete": function() {
874                     self.reconsiderClaimControl(li, row);
875                     if (typeof(callback) == "function")
876                         callback();
877                 }
878             }
879         );
880         */
881     };
882
883     this.updateLiNotesCount = function(li, row) {
884         if (!row) row = this._findLiRow(li);
885
886         var has_notes = (li.lineitem_notes().filter(
887                 function(o) { return Boolean (o.alert_text()); }
888             ).length > 0);
889
890         /* U+2691 is the code point for a filled-in flag character */
891         nodeByName("notes_alert_flag", row).innerHTML =
892              has_notes ? "&#x2691;" : "";
893         nodeByName("noteslink", row).style.fontStyle =
894             has_notes ? "italic" : "normal";
895         nodeByName("notes_count", row).innerHTML = li.lineitem_notes().length;
896     };
897
898     /* XXX NOT related to _updateLiState(). rethink */
899     this.updateLiState = function(li, row) {
900         if (!row) row = this._findLiRow(li);
901
902         var actUpdateBarcodes = nodeByName("action_update_barcodes", row);
903         var actHoldingsMaint = nodeByName("action_holdings_maint", row);
904
905         // always allow access to LI history
906         nodeByName('action_view_history', row).onclick = 
907             function() { location.href = oilsBasePath + '/acq/lineitem/history/' + li.id(); };
908
909         /* handle row coloring for based on LI state */
910         openils.Util.removeCSSClass(row, /^oils-acq-li-state-/);
911         openils.Util.addCSSClass(row, "oils-acq-li-state-" + li.state());
912
913         // Expose invoice actions for any lineitem that is linked to a PO 
914         if (li.purchase_order()) {
915             openils.Util.show(nodeByName("invoices_span", row), "inline");
916             var link = nodeByName("invoices_link", row);
917             link.onclick = function() {
918                 openils.XUL.newTabEasy(
919                     oilsBasePath + "/acq/search/unified?so=" +
920                     base64Encode({"jub":[{"id": li.id()}]}) + "&rt=invoice"
921                 );
922                 return false;
923             };
924         }
925                 
926
927         /*
928          * If we haven't fleshed the lineitem_details, default to allowing access to the 
929          * holdings maintenence actions.  The alternative is to flesh LIDs on every lineitem, 
930          * but that will add to page render time.  Let's see if this will suffice...
931          */
932         var lids = li.lineitem_details();
933         if( !lids || 
934                 (lids && !lids.filter(function(lid) { return lid.eg_copy_id() })[0] )) {
935
936             actUpdateBarcodes.disabled = false;
937             actUpdateBarcodes.onclick = function() {
938                 self.showRealCopyEditUI(li);
939                 nodeByName("action_none", row).selected = true;
940             }
941             actHoldingsMaint.disabled = false;
942             actHoldingsMaint.onclick = 
943                 self.generateMakeRecTab( li.eg_bib_id(), 'copy_browser', row );
944         }
945
946         var state_cell = nodeByName("li_state", row);
947
948         switch(li.state()) {
949
950             case 'cancelled':
951                 if(typeof li.cancel_reason() == "object") {
952                     var holds_state = dojo.create(
953                         "span", {
954                             "style": "border-bottom: 1px dashed #000;",
955                             "innerHTML": li.state()
956                         }, state_cell, "only"
957                     );
958                     new dijit.Tooltip(
959                         {
960                             "label": "<em>" + li.cancel_reason().label() +
961                                 "</em><br />" + li.cancel_reason().description(),
962                             "connectId": [holds_state]
963                         }, dojo.create("span", null, state_cell, "last")
964                     );
965                 }
966                 return; // all done
967
968             case "on-order":
969                 break;
970
971             case "received":
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 'add_to_order':
2490                 addToPoDialog._get_li = dojo.hitch(
2491                     this,
2492                     function() { return this.getSelected(false, null, true); }
2493                 );
2494                 addToPoDialog.show();
2495                 break;
2496
2497             case 'create_order':
2498                 this._loadPOSelect();
2499                 acqLitPoCreateDialog.show();
2500                 break;
2501
2502             case 'save_picklist':
2503                 acqLitSavePlDialog.show();
2504                 break;
2505
2506             case 'selector_ready':
2507             case 'order_ready':
2508                 acqLitChangeLiStateDialog.attr('state', action.replace('_', '-'));
2509                 acqLitChangeLiStateDialog.show();
2510                 break;
2511
2512             case 'print_po':
2513                 this.printPO();
2514                 break;
2515
2516             case 'po_history':
2517                 location.href = oilsBasePath + '/acq/po/history/' + this.isPO;
2518                 break;
2519
2520             case 'batch_create_invoice':
2521                 this.batchCreateInvoice();
2522                 break;
2523
2524             case 'batch_link_invoice':
2525                 this.batchLinkInvoice();
2526                 break;
2527
2528             case 'receive_lineitems':
2529                 this.receiveSelectedLineitems();
2530                 break;
2531
2532             case 'rollback_receive_lineitems':
2533                 this.rollbackReceiveLineitems();
2534                 break;
2535
2536             case 'create_assets':
2537                 this.showAssetCreator();
2538                 break;
2539
2540             case 'export_attr_list':
2541                 this.chooseExportAttr();
2542                 break;
2543
2544             case 'batch_apply_funds':
2545                 this.applyBatchLiFunds();
2546                 break;
2547
2548             case 'add_brief_record':
2549                 if(this.isPO)
2550                     location.href = oilsBasePath + '/acq/picklist/brief_record?po=' + this.isPO;
2551                 else
2552                     location.href = oilsBasePath + '/acq/picklist/brief_record?pl=' + this.isPL;
2553
2554                 break;
2555
2556             case "cancel_lineitems":
2557                 this.maybeCancelLineitems();
2558                 break;
2559
2560             case "apply_claim_policy":
2561                 var li_list = this.getSelected();
2562                 this.claimPolicyPicker.attr("value", null);
2563                 liClaimPolicyDialog.show();
2564                 liClaimPolicySave.onClick = function() {
2565                     self.changeClaimPolicy(
2566                         li_list,
2567                         self.claimPolicyPicker.attr("value"),
2568                         function() {
2569                             li_list.forEach(
2570                                 function(li) {
2571                                     self.setClaimPolicyControl(li);
2572                                     self.reconsiderClaimControl(li);
2573                                 }
2574                             );
2575                             liClaimPolicyDialog.hide();
2576                         }
2577                     )
2578                 };
2579                 break;
2580         }
2581     };
2582
2583     this.changeClaimPolicy = function(li_list, value, callback) {
2584         li_list.forEach(
2585             function(li) { li.claim_policy(value); }
2586         );
2587         fieldmapper.standardRequest(
2588             ["open-ils.acq", "open-ils.acq.lineitem.update"], {
2589                 "params": [openils.User.authtoken, li_list],
2590                 "async": true,
2591                 "oncomplete": function(r) {
2592                     r = openils.Util.readResponse(r);
2593                     if (callback) callback(r);
2594                 }
2595             }
2596         );
2597     };
2598
2599     this.showAssetCreator = function(onAssetsCreated) {
2600         if(!this.isPO) return;
2601         var self = this;
2602     
2603         // first, let's see if this PO has any LI's that need to be merged/imported
2604         self.pcrud.search('jub', {purchase_order : this.isPO, eg_bib_id : null}, {
2605             id_list : true,
2606             oncomplete : function(r) {
2607                 var resp = openils.Util.readResponse(r);
2608                 if (resp && resp.length) {
2609                     // PO has some non-linked jubs.  
2610                     
2611                     self.show('asset-creator');
2612                     if(!self.vlAgent.loaded)
2613                         self.vlAgent.init();
2614
2615                     dojo.connect(assetCreatorButton, 'onClick', 
2616                         function() { self.createAssets(onAssetsCreated) });
2617
2618                 } else {
2619
2620                     // all jubs linked, move on to asset creation
2621                     self.createAssets(onAssetsCreated, true); 
2622                 }
2623             }
2624         });
2625     }
2626
2627     this.createAssets = function(onAssetsCreated, noVl) {
2628         this.show('acq-lit-progress-numbers');
2629         var self = this;
2630         var vlArgs = (noVl) ? {} : {vandelay : this.vlAgent.values()};
2631         fieldmapper.standardRequest(
2632             ['open-ils.acq', 'open-ils.acq.purchase_order.assets.create'],
2633             {   async: true,
2634                 params: [this.authtoken, this.isPO, vlArgs],
2635                 onresponse: function(r) {
2636                     var resp = openils.Util.readResponse(r);
2637                     self._updateProgressNumbers(resp, !Boolean(onAssetsCreated), onAssetsCreated);
2638                 }
2639             }
2640         );
2641     }
2642
2643     this.maybeCancelLineitems = function() {
2644         openils.Util.show("acq-lit-cancel-reason", "inline");
2645         if (!acqLitCancelLineitemsButton._prepared) {
2646             var widget = new openils.widget.AutoFieldWidget({
2647                 "fmField": "cancel_reason",
2648                 "fmClass": "jub",
2649                 "parentNode": dojo.byId("acq-lit-cancel-reason-selector"),
2650                 "orgLimitPerms": ["CREATE_PURCHASE_ORDER"],
2651                 "forceSync": true
2652             });
2653             widget.build(
2654                 function(w, ww) {
2655                     acqLitCancelLineitemsButton.onClick = function() {
2656                         if (w.attr("value")) {
2657                             if (confirm(localeStrings.LI_CANCEL_CONFIRM)) {
2658                                 self._cancelLineitems(w.attr("value"));
2659                             }
2660                             openils.Util.hide("acq-lit-cancel-reason");
2661                         }
2662                     };
2663                     acqLitCancelLineitemsButton._prepared = true;
2664                 }
2665             );
2666         }
2667     };
2668
2669     this._cancelLineitems = function(reason) {
2670         var id_list = this.getSelected().map(function(o) { return o.id(); });
2671         fieldmapper.standardRequest(
2672             ["open-ils.acq", "open-ils.acq.lineitem.cancel.batch"], {
2673                 "params": [openils.User.authtoken, id_list, reason],
2674                 "async": true,
2675                 "onresponse": function(r) {
2676                     if (r = openils.Util.readResponse(r)) {
2677                         if (r.li) {
2678                             for (var id in r.li) {
2679                                 self.liCache[id].state(r.li[id].state);
2680                                 self.liCache[id].cancel_reason(
2681                                     r.li[id].cancel_reason
2682                                 );
2683                                 self.updateLiState(self.liCache[id]);
2684                             }
2685                         }
2686                         if (r.lid && self.copyCache) {
2687                             for (var id in r.lid) {
2688                                 if (self.copyCache[id]) {
2689                                     self.copyCache[id].cancel_reason(
2690                                         r.lid[id].cancel_reason
2691                                     );
2692                                     self.updateLidState(self.copyCache[id]);
2693                                 }
2694                             }
2695                         }
2696                     }
2697                 }
2698             }
2699         );
2700     };
2701
2702     this.chooseExportAttr = function() {
2703         if (!acqLitExportAttrSelector._li_setup) {
2704             var self = this;
2705             acqLitExportAttrSelector.store = new dojo.data.ItemFileReadStore(
2706                 {
2707                     "data": acqlimad.toStoreData(
2708                         this.pcrud.search(
2709                             "acqlimad", {"code": li_exportable_attrs}
2710                         )
2711                     )
2712                 }
2713             );
2714             acqLitExportAttrSelector.setValue();
2715             acqLitExportAttrButton.onClick = function(){self.exportAttrList();};
2716             acqLitExportAttrSelector._li_setup = true;
2717         }
2718         openils.Util.show("acq-lit-export-attr-holder", "inline");
2719     };
2720
2721     this.exportAttrList = function() {
2722         var attr_def = acqLitExportAttrSelector.item;
2723         var li_list = this.getSelected();
2724         var value_list = li_list.map(
2725             function(li) {
2726                 return (new openils.acq.Lineitem({"lineitem": li})).findAttr(
2727                     attr_def.code, "lineitem_marc_attr_definition"
2728                 );
2729             }
2730         ).filter(function(attr) { return Boolean(attr); });
2731
2732         if (value_list.length > 0) {
2733             if (value_list.length < li_list.length) {
2734                 if (!confirm(
2735                     dojo.string.substitute(
2736                         localeStrings.EXPORT_SHORT_LIST, [attr_def.description]
2737                     )
2738                 )) {
2739                     return;
2740                 }
2741             }
2742             try {
2743                 openils.XUL.contentToFileSaveDialog(
2744                     value_list.join("\n"),
2745                     localeStrings.EXPORT_SAVE_DIALOG_TITLE
2746                 );
2747             } catch (E) {
2748                 alert(E);
2749             }
2750         } else {
2751             alert(dojo.string.substitute(
2752                 localeStrings.EXPORT_EMPTY_LIST, [attr_def.description]
2753             ));
2754         }
2755
2756         openils.Util.hide("acq-lit-export-attr-holder");
2757     };
2758
2759     this.printPO = function() {
2760         if(!this.isPO) return;
2761         progressDialog.show(true);
2762         fieldmapper.standardRequest(
2763             ['open-ils.acq', 'open-ils.acq.purchase_order.format'],
2764             {   async: true,
2765                 params: [this.authtoken, this.isPO, 'html'],
2766                 oncomplete: function(r) {
2767                     progressDialog.hide();
2768                     var evt = openils.Util.readResponse(r);
2769                     if(evt && evt.template_output()) {
2770                         openils.Util.printHtmlString(evt.template_output().data());
2771                     }
2772                 }
2773             }
2774         );
2775     };
2776
2777     this.batchCreateInvoice = function() {
2778         var liIds = this.getSelected(false, null, true /* id_list */)
2779         if (!liIds.length) return;
2780         var path = oilsBasePath + '/acq/invoice/view?create=1';
2781         dojo.forEach(liIds, function(li, idx) { path += '&attach_li=' + li });
2782         if (openils.XUL.isXUL())
2783             openils.XUL.newTabEasy(path, localeStrings.NEW_INVOICE, null, true);
2784         else
2785             location.href = path;
2786     };
2787
2788     this.batchLinkInvoice = function(create) {
2789         var liIds = this.getSelected(false, null, true /* id_list */)
2790         if (!liIds.length) return;
2791         if (!self.invoiceLinkDialogManager) {
2792             self.invoiceLinkDialogManager =
2793                 new InvoiceLinkDialogManager("li");
2794         }
2795         self.invoiceLinkDialogManager.target = liIds;
2796         acqLitLinkInvoiceDialog.show();
2797     };
2798
2799     this.receiveSelectedLineitems = function() {
2800         var li_list = this.getSelected();
2801
2802         for (var i = 0; i < li_list.length; i++) {
2803             var li = li_list[i];
2804
2805             if (li.state() != "received" &&
2806                 !this.checkLiAlerts(li.id())) return;
2807         }
2808
2809         this.show('acq-lit-progress-numbers');
2810
2811         var self = this;
2812         fieldmapper.standardRequest(
2813             ['open-ils.acq', 'open-ils.acq.lineitem.receive.batch'],
2814             {   async: true,
2815                 params: [
2816                     this.authtoken,
2817                     li_list.map(function(li) { return li.id(); })
2818                 ],
2819                 onresponse : function(r) {
2820                     var resp = openils.Util.readResponse(r);
2821                     self._updateProgressNumbers(resp, true);
2822                 },
2823             }
2824         );
2825     };
2826
2827     this.issueReceive = function(obj, rollback) {
2828         var part =
2829             {"jub": "lineitem", "acqlid": "lineitem_detail"}[obj.classname];
2830         var method =
2831             "open-ils.acq." + part + ".receive" + (rollback ? ".rollback" : "");
2832
2833         progressDialog.show(true);
2834         fieldmapper.standardRequest(
2835             ["open-ils.acq", method], {
2836                 "async": true,
2837                 "params": [this.authtoken, obj.id()],
2838                 "onresponse": function(r) {
2839                     if (r = openils.Util.readResponse(r)) {
2840                         self.fetchClaimInfo(
2841                             part == "lineitem" ? obj.id() : obj.lineitem(),
2842                             /* force */ true,
2843                             function() { self.handleReceive(r); }
2844                         );
2845                         progressDialog.hide();
2846                     }
2847                 }
2848             }
2849         );
2850     };
2851
2852     /**
2853      * Handles the responses from receive and rollback ML calls.
2854      */
2855     this.handleReceive = function(resp) {
2856         if (resp) {
2857             if (resp.li) {
2858                 for (var li_id in resp.li) {
2859                     for (var key in resp.li[li_id])
2860                         self.liCache[li_id][key](resp.li[li_id][key]);
2861                     self.updateLiState(self.liCache[li_id]);
2862                 }
2863             }
2864             if (resp.po) {
2865                 if (typeof(self.poUpdateCallback) == "function")
2866                     self.poUpdateCallback(resp.po);
2867             }
2868             if (resp.lid) {
2869                 for (var lid_id in resp.lid) {
2870                     for (var key in resp.lid[lid_id])
2871                         self.copyCache[lid_id][key](resp.lid[lid_id][key]);
2872                     self.updateLidState(self.copyCache[lid_id]);
2873                 }
2874             }
2875         }
2876     };
2877
2878     this.rollbackReceiveLineitems = function() {
2879         if (!confirm(localeStrings.ROLLBACK_LI_RECEIVE_CONFIRM)) return;
2880
2881         this.show('acq-lit-progress-numbers');
2882         var self = this;
2883
2884         fieldmapper.standardRequest(
2885             ['open-ils.acq', 'open-ils.acq.lineitem.receive.rollback.batch'],
2886             {   async: true,
2887                 params: [this.authtoken, this.getSelected(false, null, true)],
2888                 onresponse : function(r) {
2889                     var resp = openils.Util.readResponse(r);
2890                     self._updateProgressNumbers(resp, true);
2891                 },
2892             }
2893         );
2894     };
2895
2896     this._updateProgressNumbers = function(resp, reloadOnComplete, onComplete) {
2897         this.vlAgent.handleResponse(resp,
2898             function(resp, res) {
2899                 if(reloadOnComplete)
2900                      location.href = location.href;
2901                 if (onComplete)
2902                     onComplete(resp, res);
2903             }
2904         );
2905     }
2906
2907
2908     this._createPO = function(fields) {
2909         var wantall = (fields.create_from == "all");
2910
2911         /* If we're a picklist or purchase order already and the user wants
2912          * all lineitems, we might have pages' worth of lineitems haven't all
2913          * been loaded yet, so getSelected() won't find them.  The server,
2914          * however, should know about all our lineitems, so let's ask the
2915          * server for a complete list.
2916          */
2917
2918         if (wantall) {
2919             this.getSelected(
2920                 true, function(list) {
2921                     self._createPOFromLineitems(fields, list);
2922                 }, /* id_list */ true
2923             );
2924         } else {
2925             this._createPOFromLineitems(fields, this.getSelected(false, null, true /* id_list */));
2926         }
2927     };
2928
2929     this._createPOFromLineitems = function(fields, selected) {
2930         if (selected.length == 0) return;
2931         var self = this;
2932
2933         var po = new fieldmapper.acqpo();
2934         po.provider(this.createPoProviderSelector.attr("value"));
2935         po.ordering_agency(this.createPoAgencySelector.attr("value"));
2936         po.prepayment_required(fields.prepayment_required[0] ? true : false);
2937
2938         // if we're creating assets, delay the asset creation 
2939         // until after the PO is created.  This will allow us to 
2940         // use showAssetCreator() directly.
2941
2942         fieldmapper.standardRequest(
2943             ["open-ils.acq", "open-ils.acq.purchase_order.create"],
2944             {   async: true,
2945                 params: [
2946                     openils.User.authtoken, 
2947                     po, {lineitems : selected}
2948                 ],
2949                 onresponse : function(r) {
2950                     var resp = openils.Util.readResponse(r);
2951                     if (resp.complete) {
2952                         // self.isPO is needed for showAssetCreator();
2953                         self.isPO = resp.purchase_order.id(); 
2954                         var redir = oilsBasePath + "/acq/po/view/" + self.isPO;
2955                         if (fields.create_assets[0]) {
2956                             self.showAssetCreator(
2957                                 function() {location.href = redir}
2958                             );
2959                         } else {
2960                            location.href = redir;
2961                         }
2962                     }
2963                 }
2964             }
2965         );
2966     };
2967
2968
2969     this.batchFundWidget = null;
2970
2971     this.applyBatchLiFunds = function() {
2972
2973         var liIds = this.getSelected().map(function(li) { return li.id(); });
2974         if(liIds.length == 0) return; // warn?
2975
2976         var self = this;
2977         batchFundUpdateDialog.show();
2978
2979         if(!this.batchFundWidget) {
2980             this.batchFundWidget = new openils.widget.AutoFieldWidget({
2981                 fmClass : 'acqf',
2982                 selfReference : true,
2983                 labelFormat : fundLabelFormat,
2984                 searchFormat : fundSearchFormat,
2985                 searchFilter : {"active": "t"},
2986                 parentNode : dojo.byId('acq-lit-batch-fund-selector'),</