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