]> git.evergreen-ils.org Git - Evergreen.git/blob - Open-ILS/web/js/ui/default/acq/common/li_table.js
plugged in fund search format. it's like label format, except the search format...
[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.User');
10 dojo.require('openils.Util');
11 dojo.require('openils.acq.Lineitem');
12 dojo.require('openils.acq.PO');
13 dojo.require('openils.acq.Picklist');
14 dojo.require('openils.widget.AutoFieldWidget');
15 dojo.require('dojo.data.ItemFileReadStore');
16 dojo.require('openils.widget.ProgressDialog');
17 dojo.require('openils.PermaCrud');
18 dojo.require('openils.XUL');
19
20 dojo.requireLocalization('openils.acq', 'acq');
21 var localeStrings = dojo.i18n.getLocalization('openils.acq', 'acq');
22 const XUL_OPAC_WRAPPER = 'chrome://open_ils_staff_client/content/cat/opac.xul';
23 var li_exportable_attrs = ["issn", "isbn", "upc"];
24
25 var fundLabelFormat = ['${0} (${1})', 'code', 'year'];
26 var fundSearchFormat = ['${0} (${1})', 'code', 'year'];
27
28 function nodeByName(name, context) {
29     return dojo.query('[name='+name+']', context)[0];
30 }
31
32
33 var liDetailBatchFields = ['fund', 'owning_lib', 'location', 'collection_code', 'circ_modifier', 'cn_label'];
34 var liDetailFields = liDetailBatchFields.concat(['barcode', 'note']);
35
36 function AcqLiTable() {
37
38     var self = this;
39     this.liCache = {};
40     this.plCache = {};
41     this.poCache = {};
42     this.realDfaCache = {};
43     this.virtDfaCounts = {};
44     this.virtDfaId = -1;
45     this.dfeOffset = 0;
46     this.toggleState = false;
47     this.tbody = dojo.byId('acq-lit-tbody');
48     this.selectors = [];
49     this.noteAcks = {};
50     this.authtoken = openils.User.authtoken;
51     this.pcrud = new openils.PermaCrud();
52     this.rowTemplate = this.tbody.removeChild(dojo.byId('acq-lit-row'));
53     this.copyTbody = dojo.byId('acq-lit-li-details-tbody');
54     this.copyRow = this.copyTbody.removeChild(dojo.byId('acq-lit-li-details-row'));
55     this.copyBatchRow = dojo.byId('acq-lit-li-details-batch-row');
56     this.copyBatchWidgets = {};
57     this.liNotesTbody = dojo.byId('acq-lit-notes-tbody');
58     this.liNotesRow = this.liNotesTbody.removeChild(dojo.byId('acq-lit-notes-row'));
59     this.realCopiesTbody = dojo.byId('acq-lit-real-copies-tbody');
60     this.realCopiesRow = this.realCopiesTbody.removeChild(dojo.byId('acq-lit-real-copies-row'));
61     this._copy_fields_for_acqdf = ['owning_lib', 'location'];
62
63     dojo.connect(acqLitLiActionsSelector, 'onChange', 
64         function() { 
65             self.applySelectedLiAction(this.attr('value')) 
66             acqLitLiActionsSelector.attr('value', '_');
67         });
68
69     acqLitCreatePoSubmit.onClick = function() {
70         acqLitPoCreateDialog.hide();
71         self._createPO(acqLitPoCreateDialog.getValues());
72     }
73
74     acqLitSavePlButton.onClick = function() {
75         acqLitSavePlDialog.hide();
76         self._savePl(acqLitSavePlDialog.getValues());
77     }
78
79     acqLitCancelLiStateButton.onClick = function() {
80         acqLitChangeLiStateDialog.hide();
81     }
82     acqLitSaveLiStateButton.onClick = function() {
83         acqLitChangeLiStateDialog.hide();
84         self._updateLiState(acqLitChangeLiStateDialog.getValues(), acqLitChangeLiStateDialog.attr('state'));
85     }
86
87
88     //dojo.byId('acq-lit-notes-new-button').onclick = function(){acqLitCreateLiNoteDialog.show();}
89
90     dojo.byId('acq-lit-select-toggle').onclick = function(){self.toggleSelect()};
91     dojo.byId('acq-lit-info-back-button').onclick = function(){self.show('list')};
92     dojo.byId('acq-lit-copies-back-button').onclick = function(){self.show('list')};
93     dojo.byId('acq-lit-notes-back-button').onclick = function(){self.show('list')};
94     dojo.byId('acq-lit-real-copies-back-button').onclick = function(){self.show('list')};
95
96     this.reset = function() {
97         while(self.tbody.childNodes[0])
98             self.tbody.removeChild(self.tbody.childNodes[0]);
99         self.selectors = [];
100         self.noteAcks = {};
101     };
102     
103     this.setNext = function(handler) {
104         var link = dojo.byId('acq-lit-next');
105         if(handler) {
106             dojo.style(link, 'visibility', 'visible');
107             link.onclick = handler;
108         } else {
109             dojo.style(link, 'visibility', 'hidden');
110         }
111     };
112
113     this.setPrev = function(handler) {
114         var link = dojo.byId('acq-lit-prev');
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.show = function(div) {
124         openils.Util.hide('acq-lit-table-div');
125         openils.Util.hide('acq-lit-info-div');
126         openils.Util.hide('acq-lit-li-details');
127         openils.Util.hide('acq-lit-notes-div');
128         openils.Util.hide('acq-lit-real-copies-div');
129         switch(div) {
130             case 'list':
131                 openils.Util.show('acq-lit-table-div');
132                 break;
133             case 'info':
134                 openils.Util.show('acq-lit-info-div');
135                 break;
136             case 'copies':
137                 openils.Util.show('acq-lit-li-details');
138                 break;
139             case 'real-copies':
140                 openils.Util.show('acq-lit-real-copies-div');
141                 break;
142             case 'notes':
143                 openils.Util.show('acq-lit-notes-div');
144                 break;
145             default:
146                 if(div) 
147                     openils.Util.show(div);
148         }
149     }
150
151     this.hide = function() {
152         this.show(null);
153     }
154
155     this.toggleSelect = function() {
156         if(self.toggleState) 
157             dojo.forEach(self.selectors, function(i){i.checked = false});
158         else 
159             dojo.forEach(self.selectors, function(i){i.checked = true});
160         self.toggleState = !self.toggleState;
161     };
162
163
164     /** @param all If true, assume all are selected */
165     this.getSelected = function(all) {
166         var selected = [];
167         dojo.forEach(self.selectors, 
168             function(i) { 
169                 if(i.checked || all)
170                     selected.push(self.liCache[i.parentNode.parentNode.getAttribute('li')]);
171             }
172         );
173         return selected;
174     };
175
176     this.setRowAttr = function(td, liWrapper, field, type) {
177         var val = liWrapper.findAttr(field, type || 'lineitem_marc_attr_definition') || '';
178         td.appendChild(document.createTextNode(val));
179     };
180
181     /**
182      * Inserts a single lineitem into the growing table of lineitems
183      * @param {Object} li The lineitem object to insert
184      */
185     this.addLineitem = function(li, skip_final_placement) {
186         this.liCache[li.id()] = li;
187
188         // sort the lineitem notes on edit_time
189         if(!li.lineitem_notes()) li.lineitem_notes([]);
190
191         var liWrapper = new openils.acq.Lineitem({lineitem:li});
192         var row = self.rowTemplate.cloneNode(true);
193         row.setAttribute('li', li.id());
194         var tds = dojo.query('[attr]', row);
195         dojo.forEach(tds, function(td) {self.setRowAttr(td, liWrapper, td.getAttribute('attr'), td.getAttribute('attr_type'));});
196         dojo.query('[name=source_label]', row)[0].appendChild(document.createTextNode(li.source_label()));
197
198         var isbn = liWrapper.findAttr('isbn', 'lineitem_marc_attr_definition');
199         if(isbn) {
200             // XXX media prefix for added content
201             dojo.query('[name=jacket]', row)[0].setAttribute('src', '/opac/extras/ac/jacket/small/' + isbn);
202         }
203
204         dojo.query('[attr=title]', row)[0].onclick = function() {self.drawInfo(li.id())};
205         dojo.query('[name=copieslink]', row)[0].onclick = function() {self.drawCopies(li.id())};
206         dojo.query('[name=noteslink]', row)[0].onclick = function() {self.drawLiNotes(li)};
207
208         this.updateLiNotesCount(li, row);
209
210         // show which PO this lineitem is a member of
211         if(li.purchase_order() && !this.isPO) {
212             var po = 
213                 this.poCache[li.purchase_order()] =
214                 this.poCache[li.purchase_order()] ||
215                 fieldmapper.standardRequest(
216                     ['open-ils.acq', 'open-ils.acq.purchase_order.retrieve'],
217                     {params: [
218                         this.authtoken, li.purchase_order(), {
219                             "flesh_price_summary": true,
220                             "flesh_lineitem_count": true
221                         }
222                     ]});
223             if(po && !this.isMeta) {
224                 openils.Util.show(nodeByName('po', row), 'inline');
225                 var link = nodeByName('po_link', row);
226                 link.setAttribute('href', oilsBasePath + '/acq/po/view/' + li.purchase_order());
227                 link.innerHTML = 'PO: ' + po.name(); // TODO i18n
228             }
229         }
230
231         // show which picklist this lineitem is a member of
232         if(li.picklist() && (this.isPO || this.isMeta)) {
233             var pl = 
234                 this.plCache[li.picklist()] = 
235                 this.plCache[li.picklist()] || 
236                 fieldmapper.standardRequest(
237                     ['open-ils.acq', 'open-ils.acq.picklist.retrieve'],
238                     {params: [this.authtoken, li.picklist()]});
239             if(pl) {
240                 openils.Util.show(nodeByName('pl', row), 'inline');
241                 var link = nodeByName('pl_link', row);
242                 link.setAttribute('href', oilsBasePath + '/acq/picklist/view/' + li.picklist());
243                 link.innerHTML = 'PL: '+pl.name(); // TODO i18n
244             }
245         }
246
247         var countNode = nodeByName('count', row);
248         var count = li.item_count() || 0;
249         if (typeof(this._copy_count_cb) == "function") {
250             this._copy_count_cb(li.id(), count);
251         }
252         countNode.innerHTML = count;
253         countNode.id = 'acq-lit-copy-count-label-' + li.id();
254
255         // lineitem state
256         nodeByName('li_state', row).innerHTML = li.state(); // TODO i18n state labels
257         // lineitem price
258         var priceInput = dojo.query('[name=price]', row)[0];
259         var priceData = liWrapper.getPrice();
260         priceInput.value = (priceData) ? priceData.price : '';
261         priceInput.onchange = function() { self.updateLiPrice(priceInput, li) };
262
263         // show either "mark received" or "unreceive" as appropriate
264         this.updateLiReceivedness(li, row);
265
266         if (!skip_final_placement) {
267             self.tbody.appendChild(row);
268             self.selectors.push(dojo.query('[name=selectbox]', row)[0]);
269         } else {
270             return row;
271         }
272     };
273
274     this.updateLiNotesCount = function(li, row) {
275         if (typeof(row) == "undefined")
276             row = dojo.query('tr[li="' + li.id() + '"]', "acq-lit-tbody")[0];
277
278         var has_notes = (li.lineitem_notes().filter(
279                 function(o) { return Boolean (o.alert_text()); }
280             ).length > 0);
281
282         /* U+2691 is the code point for a filled-in flag character */
283         nodeByName("notes_alert_flag", row).innerHTML =
284              has_notes ? "⚑" : "";
285         nodeByName("noteslink", row).style.fontStyle =
286             has_notes ? "italic" : "normal";
287         nodeByName("notes_count", row).innerHTML = li.lineitem_notes().length;
288     };
289
290     this.updateLiReceivedness = function(li, row) {
291         if (typeof(row) == "undefined")
292             row = dojo.query('tr[li="' + li.id() + '"]', "acq-lit-tbody")[0];
293
294         var recv_link = nodeByName("receive_link", row);
295         var unrecv_link = nodeByName("unreceive_link", row);
296         var real_copies_link = nodeByName("real_copies_link", row);
297
298         /* handle row coloring for based on LI state */
299         openils.Util.removeCSSClass(row, /^oils-acq-li-state-/);
300         openils.Util.addCSSClass(row, "oils-acq-li-state-" + li.state());
301
302         /* handle links that appear/disappear based on whether LI is received */
303         if (this.isPO) {
304             var self = this;
305             switch(li.state()) {
306                 case "on-order":
307                     openils.Util.hide(real_copies_link);
308                     openils.Util.hide(unrecv_link);
309                     openils.Util.show(recv_link, "inline");
310                     recv_link.onclick = function() {
311                         if (self.checkLiAlerts(li.id()))
312                             self.issueReceive(li);
313                     };
314                     return;
315                 case "received":
316                     openils.Util.hide(recv_link);
317                     openils.Util.show(unrecv_link, "inline");
318                     unrecv_link.onclick = function() {
319                         if (confirm(localeStrings.UNRECEIVE_LI))
320                             self.issueReceive(li, /* rollback */ true);
321                     };
322                     // TODO we should allow editing before receipt, in which case the
323                     // test should be "if 1 or more real (acp) copies exist
324                     openils.Util.show(real_copies_link);
325                     real_copies_link.onclick = function() {
326                         self.showRealCopies(li);
327                     }
328                     return;
329             }
330         }
331
332         openils.Util.hide(recv_link);
333         openils.Util.hide(unrecv_link);
334         openils.Util.hide(real_copies_link);
335     };
336
337
338     this._setAlertStore = function() {
339         acqLitAlertAlertText.store = new dojo.data.ItemFileReadStore(
340             {
341                 "data": acqliat.toStoreData(
342                     this.pcrud.search(
343                         "acqliat", {"id": {"!=": null}}
344                     )
345                 )
346             }
347         );
348         acqLitAlertAlertText.setValue(); /* make the store "live" */
349         acqLitAlertAlertText._store_ready = true;
350     };
351
352     /**
353      * Draws and shows the lineitem notes pane
354      */
355     this.drawLiNotes = function(li) {
356         var self = this;
357
358         if (!acqLitAlertAlertText._store_ready)
359             this._setAlertStore();
360
361         li.lineitem_notes(
362             li.lineitem_notes().sort(
363                 function(a, b) { 
364                     if(a.edit_time() < b.edit_time()) return 1;
365                     return -1;
366                 }
367             )
368         );
369
370         while(this.liNotesTbody.childNodes[0])
371             this.liNotesTbody.removeChild(this.liNotesTbody.childNodes[0]);
372         this.show('notes');
373
374         acqLitCreateLiNoteSubmit.onClick = function() {
375             var value = acqLitCreateNoteText.attr('value');
376             if(!value) return;
377             var note = new fieldmapper.acqlin();
378             note.isnew(true);
379             note.value(value);
380             note.lineitem(li.id());
381
382             self.updateLiNotes(li, note);
383         }
384
385         acqLitCreateAlertSubmit.onClick = function() {
386             if (!acqLitAlertAlertText.item) {
387                 alert(localeStrings.ALERT_UNSELECTED);
388                 return;
389             }
390
391             var alert_text = new fieldmapper.acqliat().fromStoreItem(
392                 acqLitAlertAlertText.item
393             );
394             var value = acqLitAlertNoteValue.attr("value") || "";
395
396             var note = new fieldmapper.acqlin();
397             note.isnew(true);
398             note.lineitem(li.id());
399             note.value(value);
400             note.alert_text(alert_text);
401
402             self.updateLiNotes(li, note);
403         }
404
405         dojo.forEach(li.lineitem_notes(), function(note) { self.addLiNote(li, note) });
406     }
407
408     /**
409      * Draws a single lineitem note in the notes pane
410      */
411     this.addLiNote = function(li, note) {
412         if(note.isdeleted()) return;
413         var self = this;
414         var row = self.liNotesRow.cloneNode(true);
415         nodeByName("value", row).innerHTML = note.value();
416         var alert_node = nodeByName("alert_code", row);
417         if (note.alert_text()) {
418             alert_node.innerHTML = note.alert_text().code();
419             if (note.alert_text().description()) {
420                 new dijit.Tooltip(
421                     {
422                         "connectId": [alert_node],
423                         "label": note.alert_text().description()
424                     }, dojo.create("span", null, alert_node, "after")
425                 );
426             }
427         }
428
429         nodeByName("delete", row).onclick = function() {
430             note.isdeleted(true);
431             self.liNotesTbody.removeChild(row);
432             self.updateLiNotes(li);
433         };
434
435         if(note.edit_time()) {
436             nodeByName("edit_time", row).innerHTML =
437                 dojo.date.locale.format(
438                     dojo.date.stamp.fromISOString(note.edit_time()), 
439                     {formatLength:'short'});
440         }
441
442         self.liNotesTbody.appendChild(row);
443     }
444
445     /**
446      * Updates any new/changed/deleted notes on the server
447      */
448     this.updateLiNotes = function(li, newNote) {
449
450         var notes;
451         if(newNote) {
452             notes = [newNote];
453         } else {
454             notes = li.lineitem_notes().filter(
455                 function(note) {
456                     if(note.ischanged() || note.isnew() || note.isdeleted())
457                         return note;
458                 }
459             );
460         }
461
462         if(notes.length == 0) return;
463         progressDialog.show();
464
465         fieldmapper.standardRequest(
466             ['open-ils.acq', 'open-ils.acq.lineitem_note.cud.batch'],
467             {   async : true,
468                 params : [this.authtoken, notes],
469                 onresponse : function(r) {
470                     var resp = openils.Util.readResponse(r);
471
472                     if(resp.complete) {
473
474                         if(!newNote) {
475                             // remove the old changed notes
476                             var list = [];
477                             dojo.forEach(li.lineitem_notes(), 
478                                 function(note) {
479                                     if(!(note.ischanged() || note.isnew() || note.isdeleted()))
480                                         list.push(note);
481                                 }
482                             );
483                             li.lineitem_notes(list);
484                         }
485
486                         progressDialog.hide();
487                         self.updateLiNotesCount(li);
488                         self.drawLiNotes(li);
489                         return;
490                     }
491
492                     progressDialog.update(resp);
493                     var newnote = resp.note;
494
495                     if(!newnote.isdeleted()) {
496                         newnote.isnew(false);
497                         newnote.ischanged(false);
498                         li.lineitem_notes().push(newnote);
499                     }
500                 },
501             }
502         );
503     }
504
505     this.updateLiPrice = function(input, li) {
506
507         var price = input.value;
508         var liWrapper = new openils.acq.Lineitem({lineitem:li});
509         var oldPrice = liWrapper.getPrice() || null;
510
511         if(oldPrice) oldPrice = oldPrice.price;
512         if(price == oldPrice) return;
513
514         fieldmapper.standardRequest(
515             ['open-ils.acq', 'open-ils.acq.lineitem.price.set'],
516             {   async : true,
517                 params : [this.authtoken, li.id(), price],
518                 oncomplete : function(r) {
519                     openils.Util.readResponse(r);
520                 }
521             }
522         );
523     }
524
525     this.removeLineitem = function(liId) {
526         this.tbody.removeChild(dojo.query('[li='+liId+']', this.tbody)[0]);
527         delete this.liCache[liId];
528         //selected.push(self.liCache[i.parentNode.parentNode.getAttribute('li')]);
529     }
530
531     this.drawInfo = function(liId) {
532         this.show('info');
533         openils.acq.Lineitem.fetchAttrDefs(
534             function() { 
535                 self._fetchLineitem(liId, function(li){self._drawInfo(li);}); 
536             } 
537         );
538     };
539
540     this._fetchLineitem = function(liId, handler) {
541
542         var li = this.liCache[liId];
543         if(li && li.marc() && li.lineitem_details())
544             return handler(li);
545         
546         fieldmapper.standardRequest(
547             ['open-ils.acq', 'open-ils.acq.lineitem.retrieve'],
548             {   async: true,
549
550                 params: [self.authtoken, liId, {
551                     flesh_attrs: true,
552                     flesh_li_details: true,
553                     flesh_fund_debit: true }],
554
555                 oncomplete: function(r) {
556                     var li = openils.Util.readResponse(r);
557                     handler(li)
558                 }
559             }
560         );
561     };
562
563     this._drawInfo = function(li) {
564
565         acqLitEditOrderMarc.onClick = function() { self.editOrderMarc(li); }
566
567         if(li.eg_bib_id()) {
568             openils.Util.hide('acq-lit-marc-order-record-label');
569             openils.Util.hide(acqLitEditOrderMarc.domNode);
570             openils.Util.show('acq-lit-marc-real-record-label');
571         } else {
572             openils.Util.show('acq-lit-marc-order-record-label');
573             openils.Util.show(acqLitEditOrderMarc.domNode);
574             openils.Util.hide('acq-lit-marc-real-record-label');
575         }
576
577         this.drawMarcHTML(li);
578         this.infoTbody = dojo.byId('acq-lit-info-tbody');
579
580         if(!this.infoRow)
581             this.infoRow = this.infoTbody.removeChild(dojo.byId('acq-lit-info-row'));
582         while(this.infoTbody.childNodes[0])
583             this.infoTbody.removeChild(this.infoTbody.childNodes[0]);
584
585         for(var i = 0; i < li.attributes().length; i++) {
586             var attr = li.attributes()[i];
587             var row = this.infoRow.cloneNode(true);
588
589             var type = attr.attr_type().replace(/lineitem_(.*)_attr_definition/, '$1');
590             var name = openils.acq.Lineitem.attrDefs[type].filter(
591                 function(a) {
592                     return (a.code() == attr.attr_name());
593                 }
594             ).pop().description();
595
596             dojo.query('[name=label]', row)[0].appendChild(document.createTextNode(name));
597             dojo.query('[name=value]', row)[0].appendChild(document.createTextNode(attr.attr_value()));
598             this.infoTbody.appendChild(row);
599         }
600
601         if(li.eg_bib_id()) {
602             openils.Util.show('acq-lit-info-cat-link');
603             var link = dojo.byId('acq-lit-info-cat-link').getElementsByTagName('a')[0];
604
605             if(openils.XUL.isXUL()) {
606
607                 var makeRecTab = function() {
608                                     xulG.new_tab(
609                         XUL_OPAC_WRAPPER,
610                                             {tab_name: localeStrings.XUL_RECORD_DETAIL_PAGE, browser:false},
611                                             {
612                             no_xulG : false, 
613                             show_nav_buttons : true, 
614                             show_print_button : true, 
615                             opac_url : xulG.url_prefix(xulG.urls.opac_rdetail + '?r=' + li.eg_bib_id())
616                         }
617                     );
618                 }
619                 link.setAttribute('href', 'javascript:void(0);');
620                 link.onclick = makeRecTab;
621
622             } else {
623                 var href = link.getAttribute('href');
624                 if(href.match(/=$/))
625                     link.setAttribute('href',  href + li.eg_bib_id());
626             }
627         } else {
628             openils.Util.hide('acq-lit-info-cat-link');
629         }
630     };
631
632     this.drawMarcHTML = function(li) {
633         var params = [null, true, li.marc()];
634         if(li.eg_bib_id()) 
635             params = [li.eg_bib_id(), true];
636
637         fieldmapper.standardRequest(
638             ['open-ils.search', 'open-ils.search.biblio.record.html'],
639             {   async: true,
640                 params: params,
641                 oncomplete: function(r) {
642                     dojo.byId('acq-lit-marc-div').innerHTML = 
643                         openils.Util.readResponse(r);
644                 }
645             }
646         );
647     }
648
649     this.drawCopies = function(liId) {
650         this.show('copies');
651         var self = this;
652         this.copyCache = {};
653         this.copyWidgetCache = {};
654         this.oldCopyWidgetCache = {};
655         this.virtDfaCounts = {};
656         this.realDfaCache = {};
657         this.dfeOffset = 0;
658
659         acqLitSaveCopies.onClick = function() { self.saveCopyChanges(liId) };
660         acqLitBatchUpdateCopies.onClick = function() { self.batchCopyUpdate() };
661         acqLitCopyCountInput.attr('value', '0');
662
663         while(this.copyTbody.childNodes[0])
664             this.copyTbody.removeChild(this.copyTbody.childNodes[0]);
665
666         this._drawBatchCopyWidgets();
667
668         this._drawDistribApplied(liId);
669
670         this._fetchDistribFormulas(
671             function() {
672                 openils.acq.Lineitem.fetchAttrDefs(
673                     function() { 
674                         self._fetchLineitem(liId, function(li){self._drawCopies(li);}); 
675                     } 
676                 );
677             }
678         );
679     };
680
681     this._saveDistribAppliedTemplates = function() {
682         if (!this._appliedDistribTemplate) {
683             this._appliedDistribTemplate =
684                 dojo.byId("acq-lit-distrib-applied-tbody").
685                     removeChild(dojo.byId("acq-lit-distrib-applied-row"));
686             dojo.attr(this._appliedDistribTemplate, "id");
687         }
688     };
689
690     this._drawDistribApplied = function(liId) {
691         /* Build this table while hidden to prevent rendering artifacts */
692         openils.Util.hide("acq-lit-distrib-applied-tbody");
693
694         this._saveDistribAppliedTemplates();
695
696         /* Remove any rows in the table from previous populations */
697         dojo.query("tr[formula]", "acq-lit-distrib-applied-tbody").
698             forEach(dojo.destroy);
699
700         /* Unregister all dijits previously created (for some reason this isn't
701          * covered by the above destroy calls). */
702         dijit.registry.forEach(
703             function(w) { if (/^dfa-/.test(w.id)) w.destroyRecursive(); }
704         );
705
706         /* Populate the table with our liId */
707         var total = 0;
708         fieldmapper.standardRequest(
709             ["open-ils.acq",
710             "open-ils.acq.distribution_formula_application.ranged.retrieve"],
711             {
712                 "async": true,
713                 "params": [self.authtoken, liId],
714                 "onresponse": function(r) {
715                     var dfa = openils.Util.readResponse(r);
716                     if (dfa) {
717                         total++;
718                         self.realDfaCache[dfa.id()] = dfa;
719                         self._drawDistribAppliedUnit(dfa);
720                     }
721                 },
722                 "oncomplete": function() {
723                     /* Reveal built table */
724                     if (total) {
725                         openils.Util.show(
726                             "acq-lit-distrib-applied-tbody", "table-row-group"
727                         );
728                     }
729                 }
730             }
731         );
732     };
733
734     this._drawDistribAppliedUnit = function(dfa) {
735         var new_row = false;
736         var row = dojo.query(
737             'tr[formula="' + dfa.formula().id() + '"]',
738             "acq-lit-distrib-applied-tbody"
739         )[0];
740
741         if (!row) {
742             new_row = true;
743             row = dojo.clone(this._appliedDistribTemplate);
744             dojo.attr(row, "formula", dfa.formula().id());
745             dojo.query("th", row)[0].innerHTML = dfa.formula().name();
746         }
747
748         var td = dojo.query("td", row)[0];
749
750         dojo.create("span", {"id": "dfa-button-" + dfa.id()}, td, "last");
751         dojo.create("span", {"id": "dfa-tip-" + dfa.id()}, td, "last");
752
753         if (new_row)
754             dojo.place(row, "acq-lit-distrib-applied-tbody", "last");
755
756         new dijit.form.Button(
757             {
758                 "onClick": function() {
759                     if (confirm(localeStrings.EXPLAIN_DFA_MGMT))
760                         self.deleteDfa(dfa);
761                 },
762                 "label": "X",
763                 /* XXX I /cannot/ make the following work in as a CSS class
764                  * for some reason. So frustrating... */
765                 "style": function(id) {
766                      return (id > 0 ?
767                         "font-weight: bold; color: #c00;" :
768                         "color: #666;");
769                      }(dfa.id()) + "margin: 0 6px;display: inline;"
770             }, "dfa-button-" + dfa.id()
771         );
772         new dijit.Tooltip(
773             {
774                 "connectId": ["dfa-button-" + dfa.id()],
775                 "label": dojo.string.substitute(
776                     localeStrings.DFA_TIP, dfa.id() > 0 ? [
777                         openils.User.formalName(dfa.creator()),
778                         dojo.date.locale.format(
779                             dojo.date.stamp.fromISOString(dfa.create_time()),
780                             {"formatLength":"short"}
781                         )
782                     ] : [localeStrings.ITS_YOU, localeStrings.JUST_NOW]
783                 )
784             }, "dfa-tip-" + dfa.id()
785         );
786     }
787
788     this.deleteDfa = function(dfa) {
789         if (dfa.id() > 0) { /* real */
790             this.pcrud.eliminate(
791                 dfa, {
792                     "async": true,
793                     "oncomplete": function() {
794                         self._removeDistribApplied(dfa.id());
795                         delete self.realDfaCache[dfa.id()];
796                     }
797                 }
798             );
799         } else { /* virtual */
800             if (--(this.virtDfaCounts[dfa.formula().id()]) < 0)
801             this.virtDfaCounts[dfa.formula().id()] = 0;
802             /* hasn't been saved yet, so no need to do anything server side */
803             this._removeDistribApplied(dfa.id());
804         }
805
806     };
807
808     this._removeDistribApplied = function(dfaId) {
809         var re = new RegExp("^dfa-\\w+-" + String(dfaId));
810         dijit.registry.forEach(
811             function(w) { if (re.test(w.id)) w.destroyRecursive(); }
812         );
813         this._removeDistribAppliedEmptyRows();
814     };
815
816     this._removeAllDistribAppliedVirtual = function() {
817         /* Unregister dijits */
818         dijit.registry.forEach(
819             function(w) { if (/^dfa-\w+--/.test(w.id)) w.destroyRecursive(); }
820         );
821         this._removeDistribAppliedEmptyRows();
822     };
823
824     this._removeDistribAppliedEmptyRows = function() {
825         /* Remove any rows with no DFA at all */
826         dojo.query("tr[formula] td", "acq-lit-distrib-applied-tbody").forEach(
827             function(o) {
828                 if (o.childNodes.length < 1) dojo.destroy(o.parentNode);
829             }
830         );
831     };
832
833     /**
834      * Insert a new row into the distribution formula selection form
835      */
836     this._addDistribFormulaRow = function() {
837         var self = this;
838
839         if (!self.distribForms) {
840             // no formulas, hide the form
841             openils.Util.hide('acq-lit-distrib-formula-tbody');
842             return;
843         }
844
845         if(!this.distribFormulaTemplate) 
846             this.distribFormulaTemplate = 
847                 dojo.byId('acq-lit-distrib-formula-tbody').removeChild(dojo.byId('acq-lit-distrib-form-row'));
848
849         var row = this.distribFormulaTemplate.cloneNode(true);
850         dojo.place(row, "acq-lit-distrib-formula-tbody", "only");
851
852         this.dfSelector = new dijit.form.FilteringSelect(
853             {"labelAttr": "dynLabel", "labelType": "html"},
854             nodeByName("selector", row)
855         );
856         this._updateFormulaStore();
857         this.dfSelector.fetchProperties =
858             {"sort": [{"attribute": "use_count", "descending": true}]};
859
860         var apply = new dijit.form.Button(
861             {"label": localeStrings.APPLY},
862             nodeByName('set_button', row)
863         ); 
864
865         var reset = new dijit.form.Button(
866             {"label": localeStrings.RESET_FORMULAE, "disabled": true},
867             nodeByName("reset_button", row)  
868         );
869
870         dojo.connect(apply, 'onClick', 
871             function() {
872                 var form_id = self.dfSelector.attr("value");
873                 if(!form_id) return;
874                 self._applyDistribFormula(form_id);
875                 reset.attr("disabled", false);
876             }
877         );
878
879         dojo.connect(reset, 'onClick', 
880             function() {
881                 self.restoreCopyFieldsBeforeDF();
882                 self.virtDfaCounts = {};
883                 self.virtDfaId = -1;
884                 self.dfeOffset = 0;
885                 self._updateFormulaStore();
886                 self._removeAllDistribAppliedVirtual();
887                 reset.attr("disabled", "true");
888             }
889         );
890
891     };
892
893     /**
894      * Applies a distrib formula to the current set of copies
895      */
896     this._applyDistribFormula = function(formula) {
897         if(!formula) return;
898
899         formula = this.distribForms.filter(
900             function(form) { return form.id() == formula; }
901         )[0];
902
903         var copyRows = dojo.query('tr', self.copyTbody);
904
905         if (this.dfeOffset >= copyRows.length) {
906             alert(localeStrings.OUT_OF_COPIES);
907             return;
908         }
909
910         var entries_applied = 0;
911         for(
912             var rowIndex = this.dfeOffset;
913             rowIndex < copyRows.length;
914             rowIndex++
915         ) {
916             
917             var row = copyRows[rowIndex];
918             var copy_id = row.getAttribute('copy_id');
919             var copyWidgets = this.copyWidgetCache[copy_id];
920             var entryIndex = this.dfeOffset;
921             var entry = null;
922
923             // find the correct entry for the current row
924             dojo.forEach(formula.entries(), 
925                 function(e) {
926                     if(!entry) {
927                         entryIndex += e.item_count();
928                         if(entryIndex > rowIndex)
929                             entry = e;
930                     }
931                 }
932             );
933
934             if(entry) {
935                 
936                 //console.log("rowIndex = " + rowIndex + ", entry = " + entry.id() + ", entryIndex=" + 
937                 //  entryIndex + ", owning_lib = " + entry.owning_lib() + ", location = " + entry.location());
938     
939                 entries_applied++;
940                 this.saveCopyFieldsBeforeDF(copy_id);
941                 this._copy_fields_for_acqdf.forEach(
942                     function(field) {
943                         if(entry[field]()) {
944                             copyWidgets[field].attr('value', (entry[field]()));
945                         }
946                     }
947                 );
948             }
949         }
950
951         if (entries_applied) {
952             this.virtDfaCounts[formula.id()] =
953                 ++(this.virtDfaCounts[formula.id()]) || 1;
954             this._updateFormulaStore();
955             this._drawDistribAppliedUnit(
956                 function(df) {
957                     var dfa = new acqdfa();
958                     dfa.formula(df); dfa.id(self.virtDfaId--); return dfa;
959                 }(formula)
960             );
961             this.dfeOffset += entries_applied;
962         };
963     };
964
965     /**
966      * This function updates the DF store for the dropdown so that use_counts
967      * can reflect DF applications from this session before they're saved
968      * server-side.
969      */
970     this._updateFormulaStore = function() {
971         this.dfSelector.store = new dojo.data.ItemFileReadStore(
972             {
973                 "data": self._labelFormulasWithCounts(
974                     acqdf.toStoreData(self.distribForms)
975                 )
976             }
977         );
978     };
979
980     this.saveCopyFieldsBeforeDF = function(copy_id) {
981         var self = this;
982         if (!this.oldCopyWidgetCache[copy_id]) {
983             var copyWidgets = this.copyWidgetCache[copy_id];
984
985             this.oldCopyWidgetCache[copy_id] = {};
986             this._copy_fields_for_acqdf.forEach(
987                 function(f) {
988                     self.oldCopyWidgetCache[copy_id][f] =
989                         copyWidgets[f].attr("value");
990                 }
991             );
992         }
993     };
994
995     this.restoreCopyFieldsBeforeDF = function() {
996         var self = this;
997         for (var copy_id in this.oldCopyWidgetCache) {
998             this._copy_fields_for_acqdf.forEach(
999                 function(f) {
1000                     self.copyWidgetCache[copy_id][f].attr(
1001                         "value", self.oldCopyWidgetCache[copy_id][f]
1002                     );
1003                 }
1004             );
1005         }
1006     };
1007
1008     this._labelFormulasWithCounts = function(store_data) {
1009         for (var key in store_data.items) {
1010             var obj = store_data.items[key];
1011             obj.use_count = Number(obj.use_count); /* needed for sorting */
1012
1013             if (this.virtDfaCounts[obj.id])
1014                 obj.use_count = obj.use_count + Number(this.virtDfaCounts[obj.id]);
1015
1016             obj.dynLabel = "<span class='acq-lit-distrib-form-use-count'>[" +
1017                 obj.use_count + "]</span>&nbsp; " + obj.name;
1018         }
1019         return store_data;
1020     };
1021
1022     /**
1023      * This method formerly would not refetch the DF formulas if they'd been
1024      * loaded already, but now it always re-fetches, since use_count changes.
1025      */
1026     this._fetchDistribFormulas = function(onload) {
1027         fieldmapper.standardRequest(
1028             ["open-ils.acq",
1029                 "open-ils.acq.distribution_formula.ranged.retrieve.atomic"],
1030             {
1031                 "async": true,
1032                 "params": [openils.User.authtoken],
1033                 "oncomplete": function(r) {
1034                     self.distribForms = openils.Util.readResponse(r);
1035                     if(!self.distribForms || self.distribForms.length == 0) {
1036                         self.distribForms = [];
1037                     }
1038                     self._addDistribFormulaRow();
1039                     onload();
1040                 }
1041             }
1042         );
1043     }
1044
1045     this._drawBatchCopyWidgets = function() {
1046         var row = this.copyBatchRow;
1047         dojo.forEach(liDetailBatchFields, 
1048             function(field) {
1049                 if(self.copyBatchRowDrawn) {
1050                     self.copyBatchWidgets[field].attr('value', null);
1051                 } else {
1052                     var widget = new openils.widget.AutoFieldWidget({
1053                         fmField : field,
1054                         fmClass : 'acqlid',
1055                         labelFormat : (field == 'fund') ? fundLabelFormat : null,
1056                         searchFormat : (field == 'fund') ? fundSearchFormat : null,
1057                         parentNode : dojo.query('[name='+field+']', row)[0],
1058                         orgLimitPerms : ['CREATE_PICKLIST'],
1059                         dijitArgs : {required:false},
1060                         forceSync : true
1061                     });
1062                     widget.build(
1063                         function(w, ww) {
1064                             self.copyBatchWidgets[field] = w;
1065                         }
1066                     );
1067                 }
1068             }
1069         );
1070         this.copyBatchRowDrawn = true;
1071     };
1072
1073     this.batchCopyUpdate = function() {
1074         var self = this;
1075         for(var k in this.copyWidgetCache) {
1076             var cache = this.copyWidgetCache[k];
1077             dojo.forEach(liDetailBatchFields, function(f) {
1078                 var newval = self.copyBatchWidgets[f].attr('value');
1079                 if(newval) cache[f].attr('value', newval);
1080             });
1081         }
1082     };
1083
1084     this._drawCopies = function(li) {
1085         var self = this;
1086
1087         // this button sets the total number of copies for a given lineitem
1088         acqLitAddCopyCount.onClick = function() { 
1089             var count = acqLitCopyCountInput.attr('value');
1090
1091             // add new rows
1092             while(self.copyCount() < count)
1093                 self.addCopy(li); 
1094             
1095             // delete rows if necessary
1096             var diff = self.copyCount() - count;
1097             if(diff > 0) {
1098                 var rows = dojo.query('tr', self.copyTbody).reverse().slice(0, diff);
1099                 if(confirm(dojo.string.substitute(localeStrings.DELETE_LI_COPIES_CONFIRM, [diff]))) {
1100                     dojo.forEach(rows, function(row) {self.deleteCopy(row); });
1101                 } else {
1102                     acqLitCopyCountInput.attr('value', self.copyCount()+'');
1103                 }
1104             }
1105         }
1106
1107
1108         if(li.lineitem_details().length > 0) {
1109             dojo.forEach(li.lineitem_details(),
1110                 function(copy) {
1111                     self.addCopy(li, copy);
1112                 }
1113             );
1114         } else {
1115             self.addCopy(li);
1116         }
1117     };
1118
1119     this.copyCount = function() {
1120         var count = 0;
1121         for(var id in this.copyCache) {
1122             if(!this.copyCache[id].isdeleted())
1123                 count++;
1124         }
1125         return count;
1126     }
1127
1128     this.virtCopyId = -1;
1129     this.addCopy = function(li, copy) {
1130         var row = this.copyRow.cloneNode(true);
1131         this.copyTbody.appendChild(row);
1132         var self = this;
1133
1134         if(!copy) {
1135             copy = new fieldmapper.acqlid();
1136             copy.isnew(true);
1137             copy.id(this.virtCopyId--);
1138             copy.lineitem(li.id());
1139         }
1140
1141         this.copyCache[copy.id()] = copy;
1142         row.setAttribute('copy_id', copy.id());
1143         self.copyWidgetCache[copy.id()] = {};
1144
1145         acqLitCopyCountInput.attr('value', self.copyCount()+'');
1146
1147         dojo.forEach(liDetailFields,
1148             function(field) {
1149                 var widget = new openils.widget.AutoFieldWidget({
1150                     fmObject : copy,
1151                     fmField : field,
1152                     labelFormat : (field == 'fund') ? fundLabelFormat : null,
1153                     searchFormat : (field == 'fund') ? fundSearchFormat : null,
1154                     fmClass : 'acqlid',
1155                     parentNode : dojo.query('[name='+field+']', row)[0],
1156                     orgLimitPerms : ['CREATE_PICKLIST', 'CREATE_PURCHASE_ORDER'],
1157                     readOnly : Boolean(copy.eg_copy_id())
1158                 });
1159                 widget.build(
1160                     // make sure we capture the value from any async widgets
1161                     function(w, ww) { 
1162                         copy[field](ww.getFormattedValue()) 
1163                         self.copyWidgetCache[copy.id()][field] = w;
1164                     }
1165                 );
1166                 dojo.connect(widget.widget, 'onChange', 
1167                     function(val) { 
1168                         if(copy.isnew() || val != copy[field]()) {
1169                             // prevent setting ischanged() automatically on widget load for existing copies
1170                             copy[field](widget.getFormattedValue()) 
1171                             copy.ischanged(true);
1172                         }
1173                     }
1174                 );
1175             }
1176         );
1177
1178         this.updateLidReceivedness(copy, row);
1179     };
1180
1181     this.updateLidReceivedness = function(copy, row) {
1182         if (typeof(row) == "undefined") {
1183             row = dojo.query(
1184                 'tr[copy_id="' + copy.id() + '"]', this.copyTbody
1185             )[0];
1186         }
1187
1188         var self = this;
1189         var recv_link = nodeByName("receive", row);
1190         var unrecv_link = nodeByName("unreceive", row);
1191         var del_link = nodeByName("delete", row);
1192
1193         if (this.isPO) {
1194             openils.Util.hide(del_link.parentNode);
1195
1196             /* Avoid showing (un)receive links for virtual copies */
1197             if (copy.id() > 0) {
1198                 if(copy.recv_time()) {
1199                     openils.Util.hide(recv_link);
1200                     openils.Util.show(unrecv_link);
1201                     unrecv_link.onclick = function() {
1202                         if (confirm(localeStrings.UNRECEIVE_LID))
1203                             self.issueReceive(copy, /* rollback */ true);
1204                     };
1205                 } else {
1206                     openils.Util.hide(unrecv_link);
1207                     openils.Util.show(recv_link);
1208                     recv_link.onclick = function() {
1209                         if (self.checkLiAlerts(copy.lineitem()))
1210                             self.issueReceive(copy);
1211                     };
1212                 }
1213             } else {
1214                 openils.Util.hide(unrecv_link);
1215                 openils.Util.hide(recv_link);
1216             }
1217         } else {
1218             openils.Util.hide(unrecv_link);
1219             openils.Util.hide(recv_link);
1220
1221             del_link.onclick = function() { self.deleteCopy(row) };
1222             openils.Util.show(del_link.parentNode);
1223         }
1224     }
1225
1226     this._confirmAlert = function(li, lin) {
1227         return confirm(
1228             dojo.string.substitute(
1229                 localeStrings.CONFIRM_LI_ALERT, [
1230                     (new openils.acq.Lineitem({"lineitem": li})).findAttr(
1231                         "title", "lineitem_marc_attr_definition"
1232                     ),
1233                     lin.alert_text().code(),
1234                     lin.alert_text().description() || "",
1235                     lin.value()
1236                 ]
1237             )
1238         );
1239     };
1240
1241     this.checkLiAlerts = function(li_id) {
1242         var li = this.liCache[li_id];
1243
1244         var alert_notes = li.lineitem_notes().filter(
1245             function(o) { return Boolean(o.alert_text()); }
1246         );
1247
1248         /* this is _intentionally_ not done in a call to forEach() ... */
1249         for (var i = 0; i < alert_notes.length; i++) {
1250             if (this.noteAcks[alert_notes[i].id()])
1251                 continue;
1252             else if (!this._confirmAlert(li, alert_notes[i]))
1253                 return false;
1254             else
1255                 this.noteAcks[alert_notes[i].id()] = true;
1256         }
1257
1258         return true;
1259     };
1260
1261     this.deleteCopy = function(row) {
1262         var copy = this.copyCache[row.getAttribute('copy_id')];
1263         copy.isdeleted(true);
1264         if(copy.isnew())
1265             delete this.copyCache[copy.id()];
1266         this.copyTbody.removeChild(row);
1267     }
1268
1269     this._virtDfaCountsAsList = function() {
1270         var L = [];
1271         for (var key in this.virtDfaCounts) {
1272             for (var i = 0; i < this.virtDfaCounts[key]; i++)
1273                 L.push(key);
1274         }
1275         return L;
1276     }
1277
1278     this.saveCopyChanges = function(liId) {
1279         var self = this;
1280         var copies = [];
1281
1282
1283         var total = 0;
1284         for(var id in this.copyCache) {
1285             var c = this.copyCache[id];
1286             if(!c.isdeleted()) total++;
1287             if(c.isnew() || c.ischanged() || c.isdeleted()) {
1288                 if(c.id() < 0) c.id(null);
1289                 copies.push(c);
1290             }
1291         }
1292
1293         if (typeof(this._copy_count_cb) == "function") {
1294             this._copy_count_cb(liId, total);
1295         }
1296
1297         dojo.byId('acq-lit-copy-count-label-' + liId).innerHTML = total;
1298
1299
1300         if (copies.length > 0) {
1301             openils.Util.show("acq-lit-update-copies-progress");
1302             fieldmapper.standardRequest(
1303                 ['open-ils.acq', 'open-ils.acq.lineitem_detail.cud.batch'],
1304                 {   async: true,
1305                     params: [openils.User.authtoken, copies],
1306                     onresponse: function(r) {
1307                         var res = openils.Util.readResponse(r);
1308                         litUpdateCopiesProgress.update(res);
1309                     },
1310                     oncomplete: function() {
1311                         self.drawCopies(liId);
1312                         openils.Util.hide("acq-lit-update-copies-progress");
1313                     }
1314                 }
1315             );
1316         }
1317
1318         var dfa_list = this._virtDfaCountsAsList();
1319         if (dfa_list.length > 0) {
1320             fieldmapper.standardRequest(
1321                 ["open-ils.acq",
1322                 "open-ils.acq.distribution_formula.record_application"],
1323                 {
1324                     "async": true,
1325                     "params": [openils.User.authtoken, dfa_list, liId],
1326                     "onresponse": function(r) {
1327                         var res = openils.Util.readResponse(r);
1328                         if (res && res.length < dfa_list.length)
1329                             alert(localeStrings.DFA_NOT_ALL);
1330                     }
1331                 }
1332             );
1333             this.virtDfaCounts = {};
1334         }
1335     }
1336
1337     this.applySelectedLiAction = function(action) {
1338         var self = this;
1339         switch(action) {
1340
1341             case 'delete_selected':
1342                 this._deleteLiList(self.getSelected());
1343                 break;
1344
1345             case 'create_order':
1346
1347                 if(!this.createPoProviderSelector) {
1348                     var widget = new openils.widget.AutoFieldWidget({
1349                         fmField : 'provider',
1350                         fmClass : 'acqpo',
1351                         searchFilter: {"active": "t"},
1352                         parentNode : dojo.byId('acq-lit-po-provider'),
1353                     });
1354                     widget.build(
1355                         function(w) { self.createPoProviderSelector = w; }
1356                     );
1357                 }
1358
1359                 if(!this.createPoAgencySelector) {
1360                     var widget = new openils.widget.AutoFieldWidget({
1361                         fmField : 'ordering_agency',
1362                         fmClass : 'acqpo',
1363                         parentNode : dojo.byId('acq-lit-po-agency'),
1364                         orgLimitPerms : ['CREATE_PURCHASE_ORDER'],
1365                     });
1366                     widget.build(
1367                         function(w) { self.createPoAgencySelector = w; }
1368                     );
1369                 }
1370
1371          
1372                 acqLitPoCreateDialog.show();
1373                 break;
1374
1375             case 'save_picklist':
1376                 this._loadPLSelect();
1377                 acqLitSavePlDialog.show();
1378                 break;
1379
1380             case 'selector_ready':
1381             case 'order_ready':
1382                 acqLitChangeLiStateDialog.attr('state', action.replace('_', '-'));
1383                 acqLitChangeLiStateDialog.show();
1384                 break;
1385
1386             case 'print_po':
1387                 this.printPO();
1388                 break;
1389
1390             case 'receive_po':
1391                 this.receivePO();
1392                 break;
1393
1394             case 'rollback_receive_po':
1395                 this.rollbackPoReceive();
1396                 break;
1397
1398             case 'create_assets':
1399                 this.createAssets();
1400                 break;
1401
1402             case 'export_attr_list':
1403                 this.chooseExportAttr();
1404                 break;
1405
1406             case 'add_brief_record':
1407                 if(this.isPO)
1408                     location.href = oilsBasePath + '/acq/picklist/brief_record?po=' + this.isPO;
1409                 else
1410                     location.href = oilsBasePath + '/acq/picklist/brief_record?pl=' + this.isPL;
1411         }
1412     }
1413
1414     this.createAssets = function() {
1415         if(!this.isPO) return;
1416         if(!confirm(localeStrings.CREATE_PO_ASSETS_CONFIRM)) return;
1417         this.show('acq-lit-progress-numbers');
1418         var self = this;
1419         fieldmapper.standardRequest(
1420             ['open-ils.acq', 'open-ils.acq.purchase_order.assets.create'],
1421             {   async: true,
1422                 params: [this.authtoken, this.isPO],
1423                 onresponse: function(r) {
1424                     var resp = openils.Util.readResponse(r);
1425                     self._updateProgressNumbers(resp, true);
1426                 }
1427             }
1428         );
1429     }
1430
1431     this.chooseExportAttr = function() {
1432         if (!acqLitExportAttrSelector._li_setup) {
1433             var self = this;
1434             acqLitExportAttrSelector.store = new dojo.data.ItemFileReadStore(
1435                 {
1436                     "data": acqliad.toStoreData(
1437                         this.pcrud.search(
1438                             "acqliad", {"code": li_exportable_attrs}
1439                         )
1440                     )
1441                 }
1442             );
1443             acqLitExportAttrSelector.setValue();
1444             acqLitExportAttrButton.onClick = function(){self.exportAttrList();};
1445             acqLitExportAttrSelector._li_setup = true;
1446         }
1447         openils.Util.show("acq-lit-export-attr-holder", "inline");
1448     };
1449
1450     this.exportAttrList = function() {
1451         var attr_def = acqLitExportAttrSelector.item;
1452         var li_list = this.getSelected();
1453         var value_list = li_list.map(
1454             function(li) {
1455                 return (new openils.acq.Lineitem({"lineitem": li})).findAttr(
1456                     attr_def.code, "lineitem_marc_attr_definition"
1457                 );
1458             }
1459         ).filter(function(attr) { return Boolean(attr); });
1460
1461         if (value_list.length > 0) {
1462             if (value_list.length < li_list.length) {
1463                 if (!confirm(
1464                     dojo.string.substitute(
1465                         localeStrings.EXPORT_SHORT_LIST, [attr_def.description]
1466                     )
1467                 )) {
1468                     return;
1469                 }
1470             }
1471             try {
1472                 openils.XUL.contentToFileSaveDialog(
1473                     value_list.join("\n"),
1474                     localeStrings.EXPORT_SAVE_DIALOG_TITLE
1475                 );
1476             } catch (E) {
1477                 alert(E);
1478             }
1479         } else {
1480             alert(dojo.string.substitute(
1481                 localeStrings.EXPORT_EMPTY_LIST, [attr_def.description]
1482             ));
1483         }
1484
1485         openils.Util.hide("acq-lit-export-attr-holder");
1486     };
1487
1488     this.printPO = function() {
1489         if(!this.isPO) return;
1490         progressDialog.show(true);
1491         fieldmapper.standardRequest(
1492             ['open-ils.acq', 'open-ils.acq.purchase_order.format'],
1493             {   async: true,
1494                 params: [this.authtoken, this.isPO, 'html'],
1495                 oncomplete: function(r) {
1496                     progressDialog.hide();
1497                     var evt = openils.Util.readResponse(r);
1498                     if(evt && evt.template_output()) {
1499                         win = window.open('','', 'resizable,width=800,height=600,scrollbars=1');
1500                         win.document.body.innerHTML = evt.template_output().data();
1501                     }
1502                 }
1503             }
1504         );
1505     }
1506
1507
1508     this.receivePO = function() {
1509         if (!this.isPO) return;
1510
1511         for (var id in this.liCache) {
1512             /* assumption: liCache reflects exactly the
1513              * set of LIs that belong to our PO */
1514             if (this.liCache[id].state() != "received" &&
1515                 !this.checkLiAlerts(id)) return;
1516         }
1517
1518         this.show('acq-lit-progress-numbers');
1519         var self = this;
1520         fieldmapper.standardRequest(
1521             ['open-ils.acq', 'open-ils.acq.purchase_order.receive'],
1522             {   async: true,
1523                 params: [this.authtoken, this.isPO],
1524                 onresponse : function(r) {
1525                     var resp = openils.Util.readResponse(r);
1526                     self._updateProgressNumbers(resp, true);
1527                 },
1528             }
1529         );
1530     }
1531
1532     this.issueReceive = function(obj, rollback) {
1533         /* (For now) there shall be no marking LI or LIDs (un)received
1534          * except from the actual "view PO" interface. */
1535         if (!this.isPO) return;
1536
1537         var part =
1538             {"jub": "lineitem", "acqlid": "lineitem_detail"}[obj.classname];
1539         var method =
1540             "open-ils.acq." + part + ".receive" + (rollback ? ".rollback" : "");
1541
1542         progressDialog.show(true);
1543         fieldmapper.standardRequest(
1544             ["open-ils.acq", method], {
1545                 "async": true,
1546                 "params": [this.authtoken, obj.id()],
1547                 "onresponse": function(r) {
1548                     self.handleReceive(openils.Util.readResponse(r));
1549                 },
1550                 "oncomplete": function() { progressDialog.hide(); }
1551             }
1552         );
1553     };
1554
1555     /**
1556      * Handles the responses from receive and rollback ML calls.
1557      */
1558     this.handleReceive = function(resp) {
1559         if (resp) {
1560             if (resp.li) {
1561                 for (var li_id in resp.li) {
1562                     for (var key in resp.li[li_id])
1563                         self.liCache[li_id][key](resp.li[li_id][key]);
1564                     self.updateLiReceivedness(self.liCache[li_id]);
1565                 }
1566             }
1567             if (resp.po) {
1568                 if (typeof(self.poUpdateCallback) == "function")
1569                     self.poUpdateCallback(resp.po);
1570             }
1571             if (resp.lid) {
1572                 for (var lid_id in resp.lid) {
1573                     for (var key in resp.lid[lid_id])
1574                         self.copyCache[lid_id][key](resp.lid[lid_id][key]);
1575                     self.updateLidReceivedness(self.copyCache[lid_id]);
1576                 }
1577             }
1578         }
1579     };
1580
1581     this.rollbackPoReceive = function() {
1582         if(!this.isPO) return;
1583         if(!confirm(localeStrings.ROLLBACK_PO_RECEIVE_CONFIRM)) return;
1584         this.show('acq-lit-progress-numbers');
1585         var self = this;
1586         fieldmapper.standardRequest(
1587             ['open-ils.acq', 'open-ils.acq.purchase_order.receive.rollback'],
1588             {   async: true,
1589                 params: [this.authtoken, this.isPO],
1590                 onresponse : function(r) {
1591                     var resp = openils.Util.readResponse(r);
1592                     self._updateProgressNumbers(resp, true);
1593                 },
1594             }
1595         );
1596     }
1597
1598     this._updateProgressNumbers = function(resp, reloadOnComplete) {
1599         if(!resp) return;
1600         dojo.byId('acq-pl-lit-li-processed').innerHTML = resp.li;
1601         dojo.byId('acq-pl-lit-lid-processed').innerHTML = resp.lid;
1602         dojo.byId('acq-pl-lit-debits-processed').innerHTML = resp.debits_accrued;
1603         dojo.byId('acq-pl-lit-bibs-processed').innerHTML = resp.bibs;
1604         dojo.byId('acq-pl-lit-indexed-processed').innerHTML = resp.indexed;
1605         dojo.byId('acq-pl-lit-copies-processed').innerHTML = resp.copies;
1606         if(resp.complete && reloadOnComplete) 
1607             location.href = location.href;
1608     }
1609
1610
1611     this._createPO = function(fields) {
1612         this.show('acq-lit-progress-numbers');
1613         var po = new fieldmapper.acqpo();
1614         po.provider(this.createPoProviderSelector.attr('value'));
1615         po.ordering_agency(this.createPoAgencySelector.attr('value'));
1616
1617         var selected = this.getSelected( (fields.create_from == 'all') );
1618         if(selected.length == 0) return;
1619
1620         var max = selected.length * 3;
1621
1622         var self = this;
1623         fieldmapper.standardRequest(
1624             ['open-ils.acq', 'open-ils.acq.purchase_order.create'],
1625             {   async: true,
1626                 params: [
1627                     openils.User.authtoken, 
1628                     po, 
1629                     {
1630                         lineitems : selected.map(function(li) { return li.id() }),
1631                         create_assets : fields.create_assets[0],
1632                     }
1633                 ],
1634
1635                 onresponse : function(r) {
1636                     var resp = openils.Util.readResponse(r);
1637                     self._updateProgressNumbers(resp);
1638                     if(resp.complete) 
1639                         location.href = oilsBasePath + '/eg/acq/po/view/' + resp.purchase_order.id();
1640                 }
1641             }
1642         );
1643     }
1644
1645     this._deleteLiList = function(list, idx) {
1646         if(idx == null) idx = 0;
1647         if(idx >= list.length) return;
1648         var liId = list[idx].id();
1649         fieldmapper.standardRequest(
1650             ['open-ils.acq', 'open-ils.acq.lineitem.delete'],
1651             {   async: true,
1652                 params: [openils.User.authtoken, liId],
1653                 oncomplete: function(r) {
1654                     self.removeLineitem(liId);
1655                     self._deleteLiList(list, ++idx);
1656                 }
1657             }
1658         );
1659     }
1660
1661     this.editOrderMarc = function(li) {
1662
1663         /*  To run in Firefox directly, must set signed.applets.codebase_principal_support
1664             to true in about:config */
1665
1666         if(!openils.XUL.enableXPConnect()) return;
1667
1668         if(openils.XUL.isXUL()) {
1669             win = window.open('/xul/' + openils.XUL.buildId() + '/server/cat/marcedit.xul');
1670         } else {
1671             win = window.open('/xul/server/cat/marcedit.xul'); 
1672         }
1673         var self = this;
1674         win.xulG = {
1675             record : {marc : li.marc()},
1676             save : {
1677                 label: 'Save Record', // XXX I18N
1678                 func: function(xmlString) {
1679                     li.marc(xmlString);
1680                     fieldmapper.standardRequest(
1681                         ['open-ils.acq', 'open-ils.acq.lineitem.update'],
1682                         {   async: true,
1683                             params: [openils.User.authtoken, li],
1684                             oncomplete: function(r) {
1685                                 openils.Util.readResponse(r);
1686                                 win.close();
1687                                 self.drawInfo(li.id())
1688                             }
1689                         }
1690                     );
1691                 },
1692             }
1693         };
1694     }
1695
1696     this._savePl = function(values) {
1697         var self = this;
1698         var selected = this.getSelected( (values.which == 'all') );
1699         openils.Util.show('acq-lit-generic-progress');
1700
1701         if(values.new_name) {
1702             openils.acq.Picklist.create(
1703                 {name: values.new_name}, 
1704                 function(id) {
1705                     self._updateLiList(id, selected, 0, 
1706                         function(){
1707                             location.href = oilsBasePath + '/eg/acq/picklist/view/' + id;
1708                         });
1709                 }
1710             );
1711         } else if(values.existing_pl) {
1712             // update lineitems to use an existing picklist
1713             self._updateLiList(values.existing_pl, selected, 0, 
1714                 function(){
1715                     location.href = oilsBasePath + '/eg/acq/picklist/view/' + values.existing_pl;
1716                 });
1717         }
1718     }
1719
1720     this._updateLiState = function(values, state) {
1721         var self = this;
1722         var selected = this.getSelected( (values.which == 'all') );
1723         if(!selected.length) return;
1724         dojo.forEach(selected, function(li) {li.state(state);});
1725         self._updateLiList(null, selected, 0, 
1726             // TODO consider inline updates for efficiency
1727             function() { location.href = location.href }
1728         );
1729     }
1730
1731     this._updateLiList = function(pl, list, idx, oncomplete) {
1732         if(idx >= list.length) return oncomplete();
1733         var li = list[idx];
1734         if(pl != null) li.picklist(pl);
1735         litGenericProgress.update({maximum: list.length, progress: idx});
1736         new openils.acq.Lineitem({lineitem:li}).update(
1737             function(r) {
1738                 self._updateLiList(pl, list, ++idx, oncomplete);
1739             }
1740         );
1741     }
1742
1743     this._loadPLSelect = function() {
1744         if(this._plSelectLoaded) return;
1745         var plList = [];
1746         function handleResponse(r) {
1747             plList.push(r.recv().content());
1748         }
1749         var method = 'open-ils.acq.picklist.user.retrieve';
1750         fieldmapper.standardRequest(
1751             ['open-ils.acq', method],
1752             {   async: true,
1753                 params: [this.authtoken],
1754                 onresponse: handleResponse,
1755                 oncomplete: function() {
1756                     self._plSelectLoaded = true;
1757                     acqLitAddExistingSelect.store = 
1758                         new dojo.data.ItemFileReadStore({data:acqpl.toStoreData(plList)});
1759                     acqLitAddExistingSelect.setValue();
1760                 }
1761             }
1762         );
1763     }
1764
1765     // grab the li-details for this lineitem, grab the linked copies and volumes, add them to the table
1766     this.showRealCopies = function(li) {
1767         while(this.realCopiesTbody.childNodes[0])
1768             this.realCopiesTbody.removeChild(this.realCopiesTbody.childNodes[0]);
1769         this.show('real-copies');
1770
1771         this.realCopyList = [];
1772         this.volCache = {};
1773         var tabIndex = 1000;
1774         var self = this;
1775
1776         acqLitSaveRealCopies.onClick = function() {
1777             self.saveRealCopies();
1778         }
1779
1780         this._fetchLineitem(li.id(), 
1781             function(fullLi) {
1782                 li = self.liCache[li.id()] = fullLi;
1783
1784                 self.pcrud.search(
1785                     'acp', {
1786                         id : li.lineitem_details().map(
1787                             function(item) { return item.eg_copy_id() }
1788                         )
1789                     }, {
1790                         async : true,
1791                         streaming : true,
1792                         onresponse : function(r) {
1793                             var copy = openils.Util.readResponse(r);
1794                             var volId = copy.call_number();
1795                             var volume = self.volCache[volId];
1796                             if(!volume) {
1797                                 volume = self.volCache[volId] = self.pcrud.retrieve('acn', volId);
1798                             }
1799                             self.addRealCopy(volume, copy, tabIndex++);
1800                         }
1801                     }
1802                 );
1803             }
1804         );
1805     }
1806
1807     this.addRealCopy = function(volume, copy, tabIndex) {
1808         var row = this.realCopiesRow.cloneNode(true);
1809         this.realCopyList.push(copy);
1810
1811         var selectNode;
1812         dojo.forEach(
1813             ['owning_lib', 'location', 'circ_modifier', 'label', 'barcode'],
1814
1815             function(field) {
1816                 var isvol = (field == 'owning_lib' || field == 'label');
1817                 var widget = new openils.widget.AutoFieldWidget({
1818                     fmField : field,
1819                     fmObject : isvol ? volume : copy,
1820                     parentNode : nodeByName(field, row),
1821                     readOnly : (field != 'barcode'),
1822                 });
1823
1824                 var widgetDrawn = null;
1825
1826                 if(field == 'barcode') {
1827
1828                     widgetDrawn = function(w, ww) {
1829                         var node = w.domNode;
1830                         node.setAttribute('tabindex', ''+tabIndex);
1831
1832                         // on enter, select the next barcode input
1833                         dojo.connect(w, 'onKeyDown',
1834                             function(e) {
1835                                 if(e.keyCode == dojo.keys.ENTER) {
1836                                     var ti = node.getAttribute('tabindex');
1837                                     var nextNode = dojo.query('[tabindex=' + String(Number(ti) + 1) + ']', self.realCopiesTbody)[0];
1838                                     if(nextNode) nextNode.select();
1839                                 }
1840                             }
1841                         );
1842
1843                         dojo.connect(w, 'onChange', 
1844                             function(val) { 
1845                                 if(!val || val == copy.barcode()) return;
1846                                 copy.ischanged(true);
1847                                 copy.barcode(val);
1848                             }
1849                         );
1850
1851
1852                         if(self.realCopiesTbody.getElementsByTagName('TR').length == 0)
1853                             selectNode = node;
1854                     }
1855                 }
1856
1857                 widget.build(widgetDrawn);
1858             }
1859         );
1860
1861         this.realCopiesTbody.appendChild(row);
1862         if(selectNode) selectNode.select();
1863     };
1864
1865     this.saveRealCopies = function() {
1866         progressDialog.show(true);
1867         var list = this.realCopyList.filter(function(copy) { return copy.ischanged(); });
1868         this.pcrud.update(list, {oncomplete: function() { 
1869             progressDialog.hide();
1870             self.show('list');
1871         }});
1872     }
1873 }