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