]> git.evergreen-ils.org Git - working/Evergreen.git/blob - Open-ILS/web/js/ui/default/acq/common/li_table.js
Acq: support manual claiming as always intended, which to some users means
[working/Evergreen.git] / Open-ILS / web / js / ui / default / acq / common / li_table.js
1 dojo.require('dojo.date.locale');
2 dojo.require('dojo.date.stamp');
3 dojo.require('dijit.form.Button');
4 dojo.require('dijit.form.TextBox');
5 dojo.require('dijit.form.FilteringSelect');
6 dojo.require('dijit.form.Textarea');
7 dojo.require('dijit.Tooltip');
8 dojo.require('dijit.ProgressBar');
9 dojo.require('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
18 dojo.requireLocalization('openils.acq', 'acq');
19 var localeStrings = dojo.i18n.getLocalization('openils.acq', 'acq');
20 const XUL_OPAC_WRAPPER = 'chrome://open_ils_staff_client/content/cat/opac.xul';
21 var li_exportable_attrs = ["issn", "isbn", "upc"];
22
23 var fundLabelFormat = [
24     '<span class="fund_${0}">${1} (${2})</span>', 'id', 'code', 'year'
25 ];
26 var fundSearchFormat = ['${0} (${1})', 'code', 'year'];
27
28 function nodeByName(name, context) {
29     return dojo.query('[name='+name+']', context)[0];
30 }
31
32
33 var liDetailBatchFields = ['fund', 'owning_lib', 'location', 'collection_code', 'circ_modifier', 'cn_label'];
34 var liDetailFields = liDetailBatchFields.concat(['barcode', 'note']);
35 var fundStyles = {
36     "stop": "color: #c00; font-weight: bold;",
37     "warning": "color: #c93;"
38 };
39
40 function AcqLiTable() {
41
42     var self = this;
43     this.liCache = {};
44     this.plCache = {};
45     this.poCache = {};
46     this.relCache = {};
47     this.haveFundClass = {}
48     this.fundBalanceState = {};
49     this.realDfaCache = {};
50     this.virtDfaCounts = {};
51     this.virtDfaId = -1;
52     this.dfeOffset = 0;
53     this.claimEligibleLidByLi = {};
54     this.claimEligibleLid = {};
55     this.toggleState = false;
56     this.tbody = dojo.byId('acq-lit-tbody');
57     this.selectors = [];
58     this.noteAcks = {};
59     this.authtoken = openils.User.authtoken;
60     this.pcrud = new openils.PermaCrud();
61     this.rowTemplate = this.tbody.removeChild(dojo.byId('acq-lit-row'));
62     this.copyTbody = dojo.byId('acq-lit-li-details-tbody');
63     this.copyRow = this.copyTbody.removeChild(dojo.byId('acq-lit-li-details-row'));
64     this.copyBatchRow = dojo.byId('acq-lit-li-details-batch-row');
65     this.copyBatchWidgets = {};
66     this.liNotesTbody = dojo.byId('acq-lit-notes-tbody');
67     this.liNotesRow = this.liNotesTbody.removeChild(dojo.byId('acq-lit-notes-row'));
68     this.realCopiesTbody = dojo.byId('acq-lit-real-copies-tbody');
69     this.realCopiesRow = this.realCopiesTbody.removeChild(dojo.byId('acq-lit-real-copies-row'));
70     this._copy_fields_for_acqdf = ['owning_lib', 'location'];
71     this.skipInitialEligibilityCheck = false;
72     this.claimDialog = new ClaimDialogManager(
73         liClaimDialog, finalClaimDialog, this.claimEligibleLidByLi,
74         function(li) {    /* callback that fires when claims are made */
75             self.fetchClaimInfo(li.id(), /* force update */ true);
76         }
77     );
78
79     dojo.byId("acq-lit-li-actions-selector").onchange = function() { 
80         self.applySelectedLiAction(this.options[this.selectedIndex].value);
81         this.selectedIndex = 0;
82     };
83
84     acqLitCreatePoSubmit.onClick = function() {
85         if (self._confirmPoPrepaySituation()) {
86             acqLitPoCreateDialog.hide();
87             self._createPO(acqLitPoCreateDialog.getValues());
88         } else {
89             return false;
90         }
91     }
92
93     acqLitSavePlButton.onClick = function() {
94         acqLitSavePlDialog.hide();
95         self._savePl(acqLitSavePlDialog.getValues());
96     }
97
98     acqLitCancelLiStateButton.onClick = function() {
99         acqLitChangeLiStateDialog.hide();
100     }
101     acqLitSaveLiStateButton.onClick = function() {
102         acqLitChangeLiStateDialog.hide();
103         self._updateLiState(acqLitChangeLiStateDialog.getValues(), acqLitChangeLiStateDialog.attr('state'));
104     }
105
106
107     dojo.byId('acq-lit-select-toggle').onclick = function(){self.toggleSelect()};
108     dojo.byId('acq-lit-info-back-button').onclick = function(){self.show('list')};
109     dojo.byId('acq-lit-copies-back-button').onclick = function(){self.show('list')};
110     dojo.byId('acq-lit-notes-back-button').onclick = function(){self.show('list')};
111     dojo.byId('acq-lit-real-copies-back-button').onclick = function(){self.show('list')};
112
113     this.reset = function(keep_selectors) {
114         while(self.tbody.childNodes[0])
115             self.tbody.removeChild(self.tbody.childNodes[0]);
116         self.noteAcks = {};
117         self.relCache = {};
118
119         if (!keep_selectors)
120             self.selectors = [];
121     };
122     
123     this.setNext = function(handler) {
124         var link = dojo.byId('acq-lit-next');
125         if(handler) {
126             dojo.style(link, 'visibility', 'visible');
127             link.onclick = handler;
128         } else {
129             dojo.style(link, 'visibility', 'hidden');
130         }
131     };
132
133     this.setPrev = function(handler) {
134         var link = dojo.byId('acq-lit-prev');
135         if(handler) {
136             dojo.style(link, 'visibility', 'visible'); 
137             link.onclick = handler; 
138         } else {
139             dojo.style(link, 'visibility', 'hidden');
140         }
141     };
142
143     this.show = function(div) {
144         openils.Util.hide('acq-lit-table-div');
145         openils.Util.hide('acq-lit-info-div');
146         openils.Util.hide('acq-lit-li-details');
147         openils.Util.hide('acq-lit-notes-div');
148         openils.Util.hide('acq-lit-real-copies-div');
149         switch(div) {
150             case 'list':
151                 openils.Util.show('acq-lit-table-div');
152                 break;
153             case 'info':
154                 openils.Util.show('acq-lit-info-div');
155                 break;
156             case 'copies':
157                 openils.Util.show('acq-lit-li-details');
158                 break;
159             case 'real-copies':
160                 openils.Util.show('acq-lit-real-copies-div');
161                 break;
162             case 'notes':
163                 openils.Util.show('acq-lit-notes-div');
164                 break;
165             default:
166                 if(div) 
167                     openils.Util.show(div);
168         }
169     }
170
171     this.hide = function() {
172         this.show(null);
173     }
174
175     this.toggleSelect = function() {
176         if(self.toggleState) 
177             dojo.forEach(self.selectors, function(i){i.checked = false});
178         else 
179             dojo.forEach(self.selectors, function(i){i.checked = true});
180         self.toggleState = !self.toggleState;
181     };
182
183
184     /** @param all If true, assume all are selected */
185     this.getSelected = function(all) {
186         var selected = [];
187         var indices = {};   /* use to uniqify. needed in paging situations. */
188         dojo.forEach(self.selectors, 
189             function(i) { 
190                 if(i.checked || all)
191                     indices[i.parentNode.parentNode.getAttribute('li')] = true;
192             }
193         );
194         return openils.Util.objectProperties(indices).map(
195             function(liId) { return self.liCache[liId]; }
196         );
197     };
198
199     this.setRowAttr = function(td, liWrapper, field, type) {
200         var val = liWrapper.findAttr(field, type || 'lineitem_marc_attr_definition') || '';
201         td.appendChild(document.createTextNode(val));
202     };
203
204     this.setClaimPolicyControl = function(li, row) {
205         if (!self.claimPolicyPicker) {
206             self.claimPolicyPicker = true; /* prevents a race condition */
207             new openils.widget.AutoFieldWidget({
208                 "parentNode": "acq-lit-li-claim-policy",
209                 "fmClass": "acqclp",
210                 "selfReference": true,
211                 "dijitArgs": {"required": true}
212             }).build(function(w) { self.claimPolicyPicker = w; });
213         }
214
215         if (!row) row = this._findLiRow(li);
216
217         var actViewPolicy = nodeByName("action_view_claim_policy", row);
218         if (li.claim_policy())
219             actViewPolicy.innerHTML = localeStrings.CHANGE_CLAIM_POLICY;
220
221         if (!actViewPolicy.onclick) {
222             actViewPolicy.onclick = function() {
223                 if (li.claim_policy())
224                     self.claimPolicyPicker.attr("value", li.claim_policy());
225                 liClaimPolicyDialog.show();
226                 liClaimPolicySave.onClick = function() {
227                     self.changeClaimPolicy(
228                         [li], self.claimPolicyPicker.attr("value"),
229                         function() {
230                             self.setClaimPolicyControl(li, row);
231                             liClaimPolicyDialog.hide();
232                         }
233                     );
234                 }
235             };
236         }
237     };
238
239     this.fetchClaimInfo = function(liId, force, callback, row) {
240         this._fetchLineitem(
241             liId, function(full) {
242                 self.liCache[full.id()] = full;
243                 self.checkClaimEligibility(full, callback, row);
244             }, force
245         );
246     }
247
248     /**
249      * Inserts a single lineitem into the growing table of lineitems
250      * @param {Object} li The lineitem object to insert
251      */
252     this.addLineitem = function(li, skip_final_placement) {
253         this.liCache[li.id()] = li;
254
255         // sort the lineitem notes on edit_time
256         if(!li.lineitem_notes()) li.lineitem_notes([]);
257
258         var liWrapper = new openils.acq.Lineitem({lineitem:li});
259         var row = self.rowTemplate.cloneNode(true);
260         row.setAttribute('li', li.id());
261         var tds = dojo.query('[attr]', row);
262         dojo.forEach(tds, function(td) {self.setRowAttr(td, liWrapper, td.getAttribute('attr'), td.getAttribute('attr_type'));});
263         dojo.query('[name=source_label]', row)[0].appendChild(document.createTextNode(li.source_label()));
264
265         var identifier =
266             liWrapper.findAttr("isbn", "lineitem_marc_attr_definition") ||
267             liWrapper.findAttr("upc", "lineitem_marc_attr_definition");
268
269         // XXX media prefix for added content
270         if (identifier) {
271             nodeByName("jacket", row).setAttribute(
272                 "src", "/opac/extras/ac/jacket/small/" + identifier
273             );
274         }
275
276         nodeByName("liid", row).innerHTML += li.id();
277
278         if(li.eg_bib_id()) {
279             openils.Util.show(nodeByName('catalog', row), 'inline');
280             nodeByName("catalog_link", row).onclick = this.generateMakeRecTab(li.eg_bib_id());
281         } else {
282             openils.Util.show(nodeByName('link_to_catalog', row), 'inline');
283             nodeByName("link_to_catalog_link", row).onclick = function() { self.drawBibFinder(li) };
284         }
285
286         nodeByName("worksheet_link", row).href =
287             oilsBasePath + "/acq/lineitem/worksheet/" + li.id();
288
289         dojo.query('[attr=title]', row)[0].onclick = function() {self.drawInfo(li.id())};
290         dojo.query('[name=copieslink]', row)[0].onclick = function() {self.drawCopies(li.id())};
291         dojo.query('[name=noteslink]', row)[0].onclick = function() {self.drawLiNotes(li)};
292
293         if (!this.skipInitialEligibilityCheck)
294             this.fetchClaimInfo(li.id(), false, null, row);
295
296         this.updateLiNotesCount(li, row);
297
298         this.setClaimPolicyControl(li, row);
299
300         // show which PO this lineitem is a member of
301         if(li.purchase_order() && !this.isPO) {
302             var po = 
303                 this.poCache[li.purchase_order()] =
304                 this.poCache[li.purchase_order()] ||
305                 fieldmapper.standardRequest(
306                     ['open-ils.acq', 'open-ils.acq.purchase_order.retrieve'],
307                     {params: [
308                         this.authtoken, li.purchase_order(), {
309                             "flesh_price_summary": true,
310                             "flesh_lineitem_count": true
311                         }
312                     ]});
313             if(po && !this.isMeta) {
314                 openils.Util.show(nodeByName('po', row), 'inline');
315                 var link = nodeByName('po_link', row);
316                 link.setAttribute('href', oilsBasePath + '/acq/po/view/' + li.purchase_order());
317                 link.innerHTML += po.name();
318             }
319         }
320
321         // show which picklist this lineitem is a member of
322         if(li.picklist() && (this.isPO || this.isMeta || this.isUni)) {
323             var pl = 
324                 this.plCache[li.picklist()] = 
325                 this.plCache[li.picklist()] || 
326                 fieldmapper.standardRequest(
327                     ['open-ils.acq', 'open-ils.acq.picklist.retrieve.authoritative'],
328                     {params: [this.authtoken, li.picklist()]});
329             if (pl) {
330                 if (pl.name() == "") {
331                     openils.Util.show(nodeByName("bib_origin", row), "inline");
332
333                 } else {
334
335                     openils.Util.show(nodeByName('pl', row), 'inline');
336                     var link = nodeByName('pl_link', row);
337                     link.setAttribute('href', oilsBasePath + '/acq/picklist/view/' + li.picklist());
338                     link.innerHTML += pl.name();
339                 }
340             }
341         }
342
343         var countNode = nodeByName('count', row);
344         var count = li.item_count() || 0;
345         if (typeof(this._copy_count_cb) == "function") {
346             this._copy_count_cb(li.id(), count);
347         }
348         countNode.innerHTML = count;
349         countNode.id = 'acq-lit-copy-count-label-' + li.id();
350
351         // lineitem price
352         var priceInput = dojo.query('[name=price]', row)[0];
353         priceInput.value = li.estimated_unit_price() || '';
354         priceInput.onchange = function() { self.updateLiPrice(priceInput, li) };
355
356         // show either "mark received" or "unreceive" as appropriate
357         this.updateLiState(li, row);
358
359         if (!skip_final_placement) {
360             self.tbody.appendChild(row);
361             self.selectors.push(dojo.query('[name=selectbox]', row)[0]);
362         } else {
363             return row;
364         }
365     };
366
367     this._liCountClaims = function(li) {
368         var total = 0;
369         for (var i = 0; i < li.lineitem_details().length; i++)
370             total += li.lineitem_details()[i].claims().length;
371         return total;
372     };
373
374     this._findLiRow = function(li) {
375         return dojo.query('tr[li="' + li.id() + '"]', "acq-lit-tbody")[0];
376     };
377
378     this.reconsiderClaimControl = function(li, row) {
379         if (!row) row = this._findLiRow(li);
380         var option = nodeByName("action_manage_claims", row);
381         var eligible = this.claimEligibleLidByLi[li.id()].length;
382         var count = this._liCountClaims(li);
383
384         option.disabled = !(count || eligible);
385         option.innerHTML =
386             dojo.string.substitute(localeStrings.NUM_CLAIMS_EXISTING, [count]);
387         option.onclick = function() { self.claimDialog.show(li); };
388     };
389
390     this.clearEligibility = function(li) {
391         this.claimEligibleLidByLi[li.id()] = [];
392
393         if (li.lineitem_details()) {
394             li.lineitem_details().forEach(
395                 function(lid) { delete self.claimEligibleLid[lid.id()]; }
396             );
397         }
398
399         if (this.copyCache) {
400             var to_del = [];
401             for (var k in this.copyCache) {
402                 if (this.copyCache[k].lineitem() == li.id())
403                     to_del.push(k);
404             }
405             to_del.forEach(
406                 function(k) { delete self.claimEligibleLid[k]; }
407             );
408         }
409     };
410
411     this.checkClaimEligibility = function(li, callback, row) {
412         /* Assume always eligible, i.e. from this interface we don't care about
413          * claim eligibility any more. this is where the user would force a
414          * claime. */
415         this.clearEligibility(li);
416         this.claimEligibleLidByLi[li.id()] = li.lineitem_details().map(
417             function(lid) { return lid.id(); }
418         );
419         li.lineitem_details().forEach(
420             function(lid) { self.claimEligibleLid[lid.id()] = true; }
421         );
422         this.reconsiderClaimControl(li, row);
423         if (callback) callback();
424         /*
425         this.clearEligibility(li);
426         fieldmapper.standardRequest(
427             ["open-ils.acq", "open-ils.acq.claim.eligible.lineitem_detail"], {
428                 "params": [openils.User.authtoken, {"lineitem": li.id()}],
429                 "async": true,
430                 "onresponse": function(r) {
431                     if (r = openils.Util.readResponse(r)) {
432                         self.claimEligibleLidByLi[li.id()].push(
433                             r.lineitem_detail()
434                         );
435                         self.claimEligibleLid[r.lineitem_detail()] = true;
436                     }
437                 },
438                 "oncomplete": function() {
439                     self.reconsiderClaimControl(li, row);
440                     if (typeof(callback) == "function")
441                         callback();
442                 }
443             }
444         );
445         */
446     };
447
448     this.updateLiNotesCount = function(li, row) {
449         if (!row) row = this._findLiRow(li);
450
451         var has_notes = (li.lineitem_notes().filter(
452                 function(o) { return Boolean (o.alert_text()); }
453             ).length > 0);
454
455         /* U+2691 is the code point for a filled-in flag character */
456         nodeByName("notes_alert_flag", row).innerHTML =
457              has_notes ? "&#x2691;" : "";
458         nodeByName("noteslink", row).style.fontStyle =
459             has_notes ? "italic" : "normal";
460         nodeByName("notes_count", row).innerHTML = li.lineitem_notes().length;
461     };
462
463     /* XXX NOT related to _updateLiState(). rethink */
464     this.updateLiState = function(li, row) {
465         if (!row) row = this._findLiRow(li);
466
467         var actReceive = nodeByName("action_mark_recv", row);
468         var actUnRecv = nodeByName("action_mark_unrecv", row);
469         var actUpdateBarcodes = nodeByName("action_update_barcodes", row);
470         var actHoldingsMaint = nodeByName("action_holdings_maint", row);
471
472         var actNewInvoice = nodeByName('action_new_invoice', row);
473         var actLinkInvoice = nodeByName('action_link_invoice', row);
474         var actViewInvoice = nodeByName('action_view_invoice', row);
475
476         nodeByName('action_view_history', row).onclick = 
477             function() { location.href = oilsBasePath + '/acq/lineitem/history/' + li.id(); };
478
479         var state_cell = nodeByName("li_state", row);
480
481         if (li.state() == "cancelled") {
482             if (typeof li.cancel_reason() == "object") {
483                 var holds_state = dojo.create(
484                     "span", {
485                         "style": "border-bottom: 1px dashed #000;",
486                         "innerHTML": li.state()
487                     }, state_cell, "only"
488                 );
489                 new dijit.Tooltip(
490                     {
491                         "label": "<em>" + li.cancel_reason().label() +
492                             "</em><br />" + li.cancel_reason().description(),
493                         "connectId": [holds_state]
494                     }, dojo.create("span", null, state_cell, "last")
495                 );
496             } else {
497                 state_cell.innerHTML = li.state(); // TODO i18n state labels
498             }
499         } else {
500             state_cell.innerHTML = li.state(); // TODO i18n state labels
501         }
502
503
504         /* handle row coloring for based on LI state */
505         openils.Util.removeCSSClass(row, /^oils-acq-li-state-/);
506         openils.Util.addCSSClass(row, "oils-acq-li-state-" + li.state());
507
508         /* handle links that appear/disappear based on whether LI is received */
509         if (this.isPO) {
510             var self = this;
511
512             actNewInvoice.onclick = function() {
513                 location.href = oilsBasePath + '/acq/invoice/view?create=1&attach_li=' + li.id();
514                 nodeByName("action_none", row).selected = true;
515             };
516             actLinkInvoice.onclick = function() {
517                 if (!self.invoiceLinkDialogManager) {
518                     self.invoiceLinkDialogManager =
519                         new InvoiceLinkDialogManager("li");
520                 }
521                 self.invoiceLinkDialogManager.target = li;
522                 acqLitLinkInvoiceDialog.show();
523                 nodeByName("action_none", row).selected = true;
524             };
525             actViewInvoice.onclick = function() {
526                 location.href = oilsBasePath +
527                     "/acq/search/unified?so=" +
528                     base64Encode({"jub":[{"id": li.id()}]}) +
529                     "&rt=invoice";
530                 nodeByName("action_none", row).selected = true;
531             };
532
533             actNewInvoice.disabled = false;
534             actLinkInvoice.disabled = false;
535             actViewInvoice.disabled = false;
536
537             switch(li.state()) {
538                 case "on-order":
539                     actReceive.disabled = false;
540                     actReceive.onclick = function() {
541                         if (self.checkLiAlerts(li.id()))
542                             self.issueReceive(li);
543                         nodeByName("action_none", row).selected = true;
544                     };
545                     return;
546
547                 case "received":
548                     actUnRecv.disabled = false;
549                     actUnRecv.onclick = function() {
550                         if (confirm(localeStrings.UNRECEIVE_LI))
551                             self.issueReceive(li, /* rollback */ true);
552                         nodeByName("action_none", row).selected = true;
553                     };
554                     // TODO we should allow editing before receipt, in which case the
555                     // test should be "if 1 or more real (acp) copies exist
556                     actUpdateBarcodes.disabled = false;
557                     actUpdateBarcodes.onclick = function() {
558                         self.showRealCopyEditUI(li);
559                         nodeByName("action_none", row).selected = true;
560                     }
561                     actHoldingsMaint.disabled = false;
562                     actHoldingsMaint.onclick = self.generateMakeRecTab( li.eg_bib_id(), 'copy_browser', row );
563
564                     return;
565             }
566         }
567     };
568
569
570     this._setAlertStore = function() {
571         acqLitAlertAlertText.store = new dojo.data.ItemFileReadStore(
572             {
573                 "data": acqliat.toStoreData(
574                     this.pcrud.search(
575                         "acqliat", {"id": {"!=": null}}
576                     )
577                 )
578             }
579         );
580         acqLitAlertAlertText.setValue(); /* make the store "live" */
581         acqLitAlertAlertText._store_ready = true;
582     };
583
584     /**
585      * Draws and shows the lineitem notes pane
586      */
587     this.drawLiNotes = function(li) {
588         var self = this;
589
590         if (!acqLitAlertAlertText._store_ready)
591             this._setAlertStore();
592
593         li.lineitem_notes(
594             li.lineitem_notes().sort(
595                 function(a, b) { 
596                     if(a.edit_time() < b.edit_time()) return 1;
597                     return -1;
598                 }
599             )
600         );
601
602         while(this.liNotesTbody.childNodes[0])
603             this.liNotesTbody.removeChild(this.liNotesTbody.childNodes[0]);
604         this.show('notes');
605
606         acqLitCreateNoteSubmit.onClick = function() {
607             var value = acqLitCreateNoteText.attr('value');
608             if(!value) return;
609             var note = new fieldmapper.acqlin();
610             note.isnew(true);
611             note.vendor_public(
612                 Boolean(acqLitCreateNoteVendorPublic.attr('checked'))
613             );
614             note.value(value);
615             note.lineitem(li.id());
616
617             self.updateLiNotes(li, note);
618             acqLitCreateNoteVendorPublic.attr("checked", false);
619             acqLitCreateNoteText.attr("value", "");
620         }
621
622         acqLitCreateAlertSubmit.onClick = function() {
623             if (!acqLitAlertAlertText.item) {
624                 alert(localeStrings.ALERT_UNSELECTED);
625                 return;
626             }
627
628             var alert_text = new fieldmapper.acqliat().fromStoreItem(
629                 acqLitAlertAlertText.item
630             );
631             var value = acqLitAlertNoteValue.attr("value") || "";
632
633             var note = new fieldmapper.acqlin();
634             note.isnew(true);
635             note.lineitem(li.id());
636             note.value(value);
637             note.alert_text(alert_text);
638
639             self.updateLiNotes(li, note);
640         }
641
642         dojo.forEach(li.lineitem_notes(), function(note) { self.addLiNote(li, note) });
643     }
644
645     /**
646      * Draws a single lineitem note in the notes pane
647      */
648     this.addLiNote = function(li, note) {
649         if(note.isdeleted()) return;
650         var self = this;
651         var row = self.liNotesRow.cloneNode(true);
652         nodeByName("value", row).innerHTML = note.value();
653         var alert_node = nodeByName("alert_code", row);
654         if (note.alert_text()) {
655             alert_node.innerHTML = note.alert_text().code();
656             if (note.alert_text().description()) {
657                 new dijit.Tooltip(
658                     {
659                         "connectId": [alert_node],
660                         "label": note.alert_text().description()
661                     }, dojo.create("span", null, alert_node, "after")
662                 );
663             }
664         }
665
666         if (openils.Util.isTrue(note.vendor_public()))
667             nodeByName("vendor_public", row).innerHTML =
668                 localeStrings.VENDOR_PUBLIC;
669
670         nodeByName("delete", row).onclick = function() {
671             note.isdeleted(true);
672             self.liNotesTbody.removeChild(row);
673             self.updateLiNotes(li);
674         };
675
676         if(note.edit_time()) {
677             nodeByName("edit_time", row).innerHTML =
678                 dojo.date.locale.format(
679                     dojo.date.stamp.fromISOString(note.edit_time()), 
680                     {formatLength:'short'});
681         }
682
683         self.liNotesTbody.appendChild(row);
684     }
685
686     /**
687      * Updates any new/changed/deleted notes on the server
688      */
689     this.updateLiNotes = function(li, newNote) {
690
691         var notes;
692         if(newNote) {
693             notes = [newNote];
694         } else {
695             notes = li.lineitem_notes().filter(
696                 function(note) {
697                     if(note.ischanged() || note.isnew() || note.isdeleted())
698                         return note;
699                 }
700             );
701         }
702
703         if(notes.length == 0) return;
704         progressDialog.show();
705
706         fieldmapper.standardRequest(
707             ['open-ils.acq', 'open-ils.acq.lineitem_note.cud.batch'],
708             {   async : true,
709                 params : [this.authtoken, notes],
710                 onresponse : function(r) {
711                     var resp = openils.Util.readResponse(r);
712
713                     if(resp.complete) {
714
715                         if(!newNote) {
716                             // remove the old changed notes
717                             var list = [];
718                             dojo.forEach(li.lineitem_notes(), 
719                                 function(note) {
720                                     if(!(note.ischanged() || note.isnew() || note.isdeleted()))
721                                         list.push(note);
722                                 }
723                             );
724                             li.lineitem_notes(list);
725                         }
726
727                         progressDialog.hide();
728                         self.updateLiNotesCount(li);
729                         self.drawLiNotes(li);
730                         return;
731                     }
732
733                     progressDialog.update(resp);
734                     var newnote = resp.note;
735
736                     if(!newnote.isdeleted()) {
737                         newnote.isnew(false);
738                         newnote.ischanged(false);
739                         li.lineitem_notes().push(newnote);
740                     }
741                 },
742             }
743         );
744     }
745
746     this.updateLiPrice = function(input, li) {
747
748         var price = input.value;
749         if(Number(price) == Number(li.estimated_unit_price())) return;
750
751         fieldmapper.standardRequest(
752             ['open-ils.acq', 'open-ils.acq.lineitem.price.set'],
753             {   async : false, // redundant w/ timeout
754                 timeout : 10,
755                 params : [this.authtoken, li.id(), price],
756                 oncomplete : function(r) {
757                     openils.Util.readResponse(r);
758                     li.estimated_unit_price(price); // update local copy
759                 }
760             }
761         );
762     }
763
764     this.removeLineitem = function(liId) {
765         this.tbody.removeChild(dojo.query('[li='+liId+']', this.tbody)[0]);
766         delete this.liCache[liId];
767         //selected.push(self.liCache[i.parentNode.parentNode.getAttribute('li')]);
768     }
769
770     this.drawInfo = function(liId) {
771         if (!this._isRelatedViewer) {
772             var d = dojo.byId("acq-lit-info-related");
773             if (!this.relCache[liId]) {
774                 fieldmapper.standardRequest(
775                     [
776                         "open-ils.acq",
777                         "open-ils.acq.lineitems_for_bib.by_lineitem_id.count"
778                     ], {
779                         "async": true,
780                         "params": [openils.User.authtoken, liId],
781                         "onresponse": function(r) {
782                             self.relCache[liId] = openils.Util.readResponse(r);
783                             nodeByName("related_number", d).innerHTML =
784                                 self.relCache[liId];
785                             openils.Util[
786                                 self.relCache[liId] >1 ? "show" : "hide"
787                             ](d);
788                         }
789                     }
790                 );
791             } else {
792                 nodeByName("related_number", d).innerHTML = this.relCache[liId];
793                 openils.Util[this.relCache[liId] > 1 ? "show" : "hide"](d);
794             }
795         }
796
797         this.show('info');
798         openils.acq.Lineitem.fetchAttrDefs(
799             function() { 
800                 self._fetchLineitem(liId, function(li){self._drawInfo(li);}); 
801             } 
802         );
803     };
804
805     this._fetchLineitem = function(liId, handler, force) {
806
807         var li = this.liCache[liId];
808         if(li && li.marc() && li.lineitem_details() && !force)
809             return handler(li);
810         
811         fieldmapper.standardRequest(
812             ['open-ils.acq', 'open-ils.acq.lineitem.retrieve.authoritative'],
813             {   async: true,
814
815                 params: [self.authtoken, liId, {
816                     flesh_attrs: true,
817                     flesh_cancel_reason: true,
818                     flesh_li_details: true,
819                     flesh_notes: true,
820                     flesh_fund_debit: true }],
821
822                 oncomplete: function(r) {
823                     var li = openils.Util.readResponse(r);
824                     self.liCache[liId] = li;
825                     handler(li)
826                 }
827             }
828         );
829     };
830
831     this._drawInfo = function(li) {
832
833         acqLitEditOrderMarc.onClick = function() { self.editOrderMarc(li); }
834
835         if(li.eg_bib_id()) {
836             openils.Util.hide('acq-lit-marc-order-record-label');
837             openils.Util.hide(acqLitEditOrderMarc.domNode);
838             openils.Util.show('acq-lit-marc-real-record-label');
839         } else {
840             openils.Util.show('acq-lit-marc-order-record-label');
841             openils.Util.show(acqLitEditOrderMarc.domNode);
842             openils.Util.hide('acq-lit-marc-real-record-label');
843         }
844
845         this.drawMarcHTML(li);
846         this.infoTbody = dojo.byId('acq-lit-info-tbody');
847
848         if(!this.infoRow)
849             this.infoRow = this.infoTbody.removeChild(dojo.byId('acq-lit-info-row'));
850         while(this.infoTbody.childNodes[0])
851             this.infoTbody.removeChild(this.infoTbody.childNodes[0]);
852
853         for(var i = 0; i < li.attributes().length; i++) {
854             var attr = li.attributes()[i];
855             var row = this.infoRow.cloneNode(true);
856
857             var type = attr.attr_type().replace(/lineitem_(.*)_attr_definition/, '$1');
858             var name = openils.acq.Lineitem.attrDefs[type].filter(
859                 function(a) {
860                     return (a.code() == attr.attr_name());
861                 }
862             ).pop().description();
863
864             dojo.query('[name=label]', row)[0].appendChild(document.createTextNode(name));
865             dojo.query('[name=value]', row)[0].appendChild(document.createTextNode(attr.attr_value()));
866             this.infoTbody.appendChild(row);
867         }
868
869         if (!this._isRelatedViewer) {
870             nodeByName("rel_link", dojo.byId("acq-lit-info-related")).href =
871                 oilsBasePath + "/acq/lineitem/related/" + li.id();
872         }
873
874     };
875
876     this.generateMakeRecTab = function(bib_id,default_view, row) {
877         return function() {
878             xulG.new_tab(
879                 XUL_OPAC_WRAPPER,
880                 {tab_name: localeStrings.XUL_RECORD_DETAIL_PAGE, browser:false},
881                 {
882                     no_xulG : false, 
883                     show_nav_buttons : true, 
884                     show_print_button : true, 
885                     opac_url : xulG.url_prefix(xulG.urls.opac_rdetail + '?r=' + bib_id),
886                     default_view : default_view
887                 }
888             );
889
890             if(row) nodeByName("action_none", row).selected = true;
891         }
892     };
893
894     this.drawMarcHTML = function(li) {
895         var params = [null, true, li.marc()];
896         if(li.eg_bib_id()) 
897             params = [li.eg_bib_id(), true];
898
899         fieldmapper.standardRequest(
900             ['open-ils.search', 'open-ils.search.biblio.record.html'],
901             {   async: true,
902                 params: params,
903                 oncomplete: function(r) {
904                     dojo.byId('acq-lit-marc-div').innerHTML = 
905                         openils.Util.readResponse(r);
906                 }
907             }
908         );
909     }
910
911     this.drawCopies = function(liId, force_fetch) {
912         if (typeof force_fetch == "undefined")
913             force_fetch = false;
914
915         this.show('copies');
916         var self = this;
917         this.copyCache = {};
918         this.copyWidgetCache = {};
919         this.oldCopyWidgetCache = {};
920         this.virtDfaCounts = {};
921         this.realDfaCache = {};
922         this.dfeOffset = 0;
923
924         acqLitSaveCopies.onClick = function() { self.saveCopyChanges(liId) };
925         acqLitBatchUpdateCopies.onClick = function() { self.batchCopyUpdate() };
926         acqLitCopyCountInput.attr('value', '0');
927
928         while(this.copyTbody.childNodes[0])
929             this.copyTbody.removeChild(this.copyTbody.childNodes[0]);
930
931         this._drawBatchCopyWidgets();
932
933         this._drawDistribApplied(liId);
934
935         this._fetchDistribFormulas(
936             function() {
937                 openils.acq.Lineitem.fetchAttrDefs(
938                     function() { 
939                         self._fetchLineitem(liId, function(li){self._drawCopies(li);}, force_fetch); 
940                     } 
941                 );
942             }
943         );
944     };
945
946     this._saveDistribAppliedTemplates = function() {
947         if (!this._appliedDistribTemplate) {
948             this._appliedDistribTemplate =
949                 dojo.byId("acq-lit-distrib-applied-tbody").
950                     removeChild(dojo.byId("acq-lit-distrib-applied-row"));
951             dojo.attr(this._appliedDistribTemplate, "id");
952         }
953     };
954
955     this._drawDistribApplied = function(liId) {
956         /* Build this table while hidden to prevent rendering artifacts */
957         openils.Util.hide("acq-lit-distrib-applied-tbody");
958
959         this._saveDistribAppliedTemplates();
960
961         /* Remove any rows in the table from previous populations */
962         dojo.query("tr[formula]", "acq-lit-distrib-applied-tbody").
963             forEach(dojo.destroy);
964
965         /* Unregister all dijits previously created (for some reason this isn't
966          * covered by the above destroy calls). */
967         dijit.registry.forEach(
968             function(w) { if (/^dfa-/.test(w.id)) w.destroyRecursive(); }
969         );
970
971         /* Populate the table with our liId */
972         var total = 0;
973         fieldmapper.standardRequest(
974             ["open-ils.acq",
975             "open-ils.acq.distribution_formula_application.ranged.retrieve"],
976             {
977                 "async": true,
978                 "params": [self.authtoken, liId],
979                 "onresponse": function(r) {
980                     var dfa = openils.Util.readResponse(r);
981                     if (dfa) {
982                         total++;
983                         self.realDfaCache[dfa.id()] = dfa;
984                         self._drawDistribAppliedUnit(dfa);
985                     }
986                 },
987                 "oncomplete": function() {
988                     /* Reveal built table */
989                     if (total) {
990                         openils.Util.show(
991                             "acq-lit-distrib-applied-tbody", "table-row-group"
992                         );
993                     }
994                 }
995             }
996         );
997     };
998
999     this._drawDistribAppliedUnit = function(dfa) {
1000         var new_row = false;
1001         var row = dojo.query(
1002             'tr[formula="' + dfa.formula().id() + '"]',
1003             "acq-lit-distrib-applied-tbody"
1004         )[0];
1005
1006         if (!row) {
1007             new_row = true;
1008             row = dojo.clone(this._appliedDistribTemplate);
1009             dojo.attr(row, "formula", dfa.formula().id());
1010             dojo.query("th", row)[0].innerHTML = dfa.formula().name();
1011         }
1012
1013         var td = dojo.query("td", row)[0];
1014
1015         dojo.create("span", {"id": "dfa-button-" + dfa.id()}, td, "last");
1016         dojo.create("span", {"id": "dfa-tip-" + dfa.id()}, td, "last");
1017
1018         if (new_row)
1019             dojo.place(row, "acq-lit-distrib-applied-tbody", "last");
1020
1021         new dijit.form.Button(
1022             {
1023                 "onClick": function() {
1024                     if (confirm(localeStrings.EXPLAIN_DFA_MGMT))
1025                         self.deleteDfa(dfa);
1026                 },
1027                 "label": "X",
1028                 /* XXX I /cannot/ make the following work in as a CSS class
1029                  * for some reason. So frustrating... */
1030                 "style": function(id) {
1031                      return (id > 0 ?
1032                         "font-weight: bold; color: #c00;" :
1033                         "color: #666;");
1034                      }(dfa.id()) + "margin: 0 6px;display: inline;"
1035             }, "dfa-button-" + dfa.id()
1036         );
1037         new dijit.Tooltip(
1038             {
1039                 "connectId": ["dfa-button-" + dfa.id()],
1040                 "label": dojo.string.substitute(
1041                     localeStrings.DFA_TIP, dfa.id() > 0 ? [
1042                         openils.User.formalName(dfa.creator()),
1043                         dojo.date.locale.format(
1044                             dojo.date.stamp.fromISOString(dfa.create_time()),
1045                             {"formatLength":"short"}
1046                         )
1047                     ] : [localeStrings.ITS_YOU, localeStrings.JUST_NOW]
1048                 )
1049             }, "dfa-tip-" + dfa.id()
1050         );
1051     }
1052
1053     this.deleteDfa = function(dfa) {
1054         if (dfa.id() > 0) { /* real */
1055             this.pcrud.eliminate(
1056                 dfa, {
1057                     "async": true,
1058                     "oncomplete": function() {
1059                         self._removeDistribApplied(dfa.id());
1060                         delete self.realDfaCache[dfa.id()];
1061                     }
1062                 }
1063             );
1064         } else { /* virtual */
1065             if (--(this.virtDfaCounts[dfa.formula().id()]) < 0)
1066             this.virtDfaCounts[dfa.formula().id()] = 0;
1067             /* hasn't been saved yet, so no need to do anything server side */
1068             this._removeDistribApplied(dfa.id());
1069         }
1070
1071     };
1072
1073     this._removeDistribApplied = function(dfaId) {
1074         var re = new RegExp("^dfa-\\w+-" + String(dfaId));
1075         dijit.registry.forEach(
1076             function(w) { if (re.test(w.id)) w.destroyRecursive(); }
1077         );
1078         this._removeDistribAppliedEmptyRows();
1079     };
1080
1081     this._removeAllDistribAppliedVirtual = function() {
1082         /* Unregister dijits */
1083         dijit.registry.forEach(
1084             function(w) { if (/^dfa-\w+--/.test(w.id)) w.destroyRecursive(); }
1085         );
1086         this._removeDistribAppliedEmptyRows();
1087     };
1088
1089     this._removeDistribAppliedEmptyRows = function() {
1090         /* Remove any rows with no DFA at all */
1091         dojo.query("tr[formula] td", "acq-lit-distrib-applied-tbody").forEach(
1092             function(o) {
1093                 if (o.childNodes.length < 1) dojo.destroy(o.parentNode);
1094             }
1095         );
1096     };
1097
1098     /**
1099      * Insert a new row into the distribution formula selection form
1100      */
1101     this._addDistribFormulaRow = function() {
1102         var self = this;
1103
1104         if (!self.distribForms) {
1105             // no formulas, hide the form
1106             openils.Util.hide('acq-lit-distrib-formula-tbody');
1107             return;
1108         }
1109
1110         if(!this.distribFormulaTemplate) 
1111             this.distribFormulaTemplate = 
1112                 dojo.byId('acq-lit-distrib-formula-tbody').removeChild(dojo.byId('acq-lit-distrib-form-row'));
1113
1114         var row = this.distribFormulaTemplate.cloneNode(true);
1115         dojo.place(row, "acq-lit-distrib-formula-tbody", "only");
1116
1117         this.dfSelector = new dijit.form.FilteringSelect(
1118             {"labelAttr": "dynLabel", "labelType": "html"},
1119             nodeByName("selector", row)
1120         );
1121         this._updateFormulaStore();
1122         this.dfSelector.fetchProperties =
1123             {"sort": [{"attribute": "use_count", "descending": true}]};
1124
1125         var apply = new dijit.form.Button(
1126             {"label": localeStrings.APPLY},
1127             nodeByName('set_button', row)
1128         ); 
1129
1130         var reset = new dijit.form.Button(
1131             {"label": localeStrings.RESET_FORMULAE, "disabled": true},
1132             nodeByName("reset_button", row)  
1133         );
1134
1135         dojo.connect(apply, 'onClick', 
1136             function() {
1137                 var form_id = self.dfSelector.attr("value");
1138                 if(!form_id) return;
1139                 self._applyDistribFormula(form_id);
1140                 reset.attr("disabled", false);
1141             }
1142         );
1143
1144         dojo.connect(reset, 'onClick', 
1145             function() {
1146                 self.restoreCopyFieldsBeforeDF();
1147                 self.virtDfaCounts = {};
1148                 self.virtDfaId = -1;
1149                 self.dfeOffset = 0;
1150                 self._updateFormulaStore();
1151                 self._removeAllDistribAppliedVirtual();
1152                 reset.attr("disabled", "true");
1153             }
1154         );
1155
1156     };
1157
1158     /**
1159      * Applies a distrib formula to the current set of copies
1160      */
1161     this._applyDistribFormula = function(formula) {
1162         if(!formula) return;
1163
1164         formula = this.distribForms.filter(
1165             function(form) { return form.id() == formula; }
1166         )[0];
1167
1168         var copyRows = dojo.query('tr', self.copyTbody);
1169
1170         if (this.dfeOffset >= copyRows.length) {
1171             alert(localeStrings.OUT_OF_COPIES);
1172             return;
1173         }
1174
1175         var entries_applied = 0;
1176         for(
1177             var rowIndex = this.dfeOffset;
1178             rowIndex < copyRows.length;
1179             rowIndex++
1180         ) {
1181             
1182             var row = copyRows[rowIndex];
1183             var copy_id = row.getAttribute('copy_id');
1184             var copyWidgets = this.copyWidgetCache[copy_id];
1185             var entryIndex = this.dfeOffset;
1186             var entry = null;
1187
1188             // find the correct entry for the current row
1189             dojo.forEach(formula.entries(), 
1190                 function(e) {
1191                     if(!entry) {
1192                         entryIndex += e.item_count();
1193                         if(entryIndex > rowIndex)
1194                             entry = e;
1195                     }
1196                 }
1197             );
1198
1199             if(entry) {
1200                 
1201                 //console.log("rowIndex = " + rowIndex + ", entry = " + entry.id() + ", entryIndex=" + 
1202                 //  entryIndex + ", owning_lib = " + entry.owning_lib() + ", location = " + entry.location());
1203     
1204                 entries_applied++;
1205                 this.saveCopyFieldsBeforeDF(copy_id);
1206                 this._copy_fields_for_acqdf.forEach(
1207                     function(field) {
1208                         if(entry[field]()) {
1209                             copyWidgets[field].attr('value', (entry[field]()));
1210                         }
1211                     }
1212                 );
1213             }
1214         }
1215
1216         if (entries_applied) {
1217             this.virtDfaCounts[formula.id()] =
1218                 ++(this.virtDfaCounts[formula.id()]) || 1;
1219             this._updateFormulaStore();
1220             this._drawDistribAppliedUnit(
1221                 function(df) {
1222                     var dfa = new acqdfa();
1223                     dfa.formula(df); dfa.id(self.virtDfaId--); return dfa;
1224                 }(formula)
1225             );
1226             this.dfeOffset += entries_applied;
1227         };
1228     };
1229
1230     /**
1231      * This function updates the DF store for the dropdown so that use_counts
1232      * can reflect DF applications from this session before they're saved
1233      * server-side.
1234      */
1235     this._updateFormulaStore = function() {
1236         this.dfSelector.store = new dojo.data.ItemFileReadStore(
1237             {
1238                 "data": self._labelFormulasWithCounts(
1239                     acqdf.toStoreData(self.distribForms)
1240                 )
1241             }
1242         );
1243     };
1244
1245     this.saveCopyFieldsBeforeDF = function(copy_id) {
1246         var self = this;
1247         if (!this.oldCopyWidgetCache[copy_id]) {
1248             var copyWidgets = this.copyWidgetCache[copy_id];
1249
1250             this.oldCopyWidgetCache[copy_id] = {};
1251             this._copy_fields_for_acqdf.forEach(
1252                 function(f) {
1253                     self.oldCopyWidgetCache[copy_id][f] =
1254                         copyWidgets[f].attr("value");
1255                 }
1256             );
1257         }
1258     };
1259
1260     this.restoreCopyFieldsBeforeDF = function() {
1261         var self = this;
1262         for (var copy_id in this.oldCopyWidgetCache) {
1263             this._copy_fields_for_acqdf.forEach(
1264                 function(f) {
1265                     self.copyWidgetCache[copy_id][f].attr(
1266                         "value", self.oldCopyWidgetCache[copy_id][f]
1267                     );
1268                 }
1269             );
1270         }
1271     };
1272
1273     this._labelFormulasWithCounts = function(store_data) {
1274         for (var key in store_data.items) {
1275             var obj = store_data.items[key];
1276             obj.use_count = Number(obj.use_count); /* needed for sorting */
1277
1278             if (this.virtDfaCounts[obj.id])
1279                 obj.use_count = obj.use_count + Number(this.virtDfaCounts[obj.id]);
1280
1281             obj.dynLabel = "<span class='acq-lit-distrib-form-use-count'>[" +
1282                 obj.use_count + "]</span>&nbsp; " + obj.name;
1283         }
1284         return store_data;
1285     };
1286
1287     /**
1288      * This method formerly would not refetch the DF formulas if they'd been
1289      * loaded already, but now it always re-fetches, since use_count changes.
1290      */
1291     /** TODO: port distrib-formula selector to autofieldwidget+pcrud/dojo store */
1292     this._fetchDistribFormulas = function(onload) {
1293         fieldmapper.standardRequest(
1294             ["open-ils.acq",
1295                 "open-ils.acq.distribution_formula.ranged.retrieve.atomic"],
1296             {
1297                 "async": true,
1298                 "params": [openils.User.authtoken, 0, 500],
1299                 "oncomplete": function(r) {
1300                     self.distribForms = openils.Util.readResponse(r);
1301                     if(!self.distribForms || self.distribForms.length == 0) {
1302                         self.distribForms = [];
1303                     }
1304                     self._addDistribFormulaRow();
1305                     onload();
1306                 }
1307             }
1308         );
1309     }
1310
1311     this._drawBatchCopyWidgets = function() {
1312         var row = this.copyBatchRow;
1313         dojo.forEach(liDetailBatchFields, 
1314             function(field) {
1315                 if(self.copyBatchRowDrawn) {
1316                     self.copyBatchWidgets[field].attr('value', null);
1317                 } else {
1318                     var widget = new openils.widget.AutoFieldWidget({
1319                         fmField : field,
1320                         fmClass : 'acqlid',
1321                         labelFormat : (field == 'fund') ? fundLabelFormat : null,
1322                         searchFormat : (field == 'fund') ? fundSearchFormat : null,
1323                         searchFilter : (field == 'fund') ? {"active": "t"} : null,
1324                         parentNode : dojo.query('[name='+field+']', row)[0],
1325                         orgLimitPerms : ['CREATE_PICKLIST'],
1326                         dijitArgs : {
1327                             "required": false,
1328                             "labelType": (field == "fund") ? "html" : null
1329                         },
1330                         noCache: (field == "fund"),
1331                         forceSync : true
1332                     });
1333                     widget.build(
1334                         function(w, ww) {
1335                             if (field == "fund" && w.store)
1336                                 self._ensureCSSFundClasses(w.store);
1337                             self.copyBatchWidgets[field] = w;
1338                         }
1339                     );
1340                     if (field == "fund") {
1341                         dojo.connect(
1342                             widget.widget, "onChange", function(val) {
1343                                 self._updateFundSelectorStyle(widget, val);
1344                             }
1345                         );
1346                     }
1347                 }
1348             }
1349         );
1350         this.copyBatchRowDrawn = true;
1351     };
1352
1353     this.batchCopyUpdate = function() {
1354         var self = this;
1355         for(var k in this.copyWidgetCache) {
1356             var cache = this.copyWidgetCache[k];
1357             dojo.forEach(liDetailBatchFields, function(f) {
1358                 var newval = self.copyBatchWidgets[f].attr('value');
1359                 if(newval) cache[f].attr('value', newval);
1360             });
1361         }
1362     };
1363
1364     this._drawCopies = function(li) {
1365         var self = this;
1366
1367         // this button sets the total number of copies for a given lineitem
1368         acqLitAddCopyCount.onClick = function() { 
1369             var count = acqLitCopyCountInput.attr('value');
1370
1371             // add new rows
1372             while(self.copyCount() < count)
1373                 self.addCopy(li); 
1374             
1375             // delete rows if necessary
1376             var diff = self.copyCount() - count;
1377             if(diff > 0) {
1378                 var rows = dojo.query('tr', self.copyTbody).reverse().slice(0, diff);
1379                 if(confirm(dojo.string.substitute(localeStrings.DELETE_LI_COPIES_CONFIRM, [diff]))) {
1380                     dojo.forEach(rows, function(row) {self.deleteCopy(row); });
1381                 } else {
1382                     acqLitCopyCountInput.attr('value', self.copyCount()+'');
1383                 }
1384             }
1385         }
1386
1387
1388         if(li.lineitem_details().length > 0) {
1389             dojo.forEach(li.lineitem_details(),
1390                 function(copy) {
1391                     self.addCopy(li, copy);
1392                 }
1393             );
1394         } else {
1395             self.addCopy(li);
1396         }
1397     };
1398
1399     this.copyCount = function() {
1400         var count = 0;
1401         for(var id in this.copyCache) {
1402             if(!this.copyCache[id].isdeleted())
1403                 count++;
1404         }
1405         return count;
1406     }
1407
1408     this.virtCopyId = -1;
1409     this.addCopy = function(li, copy) {
1410         var row = this.copyRow.cloneNode(true);
1411         this.copyTbody.appendChild(row);
1412         var self = this;
1413
1414         if(!copy) {
1415             copy = new fieldmapper.acqlid();
1416             copy.isnew(true);
1417             copy.id(this.virtCopyId--);
1418             copy.lineitem(li.id());
1419         }
1420
1421         this.copyCache[copy.id()] = copy;
1422         row.setAttribute('copy_id', copy.id());
1423         self.copyWidgetCache[copy.id()] = {};
1424
1425         acqLitCopyCountInput.attr('value', self.copyCount()+'');
1426
1427         dojo.forEach(liDetailFields,
1428             function(field) {
1429                 var searchFilter;
1430                 if (field == "fund") {
1431                     searchFilter = (copy.fund() ?
1432                         {"-or": {"active": "t", "id": copy.fund()}} :
1433                         {"active" : "t"});
1434                 } else {
1435                     searchFilter = null;
1436                 }
1437
1438                 var readOnly = false;
1439                 
1440                 // TODO: Add support for changing the owning_lib after real copies have been made.  
1441                 // owning_lib is order data as much as its item data
1442                 if(copy.eg_copy_id() && ['owning_lib', 'location', 'circ_modifier', 'cn_label', 'barcode'].indexOf(field) >= 0) {
1443                     readOnly = true;
1444                 }
1445
1446                 // TODO: add support for changing the fund after debits have been created
1447                 // Note: invoicing allows the change
1448                 if(copy.fund_debit() && field == 'fund') {
1449                     readOnly = true;
1450                 }
1451
1452                 var widget = new openils.widget.AutoFieldWidget({
1453                     fmObject : copy,
1454                     fmField : field,
1455                     labelFormat : (field == 'fund') ? fundLabelFormat : null,
1456                     searchFormat : (field == 'fund') ? fundSearchFormat : null,
1457                     dijitArgs: {"labelType": (field == 'fund') ? "html" : null},
1458                     searchFilter : searchFilter,
1459                     noCache: (field == "fund"),
1460                     fmClass : 'acqlid',
1461                     parentNode : dojo.query('[name='+field+']', row)[0],
1462                     orgLimitPerms : ['CREATE_PICKLIST', 'CREATE_PURCHASE_ORDER'],
1463                     readOnly : readOnly,
1464                     orgDefaultsToWs : true
1465                 });
1466
1467                 widget.build(
1468                     // make sure we capture the value from any async widgets
1469                     function(w, ww) { 
1470
1471                         if (field == "fund" && w.store)
1472                             self._ensureCSSFundClasses(w.store);
1473
1474                         if(!readOnly) 
1475                             copy[field](ww.getFormattedValue()) 
1476
1477                         self.copyWidgetCache[copy.id()][field] = w;
1478
1479                         dojo.connect(w, 'onChange', 
1480                             function(val) { 
1481                                 if (field == "fund")
1482                                     self._updateFundSelectorStyle(widget, val);
1483
1484                                 if (!readOnly && (copy.isnew() || val != copy[field]())) {
1485                                     // prevent setting ischanged() automatically on widget load for existing copies
1486                                     copy[field](widget.getFormattedValue()) 
1487                                     copy.ischanged(true);
1488                                 }
1489                             }
1490                         );
1491                     }
1492                 );
1493             }
1494         );
1495
1496         this.updateLidState(copy, row);
1497     };
1498
1499     this._ensureCSSFundClass = function(id) {
1500         if (!this.fundStyleSheet) {
1501             dojo.create(
1502                 "style", {"type": "text/css"},
1503                 document.getElementsByTagName("head")[0], "last"
1504             );
1505             this.fundStyleSheet = document.styleSheets[
1506                 document.styleSheets.length - 1
1507             ];
1508         }
1509
1510         var cn = "fund_" + id;
1511         if (!this.haveFundClass[cn]) {
1512             fieldmapper.standardRequest(
1513                 ["open-ils.acq", "open-ils.acq.fund.check_balance_percentages"],
1514                 {
1515                     "params": [openils.User.authtoken, id],
1516                     "async": true,
1517                     "oncomplete": function(r) {
1518                         r = openils.Util.readResponse(r);
1519                         self.fundBalanceState[id] = r;
1520                         var style = "";
1521                         if (r[0] /* stop */)
1522                             style = fundStyles.stop;
1523                         else if (r[1] /* warning */)
1524                             style = fundStyles.warning;
1525                         self.fundStyleSheet.insertRule(
1526                             "." + cn + " { " + style + " }",
1527                             self.fundStyleSheet.cssRules.length
1528                         );
1529                         self.haveFundClass[cn] = true;
1530                     }
1531                 }
1532             );
1533         }
1534     };
1535
1536     this._ensureCSSFundClasses = function(store) {
1537         store.fetch({
1538             "query": {"id": "*"},
1539             "onItem": function(o) { self._ensureCSSFundClass(o.id[0]); }
1540         });
1541     };
1542
1543     this._updateFundSelectorStyle = function(widget, fund_id) {
1544         openils.Util.removeCSSClass(widget.widget.domNode, /fund_\d+/);
1545         openils.Util.addCSSClass(widget.widget.domNode, "fund_" + fund_id);
1546     };
1547
1548     this.updateLidState = function(copy, row) {
1549         if (typeof(row) == "undefined") {
1550             row = dojo.query(
1551                 'tr[copy_id="' + copy.id() + '"]', this.copyTbody
1552             )[0];
1553         }
1554
1555         var self = this;
1556         var recv_link = nodeByName("receive", row);
1557         var unrecv_link = nodeByName("unreceive", row);
1558         var del_link = nodeByName("delete", row);
1559         var cxl_link = nodeByName("cancel", row);
1560         var claim_link = nodeByName("claim", row);
1561         var cxl_reason_link = nodeByName("cancel_reason", row);
1562
1563         if (copy.cancel_reason()) {
1564             openils.Util.hide(del_link.parentNode);
1565             openils.Util.hide(recv_link);
1566             openils.Util.hide(unrecv_link);
1567             openils.Util.hide(cxl_link);
1568             openils.Util.hide(claim_link);
1569
1570             /* XXX the following may leak memory in a long lived table: dijits may not get destroyed... not positive. revisit. */
1571             var holds_reason = dojo.create(
1572                 "span", {
1573                     "style": "border-bottom: 1px dashed #000;",
1574                     "innerHTML": "Cancelled" /* XXX [sic] and i18n */
1575                 }, cxl_reason_link, "only"
1576             );
1577             new dijit.Tooltip(
1578                 {
1579                     "label": "<em>" + copy.cancel_reason().label() +
1580                         "</em><br />" + copy.cancel_reason().description(),
1581                     "connectId": [holds_reason]
1582                 }, dojo.create("span", null, cxl_reason_link, "last")
1583             );
1584             openils.Util.show(cxl_reason_link, "inline");
1585         } else if (this.isPO) {
1586             /* Only using this in one place so far, but may want it for better
1587              * decisions on when to display certain controls. */
1588             var li_state = this.liCache[copy.lineitem()].state();
1589
1590             openils.Util.hide(del_link.parentNode);
1591             openils.Util.hide(cxl_reason_link);
1592
1593             /* Avoid showing (un)receive links, cancel links, for virt copies */
1594             if (copy.id() > 0) {
1595                 if (copy.recv_time()) {
1596                     openils.Util.hide(cxl_link);
1597                     openils.Util.hide(recv_link);
1598                     openils.Util.hide(claim_link);
1599
1600                     openils.Util.show(unrecv_link, "inline");
1601                     unrecv_link.onclick = function() {
1602                         if (confirm(localeStrings.UNRECEIVE_LID))
1603                             self.issueReceive(copy, /* rollback */ true);
1604                     };
1605                 } else {
1606                     openils.Util.hide(unrecv_link);
1607
1608                     if (this.claimEligibleLid[copy.id()]) {
1609                         openils.Util.show(claim_link, "inline");
1610                         claim_link.onclick = function() {
1611                             self.claimDialog.show(
1612                                 self.liCache[copy.lineitem()], copy.id()
1613                             );
1614                         };
1615                     } else {
1616                         openils.Util.hide(claim_link);
1617                     }
1618
1619                     openils.Util[li_state == "on-order" ? "show" : "hide"](
1620                         recv_link, "inline"
1621                     );
1622                     openils.Util.show(cxl_link, "inline");
1623                     recv_link.onclick = function() {
1624                         if (self.checkLiAlerts(copy.lineitem()))
1625                             self.issueReceive(copy);
1626                     };
1627                     cxl_link.onclick = function() {
1628                         self.cancelLid(copy.id());
1629                     };
1630                 }
1631             } else {
1632                 openils.Util.hide(cxl_link);
1633                 openils.Util.hide(unrecv_link);
1634                 openils.Util.hide(recv_link);
1635                 openils.Util.hide(claim_link);
1636             }
1637         } else {
1638             openils.Util.hide(unrecv_link);
1639             openils.Util.hide(recv_link);
1640             openils.Util.hide(cxl_reason_link);
1641             openils.Util.hide(claim_link);
1642
1643             del_link.onclick = function() { self.deleteCopy(row) };
1644             openils.Util.show(del_link.parentNode);
1645         }
1646     }
1647
1648     this.cancelLid = function(lid_id) {
1649         lidCancelDialog._lid_id = lid_id;
1650         openils.Util.show(lidCancelDialog.domNode.parentNode);
1651         lidCancelDialog.show();
1652         if (!lidCancelDialog._prepared) {
1653             var widget = new openils.widget.AutoFieldWidget({
1654                 "fmField": "cancel_reason",
1655                 "fmClass": "acqlid",
1656                 "parentNode": dojo.byId("acq-lit-lid-cancel-reason"),
1657                 "orgLimitPerms": ["CREATE_PURCHASE_ORDER"],
1658                 "forceSync": true
1659             });
1660             widget.build(
1661                 function(w, ww) {
1662                     acqLidCancelButton.onClick = function() {
1663                         if (w.attr("value")) {
1664                             if (confirm(localeStrings.LID_CANCEL_CONFIRM)) {
1665                                 self._cancelLid(
1666                                     lidCancelDialog._lid_id,
1667                                     w.attr("value")
1668                                 );
1669                             }
1670                             lidCancelDialog.hide();
1671                         }
1672                     };
1673                     lidCancelDialog._prepared = true;
1674                 }
1675             );
1676         }
1677     };
1678
1679     this._cancelLid = function(lid_id, reason) {
1680         fieldmapper.standardRequest(
1681             ["open-ils.acq", "open-ils.acq.lineitem_detail.cancel"], {
1682                 "params": [openils.User.authtoken, lid_id, reason],
1683                 "async": true,
1684                 "onresponse": function(r) {
1685                     if (r = openils.Util.readResponse(r)) {
1686                         if (r.lid) {
1687                             for (var id in r.lid) {
1688                                 /* actually this should only iterate once */
1689                                 self.copyCache[id].cancel_reason(
1690                                     r.lid[id].cancel_reason
1691                                 );
1692                                 self.updateLidState(self.copyCache[id]);
1693                             }
1694                         }
1695                     }
1696                 }
1697             }
1698         );
1699     };
1700
1701     this._confirmAlert = function(li, lin) {
1702         return confirm(
1703             dojo.string.substitute(
1704                 localeStrings.CONFIRM_LI_ALERT, [
1705                     (new openils.acq.Lineitem({"lineitem": li})).findAttr(
1706                         "title", "lineitem_marc_attr_definition"
1707                     ),
1708                     lin.alert_text().code(),
1709                     lin.alert_text().description() || "",
1710                     lin.value()
1711                 ]
1712             )
1713         );
1714     };
1715
1716     this.checkLiAlerts = function(li_id) {
1717         var li = this.liCache[li_id];
1718
1719         var alert_notes = li.lineitem_notes().filter(
1720             function(o) { return Boolean(o.alert_text()); }
1721         );
1722
1723         /* this is _intentionally_ not done in a call to forEach() ... */
1724         for (var i = 0; i < alert_notes.length; i++) {
1725             if (this.noteAcks[alert_notes[i].id()])
1726                 continue;
1727             else if (!this._confirmAlert(li, alert_notes[i]))
1728                 return false;
1729             else
1730                 this.noteAcks[alert_notes[i].id()] = true;
1731         }
1732
1733         return true;
1734     };
1735
1736     this.deleteCopy = function(row) {
1737         var copy = this.copyCache[row.getAttribute('copy_id')];
1738         copy.isdeleted(true);
1739         if(copy.isnew())
1740             delete this.copyCache[copy.id()];
1741         this.copyTbody.removeChild(row);
1742     }
1743
1744     this._virtDfaCountsAsList = function() {
1745         var L = [];
1746         for (var key in this.virtDfaCounts) {
1747             for (var i = 0; i < this.virtDfaCounts[key]; i++)
1748                 L.push(key);
1749         }
1750         return L;
1751     }
1752
1753     this.confirmBreachedCopyFunds = function(copies) {
1754         var stop = 0, warning = 0;
1755         copies.forEach(
1756             function(o) {
1757                 if (o.fund()) {
1758                     var state = self.fundBalanceState[o.fund()];
1759                     if (state[0] /* stop */)
1760                         stop++;
1761                     else if (state[1] /* warning */)
1762                         warning++;
1763                 }
1764             }
1765         );
1766
1767         if (stop) {
1768             return confirm(localeStrings.CONFIRM_FUNDS_AT_STOP);
1769         } else if (warning) {
1770             return confirm(localeStrings.CONFIRM_FUNDS_AT_WARNING);
1771         }
1772         return true;
1773     };
1774
1775     this.saveCopyChanges = function(liId) {
1776         var self = this;
1777         var copies = [];
1778
1779
1780         var total = 0;
1781         for(var id in this.copyCache) {
1782             var c = this.copyCache[id];
1783             if(!c.isdeleted()) total++;
1784             if(c.isnew() || c.ischanged() || c.isdeleted()) {
1785                 if(c.id() < 0) c.id(null);
1786                 copies.push(c);
1787             }
1788         }
1789
1790
1791         dojo.byId('acq-lit-copy-count-label-' + liId).innerHTML = total;
1792
1793
1794         if (copies.length > 0) {
1795             if (!this.confirmBreachedCopyFunds(copies))
1796                 return;
1797
1798             if (typeof(this._copy_count_cb) == "function")
1799                 this._copy_count_cb(liId, total);
1800
1801             openils.Util.show("acq-lit-update-copies-progress");
1802             fieldmapper.standardRequest(
1803                 ['open-ils.acq', 'open-ils.acq.lineitem_detail.cud.batch'],
1804                 {   async: true,
1805                     params: [openils.User.authtoken, copies],
1806                     onresponse: function(r) {
1807                         var res = openils.Util.readResponse(r);
1808                         litUpdateCopiesProgress.update(res);
1809                     },
1810                     oncomplete: function() {
1811                         self.drawCopies(liId, true /* force_fetch */);
1812                         openils.Util.hide("acq-lit-update-copies-progress");
1813                     }
1814                 }
1815             );
1816         }
1817
1818         var dfa_list = this._virtDfaCountsAsList();
1819         if (dfa_list.length > 0) {
1820             fieldmapper.standardRequest(
1821                 ["open-ils.acq",
1822                 "open-ils.acq.distribution_formula.record_application"],
1823                 {
1824                     "async": true,
1825                     "params": [openils.User.authtoken, dfa_list, liId],
1826                     "onresponse": function(r) {
1827                         var res = openils.Util.readResponse(r);
1828                         if (res && res.length < dfa_list.length)
1829                             alert(localeStrings.DFA_NOT_ALL);
1830                     }
1831                 }
1832             );
1833             this.virtDfaCounts = {};
1834         }
1835     }
1836
1837     this._updateCreatePoPrepayCheckbox = function(prepay) {
1838         var prepay = openils.Util.isTrue(prepay);
1839         this._prepayRequiredByVendor = prepay;
1840         dijit.byId("acq-lit-po-prepay").attr("checked", prepay);
1841     };
1842
1843     this._confirmPoPrepaySituation = function() {
1844         var want_prepay = dijit.byId("acq-lit-po-prepay").attr("checked");
1845         if (want_prepay != this._prepayRequiredByVendor) {
1846             return confirm(
1847                 want_prepay ?
1848                     localeStrings.VENDOR_SAYS_PREPAY_NOT_NEEDED :
1849                     localeStrings.VENDOR_SAYS_PREPAY_NEEDED
1850             );
1851         } else {
1852             return true;
1853         }
1854     };
1855
1856     this.applySelectedLiAction = function(action) {
1857         var self = this;
1858         switch(action) {
1859
1860             case 'delete_selected':
1861                 this._deleteLiList(self.getSelected());
1862                 break;
1863
1864             case 'create_order':
1865                 this._loadPOSelect();
1866                 acqLitPoCreateDialog.show();
1867                 break;
1868
1869             case 'save_picklist':
1870                 acqLitSavePlDialog.show();
1871                 break;
1872
1873             case 'selector_ready':
1874             case 'order_ready':
1875                 acqLitChangeLiStateDialog.attr('state', action.replace('_', '-'));
1876                 acqLitChangeLiStateDialog.show();
1877                 break;
1878
1879             case 'print_po':
1880                 this.printPO();
1881                 break;
1882
1883             case 'po_history':
1884                 location.href = oilsBasePath + '/acq/po/history/' + this.isPO;
1885                 break;
1886
1887             case 'receive_po':
1888                 this.receivePO();
1889                 break;
1890
1891             case 'rollback_receive_po':
1892                 this.rollbackPoReceive();
1893                 break;
1894
1895             case 'create_assets':
1896                 this.createAssets();
1897                 break;
1898
1899             case 'export_attr_list':
1900                 this.chooseExportAttr();
1901                 break;
1902
1903             case 'batch_apply_funds':
1904                 this.applyBatchLiFunds();
1905                 break;
1906
1907             case 'add_brief_record':
1908                 if(this.isPO)
1909                     location.href = oilsBasePath + '/acq/picklist/brief_record?po=' + this.isPO;
1910                 else
1911                     location.href = oilsBasePath + '/acq/picklist/brief_record?pl=' + this.isPL;
1912
1913                 break;
1914
1915             case "cancel_lineitems":
1916                 this.maybeCancelLineitems();
1917                 break;
1918
1919             case "change_claim_policy":
1920                 var li_list = this.getSelected();
1921                 this.claimPolicyPicker.attr("value", null);
1922                 liClaimPolicyDialog.show();
1923                 liClaimPolicySave.onClick = function() {
1924                     self.changeClaimPolicy(
1925                         li_list,
1926                         self.claimPolicyPicker.attr("value"),
1927                         function() {
1928                             li_list.forEach(
1929                                 function(li) { self.setClaimPolicyControl(li); }
1930                             );
1931                             liClaimPolicyDialog.hide();
1932                         }
1933                     )
1934                 };
1935                 break;
1936         }
1937     };
1938
1939     this.changeClaimPolicy = function(li_list, value, callback) {
1940         li_list.forEach(
1941             function(li) { li.claim_policy(value); }
1942         );
1943         fieldmapper.standardRequest(
1944             ["open-ils.acq", "open-ils.acq.lineitem.update"], {
1945                 "params": [openils.User.authtoken, li_list],
1946                 "async": true,
1947                 "oncomplete": function(r) {
1948                     r = openils.Util.readResponse(r);
1949                     if (callback) callback(r);
1950                 }
1951             }
1952         );
1953     };
1954
1955     this.createAssets = function() {
1956         if(!this.isPO) return;
1957         if(!confirm(localeStrings.CREATE_PO_ASSETS_CONFIRM)) return;
1958         this.show('acq-lit-progress-numbers');
1959         var self = this;
1960         fieldmapper.standardRequest(
1961             ['open-ils.acq', 'open-ils.acq.purchase_order.assets.create'],
1962             {   async: true,
1963                 params: [this.authtoken, this.isPO],
1964                 onresponse: function(r) {
1965                     var resp = openils.Util.readResponse(r);
1966                     self._updateProgressNumbers(resp, true);
1967                 }
1968             }
1969         );
1970     }
1971
1972     this.maybeCancelLineitems = function() {
1973         openils.Util.show("acq-lit-cancel-reason", "inline");
1974         if (!acqLitCancelLineitemsButton._prepared) {
1975             var widget = new openils.widget.AutoFieldWidget({
1976                 "fmField": "cancel_reason",
1977                 "fmClass": "jub",
1978                 "parentNode": dojo.byId("acq-lit-cancel-reason-selector"),
1979                 "orgLimitPerms": ["CREATE_PURCHASE_ORDER"],
1980                 "forceSync": true
1981             });
1982             widget.build(
1983                 function(w, ww) {
1984                     acqLitCancelLineitemsButton.onClick = function() {
1985                         if (w.attr("value")) {
1986                             if (confirm(localeStrings.LI_CANCEL_CONFIRM)) {
1987                                 self._cancelLineitems(w.attr("value"));
1988                             }
1989                             openils.Util.hide("acq-lit-cancel-reason");
1990                         }
1991                     };
1992                     acqLitCancelLineitemsButton._prepared = true;
1993                 }
1994             );
1995         }
1996     };
1997
1998     this._cancelLineitems = function(reason) {
1999         var id_list = this.getSelected().map(function(o) { return o.id(); });
2000         fieldmapper.standardRequest(
2001             ["open-ils.acq", "open-ils.acq.lineitem.cancel.batch"], {
2002                 "params": [openils.User.authtoken, id_list, reason],
2003                 "async": true,
2004                 "onresponse": function(r) {
2005                     if (r = openils.Util.readResponse(r)) {
2006                         if (r.li) {
2007                             for (var id in r.li) {
2008                                 self.liCache[id].state(r.li[id].state);
2009                                 self.liCache[id].cancel_reason(
2010                                     r.li[id].cancel_reason
2011                                 );
2012                                 self.updateLiState(self.liCache[id]);
2013                             }
2014                         }
2015                         if (r.lid && self.copyCache) {
2016                             for (var id in r.lid) {
2017                                 if (self.copyCache[id]) {
2018                                     self.copyCache[id].cancel_reason(
2019                                         r.lid[id].cancel_reason
2020                                     );
2021                                     self.updateLidState(self.copyCache[id]);
2022                                 }
2023                             }
2024                         }
2025                     }
2026                 }
2027             }
2028         );
2029     };
2030
2031     this.chooseExportAttr = function() {
2032         if (!acqLitExportAttrSelector._li_setup) {
2033             var self = this;
2034             acqLitExportAttrSelector.store = new dojo.data.ItemFileReadStore(
2035                 {
2036                     "data": acqliad.toStoreData(
2037                         this.pcrud.search(
2038                             "acqliad", {"code": li_exportable_attrs}
2039                         )
2040                     )
2041                 }
2042             );
2043             acqLitExportAttrSelector.setValue();
2044             acqLitExportAttrButton.onClick = function(){self.exportAttrList();};
2045             acqLitExportAttrSelector._li_setup = true;
2046         }
2047         openils.Util.show("acq-lit-export-attr-holder", "inline");
2048     };
2049
2050     this.exportAttrList = function() {
2051         var attr_def = acqLitExportAttrSelector.item;
2052         var li_list = this.getSelected();
2053         var value_list = li_list.map(
2054             function(li) {
2055                 return (new openils.acq.Lineitem({"lineitem": li})).findAttr(
2056                     attr_def.code, "lineitem_marc_attr_definition"
2057                 );
2058             }
2059         ).filter(function(attr) { return Boolean(attr); });
2060
2061         if (value_list.length > 0) {
2062             if (value_list.length < li_list.length) {
2063                 if (!confirm(
2064                     dojo.string.substitute(
2065                         localeStrings.EXPORT_SHORT_LIST, [attr_def.description]
2066                     )
2067                 )) {
2068                     return;
2069                 }
2070             }
2071             try {
2072                 openils.XUL.contentToFileSaveDialog(
2073                     value_list.join("\n"),
2074                     localeStrings.EXPORT_SAVE_DIALOG_TITLE
2075                 );
2076             } catch (E) {
2077                 alert(E);
2078             }
2079         } else {
2080             alert(dojo.string.substitute(
2081                 localeStrings.EXPORT_EMPTY_LIST, [attr_def.description]
2082             ));
2083         }
2084
2085         openils.Util.hide("acq-lit-export-attr-holder");
2086     };
2087
2088     this.printPO = function() {
2089         if(!this.isPO) return;
2090         progressDialog.show(true);
2091         fieldmapper.standardRequest(
2092             ['open-ils.acq', 'open-ils.acq.purchase_order.format'],
2093             {   async: true,
2094                 params: [this.authtoken, this.isPO, 'html'],
2095                 oncomplete: function(r) {
2096                     progressDialog.hide();
2097                     var evt = openils.Util.readResponse(r);
2098                     if(evt && evt.template_output()) {
2099                         openils.Util.printHtmlString(evt.template_output().data());
2100                     }
2101                 }
2102             }
2103         );
2104     }
2105
2106
2107     this.receivePO = function() {
2108         if (!this.isPO) return;
2109
2110         for (var id in this.liCache) {
2111             /* assumption: liCache reflects exactly the
2112              * set of LIs that belong to our PO */
2113             if (this.liCache[id].state() != "received" &&
2114                 !this.checkLiAlerts(id)) return;
2115         }
2116
2117         this.show('acq-lit-progress-numbers');
2118         var self = this;
2119         fieldmapper.standardRequest(
2120             ['open-ils.acq', 'open-ils.acq.purchase_order.receive'],
2121             {   async: true,
2122                 params: [this.authtoken, this.isPO],
2123                 onresponse : function(r) {
2124                     var resp = openils.Util.readResponse(r);
2125                     self._updateProgressNumbers(resp, true);
2126                 },
2127             }
2128         );
2129     }
2130
2131     this.issueReceive = function(obj, rollback) {
2132         /* (For now) there shall be no marking LI or LIDs (un)received
2133          * except from the actual "view PO" interface. */
2134         if (!this.isPO) return;
2135
2136         var part =
2137             {"jub": "lineitem", "acqlid": "lineitem_detail"}[obj.classname];
2138         var method =
2139             "open-ils.acq." + part + ".receive" + (rollback ? ".rollback" : "");
2140
2141         progressDialog.show(true);
2142         fieldmapper.standardRequest(
2143             ["open-ils.acq", method], {
2144                 "async": true,
2145                 "params": [this.authtoken, obj.id()],
2146                 "onresponse": function(r) {
2147                     if (r = openils.Util.readResponse(r)) {
2148                         self.fetchClaimInfo(
2149                             part == "lineitem" ? obj.id() : obj.lineitem(),
2150                             /* force */ true,
2151                             function() { self.handleReceive(r); }
2152                         );
2153                         progressDialog.hide();
2154                     }
2155                 }
2156             }
2157         );
2158     };
2159
2160     /**
2161      * Handles the responses from receive and rollback ML calls.
2162      */
2163     this.handleReceive = function(resp) {
2164         if (resp) {
2165             if (resp.li) {
2166                 for (var li_id in resp.li) {
2167                     for (var key in resp.li[li_id])
2168                         self.liCache[li_id][key](resp.li[li_id][key]);
2169                     self.updateLiState(self.liCache[li_id]);
2170                 }
2171             }
2172             if (resp.po) {
2173                 if (typeof(self.poUpdateCallback) == "function")
2174                     self.poUpdateCallback(resp.po);
2175             }
2176             if (resp.lid) {
2177                 for (var lid_id in resp.lid) {
2178                     for (var key in resp.lid[lid_id])
2179                         self.copyCache[lid_id][key](resp.lid[lid_id][key]);
2180                     self.updateLidState(self.copyCache[lid_id]);
2181                 }
2182             }
2183         }
2184     };
2185
2186     this.rollbackPoReceive = function() {
2187         if(!this.isPO) return;
2188         if(!confirm(localeStrings.ROLLBACK_PO_RECEIVE_CONFIRM)) return;
2189         this.show('acq-lit-progress-numbers');
2190         var self = this;
2191         fieldmapper.standardRequest(
2192             ['open-ils.acq', 'open-ils.acq.purchase_order.receive.rollback'],
2193             {   async: true,
2194                 params: [this.authtoken, this.isPO],
2195                 onresponse : function(r) {
2196                     var resp = openils.Util.readResponse(r);
2197                     self._updateProgressNumbers(resp, true);
2198                 },
2199             }
2200         );
2201     }
2202
2203     this._updateProgressNumbers = function(resp, reloadOnComplete) {
2204         if(!resp) return;
2205         dojo.byId('acq-pl-lit-li-processed').innerHTML = resp.li;
2206         dojo.byId('acq-pl-lit-lid-processed').innerHTML = resp.lid;
2207         dojo.byId('acq-pl-lit-debits-processed').innerHTML = resp.debits_accrued;
2208         dojo.byId('acq-pl-lit-bibs-processed').innerHTML = resp.bibs;
2209         dojo.byId('acq-pl-lit-indexed-processed').innerHTML = resp.indexed;
2210         dojo.byId('acq-pl-lit-copies-processed').innerHTML = resp.copies;
2211         if(resp.complete && reloadOnComplete) 
2212             location.href = location.href;
2213     }
2214
2215
2216     this._createPO = function(fields) {
2217         this.show('acq-lit-progress-numbers');
2218         var po = new fieldmapper.acqpo();
2219         po.provider(this.createPoProviderSelector.attr('value'));
2220         po.ordering_agency(this.createPoAgencySelector.attr('value'));
2221         po.prepayment_required(fields.prepayment_required[0] ? true : false);
2222
2223         var selected = this.getSelected( (fields.create_from == 'all') );
2224         if(selected.length == 0) return;
2225
2226         var max = selected.length * 3;
2227
2228         var self = this;
2229         fieldmapper.standardRequest(
2230             ['open-ils.acq', 'open-ils.acq.purchase_order.create'],
2231             {   async: true,
2232                 params: [
2233                     openils.User.authtoken, 
2234                     po, 
2235                     {
2236                         lineitems : selected.map(function(li) { return li.id() }),
2237                         create_assets : fields.create_assets[0],
2238                     }
2239                 ],
2240
2241                 onresponse : function(r) {
2242                     var resp = openils.Util.readResponse(r);
2243                     self._updateProgressNumbers(resp);
2244                     if(resp.complete) 
2245                         location.href = oilsBasePath + '/acq/po/view/' + resp.purchase_order.id();
2246                 }
2247             }
2248         );
2249     }
2250
2251     this.batchFundWidget = null;
2252
2253     this.applyBatchLiFunds = function() {
2254
2255         var liIds = this.getSelected().map(function(li) { return li.id(); });
2256         if(liIds.length == 0) return; // warn?
2257
2258         var self = this;
2259         batchFundUpdateDialog.show();
2260
2261         if(!this.batchFundWidget) {
2262             this.batchFundWidget = new openils.widget.AutoFieldWidget({
2263                 fmClass : 'acqf',
2264                 selfReference : true,
2265                 labelFormat : fundLabelFormat,
2266                 searchFormat : fundSearchFormat,
2267                 searchFilter : {"active": "t"},
2268                 parentNode : dojo.byId('acq-lit-batch-fund-selector'),
2269                 orgLimitPerms : ['CREATE_PICKLIST', 'CREATE_PURCHASE_ORDER'],
2270                 dijitArgs : { "required": true, "labelType": "html" },
2271                 forceSync : true
2272             });
2273             this.batchFundWidget.build();
2274         }
2275
2276         dojo.connect(batchFundUpdateCancel, 'onClick', function() { batchFundUpdateDialog.hide(); });
2277         dojo.connect(batchFundUpdateSubmit, 'onClick', 
2278             function() { 
2279
2280                 // TODO: call .dry_run first to test thresholds
2281                 fieldmapper.standardRequest(
2282                     ['open-ils.acq', 'open-ils.acq.lineitem.fund.update.batch'],
2283                     {
2284                         params : [
2285                             openils.User.authtoken, 
2286                             liIds,
2287                             self.batchFundWidget.widget.attr('value')
2288                         ],
2289                         oncomplete : function(r) {
2290                             var resp = openils.Util.readResponse(r);
2291                             if(resp) {
2292                                 location.href = location.href;
2293                             }
2294                         }
2295                     }
2296                 )
2297             }
2298         );
2299     }
2300
2301     this._deleteLiList = function(list, idx) {
2302         if(idx == null) idx = 0;
2303         if(idx >= list.length) return;
2304         var liId = list[idx].id();
2305         fieldmapper.standardRequest(
2306             ['open-ils.acq', 'open-ils.acq.lineitem.delete'],
2307             {   async: true,
2308                 params: [openils.User.authtoken, liId],
2309                 oncomplete: function(r) {
2310                     self.removeLineitem(liId);
2311                     self._deleteLiList(list, ++idx);
2312                 }
2313             }
2314         );
2315     }
2316
2317     this.editOrderMarc = function(li) {
2318
2319         /*  To run in Firefox directly, must set signed.applets.codebase_principal_support
2320             to true in about:config */
2321
2322         if(!openils.XUL.enableXPConnect()) return;
2323
2324         if(openils.XUL.isXUL()) {
2325             win = window.open('/xul/' + openils.XUL.buildId() + '/server/cat/marcedit.xul');
2326         } else {
2327             win = window.open('/xul/server/cat/marcedit.xul'); 
2328         }
2329         var self = this;
2330         win.xulG = {
2331             record : {marc : li.marc(), "rtype": "bre"},
2332             save : {
2333                 label: 'Save Record', // XXX I18N
2334                 func: function(xmlString) {
2335                     li.marc(xmlString);
2336                     fieldmapper.standardRequest(
2337                         ['open-ils.acq', 'open-ils.acq.lineitem.update'],
2338                         {   async: true,
2339                             params: [openils.User.authtoken, li],
2340                             oncomplete: function(r) {
2341                                 openils.Util.readResponse(r);
2342                                 win.close();
2343                                 self.drawInfo(li.id())
2344                             }
2345                         }
2346                     );
2347                 },
2348             },
2349             'lock_tab' : typeof xulG != 'undefined' ? (typeof xulG['lock_tab'] != 'undefined' ? xulG.lock_tab : undefined) : undefined,
2350             'unlock_tab' : typeof xulG != 'undefined' ? (typeof xulG['unlock_tab'] != 'undefined' ? xulG.unlock_tab : undefined) : undefined
2351         };
2352     }
2353
2354     this._savePl = function(values) {
2355         var self = this;
2356         var selected = this.getSelected( (values.which == 'all') );
2357         openils.Util.show('acq-lit-generic-progress');
2358
2359         if(values.new_name) {
2360             openils.acq.Picklist.create(
2361                 {name: values.new_name}, 
2362                 function(id) {
2363                     self._updateLiList(id, selected, 0, 
2364                         function(){
2365                             location.href = oilsBasePath + '/acq/picklist/view/' + id;
2366                         });
2367                 }
2368             );
2369         } else if(values.existing_pl) {
2370             // update lineitems to use an existing picklist
2371             self._updateLiList(values.existing_pl, selected, 0, 
2372                 function(){
2373                     location.href = oilsBasePath + '/acq/picklist/view/' + values.existing_pl;
2374                 });
2375         }
2376     }
2377
2378     this._updateLiState = function(values, state) {
2379         var self = this;
2380         var selected = this.getSelected( (values.which == 'all') );
2381         if(!selected.length) return;
2382         dojo.forEach(selected, function(li) {li.state(state);});
2383         self._updateLiList(null, selected, 0, 
2384             // TODO consider inline updates for efficiency
2385             function() { location.href = location.href }
2386         );
2387     }
2388
2389     this._updateLiList = function(pl, list, idx, oncomplete) {
2390         if(idx >= list.length) return oncomplete();
2391         var li = list[idx];
2392         if(pl != null) li.picklist(pl);
2393         litGenericProgress.update({maximum: list.length, progress: idx});
2394         new openils.acq.Lineitem({lineitem:li}).update(
2395             function(r) {
2396                 self._updateLiList(pl, list, ++idx, oncomplete);
2397             }
2398         );
2399     }
2400
2401     this._loadPOSelect = function() {
2402         if (!this.createPoProviderSelector) {
2403             var widget = new openils.widget.AutoFieldWidget({
2404                 "fmField": "provider",
2405                 "fmClass": "acqpo",
2406                 "searchFilter": {"active": "t"},
2407                 "parentNode": dojo.byId("acq-lit-po-provider"),
2408                 "dijitArgs": {
2409                     "onChange": function() {
2410                         if (this.item) {
2411                             self._updateCreatePoPrepayCheckbox(
2412                                 this.item.prepayment_required
2413                             );
2414                         }
2415                     }
2416                 }
2417             });
2418             widget.build(function(w) { self.createPoProviderSelector = w; });
2419         }
2420
2421         if (!this.createPoAgencySelector) {
2422             var widget = new openils.widget.AutoFieldWidget({
2423                 "fmField": "ordering_agency",
2424                 "fmClass": "acqpo",
2425                 "parentNode": dojo.byId("acq-lit-po-agency"),
2426                 "orgLimitPerms": ["CREATE_PURCHASE_ORDER"],
2427             });
2428             widget.build(function(w) { self.createPoAgencySelector = w; });
2429         }
2430     };
2431
2432     this.showRealCopyEditUI = function(li) {
2433         copyList = [];
2434         var self = this;
2435         this.volCache = {};
2436
2437         this._fetchLineitem(li.id(), 
2438             function(fullLi) {
2439                 li = self.liCache[li.id()] = fullLi;
2440
2441                 self.pcrud.search(
2442                     'acp', {
2443                         id : li.lineitem_details().map(
2444                             function(item) { return item.eg_copy_id() }
2445                         )
2446                     }, {
2447                         async : true,
2448                         oncomplete : function(r) {
2449                             try {
2450                                 var r_list = openils.Util.readResponse( r );
2451                                 for (var i = 0; i < r_list.length; i++) {
2452                                     var copy = r_list[i];
2453                                     var volId = copy.call_number();
2454                                     var volume = self.volCache[volId];
2455                                     if(!volume) {
2456                                         volume = self.volCache[volId] = self.pcrud.retrieve('acn', volId);
2457                                     }
2458                                     copy.call_number(volume);
2459                                     copyList.push(copy);
2460                                 }
2461                                 if (xulG) {
2462                                     // If we need to, we can pass in an update_copy function to handle the update instead of volume_item_creator
2463                                     xulG.volume_item_creator( { 'existing_copies' : copyList } );
2464                                 }
2465                             } catch(E) {
2466                                 alert('error in oncomplete: ' + E);
2467                             }
2468                         }
2469                     }
2470                 );
2471             }
2472         );
2473     },
2474
2475     this.drawBibFinder = function(li) {
2476
2477         var query = '';
2478         var liWrapper = new openils.acq.Lineitem({lineitem:li});
2479
2480         dojo.forEach(
2481             ['isbn', 'upc', 'issn', 'title', 'author'],
2482             function(field) {
2483                 var val = liWrapper.findAttr(field, 'lineitem_marc_attr_definition');
2484                 if(val) {
2485                     if(field == 'title' || field == 'author') {
2486                         query += field +':' + val + ' ';
2487                     } else {
2488                         query += 'identifier|' + field + ':' + val + ' ';
2489                     }
2490                 }
2491             }
2492         );
2493
2494         win = window.open(
2495             oilsBasePath + '/acq/lineitem/findbib?query=' + escape(query),
2496             '', 'resizable,scrollbars=1');
2497
2498         win.window.recordFound = function(bibId) { 
2499             win.close();
2500
2501             var attrs = li.attributes();
2502             li.attributes(null);
2503             li.eg_bib_id(bibId);
2504
2505             fieldmapper.standardRequest(
2506                 ["open-ils.acq", "open-ils.acq.lineitem.update"], 
2507                 {
2508                     "params": [openils.User.authtoken, li],
2509                     "async": true,
2510                     "oncomplete": function(r) {
2511                         if(openils.Util.readResponse(r)) {
2512                             location.href = location.href;
2513                         }
2514                     }
2515                 }
2516             );
2517         }
2518     }
2519 }
2520