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