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