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