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