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