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