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