removed duplicate require
[Evergreen.git] / Open-ILS / web / 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.Button"); 
19 dojo.require("dijit.form.FilteringSelect"); 
20 dojo.require("dijit.layout.LayoutContainer");
21 dojo.require("dijit.layout.ContentPane");
22 dojo.require("dijit.layout.TabContainer");
23 dojo.require('dijit.form.Button');
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.Grid");
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('openils.CGI');
36 dojo.require('openils.User');
37 dojo.require('openils.Event');
38 dojo.require('openils.MarcXPathParser');
39 dojo.require('openils.GridColumnPicker');
40
41
42 var globalDivs = [
43     'vl-generic-progress',
44     'vl-generic-progress-with-total',
45     'vl-marc-upload-div',
46     'vl-queue-div',
47     'vl-match-div',
48     'vl-marc-html-div',
49     'vl-queue-select-div',
50     'vl-marc-upload-status-div',
51     'vl-bib-attr-defs-div',
52 ];
53
54 var authtoken;
55 var VANDELAY_URL = '/vandelay-upload';
56 var bibAttrDefs = [];
57 var authAttrDefs = [];
58 var queuedRecords = [];
59 var queuedRecordsMap = {};
60 var bibAttrsFetched = false;
61 var authAttrsFetched = false;
62 var attrDefMap = {}; // maps attr def code names to attr def ids
63 var currentType;
64 var currentQueueId = null;
65 var userCache = {};
66 var currentMatchedRecords; // set of loaded matched bib records
67 var currentOverlayRecordsMap; // map of import record to overlay record
68 var currentImportRecId; // when analyzing matches, this is the current import record
69 var userBibQueues = []; // only non-complete queues
70 var userAuthQueues = []; // only non-complete queues
71 var allUserBibQueues;
72 var allUserAuthQueues;
73 var selectableGridRecords;
74 var cgi = new openils.CGI();
75 var vlQueueGridColumePicker;
76
77 /**
78   * Grab initial data
79   */
80 function vlInit() {
81     authtoken = dojo.cookie('ses') || cgi.param('ses');
82     var initNeeded = 4; // how many async responses do we need before we're init'd 
83     var initCount = 0; // how many async reponses we've received
84
85     function checkInitDone() {
86         initCount++;
87         if(initCount == initNeeded)
88             runStartupCommands();
89     }
90
91     // Fetch the bib and authority attribute definitions
92     fieldmapper.standardRequest(
93         ['open-ils.permacrud', 'open-ils.permacrud.search.vqbrad'],
94         {   async: true,
95             params: [authtoken, {id:{'!=':null}}],
96             onresponse: function(r) {
97                 var def = r.recv().content(); 
98                 if(e = openils.Event.parse(def[0])) 
99                     return alert(e);
100                 bibAttrDefs.push(def);
101             },
102             oncomplete: function() {
103                 bibAttrDefs = bibAttrDefs.sort(
104                     function(a, b) {
105                         if(a.id() > b.id()) return 1;
106                         if(a.id() < b.id()) return -1;
107                         return 0;
108                     }
109                 );
110                 checkInitDone();
111             }
112         }
113     );
114
115     fieldmapper.standardRequest(
116         ['open-ils.permacrud', 'open-ils.permacrud.search.vqarad'],
117         {   async: true,
118             params: [authtoken, {id:{'!=':null}}],
119             onresponse: function(r) {
120                 var def = r.recv().content(); 
121                 if(e = openils.Event.parse(def[0])) 
122                     return alert(e);
123                 authAttrDefs.push(def);
124             },
125             oncomplete: function() {
126                 authAttrDefs = authAttrDefs.sort(
127                     function(a, b) {
128                         if(a.id() > b.id()) return 1;
129                         if(a.id() < b.id()) return -1;
130                         return 0;
131                     }
132                 );
133                 checkInitDone();
134             }
135         }
136     );
137
138     vlRetrieveQueueList('bib', null, 
139         function(list) {
140             allUserBibQueues = list;
141             for(var i = 0; i < allUserBibQueues.length; i++) {
142                 if(allUserBibQueues[i].complete() == 'f')
143                     userBibQueues.push(allUserBibQueues[i]);
144             }
145             checkInitDone();
146         }
147     );
148
149     vlRetrieveQueueList('auth', null, 
150         function(list) {
151             allUserAuthQueues = list;
152             for(var i = 0; i < allUserAuthQueues.length; i++) {
153                 if(allUserAuthQueues[i].complete() == 'f')
154                     userAuthQueues.push(allUserAuthQueues[i]);
155             }
156             checkInitDone();
157         }
158     );
159
160     bibAttrInit();
161 }
162
163 function vlRetrieveQueueList(type, filter, onload) {
164     type = (type == 'bib') ? type : 'authority';
165     fieldmapper.standardRequest(
166         ['open-ils.vandelay', 'open-ils.vandelay.'+type+'_queue.owner.retrieve.atomic'],
167         {   async: true,
168             params: [authtoken, null, filter],
169             oncomplete: function(r) {
170                 var list = r.recv().content();
171                 if(e = openils.Event.parse(list[0]))
172                     return alert(e);
173                 onload(list);
174             }
175         }
176     );
177
178 }
179
180 function displayGlobalDiv(id) {
181     for(var i = 0; i < globalDivs.length; i++) {
182         try {
183             dojo.style(dojo.byId(globalDivs[i]), 'display', 'none');
184         } catch(e) {
185             alert('please define div ' + globalDivs[i]);
186         }
187     }
188     dojo.style(dojo.byId(id),'display','block');
189 }
190
191 function runStartupCommands() {
192     currentQueueId = cgi.param('qid');
193     currentType = cgi.param('qtype');
194     if(currentQueueId)
195         return retrieveQueuedRecords(currentType, currentQueueId, handleRetrieveRecords);
196     vlShowUploadForm();
197
198 }
199
200 /**
201   * asynchronously upload a file of MARC records
202   */
203 function uploadMARC(onload){
204     dojo.byId('vl-upload-status-count').innerHTML = '0';
205     dojo.byId('vl-ses-input').value = authtoken;
206     displayGlobalDiv('vl-marc-upload-status-div');
207     dojo.io.iframe.send({
208         url: VANDELAY_URL,
209         method: "post",
210         handleAs: "html",
211         form: dojo.byId('vl-marc-upload-form'),
212         handle: function(data,ioArgs){
213             var content = data.documentElement.textContent;
214             onload(content);
215         }
216     });
217 }       
218
219 /**
220   * Creates a new vandelay queue
221   */
222 function createQueue(queueName, type, onload) {
223     fieldmapper.standardRequest(
224         ['open-ils.vandelay', 'open-ils.vandelay.'+type+'_queue.create'],
225         {   async: true,
226             params: [authtoken, queueName, null, type],
227             oncomplete : function(r) {
228                 var queue = r.recv().content();
229                 if(e = openils.Event.parse(queue)) 
230                     return alert(e);
231                 onload(queue);
232             }
233         }
234     );
235 }
236
237 /**
238   * Tells vendelay to pull a batch of records from the cache and explode them
239   * out into the vandelay tables
240   */
241 function processSpool(key, queueId, type, onload) {
242     fieldmapper.standardRequest(
243         ['open-ils.vandelay', 'open-ils.vandelay.'+type+'.process_spool'],
244         {   async: true,
245             params: [authtoken, key, queueId],
246             onresponse : function(r) {
247                 var resp = r.recv().content();
248                 if(e = openils.Event.parse(resp)) 
249                     return alert(e);
250                 dojo.byId('vl-upload-status-count').innerHTML = resp;
251             },
252             oncomplete : function(r) {onload();}
253         }
254     );
255 }
256
257 function retrieveQueuedRecords(type, queueId, onload) {
258     displayGlobalDiv('vl-generic-progress');
259     queuedRecords = [];
260     queuedRecordsMap = {};
261     currentOverlayRecordsMap = {};
262     selectableGridRecords = {};
263     resetVlQueueGridLayout();
264
265     var method = 'open-ils.vandelay.'+type+'_queue.records.retrieve.atomic';
266     if(vlQueueGridShowMatches.checked)
267         method = method.replace('records', 'records.matches');
268     var params = [authtoken, queueId, {clear_marc: 1, offset: offset, limit: limit}];
269
270     if(vlQueueGridShowNonImport.checked)
271         params[2].non_imported = 1;
272         
273
274     var limit = parseInt(vlQueueDisplayLimit.getValue());
275     var offset = limit * parseInt(vlQueueDisplayPage.getValue()-1);
276
277     fieldmapper.standardRequest(
278         ['open-ils.vandelay', method],
279         {   async: true,
280             params: params,
281
282             /* intermittent bug in streaming, multipart requests prevents use of onreponse for now...
283             onresponse: function(r) {
284                 var rec = r.recv().content();
285                 if(e = openils.Event.parse(rec))
286                     return alert(e);
287                 queuedRecords.push(rec);
288                 queuedRecordsMap[rec.id()] = rec;
289             },
290             */
291             oncomplete: function(r){
292                 var recs = r.recv().content();
293                 if(e = openils.Event.parse(recs[0]))
294                     return alert(e);
295                 for(var i = 0; i < recs.length; i++) {
296                     var rec = recs[i];
297                     queuedRecords.push(rec);
298                     queuedRecordsMap[rec.id()] = rec;
299                 }
300                 onload();
301             }
302         }
303     );
304 }
305
306 //function vlLoadMatchUI(recId, attrCode) {
307 function vlLoadMatchUI(recId) {
308     displayGlobalDiv('vl-generic-progress');
309     //var matches = getRecMatchesFromAttrCode(queuedRecordsMap[recId], attrCode);
310     var matches = queuedRecordsMap[recId].matches();
311     var records = [];
312     currentImportRecId = recId;
313     for(var i = 0; i < matches.length; i++)
314         records.push(matches[i].eg_record());
315
316     var retrieve = ['open-ils.search', 'open-ils.search.biblio.record_entry.slim.retrieve'];
317     var params = [records];
318     if(currentType == 'auth') {
319         retrieve = ['open-ils.cat', 'open-ils.cat.authority.record.retrieve'];
320         parmas = [authtoken, records, {clear_marc:1}];
321     }
322
323     fieldmapper.standardRequest(
324         retrieve,
325         {   async: true,
326             params:params,
327             oncomplete: function(r) {
328                 var recs = r.recv().content();
329                 if(e = openils.Event.parse(recs))
330                     return alert(e);
331
332                 /* ui mangling */
333                 displayGlobalDiv('vl-match-div');
334                 resetVlMatchGridLayout();
335                 currentMatchedRecords = recs;
336                 vlMatchGrid.setStructure(vlMatchGridLayout);
337
338                 // build the data store of records with match information
339                 var dataStore = bre.toStoreData(recs, null, 
340                     {virtualFields:['dest_matchpoint', 'src_matchpoint', '_id']});
341                 dataStore.identifier = '_id';
342
343
344                 for(var i = 0; i < dataStore.items.length; i++) {
345                     var item = dataStore.items[i];
346                     item._id = i; // just need something unique
347                     for(var j = 0; j < matches.length; j++) {
348                         var match = matches[j];
349                         if(match.eg_record() == item.id) {
350                             item.dest_matchpoint = match.field_type();
351                             var attr = getRecAttrFromMatch(queuedRecordsMap[recId], match);
352                             //item.src_matchpoint = getRecAttrDefFromAttr(attr, currentType).description();
353                             item.src_matchpoint = getRecAttrDefFromAttr(attr, currentType).code();
354                         }
355                     }
356                 }
357
358                 // now populate the grid
359                 vlPopulateGrid(vlMatchGrid, dataStore);
360             }
361         }
362     );
363 }
364
365 function vlPopulateGrid(grid, data) {
366     var store = new dojo.data.ItemFileReadStore({data:data});
367     var model = new dojox.grid.data.DojoData(
368         null, store, {rowsPerPage: 100, clientSort: true, query:{id:'*'}});
369     grid.setModel(model);
370     grid.update();
371 }
372
373
374 function vlLoadMARCHtml(recId, inCat, oncomplete) {
375     dijit.byId('vl-marc-html-done-button').onClick = oncomplete;
376     displayGlobalDiv('vl-generic-progress');
377     var api;
378     var params = [recId, 1];
379     if(inCat) {
380         api = ['open-ils.search', 'open-ils.search.biblio.record.html'];
381         if(currentType == 'auth')
382             api = ['open-ils.search', 'open-ils.search.authority.to_html'];
383     } else {
384         params = [authtoken, recId];
385         api = ['open-ils.vandelay', 'open-ils.vandelay.queued_bib_record.html'];
386         if(currentType == 'auth')
387             api = ['open-ils.vandelay', 'open-ils.vandelay.queued_authority_record.html'];
388     }
389     fieldmapper.standardRequest(
390         api, 
391         {   async: true,
392             params: params,
393             oncomplete: function(r) {
394             displayGlobalDiv('vl-marc-html-div');
395                 var html = r.recv().content();
396                 dojo.byId('vl-marc-record-html').innerHTML = html;
397             }
398         }
399     );
400 }
401
402
403 /*
404 function getRecMatchesFromAttrCode(rec, attrCode) {
405     var matches = [];
406     var attr = getRecAttrFromCode(rec, attrCode);
407     for(var j = 0; j < rec.matches().length; j++) {
408         var match = rec.matches()[j];
409         if(match.matched_attr() == attr.id()) 
410             matches.push(match);
411     }
412     return matches;
413 }
414 */
415
416 function getRecAttrFromMatch(rec, match) {
417     for(var i = 0; i < rec.attributes().length; i++) {
418         var attr = rec.attributes()[i];
419         if(attr.id() == match.matched_attr())
420             return attr;
421     }
422 }
423
424 function getRecAttrDefFromAttr(attr, type) {
425     var defs = (type == 'bib') ? bibAttrDefs : authAttrDefs;
426     for(var i = 0; i < defs.length; i++) {
427         var def = defs[i];
428         if(def.id() == attr.field())
429             return def;
430     }
431 }
432
433 function getRecAttrFromCode(rec, attrCode) {
434     var defId = attrDefMap[attrCode];
435     var attrs = rec.attributes();
436     for(var i = 0; i < attrs.length; i++) {
437         var attr = attrs[i];
438         if(attr.field() == defId) 
439             return attr;
440     }
441     return null;
442 }
443
444 function vlGetViewMatches(rowIdx) {
445     var data = this.grid.model.getRow(rowIdx);
446     if(!data) return '';
447     var rec = queuedRecordsMap[data.id];
448     if(rec.matches().length > 0)
449         return this.value.replace('RECID', data.id);
450     return '';
451 }
452
453 function getAttrValue(rowIdx) {
454     var data = this.grid.model.getRow(rowIdx);
455     if(!data) return '';
456     var attrCode = this.field.split('.')[1];
457     var rec = queuedRecordsMap[data.id];
458     var attr = getRecAttrFromCode(rec, attrCode);
459     return (attr) ? attr.attr_value() : '';
460 }
461
462 function vlGetDateTimeField(rowIdx) {
463     data = this.grid.model.getRow(rowIdx);
464     if(!data) return '';
465     if(!data[this.field]) return '';
466     var date = dojo.date.stamp.fromISOString(data[this.field]);
467     return dojo.date.locale.format(date, {selector:'date'});
468 }
469
470 function vlGetCreator(rowIdx) {
471     data = this.grid.model.getRow(rowIdx);
472     if(!data) return '';
473     var id = data.creator;
474     if(userCache[id])
475         return userCache[id].usrname();
476     var user = fieldmapper.standardRequest(
477         ['open-ils.actor', 'open-ils.actor.user.retrieve'], [authtoken, id]);
478     if(e = openils.Event.parse(user))
479         return alert(e);
480     userCache[id] = user;
481     return user.usrname();
482 }
483
484 function vlGetViewMARC(rowIdx) {
485     data = this.grid.model.getRow(rowIdx);
486     if(data) 
487         return this.value.replace('RECID', data.id);
488 }
489
490 function vlGetOverlayTargetSelector(rowIdx) {
491     data = this.grid.model.getRow(rowIdx);
492     if(data) {
493         var value = this.value.replace('ID', data.id);
494         var overlay = currentOverlayRecordsMap[currentImportRecId];
495         if(overlay && overlay == data.id) 
496             value = value.replace('/>', 'checked="checked"/>');
497         return value;
498     }
499 }
500
501 /**
502   * see if the user has enabled overlays for the current match set and, 
503   * if so, map the current import record to the overlay target.
504   */
505 function vlHandleOverlayTargetSelected() {
506     if(vlOverlayTargetEnable.checked) {
507         for(var i = 0; i < currentMatchedRecords.length; i++) {
508             var matchRecId = currentMatchedRecords[i].id();
509             if(dojo.byId('vl-overlay-target-'+matchRecId).checked) {
510                 console.log("found overlay target " + matchRecId);
511                 currentOverlayRecordsMap[currentImportRecId] = matchRecId;
512                 dojo.byId('vl-record-list-selected-' + currentImportRecId).checked = true;
513                 dojo.byId('vl-record-list-selected-' + currentImportRecId).parentNode.className = 'overlay_selected';
514                 return;
515             }
516         }
517     } else {
518         delete currentOverlayRecordsMap[currentImportRecId];
519         dojo.byId('vl-record-list-selected-' + currentImportRecId).checked = false;
520     }
521 }
522
523 var vlQueueGridBuilt = false;
524 function buildRecordGrid(type) {
525     displayGlobalDiv('vl-queue-div');
526
527     currentOverlayRecordsMap = {};
528
529     if(!vlQueueGridBuilt) {
530         var defs = (type == 'bib') ? bibAttrDefs : authAttrDefs;
531         for(var i = 0; i < defs.length; i++) {
532             var def = defs[i]
533             attrDefMap[def.code()] = def.id();
534             var col = {
535                 name:def.description(), 
536                 field:'attr.' + def.code(),
537                 get: getAttrValue,
538                 selectableColumn:true
539             };
540             vlQueueGridLayout[0].cells[0].push(col);
541         }
542         vlQueueGridBuilt = true;
543     }
544
545     var storeData;
546     if(type == 'bib')
547         storeData = vqbr.toStoreData(queuedRecords);
548     else
549         storeData = vqar.toStoreData(queuedRecords);
550
551     var store = new dojo.data.ItemFileReadStore({data:storeData});
552     var model = new dojox.grid.data.DojoData(
553         null, store, {rowsPerPage: 100, clientSort: true, query:{id:'*'}});
554
555     vlQueueGrid.setModel(model);
556     if(vlQueueGridColumePicker) 
557         vlQueueGrid.setStructure(vlQueueGridColumePicker.structure);
558     else
559         vlQueueGrid.setStructure(vlQueueGridLayout);
560     vlQueueGrid.update();
561
562     if(!vlQueueGridColumePicker) {
563         vlQueueGridColumePicker = 
564             new openils.GridColumnPicker(vlQueueGridColumePickerDialog, vlQueueGrid);
565     }
566 }
567
568 function vlQueueGridPrevPage() {
569     var page = parseInt(vlQueueDisplayPage.getValue());
570     if(page < 2) return;
571     vlQueueDisplayPage.setValue(page - 1);
572     retrieveQueuedRecords(currentType, currentQueueId, handleRetrieveRecords);
573 }
574
575 function vlQueueGridNextPage() {
576     vlQueueDisplayPage.setValue(parseInt(vlQueueDisplayPage.getValue())+1);
577     retrieveQueuedRecords(currentType, currentQueueId, handleRetrieveRecords);
578 }
579
580 function vlDeleteQueue(type, queueId, onload) {
581     fieldmapper.standardRequest(
582         ['open-ils.vandelay', 'open-ils.vandelay.'+type+'_queue.delete'],
583         {   async: true,
584             params: [authtoken, queueId],
585             oncomplete: function(r) {
586                 var resp = r.recv().content();
587                 if(e = openils.Event.parse(resp))
588                     return alert(e);
589                 onload();
590             }
591         }
592     );
593 }
594
595
596 function vlQueueGridDrawSelectBox(rowIdx) {
597     var data = this.grid.model.getRow(rowIdx);
598     if(!data) return '';
599     var domId = 'vl-record-list-selected-' +data.id;
600     selectableGridRecords[domId] = data.id;
601     return "<div><input type='checkbox' id='"+domId+"'/></div>";
602 }
603
604 function vlSelectAllQueueGridRecords() {
605     for(var id in selectableGridRecords) 
606         dojo.byId(id).checked = true;
607 }
608 function vlSelectNoQueueGridRecords() {
609     for(var id in selectableGridRecords) 
610         dojo.byId(id).checked = false;
611 }
612 function vlToggleQueueGridSelect() {
613     if(dojo.byId('vl-queue-grid-row-selector').checked)
614         vlSelectAllQueueGridRecords();
615     else
616         vlSelectNoQueueGridRecords();
617 }
618
619 var handleRetrieveRecords = function() {
620     buildRecordGrid(currentType);
621 }
622
623 function vlImportSelectedRecords() {
624     displayGlobalDiv('vl-generic-progress-with-total');
625     var records = [];
626
627     for(var id in selectableGridRecords) {
628         if(dojo.byId(id).checked) {
629             var recId = selectableGridRecords[id];
630             var rec = queuedRecordsMap[recId];
631             if(!rec.import_time()) 
632                 records.push(recId);
633         }
634     }
635
636     fieldmapper.standardRequest(
637         ['open-ils.vandelay', 'open-ils.vandelay.'+currentType+'_record.list.import'],
638         {   async: true,
639             params: [authtoken, records, {overlay_map:currentOverlayRecordsMap}],
640             onresponse: function(r) {
641                 var resp = r.recv().content();
642                 if(e = openils.Event.parse(resp))
643                     return alert(e);
644                 vlControlledProgressBar.update({maximum:resp.total, progress:resp.progress});
645             },
646             oncomplete: function() {
647                 return retrieveQueuedRecords(currentType, currentQueueId, handleRetrieveRecords);
648             }
649         }
650     );
651 }
652
653 function vlImportRecordQueue(type, queueId, noMatchOnly, onload) {
654     displayGlobalDiv('vl-generic-progress-with-total');
655     var method = 'open-ils.vandelay.bib_queue.import';
656     if(noMatchOnly)
657         method = method.replace('import', 'nomatch.import');
658     if(type == 'auth')
659         method = method.replace('bib', 'auth');
660
661     fieldmapper.standardRequest(
662         ['open-ils.vandelay', method],
663         {   async: true,
664             params: [authtoken, queueId],
665             onresponse: function(r) {
666                 var resp = r.recv().content();
667                 if(e = openils.Event.parse(resp))
668                     return alert(e);
669                 vlControlledProgressBar.update({maximum:resp.total, progress:resp.progress});
670             },
671             oncomplete: function() {onload();}
672         }
673     );
674 }
675
676
677 /**
678   * Create queue, upload MARC, process spool, load the newly created queue 
679   */
680 function batchUpload() {
681     var queueName = dijit.byId('vl-queue-name').getValue();
682     currentType = dijit.byId('vl-record-type').getValue();
683
684     var handleProcessSpool = function() {
685         console.log('records uploaded and spooled');
686         if(vlUploadQueueAutoImport.checked) {
687             vlImportRecordQueue(currentType, currentQueueId, true,  
688                 function() {
689                     retrieveQueuedRecords(currentType, currentQueueId, handleRetrieveRecords);
690                 }
691             );
692         } else {
693             retrieveQueuedRecords(currentType, currentQueueId, handleRetrieveRecords);
694         }
695     }
696
697     var handleUploadMARC = function(key) {
698         console.log('marc uploaded');
699         dojo.style(dojo.byId('vl-upload-status-processing'), 'display', 'block');
700         processSpool(key, currentQueueId, currentType, handleProcessSpool);
701     };
702
703     var handleCreateQueue = function(queue) {
704         console.log('queue created ' + queue.name());
705         currentQueueId = queue.id();
706         uploadMARC(handleUploadMARC);
707     };
708     
709     if(vlUploadQueueSelector.getValue() && !queueName) {
710         currentQueueId = vlUploadQueueSelector.getValue();
711         console.log('adding records to existing queue ' + currentQueueId);
712         uploadMARC(handleUploadMARC);
713     } else {
714         createQueue(queueName, currentType, handleCreateQueue);
715     }
716 }
717
718
719 function vlFleshQueueSelect(selector, type) {
720     var data = (type == 'bib') ? vbq.toStoreData(allUserBibQueues) : vaq.toStoreData(allUserAuthQueues);
721     selector.store = new dojo.data.ItemFileReadStore({data:data});
722     selector.setValue(null);
723     selector.setDisplayedValue('');
724     if(data[0])
725         selector.setValue(data[0].id());
726 }
727
728 function vlShowUploadForm() {
729     displayGlobalDiv('vl-marc-upload-div');
730     vlFleshQueueSelect(vlUploadQueueSelector, vlUploadRecordType.getValue());
731 }
732
733 function vlShowQueueSelect() {
734     displayGlobalDiv('vl-queue-select-div');
735     vlFleshQueueSelect(vlQueueSelectQueueList, vlQueueSelectType.getValue());
736 }
737
738 function vlFetchQueueFromForm() {
739     currentType = vlQueueSelectType.getValue();
740     currentQueueId = vlQueueSelectQueueList.getValue();
741     retrieveQueuedRecords(currentType, currentQueueId, handleRetrieveRecords);
742 }
743
744 dojo.addOnLoad(vlInit);
745
746
747 //------------------------------------------------------------
748 // bib-attr, auth-attr 
749
750 function bibAttrInit() {
751     // set up tooltips on attr_record forms
752     connectTooltip('bib-attr-tag'); 
753     connectTooltip('bib-attr-subfield'); 
754 }
755
756 function vlShowBibAttrDefs() {
757     displayGlobalDiv('vl-bib-attr-defs-div');
758     loadBibAttrGrid();
759 }
760
761 function idStyle(obid, k, v) { document.getElementById(obid).style[k] = v; }
762 function show(obid) { idStyle(obid, 'display', 'block'); }
763 function hide(obid) { idStyle(obid, 'display' , 'none'); }
764 function textOf(obid) { return document.getElementById(obid).innerHTML; }
765
766 function saveNewBibAttrRecord(arg) {
767     // pretend to save...
768     hide('vl-bib-attr-defs-div');
769     show('vl-generic-progress');
770     // not really saving anything yet. For now, just remove the
771     // progress bar after a moment and return to the table.
772     setTimeout("show('vl-bib-attr-defs-div');hide('vl-generic-progress');", 1000);
773 }
774
775 function onAttrEditorOpen() {
776 }
777
778 function onAttrEditorClose() {
779     // reset the form to a "create" form. (We may have borrowed it for "editing".)
780     var dialog = dojo.byId('bib-attr-dialog');
781     var create_bar = dialog.getElementsByClassName('create_bar')[0];
782     var update_bar = dialog.getElementsByClassName('update_bar')[0];
783     create_bar.style.display='table-row';
784     update_bar.style.display='none';
785     idStyle('vl-create-bib-attr-button', 'visibility', 'visible');
786     dijit.byId('bib-attr-dialog').reset();
787 }
788
789 function loadBibAttrGrid() {
790     var store = new dojo.data.ItemFileReadStore({data:vqbrad.toStoreData(bibAttrDefs)});
791     var model = new dojox.grid.data.DojoData(
792         null, store, {rowsPerPage: 100, clientSort: true, query:{id:'*'}});
793     bibAttrGrid.setModel(model);
794     bibAttrGrid.setStructure(bibAttrGridLayout);
795     bibAttrGrid.onRowClick = onBibAttrClick;
796     bibAttrGrid.update();
797 }
798
799 var xpathParser = new openils.MarcXPathParser();
800
801 function getTag(n) {
802     // grid helper: return the tags from the row's xpath column.
803     var xp = this.grid.model.getRow(n);
804     return xp && xpathParser.parse(xp.xpath).tags;
805 }
806
807 function getSubfield(n) {
808     // grid helper: return the subfields from the row's xpath column.
809     var xp = this.grid.model.getRow(n);
810     return xp && xpathParser.parse(xp.xpath).subfields;
811 }
812
813 function connectTooltip(fieldId) {
814     // Given an element id, look up a tooltip element in the doc (same
815     // id with a '-tip' suffix) and associate the two. Maybe dojo has
816     // a better way to do this?
817     var fld = dojo.byId(fieldId);
818     var tip = dojo.byId(fieldId + '-tip');
819     dojo.connect(fld, 'onfocus', function(evt) {
820                      dijit.showTooltip(tip.innerHTML, fld, ['below', 'after']); });
821     dojo.connect(fld, 'onblur', function(evt) { dijit.hideTooltip(fld); });
822 }
823
824
825 function onBibAttrClick(evt) {
826     var row = bibAttrGrid.model.getRow(evt.rowIndex);
827     // populate the popup editor.
828     dojo.byId('oils-bib-attr-code').value = row.code;
829     dojo.byId('bib-attr-description').value = row.description;
830     var _xpath = row.xpath;
831     var xpath = xpathParser.parse(_xpath);
832     dojo.byId('bib-attr-tag').value = xpath.tags;
833     dojo.byId('bib-attr-subfield').value = xpath.subfields;
834     dojo.byId('bib-attr-ident-selector').value = (row.ident ? 'True':'False');
835     dojo.byId('bib-attr-xpath').value = _xpath;
836     dojo.byId('bib-attr-remove').value = row.remove;
837
838     // set up UI for editing
839     var dialog = dojo.byId('bib-attr-dialog');
840     var create_bar = dialog.getElementsByClassName('create_bar')[0];
841     var update_bar = dialog.getElementsByClassName('update_bar')[0];
842     create_bar.style.display='none';
843     update_bar.style.display='table-row';
844     idStyle('vl-create-bib-attr-button', 'visibility', 'hidden');
845     dojo.byId('vl-create-bib-attr-button').click();
846 }