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