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