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