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