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