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