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