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