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