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