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