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