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