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