e0a5ed2d07bc1310aea2f77ea84a395f5d6ab2a1
[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.layout.LayoutContainer");
24 dojo.require('dijit.form.Button');
25 dojo.require('dijit.Toolbar');
26 dojo.require('dijit.Tooltip');
27 dojo.require('dijit.Menu');
28 dojo.require("dijit.Dialog");
29 dojo.require("dojo.cookie");
30 dojo.require("dojox.grid.Grid");
31 dojo.require("dojo.data.ItemFileReadStore");
32 dojo.require('dojo.date.locale');
33 dojo.require('dojo.date.stamp');
34 dojo.require("fieldmapper.Fieldmapper");
35 dojo.require("fieldmapper.dojoData");
36 dojo.require('openils.CGI');
37 dojo.require('openils.User');
38 dojo.require('openils.Event');
39 dojo.require('openils.MarcXPathParser');
40 dojo.require('openils.GridColumnPicker');
41
42
43 var globalDivs = [
44     'vl-generic-progress',
45     'vl-generic-progress-with-total',
46     'vl-marc-upload-div',
47     'vl-queue-div',
48     'vl-match-div',
49     'vl-marc-html-div',
50     'vl-queue-select-div',
51     'vl-marc-upload-status-div',
52     'vl-bib-attr-defs-div',
53 ];
54
55 var authtoken;
56 var VANDELAY_URL = '/vandelay-upload';
57 var bibAttrDefs = [];
58 var authAttrDefs = [];
59 var queuedRecords = [];
60 var queuedRecordsMap = {};
61 var bibAttrsFetched = false;
62 var authAttrsFetched = false;
63 var attrDefMap = {}; // maps attr def code names to attr def ids
64 var currentType;
65 var currentQueueId = null;
66 var userCache = {};
67 var currentMatchedRecords; // set of loaded matched bib records
68 var currentOverlayRecordsMap; // map of import record to overlay record
69 var currentImportRecId; // when analyzing matches, this is the current import record
70 var userBibQueues = []; // only non-complete queues
71 var userAuthQueues = []; // only non-complete queues
72 var allUserBibQueues;
73 var allUserAuthQueues;
74 var selectableGridRecords;
75 var cgi = new openils.CGI();
76 var vlQueueGridColumePicker;
77
78 /**
79   * Grab initial data
80   */
81 function vlInit() {
82     authtoken = dojo.cookie('ses') || cgi.param('ses');
83     var initNeeded = 4; // how many async responses do we need before we're init'd 
84     var initCount = 0; // how many async reponses we've received
85
86     function checkInitDone() {
87         initCount++;
88         if(initCount == initNeeded)
89             runStartupCommands();
90     }
91
92     // Fetch the bib and authority attribute definitions
93     fieldmapper.standardRequest(
94         ['open-ils.permacrud', 'open-ils.permacrud.search.vqbrad'],
95         {   async: true,
96             params: [authtoken, {id:{'!=':null}}],
97             onresponse: function(r) {
98                 var def = r.recv().content(); 
99                 if(e = openils.Event.parse(def[0])) 
100                     return alert(e);
101                 bibAttrDefs.push(def);
102             },
103             oncomplete: function() {
104                 bibAttrDefs = bibAttrDefs.sort(
105                     function(a, b) {
106                         if(a.id() > b.id()) return 1;
107                         if(a.id() < b.id()) return -1;
108                         return 0;
109                     }
110                 );
111                 checkInitDone();
112             }
113         }
114     );
115
116     fieldmapper.standardRequest(
117         ['open-ils.permacrud', 'open-ils.permacrud.search.vqarad'],
118         {   async: true,
119             params: [authtoken, {id:{'!=':null}}],
120             onresponse: function(r) {
121                 var def = r.recv().content(); 
122                 if(e = openils.Event.parse(def[0])) 
123                     return alert(e);
124                 authAttrDefs.push(def);
125             },
126             oncomplete: function() {
127                 authAttrDefs = authAttrDefs.sort(
128                     function(a, b) {
129                         if(a.id() > b.id()) return 1;
130                         if(a.id() < b.id()) return -1;
131                         return 0;
132                     }
133                 );
134                 checkInitDone();
135             }
136         }
137     );
138
139     vlRetrieveQueueList('bib', null, 
140         function(list) {
141             allUserBibQueues = list;
142             for(var i = 0; i < allUserBibQueues.length; i++) {
143                 if(allUserBibQueues[i].complete() == 'f')
144                     userBibQueues.push(allUserBibQueues[i]);
145             }
146             checkInitDone();
147         }
148     );
149
150     vlRetrieveQueueList('auth', null, 
151         function(list) {
152             allUserAuthQueues = list;
153             for(var i = 0; i < allUserAuthQueues.length; i++) {
154                 if(allUserAuthQueues[i].complete() == 'f')
155                     userAuthQueues.push(allUserAuthQueues[i]);
156             }
157             checkInitDone();
158         }
159     );
160
161     bibAttrInit();
162 }
163
164 function vlRetrieveQueueList(type, filter, onload) {
165     type = (type == 'bib') ? type : 'authority';
166     fieldmapper.standardRequest(
167         ['open-ils.vandelay', 'open-ils.vandelay.'+type+'_queue.owner.retrieve.atomic'],
168         {   async: true,
169             params: [authtoken, null, filter],
170             oncomplete: function(r) {
171                 var list = r.recv().content();
172                 if(e = openils.Event.parse(list[0]))
173                     return alert(e);
174                 onload(list);
175             }
176         }
177     );
178
179 }
180
181 function displayGlobalDiv(id) {
182     for(var i = 0; i < globalDivs.length; i++) {
183         try {
184             dojo.style(dojo.byId(globalDivs[i]), 'display', 'none');
185         } catch(e) {
186             alert('please define div ' + globalDivs[i]);
187         }
188     }
189     dojo.style(dojo.byId(id),'display','block');
190 }
191
192 function runStartupCommands() {
193     currentQueueId = cgi.param('qid');
194     currentType = cgi.param('qtype');
195     if(currentQueueId)
196         return retrieveQueuedRecords(currentType, currentQueueId, handleRetrieveRecords);
197     vlShowUploadForm();
198
199 }
200
201 /**
202   * asynchronously upload a file of MARC records
203   */
204 function uploadMARC(onload){
205     dojo.byId('vl-upload-status-count').innerHTML = '0';
206     dojo.byId('vl-ses-input').value = authtoken;
207     displayGlobalDiv('vl-marc-upload-status-div');
208     dojo.io.iframe.send({
209         url: VANDELAY_URL,
210         method: "post",
211         handleAs: "html",
212         form: dojo.byId('vl-marc-upload-form'),
213         handle: function(data,ioArgs){
214             var content = data.documentElement.textContent;
215             onload(content);
216         }
217     });
218 }       
219
220 /**
221   * Creates a new vandelay queue
222   */
223 function createQueue(queueName, type, onload) {
224     fieldmapper.standardRequest(
225         ['open-ils.vandelay', 'open-ils.vandelay.'+type+'_queue.create'],
226         {   async: true,
227             params: [authtoken, queueName, null, type],
228             oncomplete : function(r) {
229                 var queue = r.recv().content();
230                 if(e = openils.Event.parse(queue)) 
231                     return alert(e);
232                 onload(queue);
233             }
234         }
235     );
236 }
237
238 /**
239   * Tells vendelay to pull a batch of records from the cache and explode them
240   * out into the vandelay tables
241   */
242 function processSpool(key, queueId, type, onload) {
243     fieldmapper.standardRequest(
244         ['open-ils.vandelay', 'open-ils.vandelay.'+type+'.process_spool'],
245         {   async: true,
246             params: [authtoken, key, queueId],
247             onresponse : function(r) {
248                 var resp = r.recv().content();
249                 if(e = openils.Event.parse(resp)) 
250                     return alert(e);
251                 dojo.byId('vl-upload-status-count').innerHTML = resp;
252             },
253             oncomplete : function(r) {onload();}
254         }
255     );
256 }
257
258 function retrieveQueuedRecords(type, queueId, onload) {
259     displayGlobalDiv('vl-generic-progress');
260     queuedRecords = [];
261     queuedRecordsMap = {};
262     currentOverlayRecordsMap = {};
263     selectableGridRecords = {};
264     resetVlQueueGridLayout();
265
266     var method = 'open-ils.vandelay.'+type+'_queue.records.retrieve.atomic';
267     if(vlQueueGridShowMatches.checked)
268         method = method.replace('records', 'records.matches');
269
270     var limit = parseInt(vlQueueDisplayLimit.getValue());
271     var offset = limit * parseInt(vlQueueDisplayPage.getValue()-1);
272
273     fieldmapper.standardRequest(
274         ['open-ils.vandelay', method],
275         {   async: true,
276             params: [authtoken, queueId, 
277                 {   clear_marc: 1, 
278                     offset: offset,
279                     limit: limit
280                 }
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 vlDeleteQueue(type, queueId, onload) {
569     fieldmapper.standardRequest(
570         ['open-ils.vandelay', 'open-ils.vandelay.'+type+'_queue.delete'],
571         {   async: true,
572             params: [authtoken, queueId],
573             oncomplete: function(r) {
574                 var resp = r.recv().content();
575                 if(e = openils.Event.parse(resp))
576                     return alert(e);
577                 onload();
578             }
579         }
580     );
581 }
582
583
584 function vlQueueGridDrawSelectBox(rowIdx) {
585     var data = this.grid.model.getRow(rowIdx);
586     if(!data) return '';
587     var domId = 'vl-record-list-selected-' +data.id;
588     selectableGridRecords[domId] = data.id;
589     return "<div><input type='checkbox' id='"+domId+"'/></div>";
590 }
591
592 function vlSelectAllQueueGridRecords() {
593     for(var id in selectableGridRecords) 
594         dojo.byId(id).checked = true;
595 }
596 function vlSelectNoQueueGridRecords() {
597     for(var id in selectableGridRecords) 
598         dojo.byId(id).checked = false;
599 }
600 function vlToggleQueueGridSelect() {
601     if(dojo.byId('vl-queue-grid-row-selector').checked)
602         vlSelectAllQueueGridRecords();
603     else
604         vlSelectNoQueueGridRecords();
605 }
606
607 var handleRetrieveRecords = function() {
608     buildRecordGrid(currentType);
609 }
610
611 function vlImportSelectedRecords() {
612     displayGlobalDiv('vl-generic-progress-with-total');
613     var records = [];
614
615     for(var id in selectableGridRecords) {
616         if(dojo.byId(id).checked) {
617             var recId = selectableGridRecords[id];
618             var rec = queuedRecordsMap[recId];
619             if(!rec.import_time()) 
620                 records.push(recId);
621         }
622     }
623
624     fieldmapper.standardRequest(
625         ['open-ils.vandelay', 'open-ils.vandelay.'+currentType+'_record.list.import'],
626         {   async: true,
627             params: [authtoken, records, {overlay_map:currentOverlayRecordsMap}],
628             onresponse: function(r) {
629                 var resp = r.recv().content();
630                 if(e = openils.Event.parse(resp))
631                     return alert(e);
632                 vlControlledProgressBar.update({maximum:resp.total, progress:resp.progress});
633             },
634             oncomplete: function() {
635                 return retrieveQueuedRecords(currentType, currentQueueId, handleRetrieveRecords);
636             }
637         }
638     );
639 }
640
641 function vlImportRecordQueue(type, queueId, noMatchOnly, onload) {
642     displayGlobalDiv('vl-generic-progress-with-total');
643     var method = 'open-ils.vandelay.bib_queue.import';
644     if(noMatchOnly)
645         method = method.replace('import', 'nomatch.import');
646     if(type == 'auth')
647         method = method.replace('bib', 'auth');
648
649     fieldmapper.standardRequest(
650         ['open-ils.vandelay', method],
651         {   async: true,
652             params: [authtoken, queueId],
653             onresponse: function(r) {
654                 var resp = r.recv().content();
655                 if(e = openils.Event.parse(resp))
656                     return alert(e);
657                 vlControlledProgressBar.update({maximum:resp.total, progress:resp.progress});
658             },
659             oncomplete: function() {onload();}
660         }
661     );
662 }
663
664
665 /**
666   * Create queue, upload MARC, process spool, load the newly created queue 
667   */
668 function batchUpload() {
669     var queueName = dijit.byId('vl-queue-name').getValue();
670     currentType = dijit.byId('vl-record-type').getValue();
671
672     var handleProcessSpool = function() {
673         console.log('records uploaded and spooled');
674         if(vlUploadQueueAutoImport.checked) {
675             vlImportRecordQueue(currentType, currentQueueId, true,  
676                 function() {
677                     retrieveQueuedRecords(currentType, currentQueueId, handleRetrieveRecords);
678                 }
679             );
680         } else {
681             retrieveQueuedRecords(currentType, currentQueueId, handleRetrieveRecords);
682         }
683     }
684
685     var handleUploadMARC = function(key) {
686         console.log('marc uploaded');
687         dojo.style(dojo.byId('vl-upload-status-processing'), 'display', 'block');
688         processSpool(key, currentQueueId, currentType, handleProcessSpool);
689     };
690
691     var handleCreateQueue = function(queue) {
692         console.log('queue created ' + queue.name());
693         currentQueueId = queue.id();
694         uploadMARC(handleUploadMARC);
695     };
696     
697     if(vlUploadQueueSelector.getValue() && !queueName) {
698         currentQueueId = vlUploadQueueSelector.getValue();
699         console.log('adding records to existing queue ' + currentQueueId);
700         uploadMARC(handleUploadMARC);
701     } else {
702         createQueue(queueName, currentType, handleCreateQueue);
703     }
704 }
705
706
707 function vlFleshQueueSelect(selector, type) {
708     var data = (type == 'bib') ? vbq.toStoreData(allUserBibQueues) : vaq.toStoreData(allUserAuthQueues);
709     selector.store = new dojo.data.ItemFileReadStore({data:data});
710     selector.setValue(null);
711     selector.setDisplayedValue('');
712     if(data[0])
713         selector.setValue(data[0].id());
714 }
715
716 function vlShowUploadForm() {
717     displayGlobalDiv('vl-marc-upload-div');
718     vlFleshQueueSelect(vlUploadQueueSelector, vlUploadRecordType.getValue());
719 }
720
721 function vlShowQueueSelect() {
722     displayGlobalDiv('vl-queue-select-div');
723     vlFleshQueueSelect(vlQueueSelectQueueList, vlQueueSelectType.getValue());
724 }
725
726 function vlFetchQueueFromForm() {
727     currentType = vlQueueSelectType.getValue();
728     currentQueueId = vlQueueSelectQueueList.getValue();
729     retrieveQueuedRecords(currentType, currentQueueId, handleRetrieveRecords);
730 }
731
732 dojo.addOnLoad(vlInit);
733
734
735 //------------------------------------------------------------
736 // bib-attr, auth-attr 
737
738 function bibAttrInit() {
739     // set up tooltips on attr_record forms
740     connectTooltip('bib-attr-tag'); 
741     connectTooltip('bib-attr-subfield'); 
742 }
743
744 function vlShowBibAttrDefs() {
745     displayGlobalDiv('vl-bib-attr-defs-div');
746     loadBibAttrGrid();
747 }
748
749 function idStyle(obid, k, v) { document.getElementById(obid).style[k] = v; }
750 function show(obid) { idStyle(obid, 'display', 'block'); }
751 function hide(obid) { idStyle(obid, 'display' , 'none'); }
752 function textOf(obid) { return document.getElementById(obid).innerHTML; }
753
754 function saveNewBibAttrRecord(arg) {
755     // pretend to save...
756     hide('vl-bib-attr-defs-div');
757     show('vl-generic-progress');
758     // not really saving anything yet. For now, just remove the
759     // progress bar after a moment and return to the table.
760     setTimeout("show('vl-bib-attr-defs-div');hide('vl-generic-progress');", 1000);
761 }
762
763 function onAttrEditorOpen() {
764 }
765
766 function onAttrEditorClose() {
767     // reset the form to a "create" form. (We may have borrowed it for "editing".)
768     var dialog = dojo.byId('bib-attr-dialog');
769     var create_bar = dialog.getElementsByClassName('create_bar')[0];
770     var update_bar = dialog.getElementsByClassName('update_bar')[0];
771     create_bar.style.display='table-row';
772     update_bar.style.display='none';
773     idStyle('vl-create-bib-attr-button', 'visibility', 'visible');
774     dijit.byId('bib-attr-dialog').reset();
775 }
776
777 function loadBibAttrGrid() {
778     var store = new dojo.data.ItemFileReadStore({data:vqbrad.toStoreData(bibAttrDefs)});
779     var model = new dojox.grid.data.DojoData(
780         null, store, {rowsPerPage: 100, clientSort: true, query:{id:'*'}});
781     bibAttrGrid.setModel(model);
782     bibAttrGrid.setStructure(bibAttrGridLayout);
783     bibAttrGrid.onRowClick = onBibAttrClick;
784     bibAttrGrid.update();
785 }
786
787 var xpathParser = new openils.MarcXPathParser();
788
789 function getTag(n) {
790     // grid helper: return the tags from the row's xpath column.
791     var xp = this.grid.model.getRow(n);
792     return xp && xpathParser.parse(xp.xpath).tags;
793 }
794
795 function getSubfield(n) {
796     // grid helper: return the subfields from the row's xpath column.
797     var xp = this.grid.model.getRow(n);
798     return xp && xpathParser.parse(xp.xpath).subfields;
799 }
800
801 function connectTooltip(fieldId) {
802     // Given an element id, look up a tooltip element in the doc (same
803     // id with a '-tip' suffix) and associate the two. Maybe dojo has
804     // a better way to do this?
805     var fld = dojo.byId(fieldId);
806     var tip = dojo.byId(fieldId + '-tip');
807     dojo.connect(fld, 'onfocus', function(evt) {
808                      dijit.showTooltip(tip.innerHTML, fld, ['below', 'after']); });
809     dojo.connect(fld, 'onblur', function(evt) { dijit.hideTooltip(fld); });
810 }
811
812
813 function onBibAttrClick(evt) {
814     var row = bibAttrGrid.model.getRow(evt.rowIndex);
815     // populate the popup editor.
816     dojo.byId('oils-bib-attr-code').value = row.code;
817     dojo.byId('bib-attr-description').value = row.description;
818     var _xpath = row.xpath;
819     var xpath = xpathParser.parse(_xpath);
820     dojo.byId('bib-attr-tag').value = xpath.tags;
821     dojo.byId('bib-attr-subfield').value = xpath.subfields;
822     dojo.byId('bib-attr-ident-selector').value = (row.ident ? 'True':'False');
823     dojo.byId('bib-attr-xpath').value = _xpath;
824     dojo.byId('bib-attr-remove').value = row.remove;
825
826     // set up UI for editing
827     var dialog = dojo.byId('bib-attr-dialog');
828     var create_bar = dialog.getElementsByClassName('create_bar')[0];
829     var update_bar = dialog.getElementsByClassName('update_bar')[0];
830     create_bar.style.display='none';
831     update_bar.style.display='table-row';
832     idStyle('vl-create-bib-attr-button', 'visibility', 'hidden');
833     dojo.byId('vl-create-bib-attr-button').click();
834 }