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