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