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