added ability to only fetch/dislplay non-imported recs in queue retrieval. hiding...
[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     var params = [authtoken, queueId, {clear_marc: 1, offset: offset, limit: limit}];
270
271     if(vlQueueGridShowNonImport.checked)
272         params[2].non_imported = 1;
273         
274
275     var limit = parseInt(vlQueueDisplayLimit.getValue());
276     var offset = limit * parseInt(vlQueueDisplayPage.getValue()-1);
277
278     fieldmapper.standardRequest(
279         ['open-ils.vandelay', method],
280         {   async: true,
281             params: params,
282
283             /* intermittent bug in streaming, multipart requests prevents use of onreponse for now...
284             onresponse: function(r) {
285                 var rec = r.recv().content();
286                 if(e = openils.Event.parse(rec))
287                     return alert(e);
288                 queuedRecords.push(rec);
289                 queuedRecordsMap[rec.id()] = rec;
290             },
291             */
292             oncomplete: function(r){
293                 var recs = r.recv().content();
294                 if(e = openils.Event.parse(recs[0]))
295                     return alert(e);
296                 for(var i = 0; i < recs.length; i++) {
297                     var rec = recs[i];
298                     queuedRecords.push(rec);
299                     queuedRecordsMap[rec.id()] = rec;
300                 }
301                 onload();
302             }
303         }
304     );
305 }
306
307 //function vlLoadMatchUI(recId, attrCode) {
308 function vlLoadMatchUI(recId) {
309     displayGlobalDiv('vl-generic-progress');
310     //var matches = getRecMatchesFromAttrCode(queuedRecordsMap[recId], attrCode);
311     var matches = queuedRecordsMap[recId].matches();
312     var records = [];
313     currentImportRecId = recId;
314     for(var i = 0; i < matches.length; i++)
315         records.push(matches[i].eg_record());
316
317     var retrieve = ['open-ils.search', 'open-ils.search.biblio.record_entry.slim.retrieve'];
318     var params = [records];
319     if(currentType == 'auth') {
320         retrieve = ['open-ils.cat', 'open-ils.cat.authority.record.retrieve'];
321         parmas = [authtoken, records, {clear_marc:1}];
322     }
323
324     fieldmapper.standardRequest(
325         retrieve,
326         {   async: true,
327             params:params,
328             oncomplete: function(r) {
329                 var recs = r.recv().content();
330                 if(e = openils.Event.parse(recs))
331                     return alert(e);
332
333                 /* ui mangling */
334                 displayGlobalDiv('vl-match-div');
335                 resetVlMatchGridLayout();
336                 currentMatchedRecords = recs;
337                 vlMatchGrid.setStructure(vlMatchGridLayout);
338
339                 // build the data store of records with match information
340                 var dataStore = bre.toStoreData(recs, null, 
341                     {virtualFields:['dest_matchpoint', 'src_matchpoint', '_id']});
342                 dataStore.identifier = '_id';
343
344
345                 for(var i = 0; i < dataStore.items.length; i++) {
346                     var item = dataStore.items[i];
347                     item._id = i; // just need something unique
348                     for(var j = 0; j < matches.length; j++) {
349                         var match = matches[j];
350                         if(match.eg_record() == item.id) {
351                             item.dest_matchpoint = match.field_type();
352                             var attr = getRecAttrFromMatch(queuedRecordsMap[recId], match);
353                             //item.src_matchpoint = getRecAttrDefFromAttr(attr, currentType).description();
354                             item.src_matchpoint = getRecAttrDefFromAttr(attr, currentType).code();
355                         }
356                     }
357                 }
358
359                 // now populate the grid
360                 vlPopulateGrid(vlMatchGrid, dataStore);
361             }
362         }
363     );
364 }
365
366 function vlPopulateGrid(grid, data) {
367     var store = new dojo.data.ItemFileReadStore({data:data});
368     var model = new dojox.grid.data.DojoData(
369         null, store, {rowsPerPage: 100, clientSort: true, query:{id:'*'}});
370     grid.setModel(model);
371     grid.update();
372 }
373
374
375 function vlLoadMARCHtml(recId, inCat, oncomplete) {
376     dijit.byId('vl-marc-html-done-button').onClick = oncomplete;
377     displayGlobalDiv('vl-generic-progress');
378     var api;
379     var params = [recId, 1];
380     if(inCat) {
381         api = ['open-ils.search', 'open-ils.search.biblio.record.html'];
382         if(currentType == 'auth')
383             api = ['open-ils.search', 'open-ils.search.authority.to_html'];
384     } else {
385         params = [authtoken, recId];
386         api = ['open-ils.vandelay', 'open-ils.vandelay.queued_bib_record.html'];
387         if(currentType == 'auth')
388             api = ['open-ils.vandelay', 'open-ils.vandelay.queued_authority_record.html'];
389     }
390     fieldmapper.standardRequest(
391         api, 
392         {   async: true,
393             params: params,
394             oncomplete: function(r) {
395             displayGlobalDiv('vl-marc-html-div');
396                 var html = r.recv().content();
397                 dojo.byId('vl-marc-record-html').innerHTML = html;
398             }
399         }
400     );
401 }
402
403
404 /*
405 function getRecMatchesFromAttrCode(rec, attrCode) {
406     var matches = [];
407     var attr = getRecAttrFromCode(rec, attrCode);
408     for(var j = 0; j < rec.matches().length; j++) {
409         var match = rec.matches()[j];
410         if(match.matched_attr() == attr.id()) 
411             matches.push(match);
412     }
413     return matches;
414 }
415 */
416
417 function getRecAttrFromMatch(rec, match) {
418     for(var i = 0; i < rec.attributes().length; i++) {
419         var attr = rec.attributes()[i];
420         if(attr.id() == match.matched_attr())
421             return attr;
422     }
423 }
424
425 function getRecAttrDefFromAttr(attr, type) {
426     var defs = (type == 'bib') ? bibAttrDefs : authAttrDefs;
427     for(var i = 0; i < defs.length; i++) {
428         var def = defs[i];
429         if(def.id() == attr.field())
430             return def;
431     }
432 }
433
434 function getRecAttrFromCode(rec, attrCode) {
435     var defId = attrDefMap[attrCode];
436     var attrs = rec.attributes();
437     for(var i = 0; i < attrs.length; i++) {
438         var attr = attrs[i];
439         if(attr.field() == defId) 
440             return attr;
441     }
442     return null;
443 }
444
445 function vlGetViewMatches(rowIdx) {
446     var data = this.grid.model.getRow(rowIdx);
447     if(!data) return '';
448     var rec = queuedRecordsMap[data.id];
449     if(rec.matches().length > 0)
450         return this.value.replace('RECID', data.id);
451     return '';
452 }
453
454 function getAttrValue(rowIdx) {
455     var data = this.grid.model.getRow(rowIdx);
456     if(!data) return '';
457     var attrCode = this.field.split('.')[1];
458     var rec = queuedRecordsMap[data.id];
459     var attr = getRecAttrFromCode(rec, attrCode);
460     return (attr) ? attr.attr_value() : '';
461 }
462
463 function vlGetDateTimeField(rowIdx) {
464     data = this.grid.model.getRow(rowIdx);
465     if(!data) return '';
466     if(!data[this.field]) return '';
467     var date = dojo.date.stamp.fromISOString(data[this.field]);
468     return dojo.date.locale.format(date, {selector:'date'});
469 }
470
471 function vlGetCreator(rowIdx) {
472     data = this.grid.model.getRow(rowIdx);
473     if(!data) return '';
474     var id = data.creator;
475     if(userCache[id])
476         return userCache[id].usrname();
477     var user = fieldmapper.standardRequest(
478         ['open-ils.actor', 'open-ils.actor.user.retrieve'], [authtoken, id]);
479     if(e = openils.Event.parse(user))
480         return alert(e);
481     userCache[id] = user;
482     return user.usrname();
483 }
484
485 function vlGetViewMARC(rowIdx) {
486     data = this.grid.model.getRow(rowIdx);
487     if(data) 
488         return this.value.replace('RECID', data.id);
489 }
490
491 function vlGetOverlayTargetSelector(rowIdx) {
492     data = this.grid.model.getRow(rowIdx);
493     if(data) {
494         var value = this.value.replace('ID', data.id);
495         var overlay = currentOverlayRecordsMap[currentImportRecId];
496         if(overlay && overlay == data.id) 
497             value = value.replace('/>', 'checked="checked"/>');
498         return value;
499     }
500 }
501
502 /**
503   * see if the user has enabled overlays for the current match set and, 
504   * if so, map the current import record to the overlay target.
505   */
506 function vlHandleOverlayTargetSelected() {
507     if(vlOverlayTargetEnable.checked) {
508         for(var i = 0; i < currentMatchedRecords.length; i++) {
509             var matchRecId = currentMatchedRecords[i].id();
510             if(dojo.byId('vl-overlay-target-'+matchRecId).checked) {
511                 console.log("found overlay target " + matchRecId);
512                 currentOverlayRecordsMap[currentImportRecId] = matchRecId;
513                 dojo.byId('vl-record-list-selected-' + currentImportRecId).checked = true;
514                 dojo.byId('vl-record-list-selected-' + currentImportRecId).parentNode.className = 'overlay_selected';
515                 return;
516             }
517         }
518     } else {
519         delete currentOverlayRecordsMap[currentImportRecId];
520         dojo.byId('vl-record-list-selected-' + currentImportRecId).checked = false;
521     }
522 }
523
524 var vlQueueGridBuilt = false;
525 function buildRecordGrid(type) {
526     displayGlobalDiv('vl-queue-div');
527
528     currentOverlayRecordsMap = {};
529
530     if(!vlQueueGridBuilt) {
531         var defs = (type == 'bib') ? bibAttrDefs : authAttrDefs;
532         for(var i = 0; i < defs.length; i++) {
533             var def = defs[i]
534             attrDefMap[def.code()] = def.id();
535             var col = {
536                 name:def.description(), 
537                 field:'attr.' + def.code(),
538                 get: getAttrValue,
539                 selectableColumn:true
540             };
541             vlQueueGridLayout[0].cells[0].push(col);
542         }
543         vlQueueGridBuilt = true;
544     }
545
546     var storeData;
547     if(type == 'bib')
548         storeData = vqbr.toStoreData(queuedRecords);
549     else
550         storeData = vqar.toStoreData(queuedRecords);
551
552     var store = new dojo.data.ItemFileReadStore({data:storeData});
553     var model = new dojox.grid.data.DojoData(
554         null, store, {rowsPerPage: 100, clientSort: true, query:{id:'*'}});
555
556     vlQueueGrid.setModel(model);
557     if(vlQueueGridColumePicker) 
558         vlQueueGrid.setStructure(vlQueueGridColumePicker.structure);
559     else
560         vlQueueGrid.setStructure(vlQueueGridLayout);
561     vlQueueGrid.update();
562
563     if(!vlQueueGridColumePicker) {
564         vlQueueGridColumePicker = 
565             new openils.GridColumnPicker(vlQueueGridColumePickerDialog, vlQueueGrid);
566     }
567 }
568
569 function vlQueueGridPrevPage() {
570     var page = parseInt(vlQueueDisplayPage.getValue());
571     if(page < 2) return;
572     vlQueueDisplayPage.setValue(page - 1);
573     retrieveQueuedRecords(currentType, currentQueueId, handleRetrieveRecords);
574 }
575
576 function vlQueueGridNextPage() {
577     vlQueueDisplayPage.setValue(parseInt(vlQueueDisplayPage.getValue())+1);
578     retrieveQueuedRecords(currentType, currentQueueId, handleRetrieveRecords);
579 }
580
581 function vlDeleteQueue(type, queueId, onload) {
582     fieldmapper.standardRequest(
583         ['open-ils.vandelay', 'open-ils.vandelay.'+type+'_queue.delete'],
584         {   async: true,
585             params: [authtoken, queueId],
586             oncomplete: function(r) {
587                 var resp = r.recv().content();
588                 if(e = openils.Event.parse(resp))
589                     return alert(e);
590                 onload();
591             }
592         }
593     );
594 }
595
596
597 function vlQueueGridDrawSelectBox(rowIdx) {
598     var data = this.grid.model.getRow(rowIdx);
599     if(!data) return '';
600     var domId = 'vl-record-list-selected-' +data.id;
601     selectableGridRecords[domId] = data.id;
602     return "<div><input type='checkbox' id='"+domId+"'/></div>";
603 }
604
605 function vlSelectAllQueueGridRecords() {
606     for(var id in selectableGridRecords) 
607         dojo.byId(id).checked = true;
608 }
609 function vlSelectNoQueueGridRecords() {
610     for(var id in selectableGridRecords) 
611         dojo.byId(id).checked = false;
612 }
613 function vlToggleQueueGridSelect() {
614     if(dojo.byId('vl-queue-grid-row-selector').checked)
615         vlSelectAllQueueGridRecords();
616     else
617         vlSelectNoQueueGridRecords();
618 }
619
620 var handleRetrieveRecords = function() {
621     buildRecordGrid(currentType);
622 }
623
624 function vlImportSelectedRecords() {
625     displayGlobalDiv('vl-generic-progress-with-total');
626     var records = [];
627
628     for(var id in selectableGridRecords) {
629         if(dojo.byId(id).checked) {
630             var recId = selectableGridRecords[id];
631             var rec = queuedRecordsMap[recId];
632             if(!rec.import_time()) 
633                 records.push(recId);
634         }
635     }
636
637     fieldmapper.standardRequest(
638         ['open-ils.vandelay', 'open-ils.vandelay.'+currentType+'_record.list.import'],
639         {   async: true,
640             params: [authtoken, records, {overlay_map:currentOverlayRecordsMap}],
641             onresponse: function(r) {
642                 var resp = r.recv().content();
643                 if(e = openils.Event.parse(resp))
644                     return alert(e);
645                 vlControlledProgressBar.update({maximum:resp.total, progress:resp.progress});
646             },
647             oncomplete: function() {
648                 return retrieveQueuedRecords(currentType, currentQueueId, handleRetrieveRecords);
649             }
650         }
651     );
652 }
653
654 function vlImportRecordQueue(type, queueId, noMatchOnly, onload) {
655     displayGlobalDiv('vl-generic-progress-with-total');
656     var method = 'open-ils.vandelay.bib_queue.import';
657     if(noMatchOnly)
658         method = method.replace('import', 'nomatch.import');
659     if(type == 'auth')
660         method = method.replace('bib', 'auth');
661
662     fieldmapper.standardRequest(
663         ['open-ils.vandelay', method],
664         {   async: true,
665             params: [authtoken, queueId],
666             onresponse: function(r) {
667                 var resp = r.recv().content();
668                 if(e = openils.Event.parse(resp))
669                     return alert(e);
670                 vlControlledProgressBar.update({maximum:resp.total, progress:resp.progress});
671             },
672             oncomplete: function() {onload();}
673         }
674     );
675 }
676
677
678 /**
679   * Create queue, upload MARC, process spool, load the newly created queue 
680   */
681 function batchUpload() {
682     var queueName = dijit.byId('vl-queue-name').getValue();
683     currentType = dijit.byId('vl-record-type').getValue();
684
685     var handleProcessSpool = function() {
686         console.log('records uploaded and spooled');
687         if(vlUploadQueueAutoImport.checked) {
688             vlImportRecordQueue(currentType, currentQueueId, true,  
689                 function() {
690                     retrieveQueuedRecords(currentType, currentQueueId, handleRetrieveRecords);
691                 }
692             );
693         } else {
694             retrieveQueuedRecords(currentType, currentQueueId, handleRetrieveRecords);
695         }
696     }
697
698     var handleUploadMARC = function(key) {
699         console.log('marc uploaded');
700         dojo.style(dojo.byId('vl-upload-status-processing'), 'display', 'block');
701         processSpool(key, currentQueueId, currentType, handleProcessSpool);
702     };
703
704     var handleCreateQueue = function(queue) {
705         console.log('queue created ' + queue.name());
706         currentQueueId = queue.id();
707         uploadMARC(handleUploadMARC);
708     };
709     
710     if(vlUploadQueueSelector.getValue() && !queueName) {
711         currentQueueId = vlUploadQueueSelector.getValue();
712         console.log('adding records to existing queue ' + currentQueueId);
713         uploadMARC(handleUploadMARC);
714     } else {
715         createQueue(queueName, currentType, handleCreateQueue);
716     }
717 }
718
719
720 function vlFleshQueueSelect(selector, type) {
721     var data = (type == 'bib') ? vbq.toStoreData(allUserBibQueues) : vaq.toStoreData(allUserAuthQueues);
722     selector.store = new dojo.data.ItemFileReadStore({data:data});
723     selector.setValue(null);
724     selector.setDisplayedValue('');
725     if(data[0])
726         selector.setValue(data[0].id());
727 }
728
729 function vlShowUploadForm() {
730     displayGlobalDiv('vl-marc-upload-div');
731     vlFleshQueueSelect(vlUploadQueueSelector, vlUploadRecordType.getValue());
732 }
733
734 function vlShowQueueSelect() {
735     displayGlobalDiv('vl-queue-select-div');
736     vlFleshQueueSelect(vlQueueSelectQueueList, vlQueueSelectType.getValue());
737 }
738
739 function vlFetchQueueFromForm() {
740     currentType = vlQueueSelectType.getValue();
741     currentQueueId = vlQueueSelectQueueList.getValue();
742     retrieveQueuedRecords(currentType, currentQueueId, handleRetrieveRecords);
743 }
744
745 dojo.addOnLoad(vlInit);
746
747
748 //------------------------------------------------------------
749 // bib-attr, auth-attr 
750
751 function bibAttrInit() {
752     // set up tooltips on attr_record forms
753     connectTooltip('bib-attr-tag'); 
754     connectTooltip('bib-attr-subfield'); 
755 }
756
757 function vlShowBibAttrDefs() {
758     displayGlobalDiv('vl-bib-attr-defs-div');
759     loadBibAttrGrid();
760 }
761
762 function idStyle(obid, k, v) { document.getElementById(obid).style[k] = v; }
763 function show(obid) { idStyle(obid, 'display', 'block'); }
764 function hide(obid) { idStyle(obid, 'display' , 'none'); }
765 function textOf(obid) { return document.getElementById(obid).innerHTML; }
766
767 function saveNewBibAttrRecord(arg) {
768     // pretend to save...
769     hide('vl-bib-attr-defs-div');
770     show('vl-generic-progress');
771     // not really saving anything yet. For now, just remove the
772     // progress bar after a moment and return to the table.
773     setTimeout("show('vl-bib-attr-defs-div');hide('vl-generic-progress');", 1000);
774 }
775
776 function onAttrEditorOpen() {
777 }
778
779 function onAttrEditorClose() {
780     // reset the form to a "create" form. (We may have borrowed it for "editing".)
781     var dialog = dojo.byId('bib-attr-dialog');
782     var create_bar = dialog.getElementsByClassName('create_bar')[0];
783     var update_bar = dialog.getElementsByClassName('update_bar')[0];
784     create_bar.style.display='table-row';
785     update_bar.style.display='none';
786     idStyle('vl-create-bib-attr-button', 'visibility', 'visible');
787     dijit.byId('bib-attr-dialog').reset();
788 }
789
790 function loadBibAttrGrid() {
791     var store = new dojo.data.ItemFileReadStore({data:vqbrad.toStoreData(bibAttrDefs)});
792     var model = new dojox.grid.data.DojoData(
793         null, store, {rowsPerPage: 100, clientSort: true, query:{id:'*'}});
794     bibAttrGrid.setModel(model);
795     bibAttrGrid.setStructure(bibAttrGridLayout);
796     bibAttrGrid.onRowClick = onBibAttrClick;
797     bibAttrGrid.update();
798 }
799
800 var xpathParser = new openils.MarcXPathParser();
801
802 function getTag(n) {
803     // grid helper: return the tags from the row's xpath column.
804     var xp = this.grid.model.getRow(n);
805     return xp && xpathParser.parse(xp.xpath).tags;
806 }
807
808 function getSubfield(n) {
809     // grid helper: return the subfields from the row's xpath column.
810     var xp = this.grid.model.getRow(n);
811     return xp && xpathParser.parse(xp.xpath).subfields;
812 }
813
814 function connectTooltip(fieldId) {
815     // Given an element id, look up a tooltip element in the doc (same
816     // id with a '-tip' suffix) and associate the two. Maybe dojo has
817     // a better way to do this?
818     var fld = dojo.byId(fieldId);
819     var tip = dojo.byId(fieldId + '-tip');
820     dojo.connect(fld, 'onfocus', function(evt) {
821                      dijit.showTooltip(tip.innerHTML, fld, ['below', 'after']); });
822     dojo.connect(fld, 'onblur', function(evt) { dijit.hideTooltip(fld); });
823 }
824
825
826 function onBibAttrClick(evt) {
827     var row = bibAttrGrid.model.getRow(evt.rowIndex);
828     // populate the popup editor.
829     dojo.byId('oils-bib-attr-code').value = row.code;
830     dojo.byId('bib-attr-description').value = row.description;
831     var _xpath = row.xpath;
832     var xpath = xpathParser.parse(_xpath);
833     dojo.byId('bib-attr-tag').value = xpath.tags;
834     dojo.byId('bib-attr-subfield').value = xpath.subfields;
835     dojo.byId('bib-attr-ident-selector').value = (row.ident ? 'True':'False');
836     dojo.byId('bib-attr-xpath').value = _xpath;
837     dojo.byId('bib-attr-remove').value = row.remove;
838
839     // set up UI for editing
840     var dialog = dojo.byId('bib-attr-dialog');
841     var create_bar = dialog.getElementsByClassName('create_bar')[0];
842     var update_bar = dialog.getElementsByClassName('update_bar')[0];
843     create_bar.style.display='none';
844     update_bar.style.display='table-row';
845     idStyle('vl-create-bib-attr-button', 'visibility', 'hidden');
846     dojo.byId('vl-create-bib-attr-button').click();
847 }