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