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