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