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