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