LP#1514085 Vandelay in-database session tracking
[working/Evergreen.git] / Open-ILS / web / js / ui / default / vandelay / vandelay.js
1 /* ---------------------------------------------------------------------------
2 # Copyright (C) 2008  Georgia Public Library Service
3 # Bill Erickson <erickson@esilibrary.com>
4
5 # This program is free software; you can redistribute it and/or
6 # modify it under the terms of the GNU General Public License
7 # as published by the Free Software Foundation; either version 2
8 # of the License, or (at your option) any later version.
9
10 # This program is distributed in the hope that it will be useful,
11 # but WITHOUT ANY WARRANTY; without even the implied warranty of
12 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13 # GNU General Public License for more details.
14 # --------------------------------------------------------------------------- */
15 dojo.require("dojo.parser");
16 dojo.require("dojo.io.iframe"); 
17 dojo.require("dijit.ProgressBar"); 
18 dojo.require("dijit.form.FilteringSelect"); 
19 dojo.require("dijit.layout.ContentPane");
20 dojo.require("dijit.layout.TabContainer");
21 dojo.require("dijit.layout.LayoutContainer");
22 dojo.require('dijit.form.Button');
23 dojo.require('dijit.form.CheckBox');
24 dojo.require('dijit.Toolbar');
25 dojo.require('dijit.Tooltip');
26 dojo.require('dijit.Menu');
27 dojo.require("dijit.Dialog");
28 dojo.require("dojo.cookie");
29 dojo.require('dojox.grid.DataGrid');
30 dojo.require("dojo.data.ItemFileReadStore");
31 dojo.require('dojo.date.locale');
32 dojo.require('dojo.date.stamp');
33 dojo.require("fieldmapper.Fieldmapper");
34 dojo.require("fieldmapper.dojoData");
35 dojo.require("fieldmapper.OrgUtils");
36 dojo.require('openils.CGI');
37 dojo.require('openils.User');
38 dojo.require('openils.Event');
39 dojo.require('openils.Util');
40 dojo.require('openils.MarcXPathParser');
41 dojo.require('openils.widget.GridColumnPicker');
42 dojo.require('openils.PermaCrud');
43 dojo.require('openils.widget.OrgUnitFilteringSelect');
44 dojo.require('openils.widget.AutoGrid');
45 dojo.require('openils.widget.AutoFieldWidget');
46 dojo.require('openils.widget.ProgressDialog');
47 dojo.require('dojox.form.CheckedMultiSelect');
48
49
50 var globalDivs = [
51     'vl-generic-progress',
52     'vl-generic-progress-with-total',
53     'vl-marc-upload-div',
54     'vl-queue-div',
55     'vl-match-div',
56     'vl-marc-html-div',
57     'vl-queue-select-div',
58     'vl-marc-upload-status-div',
59     'vl-attr-editor-div',
60     'vl-marc-export-div',
61     'vl-profile-editor-div',
62     'vl-item-attr-editor-div',
63     'vl-import-error-div'
64 ];
65
66 var authtoken;
67 var VANDELAY_URL = '/vandelay-upload';
68 var bibAttrDefs = [];
69 var authAttrDefs = [];
70 var queuedRecords = [];
71 var queuedRecordsMap = {};
72 var bibAttrsFetched = false;
73 var authAttrsFetched = false;
74 var attrDefMap = {}; // maps attr def code names to attr def ids
75 var currentType;
76 var currentQueueId = null;
77 var currentQueueName = null;
78 var userCache = {};
79 var currentMatchedRecords; // set of loaded matched bib records
80 var currentOverlayRecordsMap; // map of import record to overlay record
81 var currentOverlayRecordsMapGid; // map of import record to overlay record grid id
82 var currentImportRecId; // when analyzing matches, this is the current import record
83 var userBibQueues = []; // only non-complete queues
84 var userAuthQueues = []; // only non-complete queues
85 var allUserBibQueues;
86 var allUserAuthQueues;
87 var selectableGridRecords;
88 var cgi = new openils.CGI();
89 var vlQueueGridColumePicker = {};
90 var vlBibSources = [];
91 var importItemDefs = [];
92 var matchSets = {biblio : [], authority : []};
93 var matchBuckets = {};
94 var mergeProfiles = [];
95 var copyStatusCache = {};
96 var copyLocationCache = {};
97 var localeStrings;
98 var trashGroups = [];
99
100 // org settings
101 var orgSettings = {};
102 const DEFAULT_MATCH_SET = 'vandelay.default_match_set';
103
104 /**
105   * Grab initial data
106   */
107 function vlInit() {
108
109     dojo.requireLocalization("openils.vandelay", "vandelay");
110     localeStrings = dojo.i18n.getLocalization("openils.vandelay", "vandelay");
111
112     authtoken = openils.User.authtoken;
113     var initNeeded = 10; // how many async responses do we need before we're init'd 
114     var initCount = 0; // how many async reponses we've received
115
116     openils.Util.registerEnterHandler(
117         vlQueueDisplayPage.domNode, function(){retrieveQueuedRecords();});
118     openils.Util.addCSSClass(dojo.byId('vl-menu-marc-upload'), 'toolbar_selected');
119
120     function checkInitDone() {
121         initCount++;
122         if(initCount == initNeeded)
123             runStartupCommands();
124     }
125
126     mergeProfiles = new openils.PermaCrud().retrieveAll('vmp');
127     vlUploadMergeProfile.store = new dojo.data.ItemFileReadStore({data:fieldmapper.vmp.toStoreData(mergeProfiles)});
128     vlUploadMergeProfile.labelAttr = 'name';
129     vlUploadMergeProfile.searchAttr = 'name';
130     vlUploadMergeProfile.startup();
131
132     vlUploadMergeProfile2.store = new dojo.data.ItemFileReadStore({data:fieldmapper.vmp.toStoreData(mergeProfiles)});
133     vlUploadMergeProfile2.labelAttr = 'name';
134     vlUploadMergeProfile2.searchAttr = 'name';
135     vlUploadMergeProfile2.startup();
136
137     vlUploadFtMergeProfile.store = new dojo.data.ItemFileReadStore({data:fieldmapper.vmp.toStoreData(mergeProfiles)});
138     vlUploadFtMergeProfile.labelAttr = 'name';
139     vlUploadFtMergeProfile.searchAttr = 'name';
140     vlUploadFtMergeProfile.startup();
141
142     vlUploadFtMergeProfile2.store = new dojo.data.ItemFileReadStore({data:fieldmapper.vmp.toStoreData(mergeProfiles)});
143     vlUploadFtMergeProfile2.labelAttr = 'name';
144     vlUploadFtMergeProfile2.searchAttr = 'name';
145     vlUploadFtMergeProfile2.startup();
146
147
148     // Fetch the bib and authority attribute definitions 
149     vlFetchBibAttrDefs(function () { checkInitDone(); });
150     vlFetchAuthAttrDefs(function () { checkInitDone(); });
151
152     vlRetrieveQueueList('bib', null, 
153         function(list) {
154             allUserBibQueues = list;
155             for(var i = 0; i < allUserBibQueues.length; i++) {
156                 if(allUserBibQueues[i].complete() == 'f')
157                     userBibQueues.push(allUserBibQueues[i]);
158             }
159             checkInitDone();
160         }
161     );
162
163     vlRetrieveQueueList('auth', null, 
164         function(list) {
165             allUserAuthQueues = list;
166             for(var i = 0; i < allUserAuthQueues.length; i++) {
167                 if(allUserAuthQueues[i].complete() == 'f')
168                     userAuthQueues.push(allUserAuthQueues[i]);
169             }
170             checkInitDone();
171         }
172     );
173
174     fieldmapper.standardRequest(
175         ['open-ils.permacrud', 'open-ils.permacrud.search.cbs.atomic'],
176         {   async: true,
177             params: [authtoken, {id:{"!=":null}}, {order_by:{cbs:'id'}}],
178             oncomplete : function(r) {
179                 vlBibSources = openils.Util.readResponse(r, false, true);
180                 checkInitDone();
181             }
182         }
183     );
184
185     var owner = fieldmapper.aou.orgNodeTrail(fieldmapper.aou.findOrgUnit(new openils.User().user.ws_ou()));
186     new openils.PermaCrud().search('viiad', 
187         {owner: owner.map(function(org) { return org.id(); })},
188         {   async: true,
189             oncomplete: function(r) {
190                 importItemDefs = openils.Util.readResponse(r);
191                 checkInitDone();
192             }
193         }
194     );
195
196     new openils.PermaCrud().search('vms',
197         {owner: owner.map(function(org) { return org.id(); })},
198         {   async: true,
199             oncomplete: function(r) {
200                 var sets = openils.Util.readResponse(r);
201                 dojo.forEach(sets, 
202                     function(set) {
203                         if(!matchSets[set.mtype()])
204                             matchSets[set.mtype()] = [];
205                         matchSets[set.mtype()].push(set);
206                     }
207                 );
208                 checkInitDone();
209             }
210         }
211     );
212
213     fieldmapper.standardRequest(
214         ['open-ils.actor', 'open-ils.actor.container.retrieve_by_class'],
215         {   async : true,
216             params : [authtoken, new openils.User().user.id(), 'biblio'],
217             oncomplete : function(r) {
218                 var buckets = openils.Util.readResponse(r);
219                 // only bib buckets are supported
220                 matchBuckets.biblio = buckets;
221                 checkInitDone();
222             }
223         }
224     );
225
226     new openils.PermaCrud().retrieveAll('ccs',
227         {   async: true,
228             oncomplete: function(r) {
229                 var stats = openils.Util.readResponse(r);
230                 dojo.forEach(stats, 
231                     function(stat){copyStatusCache[stat.id()] = stat});
232                 checkInitDone();
233             }
234         }
235     );
236
237     new openils.PermaCrud().search('vibtg',
238         {   always_apply : 'f',
239             owner: owner.map(function(org) { return org.id(); })
240         }, 
241         {   order_by : {vibtg : ['label']},
242             async: true,
243             oncomplete: function(r) {
244                 trashGroups = openils.Util.readResponse(r);
245
246                 if (trashGroups.length == 0) {
247                     openils.Util.hide('vl-trash-groups-row');
248                     openils.Util.hide('vl-trash-groups-row2');
249                     checkInitDone();
250                     return;
251                 }
252
253                 dojo.forEach(trashGroups, function(grp) {
254                     var sn = fieldmapper.aou.findOrgUnit(grp.owner()).shortname();
255                     var opt = {
256                         label : grp.label() + '&nbsp;(' + sn + ')',
257                         value : grp.id()
258                     };
259                     vlUploadTrashGroups.addOption(opt);
260                     vlUploadTrashGroups2.addOption(opt);
261                 });
262
263                 checkInitDone();
264             }
265         }
266     );
267
268     orgSettings = fieldmapper.aou.fetchOrgSettingBatch(openils.User.user.ws_ou(), [
269         DEFAULT_MATCH_SET
270     ]);
271     for(k in orgSettings)
272         if(orgSettings[k])
273             orgSettings[k] = orgSettings[k].value;
274
275     vlAttrEditorInit();
276     vlExportInit();
277 }
278
279
280 openils.Util.addOnLoad(vlInit);
281
282
283 // fetch the bib and authority attribute definitions
284
285 function vlFetchBibAttrDefs(postcomplete) {
286     bibAttrDefs = [];
287     fieldmapper.standardRequest(
288         ['open-ils.permacrud', 'open-ils.permacrud.search.vqbrad'],
289         {   async: true,
290             params: [authtoken, {id:{'!=':null}}],
291             onresponse: function(r) {
292                 var def = r.recv().content(); 
293                 if(e = openils.Event.parse(def[0])) 
294                     return alert(e);
295                 bibAttrDefs.push(def);
296             },
297             oncomplete: function() {
298                 bibAttrDefs = bibAttrDefs.sort(
299                     function(a, b) {
300                         if(a.id() > b.id()) return 1;
301                         if(a.id() < b.id()) return -1;
302                         return 0;
303                     }
304                 );
305                 postcomplete();
306             }
307         }
308     );
309 }
310
311 function vlFetchAuthAttrDefs(postcomplete) {
312     authAttrDefs = [];
313     fieldmapper.standardRequest(
314         ['open-ils.permacrud', 'open-ils.permacrud.search.vqarad'],
315         {   async: true,
316             params: [authtoken, {id:{'!=':null}}],
317             onresponse: function(r) {
318                 var def = r.recv().content(); 
319                 if(e = openils.Event.parse(def[0])) 
320                     return alert(e);
321                 authAttrDefs.push(def);
322             },
323             oncomplete: function() {
324                 authAttrDefs = authAttrDefs.sort(
325                     function(a, b) {
326                         if(a.id() > b.id()) return 1;
327                         if(a.id() < b.id()) return -1;
328                         return 0;
329                     }
330                 );
331                 postcomplete();
332             }
333         }
334     );
335 }
336
337 function vlRetrieveQueueList(type, filter, onload) {
338     type = (type == 'bib') ? type : 'authority';
339     fieldmapper.standardRequest(
340         ['open-ils.vandelay', 'open-ils.vandelay.'+type+'_queue.owner.retrieve.atomic'],
341         {   async: true,
342             params: [authtoken, null, filter],
343             oncomplete: function(r) {
344                 var list = r.recv().content();
345                 if(e = openils.Event.parse(list[0]))
346                     return alert(e);
347                 onload(list);
348             }
349         }
350     );
351
352 }
353
354 function displayGlobalDiv(id) {
355     for(var i = 0; i < globalDivs.length; i++) {
356         try {
357             dojo.style(dojo.byId(globalDivs[i]), 'display', 'none');
358         } catch(e) {
359             alert('please define div ' + globalDivs[i]);
360         }
361     }
362     dojo.style(dojo.byId(id),'display','block');
363
364     openils.Util.removeCSSClass(dojo.byId('vl-menu-marc-export'), 'toolbar_selected');
365     openils.Util.removeCSSClass(dojo.byId('vl-menu-marc-upload'), 'toolbar_selected');
366     openils.Util.removeCSSClass(dojo.byId('vl-menu-queue-select'), 'toolbar_selected');
367     openils.Util.removeCSSClass(dojo.byId('vl-menu-attr-editor'), 'toolbar_selected');
368     openils.Util.removeCSSClass(dojo.byId('vl-menu-profile-editor'), 'toolbar_selected');
369     openils.Util.removeCSSClass(dojo.byId('vl-menu-match-set-editor'), 'toolbar_selected');
370
371     if(dojo.byId('vl-match-set-iframe'))
372         dojo.byId('vl-match-set-editor-div').removeChild(dojo.byId('vl-match-set-iframe'));
373
374     switch(id) {
375         case 'vl-marc-export-div':
376             openils.Util.addCSSClass(dojo.byId('vl-menu-marc-export'), 'toolbar_selected');
377             break;
378         case 'vl-marc-upload-div':
379             openils.Util.addCSSClass(dojo.byId('vl-menu-marc-upload'), 'toolbar_selected');
380             break;
381         case 'vl-queue-select-div':
382             openils.Util.addCSSClass(dojo.byId('vl-menu-queue-select'), 'toolbar_selected');
383             break;
384         case 'vl-attr-editor-div':
385             openils.Util.addCSSClass(dojo.byId('vl-menu-attr-editor'), 'toolbar_selected');
386             break;
387         case 'vl-profile-editor-div':
388             openils.Util.addCSSClass(dojo.byId('vl-menu-profile-editor'), 'toolbar_selected');
389             break;
390         case 'vl-item-attr-editor-div':
391             openils.Util.addCSSClass(dojo.byId('vl-menu-import-item-attr-editor'), 'toolbar_selected');
392             break;
393         case 'vl-match-set-editor-div':
394             openils.Util.addCSSClass(dojo.byId('vl-menu-match-set-editor'), 'toolbar_selected');
395             break;
396     }
397 }
398
399 function runStartupCommands() {
400     openils.Util.hide(dojo.byId('vl-page-loading'));
401     openils.Util.show(dojo.byId('vl-body-wrapper'));
402     currentQueueId = cgi.param('qid');
403     currentType = cgi.param('qtype');
404     dojo.style('vl-nav-bar', 'visibility', 'visible');
405     if(currentQueueId)
406         return retrieveQueuedRecords(currentType, currentQueueId, handleRetrieveRecords);
407     if (cgi.param('page') == 'inspectq')
408         return vlShowQueueSelect();
409         
410     vlShowUploadForm();
411 }
412
413 /**
414   * asynchronously upload a file of MARC records
415   */
416 function uploadMARC(onload){
417     dojo.byId('vl-upload-status-count').innerHTML = '0';
418     dojo.byId('vl-ses-input').value = authtoken;
419     displayGlobalDiv('vl-marc-upload-status-div');
420     dojo.io.iframe.send({
421         url: VANDELAY_URL,
422         method: "post",
423         handleAs: "html",
424         form: dojo.byId('vl-marc-upload-form'),
425         handle: function(data,ioArgs){
426             var content = data.documentElement.textContent;
427             onload(content);
428         }
429     });
430 }       
431
432 /**
433   * Creates a new vandelay queue
434   */
435 function createQueue(
436         queueName, type, onload, importDefId, matchSet, matchBucket) {
437
438     var name = (type=='bib') ? 'bib' : 'authority';
439     var method = 'open-ils.vandelay.'+ name +'_queue.create'
440
441     var qType = name;
442     if (vlUploadRecordType.getValue().match(/acq/)) 
443         var qType = 'acq';
444
445     console.log('record type ' + vlUploadRecordType.getValue());
446     console.log('record type ' + vlUploadRecordType.getValue());
447
448     fieldmapper.standardRequest(
449         ['open-ils.vandelay', method],
450         {   async: true,
451             params: [
452                 authtoken, queueName, null, 
453                 qType, matchSet, importDefId, matchBucket
454             ],
455             oncomplete : function(r) {
456                 var queue = r.recv().content();
457                 if(e = openils.Event.parse(queue)) 
458                     return alert(e);
459                 onload(queue);
460             }
461         }
462     );
463 }
464
465 /**
466   * Tells vandelay to pull a batch of records from the cache and explode them
467   * out into the vandelay tables
468   */
469 function processSpool(key, queueId, type, onload) {
470
471     fieldmapper.standardRequest(
472         ['open-ils.vandelay', 'open-ils.vandelay.'+type+'.process_spool'],
473         {   async: true,
474             params: [authtoken, key, queueId, null, null, null, null, 1],
475
476             // exit_early mode returns the tracker
477             // watch it until it completes.
478             oncomplete: function(r) {
479                 var tracker = r.recv().content();
480                 if(e = openils.Event.parse(tracker)) 
481                     return alert(e);
482
483                 // Then poll for tracker updates.
484                 pollSessionTracker(tracker.id(),
485                     function(tracker) {
486                         dojo.byId('vl-upload-status-count').innerHTML = 
487                             tracker.actions_performed();
488                     },
489                     function() { onload(); }
490                 );
491             }
492         }
493     );
494 }
495
496 function pollSessionTracker(id, onresponse, oncomplete) {
497
498     function pollTrackerOnce() {
499         // Note this is not an authoritative API call.
500         // Thinking is it will complete eventually regardless.
501
502         fieldmapper.standardRequest(
503             ['open-ils.pcrud', 'open-ils.pcrud.retrieve.vst'], {   
504             params: [authtoken, id],
505             async: true,
506             oncomplete: function(r) {
507                 var tracker = openils.Util.readResponse(r);
508                 if (tracker && tracker.state() === 'active') {
509                     if (onresponse) {
510                         onresponse(tracker);
511                     }
512                     setTimeout(pollTrackerOnce, 2000);
513                 } else {
514                     // tracker is no longer active, session is complete.
515                     if (oncomplete) {
516                         oncomplete();
517                     }
518                 }
519             }
520         });
521     }
522     
523     setTimeout(pollTrackerOnce, 1000);
524 }
525
526 function vlExportInit() {
527
528     // queue export
529     var qsel = dojo.byId('vl-queue-export-options');
530     qsel.onchange = function(newVal) {
531         var value = qsel.options[qsel.selectedIndex].value;
532         qsel.selectedIndex = 0;
533         if(!value) return;
534         if(!confirm('Export as "' + value + '"?')) return; // TODO: i18n
535         retrieveQueuedRecords(
536             currentType, 
537             currentQueueId, 
538             function(r) { 
539                 exportHandler(value, r);
540                 displayGlobalDiv('vl-queue-div');
541             },
542             value
543         );
544     }
545
546     // item export
547     var isel = dojo.byId('vl-item-export-options');
548     isel.onchange = function(newVal) {
549         var value = isel.options[isel.selectedIndex].value;
550         isel.selectedIndex = 0;
551         if(!value) return;
552         if(!confirm('Export as "' + value + '"?')) return; // TODO: i18n
553
554         displayGlobalDiv('vl-generic-progress');
555         var method = 'open-ils.vandelay.import_item.queue.export.' + value + '.atomic';
556
557         fieldmapper.standardRequest(
558             ['open-ils.vandelay', method],
559             {
560                 params : [
561                     authtoken, 
562                     currentQueueId, 
563                     {with_import_error: (vlImportItemsShowErrors.checked) ? 1 : null}
564                 ],
565                 async : true,
566                 oncomplete : function(r) {exportHandler(value, r)}
567             }
568         );
569     }
570 }
571
572 function exportHandler(type, response) {
573     displayGlobalDiv('vl-import-error-div');
574     try {
575         var content = openils.Util.readResponse(response);
576         if (type=='email') {
577             if (content==1) { alert('Email sent.'); return; }
578             throw(content);
579         }
580         /* handle .atomic versus non-atomic method calls */
581         content = content.constructor == Array
582             ? content[0].template_output().data()
583             : content.template_output().data();
584         switch(type) {
585             case 'print':
586                 openils.Util.printHtmlString(content);
587             break;
588             case 'csv':
589                 //content = content.replace(/\\t/g,'\t'); // if we really wanted to do .tsv instead
590                 openils.XUL.contentToFileSaveDialog(content, null, {
591                     defaultString : 'VandelayExport.csv',
592                     defaultExtension : '.csv',
593                     filterName : 'CSV',
594                     filterExtension : '*.csv',
595                     filterAll : true
596                 } );
597             break;
598             default:
599                 alert('response = ' + response + '\tcontent:\n' + content);
600         }
601     } catch(E) {
602         alert('Error exporting data: ' + E);
603     }
604 }
605
606 /* export all (or just non-imported) queue records */
607 function vlExportRecordQueue(opts) {
608     /* conform type to exporter */
609     var type = currentType == 'auth' ? 'auth' : 'biblio';
610     var url = '/exporter?type='+type+'&queueid='+currentQueueId;
611     if (opts.nonimported) {
612         url += '&nonimported=1';
613     }
614
615     var req = new XMLHttpRequest();
616     req.open('GET',url,true);
617     req.send(null);
618     req.onreadystatechange = function () {
619         if (req.readyState == 4) {
620             var file_tag = opts.nonimported ? '_nonimported' : '';
621             var filename = currentQueueName + file_tag + '.mrc';
622
623             try {
624                 if (window.IAMBROWSER) {
625                     var blob = new Blob([req.responseText], {type: "application/octet-stream"});
626                     saveAs(blob, filename);
627                 } else {
628                     openils.XUL.contentToFileSaveDialog(req.responseText, null, {
629                         defaultString : filename,
630                         defaultExtension : '.mrc',
631                         filterName : 'MARC21',
632                         filterExtension : '*.mrc',
633                         filterAll : true
634                     } );
635                 }
636             } catch (E) {
637                 alert(E);
638             }
639         }
640     }
641 }
642
643 function retrieveQueuedRecords(type, queueId, onload, doExport) {
644     displayGlobalDiv('vl-generic-progress');
645     queuedRecords = [];
646     queuedRecordsMap = {};
647     currentOverlayRecordsMap = {};
648     currentOverlayRecordsMapGid = {};
649     selectableGridRecords = {};
650
651     if(!type) type = currentType;
652     else currentType = type;
653     if(!queueId) queueId = currentQueueId;
654     else currentQueueId = queueId;
655     if(!onload) onload = handleRetrieveRecords;
656
657     var method = 'open-ils.vandelay.'+type+'_queue.records.retrieve';
658
659     if(doExport) method += '.export.' + doExport;
660     if(vlQueueGridShowMatches.checked)
661         method = method.replace('records', 'records.matches');
662
663     method += '.atomic';
664
665     var sel = dojo.byId('vl-queue-display-limit-selector');
666     var limit = parseInt(sel.options[sel.selectedIndex].value);
667     var offset = limit * parseInt(vlQueueDisplayPage.attr('value')-1);
668
669     var params =  [authtoken, queueId, {clear_marc: 1, offset: offset, limit: limit, flesh_import_items:1}];
670     if(vlQueueGridShowNonImport.checked)
671         params[2].non_imported = 1;
672
673     if(vlQueueGridShowImportErrors.checked)
674         params[2].with_import_error = 1;
675
676     fieldmapper.standardRequest(
677         ['open-ils.vandelay', method],
678         {   async: true,
679             params: params,
680             oncomplete: function(r){
681                 if(doExport) return onload(r);
682                 var recs = r.recv().content();
683                 if(e = openils.Event.parse(recs[0]))
684                     return alert(e);
685                 for(var i = 0; i < recs.length; i++) {
686                     var rec = recs[i];
687                     queuedRecords.push(rec);
688                     queuedRecordsMap[rec.id()] = rec;
689                 }
690                 onload();
691             }
692         }
693     );
694 }
695
696 function vlLoadMatchUI(recId) {
697     displayGlobalDiv('vl-generic-progress');
698     var queuedRec = queuedRecordsMap[recId];
699     var matches = queuedRec.matches();
700     var records = [];
701     currentImportRecId = recId;
702     for(var i = 0; i < matches.length; i++)
703         records.push(matches[i].eg_record());
704
705     var retrieve = ['open-ils.search', 'open-ils.search.biblio.record_entry.slim.retrieve'];
706     var params = [records];
707     if(currentType == 'auth') {
708         retrieve = ['open-ils.pcrud', 'open-ils.pcrud.search.are.atomic'];
709         // retrieve all authority record fields except 'marc' for lightness
710         var fields = fieldmapper.IDL.fmclasses.are.fields
711             .filter(function(f) {return (!f.virtual && f.name != 'marc')})
712             .map(function(f) {return f.name});
713         params = [authtoken, {id : records}, {select : {are : fields}}]
714     }
715
716     fieldmapper.standardRequest(
717         retrieve,
718         {   async: true,
719             params:params,
720             oncomplete: function(r) {
721                 var recs = r.recv().content();
722                 if(e = openils.Event.parse(recs))
723                     return alert(e);
724
725                 /* ui mangling */
726                 displayGlobalDiv('vl-match-div');
727                 resetVlMatchGridLayout(currentType);
728                 currentMatchedRecords = recs;
729                 vlMatchGrid.setStructure(vlMatchGridLayout);
730
731                 var cls = 'bre';
732                 if (currentType == 'auth') {
733                     cls = 'are';
734
735                     // When fetching authority records from matches, we 
736                     // only fetch one instance of each record, even though
737                     // it may be used by multiple matches.  Modify the
738                     // array of records so that each match has a 
739                     // corresponding authority record in the list.
740                     var new_recs = [];
741                     dojo.forEach(matches, function(match) {
742                         var rec = recs.filter(function(r) { 
743                             return r.id() == match.eg_record() })[0];
744                         new_recs.push(rec);
745                     });
746                     recs = new_recs;
747                 }
748
749                 // build the data store of records with match information
750                 var dataStore = fieldmapper[cls].toStoreData(recs, null,
751                     {virtualFields:['_id', 'match_score', 'match_quality', 'rec_quality']});
752                 dataStore.identifier = '_id';
753
754                 var matchSeenMap = {};
755
756                 for(var i = 0; i < dataStore.items.length; i++) {
757                     var item = dataStore.items[i];
758                     item._id = i; // just need something unique
759                     for(var j = 0; j < matches.length; j++) {
760                         var match = matches[j];
761                         if(match.eg_record() == item.id && !matchSeenMap[match.id()]) {
762                             if(match.match_score)
763                                 item.match_score = match.match_score();
764                             item.match_quality = match.quality();
765                             item.rec_quality = queuedRec.quality();
766                             matchSeenMap[match.id()] = 1;
767                             break;
768                         }
769                     }
770                 }
771
772                 // now populate the grid
773                 vlPopulateMatchGrid(vlMatchGrid, dataStore);
774             }
775         }
776     );
777 }
778
779 function vlPopulateMatchGrid(grid, data) {
780     var store = new dojo.data.ItemFileReadStore({data:data});
781     grid.setStore(store);
782     grid.update();
783 }
784
785 function showMe(id) {
786     dojo.style(dojo.byId(id), 'display', 'block');
787 }
788 function hideMe(id) {
789     dojo.style(dojo.byId(id), 'display', 'none');
790 }
791
792
793 function vlLoadMARCHtml(recId, inCat, oncomplete) {
794     dijit.byId('vl-marc-html-done-button').onClick = oncomplete;
795     displayGlobalDiv('vl-generic-progress');
796     var api;
797     var params = [recId, 1];
798
799     if(inCat) {
800         hideMe('vl-marc-html-edit-button'); // don't show marc editor button
801         dijit.byId('vl-marc-html-edit-button').onClick = function(){}
802         api = ['open-ils.search', 'open-ils.search.biblio.record.html'];
803         if(currentType == 'auth')
804             api = ['open-ils.search', 'open-ils.search.authority.to_html'];
805     } else {
806         showMe('vl-marc-html-edit-button'); // plug in the marc editor button
807         dijit.byId('vl-marc-html-edit-button').onClick = 
808             function() {vlLoadMarcEditor(currentType, recId, oncomplete);};
809         params = [authtoken, recId];
810         api = ['open-ils.vandelay', 'open-ils.vandelay.queued_bib_record.html'];
811         if(currentType == 'auth')
812             api = ['open-ils.vandelay', 'open-ils.vandelay.queued_authority_record.html'];
813     }
814
815     fieldmapper.standardRequest(
816         api, 
817         {   async: true,
818             params: params,
819             oncomplete: function(r) {
820             displayGlobalDiv('vl-marc-html-div');
821                 var html = r.recv().content();
822                 dojo.byId('vl-marc-record-html').innerHTML = html;
823             }
824         }
825     );
826 }
827
828
829 /*
830 function getRecMatchesFromAttrCode(rec, attrCode) {
831     var matches = [];
832     var attr = getRecAttrFromCode(rec, attrCode);
833     for(var j = 0; j < rec.matches().length; j++) {
834         var match = rec.matches()[j];
835         if(match.matched_attr() == attr.id()) 
836             matches.push(match);
837     }
838     return matches;
839 }
840 */
841
842 /*
843 function getRecAttrFromMatch(rec, match) {
844     for(var i = 0; i < rec.attributes().length; i++) {
845         var attr = rec.attributes()[i];
846         if(attr.id() == match.matched_attr())
847             return attr;
848     }
849 }
850 */
851
852 function getRecAttrDefFromAttr(attr, type) {
853     var defs = (type == 'bib') ? bibAttrDefs : authAttrDefs;
854     for(var i = 0; i < defs.length; i++) {
855         var def = defs[i];
856         if(def.id() == attr.field())
857             return def;
858     }
859 }
860
861 function getRecAttrFromCode(rec, attrCode) {
862     var defId = attrDefMap[currentType][attrCode];
863     var attrs = rec.attributes();
864     for(var i = 0; i < attrs.length; i++) {
865         var attr = attrs[i];
866         if(attr.field() == defId) 
867             return attr;
868     }
869     return null;
870 }
871
872 function vlGetViewMatches(rowIdx, item) {
873     if(item) {
874         var id = this.grid.store.getValue(item, 'id');
875         var rec = queuedRecordsMap[id];
876         if(rec.matches().length > 0)
877             return id + ':' + rec.matches().length;
878     }
879     return -1
880 }
881
882 function vlFormatViewMatches(id) {
883     if(id == -1) return '';
884     var chunks = id.split(':');
885     id = chunks[0];
886     count = chunks[1];
887     return '<a href="javascript:void(0);" onclick="vlLoadMatchUI(' + id + ');">' + this.name + ' (' + count + ')</a>';
888 }
889
890 function vlGetViewErrors(rowIdx, item) {
891     if(item) {
892         var id = this.grid.store.getValue(item, 'id');
893         var rec = queuedRecordsMap[id];
894         // id:rec_error:item_import_error_count
895         return id + ':' + 
896             (rec.import_error() ? 1 : '') + ':' + 
897             (typeof rec.import_items == 'function'
898                 ? rec.import_items().filter(function(i) {return i.import_error()}).length
899                 :''
900             );
901     }
902     return -1
903 }
904
905 function vlFormatViewErrors(chunk) {
906     if(chunk == -1) return '';
907     var id = chunk.split(':')[0];
908     var rec = chunk.split(':')[1];
909     var count = chunk.split(':')[2];
910     var links = '';
911     if(rec) 
912         links += '<a href="javascript:void(0);" onclick="vlLoadErrorUI(' + id + ');">Record</a><br/>'; // TODO I18N
913     if(Number(count))
914         links += '<a href="javascript:void(0);" onclick="vlLoadErrorUI(' + id + ');">Items ('+count+')</a>'; // TODO I18N
915     return links;
916 }
917
918 //var vlItemErrorColumnPicker;
919 function vlLoadErrorUI(id) {
920
921     displayGlobalDiv('vl-import-error-div');
922     openils.Util.hide('vl-import-error-grid-all');
923     openils.Util.show('vl-import-error-record');
924
925     var rec = queuedRecordsMap[id];
926
927     dojo.byId('vl-error-id').innerHTML = rec.id();
928     dojo.forEach( // TODO sane authority rec. fields
929         ['title', 'author', 'isbn', 'issn', 'upc'],
930         function(field) {
931             var attr =  getRecAttrFromCode(rec, field);
932             var eid = 'vl-error-' + field;
933             if(attr) {
934                 openils.Util.show(dojo.byId(eid).parentNode, 'table-row');
935                 dojo.byId(eid).innerHTML = attr.attr_value();
936             } else {
937                 openils.Util.hide(dojo.byId(eid).parentNode);
938             }
939         }
940     );
941     var iediv = dojo.byId('vl-error-import-error');
942     var eddiv = dojo.byId('vl-error-error-detail');
943     if(rec.import_error()) {
944         openils.Util.show(iediv.parentNode, 'table-row');
945         openils.Util.show(eddiv.parentNode, 'table-row');
946         iediv.innerHTML = rec.import_error();
947         eddiv.innerHTML = rec.error_detail();
948     } else {
949         openils.Util.hide(iediv.parentNode);
950         openils.Util.hide(eddiv.parentNode);
951     }
952
953     var errorItems = rec.import_items().filter(function(i) {return i.import_error()});
954     if(errorItems.length) {
955         openils.Util.show('vl-import-error-grid-some');
956         storeData = vqbr.toStoreData(errorItems);
957         var store = new dojo.data.ItemFileReadStore({data:storeData});
958         vlImportErrorGrid.setStore(store);
959         vlImportErrorGrid.update();
960     } else {
961         openils.Util.hide('vl-import-error-grid-some');
962     }
963 }
964
965 function vlLoadErrorUIAll() {
966
967     displayGlobalDiv('vl-import-error-div');
968     openils.Util.hide('vl-import-error-grid-some');
969     openils.Util.hide('vl-import-error-record');
970     openils.Util.show('vl-import-error-grid-all');
971     vlAllImportErrorGrid.resetStore();
972
973     vlImportErrorGrid.displayOffset = 0;
974
975     vlAllImportErrorGrid.dataLoader = function() {
976
977         vlAllImportErrorGrid.showLoadProgressIndicator();
978
979         fieldmapper.standardRequest(
980             ['open-ils.vandelay', 'open-ils.vandelay.import_item.queue.retrieve'],
981             {
982                 async : true,
983                 params : [
984                     authtoken, currentQueueId, {   
985                         with_import_error: (vlImportItemsShowErrors.checked) ? 1 : null,
986                         offset : vlAllImportErrorGrid.displayOffset,
987                         limit : vlAllImportErrorGrid.displayLimit
988                     }
989                 ],
990                 onresponse : function(r) {
991                     var item = openils.Util.readResponse(r);
992                     if(!item) return;
993                     vlAllImportErrorGrid.store.newItem(vii.toStoreItem(item));
994                 },
995                 oncomplete : function() {
996                     vlAllImportErrorGrid.hideLoadProgressIndicator();
997                 }
998             }
999         );
1000     };
1001
1002     vlAllImportErrorGrid.dataLoader();
1003 }
1004
1005 function vlGetOrg(rowIdx, item) {
1006     if(!item) return '';
1007     var value = this.grid.store.getValue(item, this.field);
1008     if(value) return fieldmapper.aou.findOrgUnit(value).shortname();
1009     return '';
1010 }
1011
1012 function vlCopyStatus(rowIdx, item) {
1013     if(!item) return '';
1014     var value = this.grid.store.getValue(item, this.field);
1015     if(value) return copyStatusCache[value].name();
1016     return '';
1017 }
1018
1019 // Note, we don't pre-fetch all copy locations because there could be 
1020 // a lot of them.  Instead, fetch-and-cache on demand.
1021 function vlCopyLocation(rowIdx, item) {
1022     if(item) {
1023         var value = this.grid.store.getValue(item, this.field);
1024         if(value) {
1025             if(!copyLocationCache[value]) {
1026                 copyLocationCache[value] = 
1027                     new openils.PermaCrud().retrieve('acpl', value);
1028             }
1029             return copyLocationCache[value].name();
1030         }
1031     }
1032     return '';
1033 }
1034
1035 function vlFormatViewMatchMARC(id) {
1036     return '<a href="javascript:void(0);" onclick="vlLoadMARCHtml(' + id + ', true, '+
1037         'function(){displayGlobalDiv(\'vl-match-div\');});">' + this.name + '</a>';
1038 }
1039
1040 function getAttrValue(rowIdx, item) {
1041     if(!item) return '';
1042     var attrCode = this.field.split('.')[1];
1043     var rec = queuedRecordsMap[this.grid.store.getValue(item, 'id')];
1044     var attr = getRecAttrFromCode(rec, attrCode);
1045     return (attr) ? attr.attr_value() : '';
1046 }
1047
1048 function vlGetDateTimeField(rowIdx, item) {
1049     if(!item) return '';
1050     var value = this.grid.store.getValue(item, this.field);
1051     if(!value) return '';
1052     var date = dojo.date.stamp.fromISOString(value);
1053     return dojo.date.locale.format(date, {selector:'date'});
1054 }
1055
1056 function vlGetCreator(rowIdx, item) {
1057     if(!item) return '';
1058     var id = this.grid.store.getValue(item, 'creator');
1059     if(userCache[id])
1060         return userCache[id].usrname();
1061     var user = fieldmapper.standardRequest(
1062         ['open-ils.actor', 'open-ils.actor.user.retrieve'], [authtoken, id]);
1063     if(e = openils.Event.parse(user))
1064         return alert(e);
1065     userCache[id] = user;
1066     return user.usrname();
1067 }
1068
1069 function vlGetViewMARC(rowIdx, item) {
1070     return item && this.grid.store.getValue(item, 'id');
1071 }
1072
1073 function vlFormatViewMARC(id) {
1074     return '<a href="javascript:void(0);" onclick="vlLoadMARCHtml(' + id + ', false, '+
1075         'function(){displayGlobalDiv(\'vl-queue-div\');});">' + this.name + '</a>';
1076 }
1077
1078 function vlGetOverlayTargetSelector(rowIdx, item) {
1079     if(!item) return;
1080     return this.grid.store.getValue(item, '_id') + ':' + this.grid.store.getValue(item, 'id');
1081 }
1082
1083 function vlFormatOverlayTargetSelector(val) {
1084     if(!val) return '';
1085     var parts = val.split(':');
1086     var _id = parts[0];
1087     var id = parts[1];
1088     var value = '<input type="checkbox" name="vl-overlay-target-RECID" '+
1089         'onclick="vlHandleOverlayTargetSelected(ID, GRIDID);" gridid="GRIDID" match="ID"/>';
1090     value = value.replace(/GRIDID/g, _id);
1091     value = value.replace(/RECID/g, currentImportRecId);
1092     value = value.replace(/ID/g, id);
1093     if(_id == currentOverlayRecordsMapGid[currentImportRecId])
1094         return value.replace('/>', 'checked="checked"/>');
1095     return value;
1096 }
1097
1098
1099 /**
1100   * see if the user has enabled overlays for the current match set and, 
1101   * if so, map the current import record to the overlay target.
1102   */
1103 function vlHandleOverlayTargetSelected(recId, gridId) {
1104     var noneSelected = true;
1105     var checkboxes = dojo.query('[name=vl-overlay-target-'+currentImportRecId+']');
1106     for(var i = 0; i < checkboxes.length; i++) {
1107         var checkbox = checkboxes[i];
1108         var matchRecId = checkbox.getAttribute('match');
1109         var gid = checkbox.getAttribute('gridid');
1110         if(checkbox.checked) {
1111             if(matchRecId == recId && gid == gridId) {
1112                 noneSelected = false;
1113                 currentOverlayRecordsMap[currentImportRecId] = matchRecId;
1114                 currentOverlayRecordsMapGid[currentImportRecId] = gid;
1115                 dojo.byId('vl-record-list-selected-' + currentImportRecId).checked = true;
1116                 dojo.byId('vl-record-list-selected-' + currentImportRecId).parentNode.className = 'overlay_selected';
1117             } else {
1118                 checkbox.checked = false;
1119             }
1120         }
1121     }
1122
1123     if(noneSelected) {
1124         delete currentOverlayRecordsMap[currentImportRecId];
1125         delete currentOverlayRecordsMapGid[currentImportRecId];
1126         dojo.byId('vl-record-list-selected-' + currentImportRecId).checked = false;
1127         dojo.byId('vl-record-list-selected-' + currentImportRecId).parentNode.className = '';
1128     }
1129 }
1130
1131 var valLastQueueType = null;
1132 var vlQueueGridLayout = null;
1133 function buildRecordGrid(type) {
1134     displayGlobalDiv('vl-queue-div');
1135
1136     vlBibQueueGrid.canSort = function(col){ if(Math.abs(col) == 1) { return false; } else { return true; } }; 
1137     vlAuthQueueGrid.canSort = function(col){ if(Math.abs(col) == 1) { return false; } else { return true; } }; 
1138
1139     if(type == 'bib') {
1140         openils.Util.show('vl-bib-queue-grid-wrapper');
1141         openils.Util.hide('vl-auth-queue-grid-wrapper');
1142         vlQueueGrid = vlBibQueueGrid;
1143         openils.Util.show('add-to-bucket-action', 'table-row');
1144     } else {
1145         openils.Util.show('vl-auth-queue-grid-wrapper');
1146         openils.Util.hide('vl-bib-queue-grid-wrapper');
1147         vlQueueGrid = vlAuthQueueGrid;
1148         openils.Util.hide('add-to-bucket-action');
1149     }
1150
1151
1152     if(valLastQueueType != type) {
1153         valLastQueueType = type;
1154         vlQueueGridLayout = vlQueueGrid.attr('structure');
1155         var defs = (type == 'bib') ? bibAttrDefs : authAttrDefs;
1156         attrDefMap[type] = {};
1157         for(var i = 0; i < defs.length; i++) {
1158             var def = defs[i]
1159             attrDefMap[type][def.code()] = def.id();
1160             var col = {
1161                 name:def.description(), 
1162                 field:'attr.' + def.code(),
1163                 get: getAttrValue,
1164                 selectableColumn:true
1165             };
1166             vlQueueGridLayout[0].cells[0].push(col);
1167         }
1168     }
1169
1170     dojo.forEach(vlQueueGridLayout[0].cells[0], 
1171         function(cell) { 
1172             if(cell.field.match(/^\+/)) 
1173                 cell.nonSelectable=true;
1174         }
1175     );
1176
1177     var storeData;
1178     if(type == 'bib')
1179         storeData = vqbr.toStoreData(queuedRecords);
1180     else
1181         storeData = vqar.toStoreData(queuedRecords);
1182
1183     var store = new dojo.data.ItemFileReadStore({data:storeData});
1184     vlQueueGrid.setStore(store);
1185
1186     if(vlQueueGridColumePicker[type]) {
1187         vlQueueGrid.update();
1188     } else {
1189
1190         vlQueueGridColumePicker[type] =
1191             new openils.widget.GridColumnPicker(
1192                 authtoken, 'vandelay.queue.'+type, vlQueueGrid, vlQueueGridLayout);
1193         vlQueueGridColumePicker[type].load();
1194     }
1195 }
1196
1197 function vlQueueGridPrevPage() {
1198     var page = parseInt(vlQueueDisplayPage.getValue());
1199     if(page < 2) return;
1200     vlQueueDisplayPage.setValue(page - 1);
1201     retrieveQueuedRecords(currentType, currentQueueId, handleRetrieveRecords);
1202 }
1203
1204 function vlQueueGridNextPage() {
1205     vlQueueDisplayPage.setValue(parseInt(vlQueueDisplayPage.getValue())+1);
1206     retrieveQueuedRecords(currentType, currentQueueId, handleRetrieveRecords);
1207 }
1208
1209 function vlDeleteQueue(type, queueId, onload) {
1210     fieldmapper.standardRequest(
1211         ['open-ils.vandelay', 'open-ils.vandelay.'+type+'_queue.delete'],
1212         {   async: false,
1213             params: [authtoken, queueId],
1214             oncomplete: function(r) {
1215                 var resp = r.recv().content();
1216                 if(e = openils.Event.parse(resp))
1217                     return alert(e);
1218                 onload();
1219             }
1220         }
1221     );
1222 }
1223
1224
1225 function vlQueueGridDrawSelectBox(rowIdx, item) {
1226     return item &&  this.grid.store.getValue(item, 'id');
1227 }
1228
1229 function vlQueueGridFormatSelectBox(id) {
1230     var domId = 'vl-record-list-selected-' + id;
1231     if (id) { selectableGridRecords[domId] = id; }
1232     return "<div><input type='checkbox' id='"+domId+"'/></div>";
1233 }
1234
1235 function vlSelectAllQueueGridRecords() {
1236     for(var id in selectableGridRecords) 
1237         dojo.byId(id).checked = true;
1238 }
1239 function vlSelectNoQueueGridRecords() {
1240     for(var id in selectableGridRecords) 
1241         dojo.byId(id).checked = false;
1242 }
1243 function vlToggleQueueGridSelect() {
1244     if(dojo.byId('vl-queue-grid-row-selector').checked)
1245         vlSelectAllQueueGridRecords();
1246     else
1247         vlSelectNoQueueGridRecords();
1248 }
1249
1250 var handleRetrieveRecords = function() {
1251     buildRecordGrid(currentType);
1252
1253     if (currentType.match(/auth/)) {
1254         openils.Util.hide('vl-queue-summary-import-item-summary');
1255     } else {
1256         openils.Util.show('vl-queue-summary-import-item-summary', 'table-body');
1257     }
1258     vlFetchQueueSummary(currentQueueId, currentType, 
1259         function(summary) {
1260             currentQueueName = summary.queue.name();
1261             dojo.byId('vl-queue-summary-name').innerHTML = currentQueueName;
1262             dojo.byId('vl-queue-summary-total-count').innerHTML = summary.total +'';
1263             dojo.byId('vl-queue-summary-import-count').innerHTML = summary.imported + '';
1264             dojo.byId('vl-queue-summary-import-item-count').innerHTML = summary.total_items + '';
1265             dojo.byId('vl-queue-summary-import-item-imported-count').innerHTML = summary.total_items_imported + '';
1266             dojo.byId('vl-queue-summary-rec-error-count').innerHTML = summary.rec_import_errors + '';
1267             dojo.byId('vl-queue-summary-item-error-count').innerHTML = summary.item_import_errors + '';
1268            
1269             if (dojo.byId('create-bucket-dialog-name')) {
1270                 dojo.byId('create-bucket-dialog-name').value = summary.queue.name();
1271             }
1272         }
1273     );
1274 }
1275
1276 function vlFetchQueueSummary(qId, type, onload) {
1277     fieldmapper.standardRequest(
1278         ['open-ils.vandelay', 'open-ils.vandelay.'+type+'_queue.summary.retrieve'],
1279         {   async: true,
1280             params: [authtoken, qId],
1281             oncomplete : function(r) {
1282                 var summary = r.recv().content();
1283                 if(e = openils.Event.parse(summary))
1284                     return alert(e);
1285                 return onload(summary);
1286             }
1287         }
1288     );
1289 }
1290
1291 function handleCreateBucket(args) {
1292     var bname = dojo.byId('create-bucket-dialog-name').value;
1293     if (!bname) return;
1294
1295     progressDialog.show(true);
1296     fieldmapper.standardRequest(
1297         ['open-ils.vandelay', 'open-ils.vandelay.bib_queue.to_bucket'],
1298         {   async : true,
1299             params : [authtoken, currentQueueId, bname],
1300             oncomplete : function(r) {
1301                 progressDialog.hide();
1302                 setTimeout(function() { 
1303                     var resp = openils.Util.readResponse(r);
1304                     if (resp.add_count == 0) {
1305                         alert(localeStrings.NO_BUCKET_ITEMS);
1306                     } else {
1307                         alert(
1308                             dojo.string.substitute(
1309                                 localeStrings.BUCKET_CREATE_SUCCESS,
1310                                 [resp.add_count, bname, resp.item_count]
1311                             )
1312                         );
1313                     }
1314                 }, 200); // give the dialog a chance to hide
1315             }
1316         }
1317     );
1318 }
1319     
1320
1321 var _importCancelHandler;
1322 var _importGoHandler;
1323 function vlHandleQueueItemsAction(action) {
1324
1325     if(_importCancelHandler) dojo.disconnect(_importCancelHandler);
1326
1327     _importCancelHandler = dojo.connect(
1328         queueItemsImportCancelButton, 
1329         'onClick', 
1330         function() {
1331             queueItemsImportDialog.hide();
1332         }
1333     );
1334
1335     if(_importGoHandler)
1336         dojo.disconnect(_importGoHandler);
1337
1338     _importGoHandler = dojo.connect(
1339         queueItemsImportGoButton,
1340         'onClick', 
1341         function() {
1342             queueItemsImportDialog.hide();
1343
1344             // hack to set the widgets the import funcs will be looking at.  Reset them below.
1345             vlUploadQueueImportNoMatch.attr('value',  vlUploadQueueImportNoMatch2.attr('value'));
1346             vlUploadQueueAutoOverlayExact.attr('value',  vlUploadQueueAutoOverlayExact2.attr('value'));
1347             vlUploadQueueAutoOverlay1Match.attr('value',  vlUploadQueueAutoOverlay1Match2.attr('value'));
1348             vlUploadMergeProfile.attr('value',  vlUploadMergeProfile2.attr('value'));
1349             vlUploadFtMergeProfile.attr('value',  vlUploadFtMergeProfile2.attr('value'));
1350             vlUploadQueueAutoOverlayBestMatch.attr('value',  vlUploadQueueAutoOverlayBestMatch2.attr('value'));
1351             vlUploadQueueAutoOverlayBestMatchRatio.attr('value',  vlUploadQueueAutoOverlayBestMatchRatio2.attr('value'));
1352             vlUploadQueueAutoOverlayInprocessAcqCopies.attr('value',  vlUploadQueueAutoOverlayInprocessAcqCopies2.attr('value'));
1353
1354             // attr('value') and various other incantations won't let me set 
1355             // the value on the checkedmultiselect, so we temporarily swap 
1356             // the dijits instead.
1357             var tmpTrashGroup = vlUploadTrashGroups;
1358             vlUploadTrashGroups = vlUploadTrashGroups2;
1359
1360             if(action == 'import') {
1361                 vlImportSelectedRecords();
1362             } else if(action == 'import_all') {
1363                 vlImportAllRecords();
1364             }
1365             
1366             // reset the widgets to prevent accidental future actions
1367             vlUploadQueueImportNoMatch.attr('value',  false);
1368             vlUploadQueueImportNoMatch2.attr('value', false);
1369             vlUploadQueueAutoOverlayExact.attr('value', false);
1370             vlUploadQueueAutoOverlayExact2.attr('value', false);
1371             vlUploadQueueAutoOverlay1Match.attr('value', false);
1372             vlUploadQueueAutoOverlay1Match2.attr('value', false);
1373             vlUploadMergeProfile.attr('value', '');
1374             vlUploadMergeProfile2.attr('value', '');
1375             vlUploadFtMergeProfile.attr('value', '');
1376             vlUploadFtMergeProfile2.attr('value', '');
1377             vlUploadTrashGroups.attr('value', '');
1378             vlUploadTrashGroups2.attr('value', '');
1379             vlUploadQueueAutoOverlayBestMatch.attr('value', false);
1380             vlUploadQueueAutoOverlayBestMatch2.attr('value', false);
1381             vlUploadQueueAutoOverlayBestMatchRatio.attr('value', '0.0');
1382             vlUploadQueueAutoOverlayBestMatchRatio2.attr('value', '0.0');
1383             vlUploadQueueAutoOverlayInprocessAcqCopies.attr('value', false);
1384             vlUploadQueueAutoOverlayInprocessAcqCopies2.attr('value', false);
1385
1386             // and... swap them back
1387             vlUploadTrashGroups2 = vlUploadTrashGroups;
1388             vlUploadTrashGroups = tmpTrashGroup;
1389         }
1390     );
1391
1392     if (currentType.match(/auth/) || trashGroups.length == 0) {
1393         openils.Util.hide('vl-trash-groups-row2');
1394     } else {
1395         openils.Util.show('vl-trash-groups-row2', 'table-row');
1396     }
1397
1398     queueItemsImportDialog.show();
1399 }
1400
1401 /* import user-selected records */
1402 function vlImportSelectedRecords() {
1403     var records = [];
1404
1405     for(var id in selectableGridRecords) {
1406         if(dojo.byId(id).checked) {
1407             var recId = selectableGridRecords[id];
1408             var rec = queuedRecordsMap[recId];
1409             if(!rec.import_time()) 
1410                 records.push(recId);
1411         }
1412     }
1413
1414     vlImportRecordQueue(
1415         currentType, 
1416         currentQueueId, 
1417         records,
1418         function(){
1419             retrieveQueuedRecords(currentType, currentQueueId, handleRetrieveRecords);
1420         }
1421     );
1422 }
1423
1424 /* import all (non-imported) queue records */
1425 function vlImportAllRecords() {
1426     vlImportRecordQueue(
1427         currentType, 
1428         currentQueueId, 
1429         null,
1430         function(){
1431             retrieveQueuedRecords(currentType, currentQueueId, handleRetrieveRecords);
1432         }
1433     );
1434 }
1435
1436 /* if recList has values, import only those records */
1437 function vlImportRecordQueue(type, queueId, recList, onload, sessionKey) {
1438     displayGlobalDiv('vl-generic-progress-with-total');
1439
1440     /* set up options */
1441     var options = {
1442         overlay_map : currentOverlayRecordsMap, 
1443         session_key: sessionKey, // link to upload session if possible
1444         exit_early: true
1445     };
1446
1447     if(vlUploadQueueImportNoMatch.checked) {
1448         options.import_no_match = true;
1449         vlUploadQueueImportNoMatch.checked = false;
1450     }
1451
1452     if(vlUploadQueueAutoOverlayExact.checked) {
1453         options.auto_overlay_exact = true;
1454         vlUploadQueueAutoOverlayExact.checked = false;
1455     }
1456
1457     if(vlUploadQueueAutoOverlayBestMatch.checked) {
1458         options.auto_overlay_best_match = true;
1459         vlUploadQueueAutoOverlayBestMatch.checked = false;
1460         options.match_quality_ratio = vlUploadQueueAutoOverlayBestMatchRatio.attr('value');
1461     }
1462
1463     if(vlUploadQueueAutoOverlay1Match.checked) {
1464         options.auto_overlay_1match = true;
1465         vlUploadQueueAutoOverlay1Match.checked = false;
1466         options.match_quality_ratio = vlUploadQueueAutoOverlayBestMatchRatio.attr('value');
1467     }
1468
1469     if(vlUploadQueueAutoOverlayInprocessAcqCopies.checked) {
1470         options.opp_acq_copy_overlay = true; //"opp" for opportunistic
1471         vlUploadQueueAutoOverlayInprocessAcqCopies.checked = false;
1472     }
1473
1474     var profile = vlUploadMergeProfile.attr('value');
1475     if(profile != null && profile != '') {
1476         options.merge_profile = profile;
1477     }
1478
1479     var ftprofile = vlUploadFtMergeProfile.attr('value');
1480     if(ftprofile != null && ftprofile != '') {
1481         options.fall_through_merge_profile = ftprofile;
1482     }
1483
1484     var strip_grps = vlUploadTrashGroups.attr('value');
1485     if (strip_grps != null && strip_grps.length) {
1486         options.strip_field_groups = strip_grps;
1487     }
1488
1489     /* determine which method we're calling */
1490
1491     var method = 'open-ils.vandelay.bib_queue.import';
1492     if(type == 'auth')
1493         method = method.replace('bib', 'auth');
1494
1495     var params = [authtoken, queueId, options];
1496     if(recList) {
1497         method = 'open-ils.vandelay.'+currentType+'_record.list.import';
1498         params[1] = recList;
1499     }
1500
1501     fieldmapper.standardRequest(
1502         ['open-ils.vandelay', method], {
1503         async: true, 
1504         params: params,
1505
1506         // In exit_early mode, the API returns quickly with the
1507         // tracker object.  Once received, poll the tracker until
1508         // it's no longer active.
1509         oncomplete : function(r) {
1510             var tracker = r.recv().content();
1511             if(e = openils.Event.parse(tracker)) 
1512                 return alert(e);
1513
1514             // Then poll for tracker updates.
1515             pollSessionTracker(tracker.id(),
1516                 function(tracker) {
1517                     vlControlledProgressBar.update({
1518                         maximum: tracker.total_actions(),  
1519                         progress: tracker.actions_performed()
1520                     });
1521                 },
1522                 function() { onload(); }
1523             );
1524         }
1525     });
1526 }
1527
1528
1529 /**
1530   * Create queue, upload MARC, process spool, load the newly created queue 
1531   */
1532 function batchUpload() {
1533     var queueName = dijit.byId('vl-queue-name').getValue();
1534     currentType = dijit.byId('vl-record-type').getValue();
1535
1536     // could be bib-acq, which makes no sense in most places
1537     if (currentType.match(/bib/)) currentType = 'bib';
1538
1539     var sessionKey;
1540     var handleProcessSpool = function() {
1541         if( 
1542             vlUploadQueueImportNoMatch.checked || 
1543             vlUploadQueueAutoOverlayExact.checked || 
1544             vlUploadQueueAutoOverlay1Match.checked ||
1545             vlUploadQueueAutoOverlayBestMatch.checked ) {
1546
1547                 vlImportRecordQueue(
1548                     currentType, 
1549                     currentQueueId, 
1550                     null,
1551                     function() {
1552                         retrieveQueuedRecords(currentType, currentQueueId, handleRetrieveRecords);
1553                     },
1554                     sessionKey
1555                 );
1556         } else {
1557             retrieveQueuedRecords(currentType, currentQueueId, handleRetrieveRecords);
1558         }
1559     }
1560
1561     var handleUploadMARC = function(key) {
1562         dojo.style(dojo.byId('vl-upload-status-processing'), 'display', 'block');
1563         sessionKey = key;
1564         processSpool(key, currentQueueId, currentType, handleProcessSpool);
1565     };
1566
1567     var handleCreateQueue = function(queue) {
1568         currentQueueId = queue.id();
1569         uploadMARC(handleUploadMARC);
1570     };
1571     
1572     if(vlUploadQueueSelector.getValue() && !queueName) {
1573         currentQueueId = vlUploadQueueSelector.getValue();
1574         uploadMARC(handleUploadMARC);
1575     } else {
1576         createQueue(queueName, currentType, handleCreateQueue, 
1577             vlUploadQueueHoldingsImportProfile.attr('value'),
1578             vlUploadQueueMatchSet.attr('value'),
1579             vlUploadQueueMatchBucket.attr('value')
1580         );
1581     }
1582 }
1583
1584 // Inspect Queue no longer uses stores, so put type matching here instead
1585 function vlGetQueueData(type, asStore) {
1586     var filter;
1587     switch(type) {
1588         case 'bib-acq':
1589             filter = 'acq';
1590         case 'bib':
1591             if(!filter) filter = 'bib';
1592             var bibList = allUserBibQueues.filter(
1593                 function(q) {
1594                     return (q.queue_type() == filter);
1595                 }
1596             );
1597             if (!asStore) return bibList;
1598             return vbq.toStoreData(bibList);
1599         case 'auth':
1600             if (!asStore) return allUserAuthQueues;
1601             return vaq.toStoreData(allUserAuthQueues);
1602     }
1603 }
1604
1605 function vlFleshQueueSelect(selector, type) {
1606     var data = vlGetQueueData(type, true);
1607     selector.store = new dojo.data.ItemFileReadStore({data:data});
1608     selector.setValue(null);
1609     selector.setDisplayedValue('');
1610     if(data[0])
1611         selector.setValue(data[0].id());
1612
1613     var qInput = dijit.byId('vl-queue-name');
1614
1615     var selChange = function(val) {
1616         console.log('selector onchange');
1617         // user selected a queue from the selector;  clear the input and 
1618         // set the item import profile already defined for the queue
1619         var queue = allUserBibQueues.filter(function(q) { return (q.id() == val) })[0];
1620         if(val) {
1621             vlUploadQueueHoldingsImportProfile.attr('value', queue.item_attr_def() || '');
1622             vlUploadQueueHoldingsImportProfile.attr('disabled', true);
1623             vlUploadQueueMatchSet.attr('value', queue.match_set() || '');
1624             vlUploadQueueMatchSet.attr('disabled', true);
1625             vlUploadQueueMatchBucket.attr('value', queue.match_bucket() || '');
1626             vlUploadQueueMatchBucket.attr('disabled', true);
1627         } else {
1628             vlUploadQueueHoldingsImportProfile.attr('value', '');
1629             vlUploadQueueHoldingsImportProfile.attr('disabled', false);
1630             vlUploadQueueMatchBucket.attr('value', '');
1631             vlUploadQueueMatchBucket.attr('disabled', false);
1632         }
1633         dojo.disconnect(qInput._onchange);
1634         qInput.attr('value', '');
1635         qInput._onchange = dojo.connect(qInput, 'onChange', inputChange);
1636     }
1637     
1638     var inputChange = function(val) {
1639         console.log('qinput onchange');
1640         // user entered a new queue name. clear the selector 
1641         vlUploadQueueHoldingsImportProfile.attr('disabled', false);
1642         vlUploadQueueMatchSet.attr('disabled', false);
1643         vlUploadQueueMatchBucket.attr('disabled', false);
1644         dojo.disconnect(selector._onchange);
1645         selector.attr('value', '');
1646         selector._onchange = dojo.connect(selector, 'onChange', selChange);
1647     }
1648
1649     selector._onchange = dojo.connect(selector, 'onChange', selChange);
1650     qInput._onchange = dojo.connect(qInput, 'onChange', inputChange);
1651 }
1652
1653 function vlUpdateMatchSetSelector(type) {
1654     type = (type.match(/bib/)) ? 'biblio' : 'authority';
1655     vlUploadQueueMatchSet.store = 
1656         new dojo.data.ItemFileReadStore({data:vms.toStoreData(matchSets[type])});
1657     // apply default match set
1658     for (var i = 0; i < matchSets[type].length; i++) {
1659         if (matchSets[type][i].id() == orgSettings[DEFAULT_MATCH_SET]) {
1660             vlUploadQueueMatchSet.setValue(matchSets[type][i].id());
1661             break;
1662         }
1663     }
1664 }
1665
1666 function vlUpdateMatchBucketSelector(type) {
1667     type = (type.match(/bib/)) ? 'biblio' : 'authority';
1668     if (type == 'authority') {
1669         vlUploadQueueMatchBucket.attr('value', '');
1670         vlUploadQueueMatchBucket.attr('disabled', true);
1671     } else {
1672         vlUploadQueueMatchBucket.attr('disabled', false);
1673         vlUploadQueueMatchBucket.store = 
1674             new dojo.data.ItemFileReadStore(
1675                 {data:cbreb.toStoreData(matchBuckets[type])});
1676     }
1677 }
1678
1679 function vlShowUploadForm() {
1680     displayGlobalDiv('vl-marc-upload-div');
1681     vlFleshQueueSelect(vlUploadQueueSelector, vlUploadRecordType.getValue());
1682     vlUploadSourceSelector.store = 
1683         new dojo.data.ItemFileReadStore({data:cbs.toStoreData(vlBibSources, 'source')});
1684     vlUploadSourceSelector.setValue(vlBibSources[0].id());
1685     vlUploadQueueHoldingsImportProfile.store = 
1686         new dojo.data.ItemFileReadStore({data:viiad.toStoreData(importItemDefs)});
1687     vlUpdateMatchSetSelector(vlUploadRecordType.getValue());
1688     vlUpdateMatchBucketSelector(vlUploadRecordType.getValue());
1689
1690     if (vlUploadRecordType.attr('value').match(/auth/) || trashGroups.length == 0) {
1691         openils.Util.hide('vl-trash-groups-row');
1692     } else {
1693         openils.Util.show('vl-trash-groups-row', 'table-row');
1694     }
1695
1696     // use ratio from the merge profile if it's set
1697     dojo.connect(
1698         vlUploadMergeProfile, 
1699         'onChange',
1700         function(val) {
1701             if(!val) return;
1702             var profile = mergeProfiles.filter(function(p) { return (p.id() == val); })[0];
1703             if(profile.lwm_ratio() != null)
1704                vlUploadQueueAutoOverlayBestMatchRatio.attr('value', profile.lwm_ratio()+''); 
1705         }
1706     );
1707     dojo.connect(
1708         vlUploadMergeProfile2, 
1709         'onChange',
1710         function(val) {
1711             if(!val) return;
1712             var profile = mergeProfiles.filter(function(p) { return (p.id() == val); })[0];
1713             if(profile.lwm_ratio() != null)
1714                vlUploadQueueAutoOverlayBestMatchRatio2.attr('value', profile.lwm_ratio()+''); 
1715         }
1716     );
1717 }
1718
1719 function vlDeleteSelectedQueues() {
1720     var checkboxes = document.getElementById('vlQueueSelectList').getElementsByTagName('input');
1721     var type = vlQueueSelectType.attr('value').replace(/-.*/, '');
1722     for(var i = 0; i < checkboxes.length; i++) {
1723         if(checkboxes[i].getAttribute('name') == 'delete' && checkboxes[i].checked) {
1724             vlDeleteQueue(type, checkboxes[i].getAttribute('value'), function () {});
1725         }
1726     }
1727     window.location.reload();
1728 }
1729
1730 function vlShowQueueSelect() {
1731     displayGlobalDiv('vl-queue-select-div');
1732     var type = vlQueueSelectType.attr('value');
1733     var data = vlGetQueueData(type, false);
1734     type = type.replace(/-.*/, ''); // To remove any sub-typeish info.
1735     var tbody = document.getElementById('vlQueueSelectList');
1736
1737 }
1738
1739 function vlDeleteSelectedQueues() {
1740     var checkboxes = document.getElementById('vlQueueSelectList').getElementsByTagName('input');
1741     var type = vlQueueSelectType.attr('value').replace(/-.*/, '');
1742     for(var i = 0; i < checkboxes.length; i++) {
1743         if(checkboxes[i].getAttribute('name') == 'delete' && checkboxes[i].checked) {
1744             vlDeleteQueue(type, checkboxes[i].getAttribute('value'), function () {});
1745         }
1746     }
1747     window.location.reload();
1748 }
1749
1750 function vlShowQueueSelect() {
1751     displayGlobalDiv('vl-queue-select-div');
1752     var type = vlQueueSelectType.attr('value');
1753     var data = vlGetQueueData(type, false);
1754     type = type.replace(/-.*/, ''); // To remove any sub-typeish info.
1755     var tbody = document.getElementById('vlQueueSelectList');
1756     // Clear it out
1757     while(tbody.firstChild) {
1758         tbody.removeChild(tbody.firstChild);
1759     }
1760     // Add entries
1761     for(var entry in data) {
1762         var name = data[entry].name();
1763         if(!name.match(/\S/))
1764             name = '-';
1765         var tr = document.createElement('tr');
1766         var td = document.createElement('td');
1767         var checkbox = document.createElement('input');
1768         checkbox.setAttribute('type', 'checkbox');
1769         checkbox.setAttribute('name', 'delete');
1770         checkbox.setAttribute('value', data[entry].id());
1771         td.appendChild(checkbox);
1772         tr.appendChild(td);
1773         td = document.createElement('td');
1774         var a = document.createElement('a');
1775         a.textContent = name;
1776         a.setAttribute('href', "javascript:retrieveQueuedRecords('" + type + "', " + data[entry].id() + ");");
1777         td.appendChild(a);
1778         tr.appendChild(td);
1779         tbody.appendChild(tr);
1780     }
1781 }
1782
1783 function vlShowMatchSetEditor() {
1784     displayGlobalDiv('vl-match-set-editor-div');
1785     dojo.byId('vl-match-set-editor-div').appendChild(
1786         dojo.create('iframe', {
1787             id : 'vl-match-set-iframe',
1788             src : oilsBasePath + '/conify/global/vandelay/match_set',
1789             style : 'width:100%; height:500px; border:none; margin:0px;'
1790         })
1791     );
1792 }
1793
1794 function vlOpenMarcEditWindow(rec, postReloadHTMLHandler) {
1795     /*
1796         To run in Firefox directly, must set signed.applets.codebase_principal_support
1797         to true in about:config
1798     */
1799     if(window.IAMBROWSER){
1800         xulG.edit_marc_modal(rec, function(breId){ vlLoadMARCHtml(breId, false, postReloadHTMLHandler); });
1801         return;
1802     }
1803
1804     win = window.open('/xul/server/cat/marcedit.xul','','chrome'); // XXX version?
1805
1806     var type;
1807     if (currentType == 'bib') {
1808         type = 'bre';
1809     } else {
1810         type = 'are';
1811     }
1812
1813     function onsave(r) {
1814         // after the record is saved, reload the HTML display
1815         var stat = r.recv().content();
1816         if(e = openils.Event.parse(stat))
1817             return alert(e);
1818         alert(dojo.byId('vl-marc-edit-complete-label').innerHTML);
1819         win.close();
1820         vlLoadMARCHtml(rec.id(), false, postReloadHTMLHandler);
1821     }
1822
1823     win.xulG = {
1824         record : {marc : rec.marc(), "rtype": type},
1825         save : {
1826             label: dojo.byId('vl-marc-edit-save-label').innerHTML,
1827             func: function(xmlString) {
1828                 var method = 'open-ils.permacrud.update.' + rec.classname;
1829                 rec.marc(xmlString);
1830                 fieldmapper.standardRequest(
1831                     ['open-ils.permacrud', method],
1832                     {   async: true,
1833                         params: [authtoken, rec],
1834                         oncomplete: onsave
1835                     }
1836                 );
1837             },
1838         },
1839         'lock_tab' : typeof xulG != 'undefined' ? (typeof xulG['lock_tab'] != 'undefined' ? xulG.lock_tab : undefined) : undefined,
1840         'unlock_tab' : typeof xulG != 'undefined' ? (typeof xulG['unlock_tab'] != 'undefined' ? xulG.unlock_tab : undefined) : undefined
1841     };
1842 }
1843
1844 function vlLoadMarcEditor(type, recId, postReloadHTMLHandler) {
1845     var method = 'open-ils.permacrud.search.vqbr';
1846     if(currentType != 'bib')
1847         method = method.replace(/vqbr/,'vqar');
1848
1849     fieldmapper.standardRequest(
1850         ['open-ils.permacrud', method],
1851         {   async: true, 
1852             params: [authtoken, {id : recId}],
1853             oncomplete: function(r) {
1854                 var rec = r.recv().content();
1855                 if(e = openils.Event.parse(rec))
1856                     return alert(e);
1857                 vlOpenMarcEditWindow(rec, postReloadHTMLHandler);
1858             }
1859         }
1860     );
1861 }
1862
1863
1864
1865 //------------------------------------------------------------
1866 // attribute editors
1867
1868 // attribute-editor global variables
1869
1870 var ATTR_EDITOR_IN_UPDATE_MODE = false; // true on 'edit', false on 'create'
1871 var ATTR_EDIT_ID = null;                // id of current 'edit' attribute
1872 var ATTR_EDIT_GROUP = 'bib';            // bib-attrs or auth-attrs
1873
1874 function vlAttrEditorInit() {
1875     // set up tooltips on the edit form
1876     connectTooltip('attr-editor-tags'); 
1877     connectTooltip('attr-editor-subfields'); 
1878 }
1879
1880 function vlShowAttrEditor() {
1881     displayGlobalDiv('vl-attr-editor-div');
1882     loadAttrEditorGrid();
1883     idHide('vl-generic-progress');
1884 }
1885
1886 function setAttrEditorGroup(groupName) {
1887     // put us into 'bib'-attr or 'auth'-attr mode.
1888     if (ATTR_EDIT_GROUP != groupName) {
1889         ATTR_EDIT_GROUP = groupName;
1890         loadAttrEditorGrid();
1891     }
1892 }
1893
1894 function onAttrEditorOpen() {
1895     // the "bars" have the create/update/cancel/etc. buttons.
1896     var create_bar = document.getElementById('attr-editor-create-bar');
1897     var update_bar = document.getElementById('attr-editor-update-bar');
1898     if (ATTR_EDITOR_IN_UPDATE_MODE) {
1899         update_bar.style.display='table-row';
1900         create_bar.style.display='none';
1901         // hide the dropdown-button
1902         idStyle('vl-create-attr-editor-button', 'visibility', 'hidden');
1903     } else {
1904         dijit.byId('attr-editor-dialog').reset();
1905         create_bar.style.display='table-row';
1906         update_bar.style.display='none';
1907
1908         // clear the currently-editing attribute ID, 
1909         // since we're creating a new attribute.
1910         ATTR_EDIT_ID = null;
1911     }
1912 }
1913
1914 function onAttrEditorClose() {
1915     // reset the form to a "create" form. (We may have borrowed it for editing.)
1916     ATTR_EDITOR_IN_UPDATE_MODE = false;
1917     // show the dropdown-button
1918     idStyle('vl-create-attr-editor-button', 'visibility', 'visible');
1919 }
1920
1921 function loadAttrEditorGrid() {
1922     var _data = (ATTR_EDIT_GROUP == 'auth') ? 
1923         vqarad.toStoreData(authAttrDefs) : vqbrad.toStoreData(bibAttrDefs) ;
1924
1925     var store = new dojo.data.ItemFileReadStore({data:_data});
1926     attrEditorGrid.setStore(store);
1927     attrEditorGrid.onRowDblClick = onAttrEditorClick;
1928     attrEditorGrid.update();
1929 }
1930
1931 function attrGridGetTag(n, item) {
1932     // grid helper: return the tags from the row's xpath column.
1933     return item && xpathParser.parse(this.grid.store.getValue(item, 'xpath')).tags;
1934 }
1935
1936 function attrGridGetSubfield(n, item) {
1937     // grid helper: return the subfields from the row's xpath column.
1938     return item && xpathParser.parse(this.grid.store.getValue(item, 'xpath')).subfields;
1939 }
1940
1941 function onAttrEditorClick() {
1942     var row = this.getItem(this.focus.rowIndex);
1943     ATTR_EDIT_ID = this.store.getValue(row, 'id');
1944     ATTR_EDITOR_IN_UPDATE_MODE = true;
1945
1946     // populate the popup editor.
1947     dijit.byId('attr-editor-code').attr('value', this.store.getValue(row, 'code'));
1948     dijit.byId('attr-editor-description').attr('value', this.store.getValue(row, 'description'));
1949     var parsed_xpath = xpathParser.parse(this.store.getValue(row, 'xpath'));
1950     dijit.byId('attr-editor-tags').attr('value', parsed_xpath.tags);
1951     dijit.byId('attr-editor-subfields').attr('value', parsed_xpath.subfields);
1952     dijit.byId('attr-editor-xpath').attr('value', this.store.getValue(row, 'xpath'));
1953     dijit.byId('attr-editor-remove').attr('value', this.store.getValue(row, 'remove'));
1954
1955     // set up UI for editing
1956     dojo.byId('vl-create-attr-editor-button').click();
1957 }
1958
1959 function vlSaveAttrDefinition(data) {
1960     idHide('vl-attr-editor-div');
1961     idShow('vl-generic-progress');
1962
1963     data.id = ATTR_EDIT_ID;
1964
1965     // this ought to honour custom xpaths, but overwrite xpaths
1966     // derived from tags/subfields.
1967     if (data.xpath == '' || looksLikeDerivedXpath(data.xpath)) {
1968         var _xpath = tagAndSubFieldsToXpath(data.tag, data.subfield);
1969         data.xpath = _xpath;
1970     }
1971
1972     // build up our permacrud params. Key variables here are
1973     // "create or update" and "bib or auth".
1974
1975     var isAuth   = (ATTR_EDIT_GROUP == 'auth');
1976     var isCreate = (ATTR_EDIT_ID == null);
1977     var rad      = isAuth ? new vqarad() : new vqbrad() ;
1978     var method   = 'open-ils.permacrud' + (isCreate ? '.create.' : '.update.') 
1979         + (isAuth ? 'vqarad' : 'vqbrad');
1980     var _data    = rad.fromStoreItem(data);
1981
1982     _data.ischanged(1);
1983
1984     fieldmapper.standardRequest(
1985         ['open-ils.permacrud', method],
1986         {   async: true,
1987             params: [authtoken, _data ],
1988             onresponse: function(r) { },
1989             oncomplete: function(r) {
1990                 attrEditorFetchAttrDefs(vlShowAttrEditor);
1991                 ATTR_EDIT_ID = null;
1992             },
1993             onerror: function(r) {
1994                 alert('vlSaveAttrDefinition comms error: ' + r);
1995             }
1996         }
1997     );
1998 }
1999
2000 function attrEditorFetchAttrDefs(callback) {
2001     var fn = (ATTR_EDIT_GROUP == 'auth') ? vlFetchAuthAttrDefs : vlFetchBibAttrDefs;
2002     return fn(callback);
2003 }
2004
2005 function vlAttrDelete() {
2006     idHide('vl-attr-editor-div');
2007     idShow('vl-generic-progress');
2008
2009     var isAuth = (ATTR_EDIT_GROUP == 'auth');
2010     var method = 'open-ils.permacrud.delete.' + (isAuth ? 'vqarad' : 'vqbrad');
2011     var rad    = isAuth ? new vqarad() : new vqbrad() ;
2012     fieldmapper.standardRequest(
2013         ['open-ils.permacrud', method],
2014         {   async: true,
2015             params: [authtoken, rad.fromHash({ id : ATTR_EDIT_ID }), ],
2016             oncomplete: function() {
2017                 dijit.byId('attr-editor-dialog').onCancel(); // close the dialog
2018                 attrEditorFetchAttrDefs(vlShowAttrEditor);
2019                 ATTR_EDIT_ID = null;
2020             },
2021             onerror: function(r) {
2022                 alert('vlAttrDelete comms error: ' + r);
2023             }
2024         }
2025     );
2026 }
2027
2028 // ------------------------------------------------------------
2029 // utilities for attribute editors
2030
2031 // dom utilities (maybe dojo does these, and these should be replaced)
2032
2033 function idStyle(obId, k, v)    { document.getElementById(obId).style[k] = v;   }
2034 function idShow(obId)           { idStyle(obId, 'display', 'block');            }
2035 function idHide(obId)           { idStyle(obId, 'display' , 'none');            }
2036
2037 function connectTooltip(fieldId) {
2038     // Given an element id, look up a tooltip element in the doc (same
2039     // id with a '-tip' suffix) and associate the two. Maybe dojo has
2040     // a better way to do this?
2041     var fld = dojo.byId(fieldId);
2042     var tip = dojo.byId(fieldId + '-tip');
2043     dojo.connect(fld, 'onfocus', function(evt) {
2044                      dijit.showTooltip(tip.innerHTML, fld, ['below', 'after']); });
2045     dojo.connect(fld, 'onblur', function(evt) { dijit.hideTooltip(fld); });
2046 }
2047
2048 // xpath utilities
2049
2050 var xpathParser = new openils.MarcXPathParser();
2051
2052 function tagAndSubFieldsToXpath(tags, subfields) {
2053     // given tags, and subfields, build up an XPath.
2054     try {
2055         var parts = {
2056             'tags':tags.match(/[\d]+/g), 
2057             'subfields':subfields.match(/[a-zA-z]/g) };
2058         return xpathParser.compile(parts);
2059     } catch (err) {
2060         return {'parts':null, 'tags':null, 'error':err};
2061     }
2062 }
2063
2064 function looksLikeDerivedXpath(path) {
2065     // Does this path look like it was derived from tags and subfields?
2066     var parsed = xpathParser.parse(path);
2067     if (parsed.tags == null) 
2068         return false;
2069     var compiled = xpathParser.compile(parsed);
2070     return (path == compiled);
2071 }
2072
2073 // amazing xpath-util unit-tests
2074 if (!looksLikeDerivedXpath('//*[@tag="901"]/*[@code="c"]'))     alert('vandelay xpath-utility error');
2075 if ( looksLikeDerivedXpath('ba-boo-ba-boo!'))                   alert('vandelay xpath-utility error');
2076
2077
2078
2079 var profileContextOrg
2080 function vlShowProfileEditor() {
2081     displayGlobalDiv('vl-profile-editor-div');
2082     buildProfileGrid();
2083
2084     var connect = function() {
2085         dojo.connect(profileContextOrgSelector, 'onChange',
2086             function() {
2087                 profileContextOrg = this.attr('value');
2088                 pGrid.resetStore();
2089                 buildProfileGrid();
2090             }
2091         );
2092     };
2093
2094     new openils.User().buildPermOrgSelector(
2095         'ADMIN_MERGE_PROFILE', profileContextOrgSelector, null, connect);
2096 }
2097
2098 function buildProfileGrid() {
2099
2100     if(profileContextOrg == null)
2101         profileContextOrg = openils.User.user.ws_ou();
2102
2103     pGrid.loadAll( 
2104         {order_by : {vmp : 'name'}}, 
2105         {owner : fieldmapper.aou.fullPath(profileContextOrg, true)}
2106     );
2107 }
2108
2109 /* --- Import Item Attr Grid --------------- */
2110
2111 var itemAttrContextOrg;
2112 var itemAttrGridFirstTime = true;
2113 function vlShowImportItemAttrEditor() {
2114     displayGlobalDiv('vl-item-attr-editor-div');
2115
2116     if (itemAttrGridFirstTime) {
2117
2118         buildImportItemAttrGrid();
2119
2120         var connect = function() {
2121             dojo.connect(itemAttrContextOrgSelector, 'onChange',
2122                 function() {
2123                     itemAttrContextOrg = this.attr('value');
2124                     itemAttrGrid.resetStore();
2125                     buildImportItemAttrGrid();
2126                 }
2127             );
2128         };
2129
2130         new openils.User().buildPermOrgSelector(
2131             'ADMIN_IMPORT_ITEM_ATTR_DEF', 
2132                 itemAttrContextOrgSelector, null, connect);
2133
2134         itemAttrGridFirstTime = false;
2135     }
2136 }
2137
2138 function buildImportItemAttrGrid() {
2139
2140     if(itemAttrContextOrg == null)
2141         itemAttrContextOrg = openils.User.user.ws_ou();
2142
2143     itemAttrGrid.loadAll( 
2144         {order_by : {viiad : 'name'}}, 
2145         {owner : fieldmapper.aou.fullPath(itemAttrContextOrg, true)}
2146     );
2147 }
2148