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