]> git.evergreen-ils.org Git - working/Evergreen.git/blob - Open-ILS/web/js/ui/default/vandelay/vandelay.js
match set selection support in vl uploage UI, part 1
[working/Evergreen.git] / Open-ILS / web / js / ui / default / vandelay / vandelay.js
1 /* ---------------------------------------------------------------------------
2 # Copyright (C) 2008  Georgia Public Library Service
3 # Bill Erickson <erickson@esilibrary.com>
4
5 # This program is free software; you can redistribute it and/or
6 # modify it under the terms of the GNU General Public License
7 # as published by the Free Software Foundation; either version 2
8 # of the License, or (at your option) any later version.
9
10 # This program is distributed in the hope that it will be useful,
11 # but WITHOUT ANY WARRANTY; without even the implied warranty of
12 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13 # GNU General Public License for more details.
14 # --------------------------------------------------------------------------- */
15 dojo.require("dojo.parser");
16 dojo.require("dojo.io.iframe"); 
17 dojo.require("dijit.ProgressBar"); 
18 dojo.require("dijit.form.FilteringSelect"); 
19 dojo.require("dijit.layout.ContentPane");
20 dojo.require("dijit.layout.TabContainer");
21 dojo.require("dijit.layout.LayoutContainer");
22 dojo.require('dijit.form.Button');
23 dojo.require('dijit.form.CheckBox');
24 dojo.require('dijit.Toolbar');
25 dojo.require('dijit.Tooltip');
26 dojo.require('dijit.Menu');
27 dojo.require("dijit.Dialog");
28 dojo.require("dojo.cookie");
29 dojo.require('dojox.grid.DataGrid');
30 dojo.require("dojo.data.ItemFileReadStore");
31 dojo.require('dojo.date.locale');
32 dojo.require('dojo.date.stamp');
33 dojo.require("fieldmapper.Fieldmapper");
34 dojo.require("fieldmapper.dojoData");
35 dojo.require("fieldmapper.OrgUtils");
36 dojo.require('openils.CGI');
37 dojo.require('openils.User');
38 dojo.require('openils.Event');
39 dojo.require('openils.Util');
40 dojo.require('openils.MarcXPathParser');
41 dojo.require('openils.widget.GridColumnPicker');
42 dojo.require('openils.PermaCrud');
43 dojo.require('openils.widget.OrgUnitFilteringSelect');
44 dojo.require('openils.widget.AutoGrid');
45 dojo.require('openils.widget.AutoFieldWidget');
46
47
48 var globalDivs = [
49     'vl-generic-progress',
50     'vl-generic-progress-with-total',
51     'vl-marc-upload-div',
52     'vl-queue-div',
53     'vl-match-div',
54     'vl-marc-html-div',
55     'vl-queue-select-div',
56     'vl-marc-upload-status-div',
57     'vl-attr-editor-div',
58     'vl-marc-export-div',
59     'vl-profile-editor-div',
60     'vl-item-attr-editor-div',
61     'vl-import-error-div'
62 ];
63
64 var authtoken;
65 var VANDELAY_URL = '/vandelay-upload';
66 var bibAttrDefs = [];
67 var authAttrDefs = [];
68 var queuedRecords = [];
69 var queuedRecordsMap = {};
70 var bibAttrsFetched = false;
71 var authAttrsFetched = false;
72 var attrDefMap = {}; // maps attr def code names to attr def ids
73 var currentType;
74 var currentQueueId = null;
75 var userCache = {};
76 var currentMatchedRecords; // set of loaded matched bib records
77 var currentOverlayRecordsMap; // map of import record to overlay record
78 var currentOverlayRecordsMapGid; // map of import record to overlay record grid id
79 var currentImportRecId; // when analyzing matches, this is the current import record
80 var userBibQueues = []; // only non-complete queues
81 var userAuthQueues = []; // only non-complete queues
82 var allUserBibQueues;
83 var allUserAuthQueues;
84 var selectableGridRecords;
85 var cgi = new openils.CGI();
86 var vlQueueGridColumePicker = {};
87 var vlBibSources = [];
88 var importItemDefs = [];
89 var matchSets = {};
90
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         parmas = [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:['dest_matchpoint', 'src_matchpoint', '_id']});
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                             item.dest_matchpoint = match.field_type();
479                             var attr = getRecAttrFromMatch(queuedRecordsMap[recId], match);
480                             item.src_matchpoint = getRecAttrDefFromAttr(attr, currentType).code();
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 function getRecAttrFromMatch(rec, match) {
558     for(var i = 0; i < rec.attributes().length; i++) {
559         var attr = rec.attributes()[i];
560         if(attr.id() == match.matched_attr())
561             return attr;
562     }
563 }
564
565 function getRecAttrDefFromAttr(attr, type) {
566     var defs = (type == 'bib') ? bibAttrDefs : authAttrDefs;
567     for(var i = 0; i < defs.length; i++) {
568         var def = defs[i];
569         if(def.id() == attr.field())
570             return def;
571     }
572 }
573
574 function getRecAttrFromCode(rec, attrCode) {
575     var defId = attrDefMap[currentType][attrCode];
576     var attrs = rec.attributes();
577     for(var i = 0; i < attrs.length; i++) {
578         var attr = attrs[i];
579         if(attr.field() == defId) 
580             return attr;
581     }
582     return null;
583 }
584
585 function vlGetViewMatches(rowIdx, item) {
586     if(item) {
587         var id = this.grid.store.getValue(item, 'id');
588         var rec = queuedRecordsMap[id];
589         if(rec.matches().length > 0)
590             return id;
591     }
592     return -1
593 }
594
595 function vlFormatViewMatches(id) {
596     if(id == -1) return '';
597     return '<a href="javascript:void(0);" onclick="vlLoadMatchUI(' + id + ');">' + this.name + '</a>';
598 }
599
600 function vlGetViewErrors(rowIdx, item) {
601     if(item) {
602         var id = this.grid.store.getValue(item, 'id');
603         var rec = queuedRecordsMap[id];
604         // id:rec_error:item_import_error_count
605         return id + ':' + 
606             (rec.import_error() ? 1 : '') + ':' + 
607             rec.import_items().filter(function(i) {return i.import_error()}).length;
608     }
609     return -1
610 }
611
612 function vlFormatViewErrors(chunk) {
613     if(chunk == -1) return '';
614     var id = chunk.split(':')[0];
615     var rec = chunk.split(':')[1];
616     var count = chunk.split(':')[2];
617     var links = '';
618     if(rec) 
619         links += '<a href="javascript:void(0);" onclick="vlLoadErrorUI(' + id + ');">Record</a><br/>'; // TODO I18N
620     if(Number(count))
621         links += '<a href="javascript:void(0);" onclick="vlLoadErrorUI(' + id + ');">Items ('+count+')</a>'; // TODO I18N
622     return links;
623 }
624
625 //var vlItemErrorColumnPicker;
626 function vlLoadErrorUI(id) {
627
628     displayGlobalDiv('vl-import-error-div');
629     openils.Util.hide('vl-import-error-grid-all');
630     openils.Util.show('vl-import-error-record');
631
632     var rec = queuedRecordsMap[id];
633
634     dojo.byId('vl-error-id').innerHTML = rec.id();
635     dojo.forEach( // TODO sane authority rec. fields
636         ['title', 'author', 'isbn', 'issn', 'upc'],
637         function(field) {
638             var attr =  getRecAttrFromCode(rec, field);
639             var eid = 'vl-error-' + field;
640             if(attr) {
641                 openils.Util.show(dojo.byId(eid).parentNode, 'table-row');
642                 dojo.byId(eid).innerHTML = attr.attr_value();
643             } else {
644                 openils.Util.hide(dojo.byId(eid).parentNode);
645             }
646         }
647     );
648     var iediv = dojo.byId('vl-error-import-error');
649     var eddiv = dojo.byId('vl-error-error-detail');
650     if(rec.import_error()) {
651         openils.Util.show(iediv.parentNode, 'table-row');
652         openils.Util.show(eddiv.parentNode, 'table-row');
653         iediv.innerHTML = rec.import_error();
654         eddiv.innerHTML = rec.error_detail();
655     } else {
656         openils.Util.hide(iediv.parentNode);
657         openils.Util.hide(eddiv.parentNode);
658     }
659
660     var errorItems = rec.import_items().filter(function(i) {return i.import_error()});
661     if(errorItems.length) {
662         openils.Util.show('vl-import-error-grid-some');
663         storeData = vqbr.toStoreData(errorItems);
664         var store = new dojo.data.ItemFileReadStore({data:storeData});
665         vlImportErrorGrid.setStore(store);
666         vlImportErrorGrid.update();
667     } else {
668         openils.Util.hide('vl-import-error-grid-some');
669     }
670 }
671
672 function vlLoadErrorUIAll() {
673
674     displayGlobalDiv('vl-import-error-div');
675     openils.Util.hide('vl-import-error-grid-some');
676     openils.Util.hide('vl-import-error-record');
677     openils.Util.show('vl-import-error-grid-all');
678     vlAllImportErrorGrid.resetStore();
679
680     vlImportErrorGrid.displayOffset = 0;
681
682     vlAllImportErrorGrid.dataLoader = function() {
683
684         vlAllImportErrorGrid.showLoadProgressIndicator();
685
686         fieldmapper.standardRequest(
687             ['open-ils.vandelay', 'open-ils.vandelay.import_item.queue.retrieve'],
688             {
689                 async : true,
690                 params : [
691                     authtoken, currentQueueId, {   
692                         with_import_error: (vlImportItemsShowErrors.checked) ? 1 : null,
693                         offset : vlAllImportErrorGrid.displayOffset,
694                         limit : vlAllImportErrorGrid.displayLimit
695                     }
696                 ],
697                 onresponse : function(r) {
698                     var item = openils.Util.readResponse(r);
699                     if(!item) return;
700                     vlAllImportErrorGrid.store.newItem(vii.toStoreItem(item));
701                 },
702                 oncomplete : function() {
703                     vlAllImportErrorGrid.hideLoadProgressIndicator();
704                 }
705             }
706         );
707     };
708
709     vlAllImportErrorGrid.dataLoader();
710 }
711
712 function vlGetOrg(rowIdx, item) {
713     if(!item) return '';
714     var value = this.grid.store.getValue(item, this.field);
715     if(value) return fieldmapper.aou.findOrgUnit(value).shortname();
716     return '';
717 }
718
719 function vlFormatViewMatchMARC(id) {
720     return '<a href="javascript:void(0);" onclick="vlLoadMARCHtml(' + id + ', true, '+
721         'function(){displayGlobalDiv(\'vl-match-div\');});">' + this.name + '</a>';
722 }
723
724 function getAttrValue(rowIdx, item) {
725     if(!item) return '';
726     var attrCode = this.field.split('.')[1];
727     var rec = queuedRecordsMap[this.grid.store.getValue(item, 'id')];
728     var attr = getRecAttrFromCode(rec, attrCode);
729     return (attr) ? attr.attr_value() : '';
730 }
731
732 function vlGetDateTimeField(rowIdx, item) {
733     if(!item) return '';
734     var value = this.grid.store.getValue(item, this.field);
735     if(!value) return '';
736     var date = dojo.date.stamp.fromISOString(value);
737     return dojo.date.locale.format(date, {selector:'date'});
738 }
739
740 function vlGetCreator(rowIdx, item) {
741     if(!item) return '';
742     var id = this.grid.store.getValue(item, 'creator');
743     if(userCache[id])
744         return userCache[id].usrname();
745     var user = fieldmapper.standardRequest(
746         ['open-ils.actor', 'open-ils.actor.user.retrieve'], [authtoken, id]);
747     if(e = openils.Event.parse(user))
748         return alert(e);
749     userCache[id] = user;
750     return user.usrname();
751 }
752
753 function vlGetViewMARC(rowIdx, item) {
754     return item && this.grid.store.getValue(item, 'id');
755 }
756
757 function vlFormatViewMARC(id) {
758     return '<a href="javascript:void(0);" onclick="vlLoadMARCHtml(' + id + ', false, '+
759         'function(){displayGlobalDiv(\'vl-queue-div\');});">' + this.name + '</a>';
760 }
761
762 function vlGetOverlayTargetSelector(rowIdx, item) {
763     if(!item) return;
764     return this.grid.store.getValue(item, '_id') + ':' + this.grid.store.getValue(item, 'id');
765 }
766
767 function vlFormatOverlayTargetSelector(val) {
768     if(!val) return '';
769     var parts = val.split(':');
770     var _id = parts[0];
771     var id = parts[1];
772     var value = '<input type="checkbox" name="vl-overlay-target-RECID" '+
773         'onclick="vlHandleOverlayTargetSelected(ID, GRIDID);" gridid="GRIDID" match="ID"/>';
774     value = value.replace(/GRIDID/g, _id);
775     value = value.replace(/RECID/g, currentImportRecId);
776     value = value.replace(/ID/g, id);
777     if(_id == currentOverlayRecordsMapGid[currentImportRecId])
778         return value.replace('/>', 'checked="checked"/>');
779     return value;
780 }
781
782
783 /**
784   * see if the user has enabled overlays for the current match set and, 
785   * if so, map the current import record to the overlay target.
786   */
787 function vlHandleOverlayTargetSelected(recId, gridId) {
788     var noneSelected = true;
789     var checkboxes = dojo.query('[name=vl-overlay-target-'+currentImportRecId+']');
790     for(var i = 0; i < checkboxes.length; i++) {
791         var checkbox = checkboxes[i];
792         var matchRecId = checkbox.getAttribute('match');
793         var gid = checkbox.getAttribute('gridid');
794         if(checkbox.checked) {
795             if(matchRecId == recId && gid == gridId) {
796                 noneSelected = false;
797                 currentOverlayRecordsMap[currentImportRecId] = matchRecId;
798                 currentOverlayRecordsMapGid[currentImportRecId] = gid;
799                 dojo.byId('vl-record-list-selected-' + currentImportRecId).checked = true;
800                 dojo.byId('vl-record-list-selected-' + currentImportRecId).parentNode.className = 'overlay_selected';
801             } else {
802                 checkbox.checked = false;
803             }
804         }
805     }
806
807     if(noneSelected) {
808         delete currentOverlayRecordsMap[currentImportRecId];
809         delete currentOverlayRecordsMapGid[currentImportRecId];
810         dojo.byId('vl-record-list-selected-' + currentImportRecId).checked = false;
811         dojo.byId('vl-record-list-selected-' + currentImportRecId).parentNode.className = '';
812     }
813 }
814
815 var valLastQueueType = null;
816 var vlQueueGridLayout = null;
817 function buildRecordGrid(type) {
818     displayGlobalDiv('vl-queue-div');
819
820     if(type == 'bib') {
821         openils.Util.show('vl-bib-queue-grid-wrapper');
822         openils.Util.hide('vl-auth-queue-grid-wrapper');
823         vlQueueGrid = vlBibQueueGrid;
824     } else {
825         openils.Util.show('vl-auth-queue-grid-wrapper');
826         openils.Util.hide('vl-bib-queue-grid-wrapper');
827         vlQueueGrid = vlAuthQueueGrid;
828     }
829
830
831     if(valLastQueueType != type) {
832         valLastQueueType = type;
833         vlQueueGridLayout = vlQueueGrid.attr('structure');
834         var defs = (type == 'bib') ? bibAttrDefs : authAttrDefs;
835         attrDefMap[type] = {};
836         for(var i = 0; i < defs.length; i++) {
837             var def = defs[i]
838             attrDefMap[type][def.code()] = def.id();
839             var col = {
840                 name:def.description(), 
841                 field:'attr.' + def.code(),
842                 get: getAttrValue,
843                 selectableColumn:true
844             };
845             vlQueueGridLayout[0].cells[0].push(col);
846         }
847     }
848
849     dojo.forEach(vlQueueGridLayout[0].cells[0], 
850         function(cell) { 
851             if(cell.field.match(/^\+/)) 
852                 cell.nonSelectable=true;
853         }
854     );
855
856     var storeData;
857     if(type == 'bib')
858         storeData = vqbr.toStoreData(queuedRecords);
859     else
860         storeData = vqar.toStoreData(queuedRecords);
861
862     var store = new dojo.data.ItemFileReadStore({data:storeData});
863     vlQueueGrid.setStore(store);
864
865     if(vlQueueGridColumePicker[type]) {
866         vlQueueGrid.update();
867     } else {
868
869         vlQueueGridColumePicker[type] =
870             new openils.widget.GridColumnPicker(
871                 authtoken, 'vandelay.queue.'+type, vlQueueGrid, vlQueueGridLayout);
872         vlQueueGridColumePicker[type].load();
873     }
874 }
875
876 function vlQueueGridPrevPage() {
877     var page = parseInt(vlQueueDisplayPage.getValue());
878     if(page < 2) return;
879     vlQueueDisplayPage.setValue(page - 1);
880     retrieveQueuedRecords(currentType, currentQueueId, handleRetrieveRecords);
881 }
882
883 function vlQueueGridNextPage() {
884     vlQueueDisplayPage.setValue(parseInt(vlQueueDisplayPage.getValue())+1);
885     retrieveQueuedRecords(currentType, currentQueueId, handleRetrieveRecords);
886 }
887
888 function vlDeleteQueue(type, queueId, onload) {
889     fieldmapper.standardRequest(
890         ['open-ils.vandelay', 'open-ils.vandelay.'+type+'_queue.delete'],
891         {   async: true,
892             params: [authtoken, queueId],
893             oncomplete: function(r) {
894                 var resp = r.recv().content();
895                 if(e = openils.Event.parse(resp))
896                     return alert(e);
897                 onload();
898             }
899         }
900     );
901 }
902
903
904 function vlQueueGridDrawSelectBox(rowIdx, item) {
905     return item &&  this.grid.store.getValue(item, 'id');
906 }
907
908 function vlQueueGridFormatSelectBox(id) {
909     var domId = 'vl-record-list-selected-' + id;
910     if (id) { selectableGridRecords[domId] = id; }
911     return "<div><input type='checkbox' id='"+domId+"'/></div>";
912 }
913
914 function vlSelectAllQueueGridRecords() {
915     for(var id in selectableGridRecords) 
916         dojo.byId(id).checked = true;
917 }
918 function vlSelectNoQueueGridRecords() {
919     for(var id in selectableGridRecords) 
920         dojo.byId(id).checked = false;
921 }
922 function vlToggleQueueGridSelect() {
923     if(dojo.byId('vl-queue-grid-row-selector').checked)
924         vlSelectAllQueueGridRecords();
925     else
926         vlSelectNoQueueGridRecords();
927 }
928
929 var handleRetrieveRecords = function() {
930     buildRecordGrid(currentType);
931     vlFetchQueueSummary(currentQueueId, currentType, 
932         function(summary) {
933             dojo.byId('vl-queue-summary-name').innerHTML = summary.queue.name();
934             dojo.byId('vl-queue-summary-total-count').innerHTML = summary.total +'';
935             dojo.byId('vl-queue-summary-import-count').innerHTML = summary.imported + '';
936             dojo.byId('vl-queue-summary-import-item-count').innerHTML = summary.total_items + '';
937             dojo.byId('vl-queue-summary-rec-error-count').innerHTML = summary.rec_import_errors + '';
938             dojo.byId('vl-queue-summary-item-error-count').innerHTML = summary.item_import_errors + '';
939         }
940     );
941 }
942
943 function vlFetchQueueSummary(qId, type, onload) {
944     fieldmapper.standardRequest(
945         ['open-ils.vandelay', 'open-ils.vandelay.'+type+'_queue.summary.retrieve'],
946         {   async: true,
947             params: [authtoken, qId],
948             oncomplete : function(r) {
949                 var summary = r.recv().content();
950                 if(e = openils.Event.parse(summary))
951                     return alert(e);
952                 return onload(summary);
953             }
954         }
955     );
956 }
957
958 function vlHandleQueueItemsAction(action) {
959
960     dojo.connect(
961         queueItemsImportCancelButton, 
962         'onClick', 
963         function() {
964             queueItemsImportDialog.hide();
965         }
966     );
967
968     dojo.connect(
969         queueItemsImportGoButton,
970         'onClick', 
971         function() {
972             queueItemsImportDialog.hide();
973
974             // hack to set the widgets the import funcs will be looking at.  Reset them below.
975             vlUploadQueueAutoImport.attr('value',  vlUploadQueueAutoImport2.attr('value'));
976             vlUploadQueueAutoOverlayExact.attr('value',  vlUploadQueueAutoOverlayExact2.attr('value'));
977             vlUploadQueueAutoOverlay1Match.attr('value',  vlUploadQueueAutoOverlay1Match2.attr('value'));
978             vlUploadMergeProfile.attr('value',  vlUploadMergeProfile2.attr('value'));
979
980             if(action == 'import') {
981                 vlImportSelectedRecords();
982             } else if(action == 'import_all') {
983                 vlImportAllRecords();
984             }
985             
986             // reset the widgets to prevent accidental future actions
987             vlUploadQueueAutoImport.attr('value',  false);
988             vlUploadQueueAutoImport2.attr('value', false);
989             vlUploadQueueAutoOverlayExact.attr('value', false);
990             vlUploadQueueAutoOverlayExact2.attr('value', false);
991             vlUploadQueueAutoOverlay1Match.attr('value', false);
992             vlUploadQueueAutoOverlay1Match2.attr('value', false);
993             vlUploadMergeProfile.attr('value', '');
994             vlUploadMergeProfile2.attr('value', '');
995         }
996     );
997
998     queueItemsImportDialog.show();
999 }
1000     
1001
1002 function vlImportSelectedRecords() {
1003     displayGlobalDiv('vl-generic-progress-with-total');
1004     var records = [];
1005
1006     for(var id in selectableGridRecords) {
1007         if(dojo.byId(id).checked) {
1008             var recId = selectableGridRecords[id];
1009             var rec = queuedRecordsMap[recId];
1010             if(!rec.import_time()) 
1011                 records.push(recId);
1012         }
1013     }
1014
1015     var options = {overlay_map : currentOverlayRecordsMap};
1016
1017     if(vlUploadQueueAutoOverlayExact.checked) {
1018         options.auto_overlay_exact = true;
1019         vlUploadQueueAutoOverlayExact.checked = false;
1020     }
1021
1022     if(vlUploadQueueAutoOverlay1Match.checked) {
1023         options.auto_overlay_1match = true;
1024         vlUploadQueueAutoOverlay1Match.checked = false;
1025     }
1026     
1027     var profile = vlUploadMergeProfile.attr('value');
1028     if(profile != null && profile != '') {
1029         options.merge_profile = profile;
1030     }
1031
1032     fieldmapper.standardRequest(
1033         ['open-ils.vandelay', 'open-ils.vandelay.'+currentType+'_record.list.import'],
1034         {   async: true,
1035             params: [authtoken, records, options],
1036             onresponse: function(r) {
1037                 var resp = r.recv().content();
1038                 if(e = openils.Event.parse(resp))
1039                     return alert(e);
1040                 if(resp.complete) {
1041                     return retrieveQueuedRecords(currentType, currentQueueId, handleRetrieveRecords);
1042                 } else {
1043                     vlControlledProgressBar.update({maximum:resp.total, progress:resp.progress});
1044                 }
1045             }, 
1046         }
1047     );
1048 }
1049
1050 function vlImportAllRecords() {
1051     vlImportRecordQueue(currentType, currentQueueId, false,
1052         function(){displayGlobalDiv('vl-queue-div');});
1053 }
1054
1055 function vlImportRecordQueue(type, queueId, noMatchOnly, onload) {
1056     displayGlobalDiv('vl-generic-progress-with-total');
1057     var method = 'open-ils.vandelay.bib_queue.import';
1058     if(noMatchOnly)
1059         method = method.replace('import', 'nomatch.import');
1060     if(type == 'auth')
1061         method = method.replace('bib', 'auth');
1062
1063     var options = {};
1064     if(vlUploadQueueAutoOverlayExact.checked) {
1065         options.auto_overlay_exact = true;
1066         vlUploadQueueAutoOverlayExact.checked = false;
1067     }
1068
1069     if(vlUploadQueueAutoOverlay1Match.checked) {
1070         options.auto_overlay_1match = true;
1071         vlUploadQueueAutoOverlay1Match.checked = false;
1072     }
1073     
1074     var profile = vlUploadMergeProfile.attr('value');
1075     if(profile != null && profile != '') {
1076         options.merge_profile = profile;
1077     }
1078
1079     fieldmapper.standardRequest(
1080         ['open-ils.vandelay', method],
1081         {   async: true,
1082             params: [authtoken, queueId, options],
1083             onresponse: function(r) {
1084                 var resp = r.recv().content();
1085                 if(e = openils.Event.parse(resp))
1086                     return alert(e);
1087                 vlControlledProgressBar.update({maximum:resp.total, progress:resp.progress});
1088             },
1089             oncomplete: function() {onload();}
1090         }
1091     );
1092 }
1093
1094
1095 /**
1096   * Create queue, upload MARC, process spool, load the newly created queue 
1097   */
1098 function batchUpload() {
1099     var queueName = dijit.byId('vl-queue-name').getValue();
1100     currentType = dijit.byId('vl-record-type').getValue();
1101
1102     var handleProcessSpool = function() {
1103         if(vlUploadQueueAutoImport.checked || vlUploadQueueAutoOverlayExact.checked || vlUploadQueueAutoOverlay1Match.checked) {
1104             var noMatchOnly = !vlUploadQueueAutoOverlayExact.checked && !vlUploadQueueAutoOverlay1Match.checked;
1105             vlImportRecordQueue(
1106                 currentType, 
1107                 currentQueueId, 
1108                 noMatchOnly,
1109                 function() {
1110                     retrieveQueuedRecords(currentType, currentQueueId, handleRetrieveRecords);
1111                 }
1112             );
1113         } else {
1114             retrieveQueuedRecords(currentType, currentQueueId, handleRetrieveRecords);
1115         }
1116     }
1117
1118     var handleUploadMARC = function(key) {
1119         dojo.style(dojo.byId('vl-upload-status-processing'), 'display', 'block');
1120         processSpool(key, currentQueueId, currentType, handleProcessSpool);
1121     };
1122
1123     var handleCreateQueue = function(queue) {
1124         currentQueueId = queue.id();
1125         uploadMARC(handleUploadMARC);
1126     };
1127     
1128     if(vlUploadQueueSelector.getValue() && !queueName) {
1129         currentQueueId = vlUploadQueueSelector.getValue();
1130         uploadMARC(handleUploadMARC);
1131     } else {
1132         createQueue(queueName, currentType, handleCreateQueue, 
1133             vlUploadQueueHoldingsImportProfile.attr('value'),
1134             vlUploadQueueMatchSet.attr('value')
1135         );
1136     }
1137 }
1138
1139
1140 function vlFleshQueueSelect(selector, type) {
1141     var data = (type == 'bib') ? vbq.toStoreData(allUserBibQueues) : vaq.toStoreData(allUserAuthQueues);
1142     selector.store = new dojo.data.ItemFileReadStore({data:data});
1143     selector.setValue(null);
1144     selector.setDisplayedValue('');
1145     if(data[0])
1146         selector.setValue(data[0].id());
1147
1148     var qInput = dijit.byId('vl-queue-name');
1149
1150     var selChange = function(val) {
1151         console.log('selector onchange');
1152         // user selected a queue from the selector;  clear the input and 
1153         // set the item import profile already defined for the queue
1154         var queue = allUserBibQueues.filter(function(q) { return (q.id() == val) })[0];
1155         if(val) {
1156             vlUploadQueueHoldingsImportProfile.attr('value', queue.item_attr_def() || '');
1157             vlUploadQueueHoldingsImportProfile.attr('disabled', true);
1158             vlUploadQueueMatchSet.attr('value', queue.match_set() || '');
1159             vlUploadQueueMatchSet.attr('disabled', true);
1160         } else {
1161             vlUploadQueueHoldingsImportProfile.attr('value', '');
1162             vlUploadQueueHoldingsImportProfile.attr('disabled', false);
1163             vlUploadQueueMatchSet.attr('value', '');
1164             vlUploadQueueMatchSet.attr('disabled', false);
1165         }
1166         dojo.disconnect(qInput._onchange);
1167         qInput.attr('value', '');
1168         qInput._onchange = dojo.connect(qInput, 'onChange', inputChange);
1169     }
1170     
1171     var inputChange = function(val) {
1172         console.log('qinput onchange');
1173         // user entered a new queue name. clear the selector 
1174         vlUploadQueueHoldingsImportProfile.attr('value', '');
1175         vlUploadQueueHoldingsImportProfile.attr('disabled', false);
1176         vlUploadQueueMatchSet.attr('value', '');
1177         vlUploadQueueMatchSet.attr('disabled', false);
1178         dojo.disconnect(selector._onchange);
1179         selector.attr('value', '');
1180         selector._onchange = dojo.connect(selector, 'onChange', selChange);
1181     }
1182
1183     selector._onchange = dojo.connect(selector, 'onChange', selChange);
1184     qInput._onchange = dojo.connect(qInput, 'onChange', inputChange);
1185 }
1186
1187 function vlUpdateMatchSetSelector(type) {
1188     type = (type.match(/bib/)) ? 'biblio' : 'authority';
1189     vlUploadQueueMatchSet.store = 
1190         new dojo.data.ItemFileReadStore({data:vms.toStoreData(matchSets[type])});
1191 }
1192
1193 function vlShowUploadForm() {
1194     displayGlobalDiv('vl-marc-upload-div');
1195     vlFleshQueueSelect(vlUploadQueueSelector, vlUploadRecordType.getValue());
1196     vlUploadSourceSelector.store = 
1197         new dojo.data.ItemFileReadStore({data:cbs.toStoreData(vlBibSources, 'source')});
1198     vlUploadSourceSelector.setValue(vlBibSources[0].id());
1199     vlUploadQueueHoldingsImportProfile.store = 
1200         new dojo.data.ItemFileReadStore({data:viiad.toStoreData(importItemDefs)});
1201     vlUpdateMatchSetSelector(vlUploadRecordType.getValue());
1202 }
1203
1204 function vlShowQueueSelect() {
1205     displayGlobalDiv('vl-queue-select-div');
1206     vlFleshQueueSelect(vlQueueSelectQueueList, vlQueueSelectType.getValue());
1207 }
1208
1209 function vlShowMatchSetEditor() {
1210     displayGlobalDiv('vl-match-set-editor-div');
1211     dojo.byId('vl-match-set-editor-div').appendChild(
1212         dojo.create('iframe', {
1213             id : 'vl-match-set-iframe',
1214             src : oilsBasePath + '/eg/conify/global/vandelay/match_set',
1215             style : 'width:100%; height:500px; border:none; margin:0px;'
1216         })
1217     );
1218 }
1219
1220 function vlFetchQueueFromForm() {
1221     currentType = vlQueueSelectType.getValue();
1222     currentQueueId = vlQueueSelectQueueList.getValue();
1223     retrieveQueuedRecords(currentType, currentQueueId, handleRetrieveRecords);
1224 }
1225
1226 function vlOpenMarcEditWindow(rec, postReloadHTMLHandler) {
1227     /*
1228         To run in Firefox directly, must set signed.applets.codebase_principal_support
1229         to true in about:config
1230     */
1231     netscape.security.PrivilegeManager.enablePrivilege('UniversalXPConnect');
1232     win = window.open('/xul/server/cat/marcedit.xul'); // XXX version?
1233
1234     var type;
1235     if (currentType == 'bib') {
1236         type = 'bre';
1237     } else {
1238         type = 'are';
1239     }
1240
1241     function onsave(r) {
1242         // after the record is saved, reload the HTML display
1243         var stat = r.recv().content();
1244         if(e = openils.Event.parse(stat))
1245             return alert(e);
1246         alert(dojo.byId('vl-marc-edit-complete-label').innerHTML);
1247         win.close();
1248         vlLoadMARCHtml(rec.id(), false, postReloadHTMLHandler);
1249     }
1250
1251     win.xulG = {
1252         record : {marc : rec.marc(), "rtype": type},
1253         save : {
1254             label: dojo.byId('vl-marc-edit-save-label').innerHTML,
1255             func: function(xmlString) {
1256                 var method = 'open-ils.permacrud.update.' + rec.classname;
1257                 rec.marc(xmlString);
1258                 fieldmapper.standardRequest(
1259                     ['open-ils.permacrud', method],
1260                     {   async: true,
1261                         params: [authtoken, rec],
1262                         oncomplete: onsave
1263                     }
1264                 );
1265             },
1266         },
1267         'lock_tab' : typeof xulG != 'undefined' ? (typeof xulG['lock_tab'] != 'undefined' ? xulG.lock_tab : undefined) : undefined,
1268         'unlock_tab' : typeof xulG != 'undefined' ? (typeof xulG['unlock_tab'] != 'undefined' ? xulG.unlock_tab : undefined) : undefined
1269     };
1270 }
1271
1272 function vlLoadMarcEditor(type, recId, postReloadHTMLHandler) {
1273     var method = 'open-ils.permacrud.search.vqbr';
1274     if(currentType != 'bib')
1275         method = method.replace(/vqbr/,'vqar');
1276
1277     fieldmapper.standardRequest(
1278         ['open-ils.permacrud', method],
1279         {   async: true, 
1280             params: [authtoken, {id : recId}],
1281             oncomplete: function(r) {
1282                 var rec = r.recv().content();
1283                 if(e = openils.Event.parse(rec))
1284                     return alert(e);
1285                 vlOpenMarcEditWindow(rec, postReloadHTMLHandler);
1286             }
1287         }
1288     );
1289 }
1290
1291
1292
1293 //------------------------------------------------------------
1294 // attribute editors
1295
1296 // attribute-editor global variables
1297
1298 var ATTR_EDITOR_IN_UPDATE_MODE = false; // true on 'edit', false on 'create'
1299 var ATTR_EDIT_ID = null;                // id of current 'edit' attribute
1300 var ATTR_EDIT_GROUP = 'bib';            // bib-attrs or auth-attrs
1301
1302 function vlAttrEditorInit() {
1303     // set up tooltips on the edit form
1304     connectTooltip('attr-editor-tags'); 
1305     connectTooltip('attr-editor-subfields'); 
1306 }
1307
1308 function vlShowAttrEditor() {
1309     displayGlobalDiv('vl-attr-editor-div');
1310     loadAttrEditorGrid();
1311     idHide('vl-generic-progress');
1312 }
1313
1314 function setAttrEditorGroup(groupName) {
1315     // put us into 'bib'-attr or 'auth'-attr mode.
1316     if (ATTR_EDIT_GROUP != groupName) {
1317         ATTR_EDIT_GROUP = groupName;
1318         loadAttrEditorGrid();
1319     }
1320 }
1321
1322 function onAttrEditorOpen() {
1323     // the "bars" have the create/update/cancel/etc. buttons.
1324     var create_bar = document.getElementById('attr-editor-create-bar');
1325     var update_bar = document.getElementById('attr-editor-update-bar');
1326     if (ATTR_EDITOR_IN_UPDATE_MODE) {
1327         update_bar.style.display='table-row';
1328         create_bar.style.display='none';
1329         // hide the dropdown-button
1330         idStyle('vl-create-attr-editor-button', 'visibility', 'hidden');
1331     } else {
1332         dijit.byId('attr-editor-dialog').reset();
1333         create_bar.style.display='table-row';
1334         update_bar.style.display='none';
1335     }
1336 }
1337
1338 function onAttrEditorClose() {
1339     // reset the form to a "create" form. (We may have borrowed it for editing.)
1340     ATTR_EDITOR_IN_UPDATE_MODE = false;
1341     // show the dropdown-button
1342     idStyle('vl-create-attr-editor-button', 'visibility', 'visible');
1343 }
1344
1345 function loadAttrEditorGrid() {
1346     var _data = (ATTR_EDIT_GROUP == 'auth') ? 
1347         vqarad.toStoreData(authAttrDefs) : vqbrad.toStoreData(bibAttrDefs) ;
1348
1349     var store = new dojo.data.ItemFileReadStore({data:_data});
1350     attrEditorGrid.setStore(store);
1351     attrEditorGrid.onRowDblClick = onAttrEditorClick;
1352     attrEditorGrid.update();
1353 }
1354
1355 function attrGridGetTag(n, item) {
1356     // grid helper: return the tags from the row's xpath column.
1357     return item && xpathParser.parse(this.grid.store.getValue(item, 'xpath')).tags;
1358 }
1359
1360 function attrGridGetSubfield(n, item) {
1361     // grid helper: return the subfields from the row's xpath column.
1362     return item && xpathParser.parse(this.grid.store.getValue(item, 'xpath')).subfields;
1363 }
1364
1365 function onAttrEditorClick() {
1366     var row = this.getItem(this.focus.rowIndex);
1367     ATTR_EDIT_ID = this.store.getValue(row, 'id');
1368     ATTR_EDITOR_IN_UPDATE_MODE = true;
1369
1370     // populate the popup editor.
1371     dijit.byId('attr-editor-code').attr('value', this.store.getValue(row, 'code'));
1372     dijit.byId('attr-editor-description').attr('value', this.store.getValue(row, 'description'));
1373     var parsed_xpath = xpathParser.parse(this.store.getValue(row, 'xpath'));
1374     dijit.byId('attr-editor-tags').attr('value', parsed_xpath.tags);
1375     dijit.byId('attr-editor-subfields').attr('value', parsed_xpath.subfields);
1376     dijit.byId('attr-editor-xpath').attr('value', this.store.getValue(row, 'xpath'));
1377     dijit.byId('attr-editor-remove').attr('value', this.store.getValue(row, 'remove'));
1378
1379     // set up UI for editing
1380     dojo.byId('vl-create-attr-editor-button').click();
1381 }
1382
1383 function vlSaveAttrDefinition(data) {
1384     idHide('vl-attr-editor-div');
1385     idShow('vl-generic-progress');
1386
1387     data.id = ATTR_EDIT_ID;
1388
1389     // this ought to honour custom xpaths, but overwrite xpaths
1390     // derived from tags/subfields.
1391     if (data.xpath == '' || looksLikeDerivedXpath(data.xpath)) {
1392         var _xpath = tagAndSubFieldsToXpath(data.tag, data.subfield);
1393         data.xpath = _xpath;
1394     }
1395
1396     // build up our permacrud params. Key variables here are
1397     // "create or update" and "bib or auth".
1398
1399     var isAuth   = (ATTR_EDIT_GROUP == 'auth');
1400     var isCreate = (ATTR_EDIT_ID == null);
1401     var rad      = isAuth ? new vqarad() : new vqbrad() ;
1402     var method   = 'open-ils.permacrud' + (isCreate ? '.create.' : '.update.') 
1403         + (isAuth ? 'vqarad' : 'vqbrad');
1404     var _data    = rad.fromStoreItem(data);
1405
1406     _data.ischanged(1);
1407
1408     fieldmapper.standardRequest(
1409         ['open-ils.permacrud', method],
1410         {   async: true,
1411             params: [authtoken, _data ],
1412             onresponse: function(r) { },
1413             oncomplete: function(r) {
1414                 attrEditorFetchAttrDefs(vlShowAttrEditor);
1415                 ATTR_EDIT_ID = null;
1416             },
1417             onerror: function(r) {
1418                 alert('vlSaveAttrDefinition comms error: ' + r);
1419             }
1420         }
1421     );
1422 }
1423
1424 function attrEditorFetchAttrDefs(callback) {
1425     var fn = (ATTR_EDIT_GROUP == 'auth') ? vlFetchAuthAttrDefs : vlFetchBibAttrDefs;
1426     return fn(callback);
1427 }
1428
1429 function vlAttrDelete() {
1430     idHide('vl-attr-editor-div');
1431     idShow('vl-generic-progress');
1432
1433     var isAuth = (ATTR_EDIT_GROUP == 'auth');
1434     var method = 'open-ils.permacrud.delete.' + (isAuth ? 'vqarad' : 'vqbrad');
1435     var rad    = isAuth ? new vqarad() : new vqbrad() ;
1436     fieldmapper.standardRequest(
1437         ['open-ils.permacrud', method],
1438         {   async: true,
1439             params: [authtoken, rad.fromHash({ id : ATTR_EDIT_ID }), ],
1440             oncomplete: function() {
1441                 dijit.byId('attr-editor-dialog').onCancel(); // close the dialog
1442                 attrEditorFetchAttrDefs(vlShowAttrEditor);
1443                 ATTR_EDIT_ID = null;
1444             },
1445             onerror: function(r) {
1446                 alert('vlAttrDelete comms error: ' + r);
1447             }
1448         }
1449     );
1450 }
1451
1452 // ------------------------------------------------------------
1453 // utilities for attribute editors
1454
1455 // dom utilities (maybe dojo does these, and these should be replaced)
1456
1457 function idStyle(obId, k, v)    { document.getElementById(obId).style[k] = v;   }
1458 function idShow(obId)           { idStyle(obId, 'display', 'block');            }
1459 function idHide(obId)           { idStyle(obId, 'display' , 'none');            }
1460
1461 function connectTooltip(fieldId) {
1462     // Given an element id, look up a tooltip element in the doc (same
1463     // id with a '-tip' suffix) and associate the two. Maybe dojo has
1464     // a better way to do this?
1465     var fld = dojo.byId(fieldId);
1466     var tip = dojo.byId(fieldId + '-tip');
1467     dojo.connect(fld, 'onfocus', function(evt) {
1468                      dijit.showTooltip(tip.innerHTML, fld, ['below', 'after']); });
1469     dojo.connect(fld, 'onblur', function(evt) { dijit.hideTooltip(fld); });
1470 }
1471
1472 // xpath utilities
1473
1474 var xpathParser = new openils.MarcXPathParser();
1475
1476 function tagAndSubFieldsToXpath(tags, subfields) {
1477     // given tags, and subfields, build up an XPath.
1478     try {
1479         var parts = {
1480             'tags':tags.match(/[\d]+/g), 
1481             'subfields':subfields.match(/[a-zA-z]/g) };
1482         return xpathParser.compile(parts);
1483     } catch (err) {
1484         return {'parts':null, 'tags':null, 'error':err};
1485     }
1486 }
1487
1488 function looksLikeDerivedXpath(path) {
1489     // Does this path look like it was derived from tags and subfields?
1490     var parsed = xpathParser.parse(path);
1491     if (parsed.tags == null) 
1492         return false;
1493     var compiled = xpathParser.compile(parsed);
1494     return (path == compiled);
1495 }
1496
1497 // amazing xpath-util unit-tests
1498 if (!looksLikeDerivedXpath('//*[@tag="901"]/*[@code="c"]'))     alert('vandelay xpath-utility error');
1499 if ( looksLikeDerivedXpath('ba-boo-ba-boo!'))                   alert('vandelay xpath-utility error');
1500
1501
1502
1503 var profileContextOrg
1504 function vlShowProfileEditor() {
1505     displayGlobalDiv('vl-profile-editor-div');
1506     buildProfileGrid();
1507
1508     var connect = function() {
1509         dojo.connect(profileContextOrgSelector, 'onChange',
1510             function() {
1511                 profileContextOrg = this.attr('value');
1512                 pGrid.resetStore();
1513                 buildProfileGrid();
1514             }
1515         );
1516     };
1517
1518     new openils.User().buildPermOrgSelector(
1519         'ADMIN_MERGE_PROFILE', profileContextOrgSelector, null, connect);
1520 }
1521
1522 function buildProfileGrid() {
1523
1524     if(profileContextOrg == null)
1525         profileContextOrg = openils.User.user.ws_ou();
1526
1527     pGrid.loadAll( 
1528         {order_by : {vmp : 'name'}}, 
1529         {owner : fieldmapper.aou.fullPath(profileContextOrg, true)}
1530     );
1531 }
1532
1533 /* --- Import Item Attr Grid --------------- */
1534
1535 var itemAttrContextOrg;
1536 function vlShowImportItemAttrEditor() {
1537     displayGlobalDiv('vl-item-attr-editor-div');
1538     buildImportItemAttrGrid();
1539
1540     var connect = function() {
1541         dojo.connect(itemAttrContextOrgSelector, 'onChange',
1542             function() {
1543                 itemAttrContextOrg = this.attr('value');
1544                 itemAttrGrid.resetStore();
1545                 vlShowImportItemAttrEditor();
1546             }
1547         );
1548     };
1549
1550     new openils.User().buildPermOrgSelector(
1551         'ADMIN_IMPORT_ITEM_ATTR_DEF', 
1552             itemAttrContextOrgSelector, null, connect);
1553 }
1554
1555 function buildImportItemAttrGrid() {
1556
1557     if(itemAttrContextOrg == null)
1558         itemAttrContextOrg = openils.User.user.ws_ou();
1559
1560     itemAttrGrid.loadAll( 
1561         {order_by : {viiad : 'name'}}, 
1562         {owner : fieldmapper.aou.fullPath(itemAttrContextOrg, true)}
1563     );
1564 }
1565