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