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