]> git.evergreen-ils.org Git - Evergreen.git/blob - Open-ILS/web/vandelay/vandelay.js
2a0c06fd0cd19a3bf075ff2f035f0dca0b4294a5
[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.ContentPane");
21 dojo.require("dijit.layout.TabContainer");
22 dojo.require("dijit.layout.LayoutContainer");
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-attr-editor-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 currentOverlayRecordsMapGid; // map of import record to overlay record grid id
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     vlFetchBibAttrDefs(function () { checkInitDone(); });
94     vlFetchAuthAttrDefs(function () { checkInitDone(); });
95
96     vlRetrieveQueueList('bib', null, 
97         function(list) {
98             allUserBibQueues = list;
99             for(var i = 0; i < allUserBibQueues.length; i++) {
100                 if(allUserBibQueues[i].complete() == 'f')
101                     userBibQueues.push(allUserBibQueues[i]);
102             }
103             checkInitDone();
104         }
105     );
106
107     vlRetrieveQueueList('auth', null, 
108         function(list) {
109             allUserAuthQueues = list;
110             for(var i = 0; i < allUserAuthQueues.length; i++) {
111                 if(allUserAuthQueues[i].complete() == 'f')
112                     userAuthQueues.push(allUserAuthQueues[i]);
113             }
114             checkInitDone();
115         }
116     );
117
118     vlAttrEditorInit();
119 }
120
121
122 dojo.addOnLoad(vlInit);
123
124
125 // fetch the bib and authority attribute definitions
126
127 function vlFetchBibAttrDefs(postcomplete) {
128     bibAttrDefs = [];
129     fieldmapper.standardRequest(
130         ['open-ils.permacrud', 'open-ils.permacrud.search.vqbrad'],
131         {   async: true,
132             params: [authtoken, {id:{'!=':null}}],
133             onresponse: function(r) {
134                 var def = r.recv().content(); 
135                 if(e = openils.Event.parse(def[0])) 
136                     return alert(e);
137                 bibAttrDefs.push(def);
138             },
139             oncomplete: function() {
140                 bibAttrDefs = bibAttrDefs.sort(
141                     function(a, b) {
142                         if(a.id() > b.id()) return 1;
143                         if(a.id() < b.id()) return -1;
144                         return 0;
145                     }
146                 );
147                 postcomplete();
148             }
149         }
150     );
151 }
152
153 function vlFetchAuthAttrDefs(postcomplete) {
154     authAttrDefs = [];
155     fieldmapper.standardRequest(
156         ['open-ils.permacrud', 'open-ils.permacrud.search.vqarad'],
157         {   async: true,
158             params: [authtoken, {id:{'!=':null}}],
159             onresponse: function(r) {
160                 var def = r.recv().content(); 
161                 if(e = openils.Event.parse(def[0])) 
162                     return alert(e);
163                 authAttrDefs.push(def);
164             },
165             oncomplete: function() {
166                 authAttrDefs = authAttrDefs.sort(
167                     function(a, b) {
168                         if(a.id() > b.id()) return 1;
169                         if(a.id() < b.id()) return -1;
170                         return 0;
171                     }
172                 );
173                 postcomplete();
174             }
175         }
176     );
177 }
178
179 function vlRetrieveQueueList(type, filter, onload) {
180     type = (type == 'bib') ? type : 'authority';
181     fieldmapper.standardRequest(
182         ['open-ils.vandelay', 'open-ils.vandelay.'+type+'_queue.owner.retrieve.atomic'],
183         {   async: true,
184             params: [authtoken, null, filter],
185             oncomplete: function(r) {
186                 var list = r.recv().content();
187                 if(e = openils.Event.parse(list[0]))
188                     return alert(e);
189                 onload(list);
190             }
191         }
192     );
193
194 }
195
196 function displayGlobalDiv(id) {
197     for(var i = 0; i < globalDivs.length; i++) {
198         try {
199             dojo.style(dojo.byId(globalDivs[i]), 'display', 'none');
200         } catch(e) {
201             alert('please define div ' + globalDivs[i]);
202         }
203     }
204     dojo.style(dojo.byId(id),'display','block');
205 }
206
207 function runStartupCommands() {
208     currentQueueId = cgi.param('qid');
209     currentType = cgi.param('qtype');
210     dojo.style('vl-nav-bar', 'visibility', 'visible');
211     if(currentQueueId)
212         return retrieveQueuedRecords(currentType, currentQueueId, handleRetrieveRecords);
213     vlShowUploadForm();
214 }
215
216 /**
217   * asynchronously upload a file of MARC records
218   */
219 function uploadMARC(onload){
220     dojo.byId('vl-upload-status-count').innerHTML = '0';
221     dojo.byId('vl-ses-input').value = authtoken;
222     displayGlobalDiv('vl-marc-upload-status-div');
223     dojo.io.iframe.send({
224         url: VANDELAY_URL,
225         method: "post",
226         handleAs: "html",
227         form: dojo.byId('vl-marc-upload-form'),
228         handle: function(data,ioArgs){
229             var content = data.documentElement.textContent;
230             onload(content);
231         }
232     });
233 }       
234
235 /**
236   * Creates a new vandelay queue
237   */
238 function createQueue(queueName, type, onload) {
239     fieldmapper.standardRequest(
240         ['open-ils.vandelay', 'open-ils.vandelay.'+type+'_queue.create'],
241         {   async: true,
242             params: [authtoken, queueName, null, type],
243             oncomplete : function(r) {
244                 var queue = r.recv().content();
245                 if(e = openils.Event.parse(queue)) 
246                     return alert(e);
247                 onload(queue);
248             }
249         }
250     );
251 }
252
253 /**
254   * Tells vandelay to pull a batch of records from the cache and explode them
255   * out into the vandelay tables
256   */
257 function processSpool(key, queueId, type, onload) {
258     fieldmapper.standardRequest(
259         ['open-ils.vandelay', 'open-ils.vandelay.'+type+'.process_spool'],
260         {   async: true,
261             params: [authtoken, key, queueId],
262             onresponse : function(r) {
263                 var resp = r.recv().content();
264                 if(e = openils.Event.parse(resp)) 
265                     return alert(e);
266                 dojo.byId('vl-upload-status-count').innerHTML = resp;
267             },
268             oncomplete : function(r) {onload();}
269         }
270     );
271 }
272
273 function retrieveQueuedRecords(type, queueId, onload) {
274     displayGlobalDiv('vl-generic-progress');
275     queuedRecords = [];
276     queuedRecordsMap = {};
277     currentOverlayRecordsMap = {};
278     currentOverlayRecordsMapGid = {};
279     selectableGridRecords = {};
280     resetVlQueueGridLayout();
281
282     var method = 'open-ils.vandelay.'+type+'_queue.records.retrieve.atomic';
283     if(vlQueueGridShowMatches.checked)
284         method = method.replace('records', 'records.matches');
285
286     var limit = parseInt(vlQueueDisplayLimit.getValue());
287     var offset = limit * parseInt(vlQueueDisplayPage.getValue()-1);
288
289     fieldmapper.standardRequest(
290         ['open-ils.vandelay', method],
291         {   async: true,
292             params: [authtoken, queueId, 
293                 {   clear_marc: 1, 
294                     offset: offset,
295                     limit: limit
296                 }
297             ],
298             /* intermittent bug in streaming, multipart requests prevents use of onreponse for now...
299             onresponse: function(r) {
300                 var rec = r.recv().content();
301                 if(e = openils.Event.parse(rec))
302                     return alert(e);
303                 queuedRecords.push(rec);
304                 queuedRecordsMap[rec.id()] = rec;
305             },
306             */
307             oncomplete: function(r){
308                 var recs = r.recv().content();
309                 if(e = openils.Event.parse(recs[0]))
310                     return alert(e);
311                 for(var i = 0; i < recs.length; i++) {
312                     var rec = recs[i];
313                     queuedRecords.push(rec);
314                     queuedRecordsMap[rec.id()] = rec;
315                 }
316                 onload();
317             }
318         }
319     );
320 }
321
322 function vlLoadMatchUI(recId) {
323     displayGlobalDiv('vl-generic-progress');
324     var matches = queuedRecordsMap[recId].matches();
325     var records = [];
326     currentImportRecId = recId;
327     for(var i = 0; i < matches.length; i++)
328         records.push(matches[i].eg_record());
329
330     var retrieve = ['open-ils.search', 'open-ils.search.biblio.record_entry.slim.retrieve'];
331     var params = [records];
332     if(currentType == 'auth') {
333         retrieve = ['open-ils.cat', 'open-ils.cat.authority.record.retrieve'];
334         parmas = [authtoken, records, {clear_marc:1}];
335     }
336
337     fieldmapper.standardRequest(
338         retrieve,
339         {   async: true,
340             params:params,
341             oncomplete: function(r) {
342                 var recs = r.recv().content();
343                 if(e = openils.Event.parse(recs))
344                     return alert(e);
345
346                 /* ui mangling */
347                 displayGlobalDiv('vl-match-div');
348                 resetVlMatchGridLayout();
349                 currentMatchedRecords = recs;
350                 if(!vlMatchGrid.structure)
351                     vlMatchGrid.setStructure(vlMatchGridLayout);
352
353                 // build the data store of records with match information
354                 var dataStore = bre.toStoreData(recs, null, 
355                     {virtualFields:['dest_matchpoint', 'src_matchpoint', '_id']});
356                 dataStore.identifier = '_id';
357
358                 var matchSeenMap = {};
359
360                 for(var i = 0; i < dataStore.items.length; i++) {
361                     var item = dataStore.items[i];
362                     item._id = i; // just need something unique
363                     for(var j = 0; j < matches.length; j++) {
364                         var match = matches[j];
365                         if(match.eg_record() == item.id && !matchSeenMap[match.id()]) {
366                             item.dest_matchpoint = match.field_type();
367                             var attr = getRecAttrFromMatch(queuedRecordsMap[recId], match);
368                             item.src_matchpoint = getRecAttrDefFromAttr(attr, currentType).code();
369                             matchSeenMap[match.id()] = 1;
370                             break;
371                         }
372                     }
373                 }
374
375                 // now populate the grid
376                 vlPopulateMatchGrid(vlMatchGrid, dataStore);
377             }
378         }
379     );
380 }
381
382 function vlPopulateMatchGrid(grid, data) {
383     var store = new dojo.data.ItemFileReadStore({data:data});
384     var model = new dojox.grid.data.DojoData(
385         null, store, {rowsPerPage: 100, clientSort: true, query:{id:'*'}});
386     grid.setModel(model);
387     grid.update();
388 }
389
390 function showMe(id) {
391     dojo.style(dojo.byId(id), 'display', 'block');
392 }
393 function hideMe(id) {
394     dojo.style(dojo.byId(id), 'display', 'none');
395 }
396
397
398 function vlLoadMARCHtml(recId, inCat, oncomplete) {
399     dijit.byId('vl-marc-html-done-button').onClick = oncomplete;
400     displayGlobalDiv('vl-generic-progress');
401     var api;
402     var params = [recId, 1];
403
404     if(inCat) {
405         hideMe('vl-marc-html-edit-button'); // don't show marc editor button
406         dijit.byId('vl-marc-html-edit-button').onClick = function(){}
407         api = ['open-ils.search', 'open-ils.search.biblio.record.html'];
408         if(currentType == 'auth')
409             api = ['open-ils.search', 'open-ils.search.authority.to_html'];
410     } else {
411         showMe('vl-marc-html-edit-button'); // plug in the marc editor button
412         dijit.byId('vl-marc-html-edit-button').onClick = 
413             function() {vlLoadMarcEditor(currentType, recId, oncomplete);};
414         params = [authtoken, recId];
415         api = ['open-ils.vandelay', 'open-ils.vandelay.queued_bib_record.html'];
416         if(currentType == 'auth')
417             api = ['open-ils.vandelay', 'open-ils.vandelay.queued_authority_record.html'];
418     }
419
420     fieldmapper.standardRequest(
421         api, 
422         {   async: true,
423             params: params,
424             oncomplete: function(r) {
425             displayGlobalDiv('vl-marc-html-div');
426                 var html = r.recv().content();
427                 dojo.byId('vl-marc-record-html').innerHTML = html;
428             }
429         }
430     );
431 }
432
433
434 /*
435 function getRecMatchesFromAttrCode(rec, attrCode) {
436     var matches = [];
437     var attr = getRecAttrFromCode(rec, attrCode);
438     for(var j = 0; j < rec.matches().length; j++) {
439         var match = rec.matches()[j];
440         if(match.matched_attr() == attr.id()) 
441             matches.push(match);
442     }
443     return matches;
444 }
445 */
446
447 function getRecAttrFromMatch(rec, match) {
448     for(var i = 0; i < rec.attributes().length; i++) {
449         var attr = rec.attributes()[i];
450         if(attr.id() == match.matched_attr())
451             return attr;
452     }
453 }
454
455 function getRecAttrDefFromAttr(attr, type) {
456     var defs = (type == 'bib') ? bibAttrDefs : authAttrDefs;
457     for(var i = 0; i < defs.length; i++) {
458         var def = defs[i];
459         if(def.id() == attr.field())
460             return def;
461     }
462 }
463
464 function getRecAttrFromCode(rec, attrCode) {
465     var defId = attrDefMap[attrCode];
466     var attrs = rec.attributes();
467     for(var i = 0; i < attrs.length; i++) {
468         var attr = attrs[i];
469         if(attr.field() == defId) 
470             return attr;
471     }
472     return null;
473 }
474
475 function vlGetViewMatches(rowIdx) {
476     var data = this.grid.model.getRow(rowIdx);
477     if(!data) return '';
478     var rec = queuedRecordsMap[data.id];
479     if(rec.matches().length > 0)
480         return this.value.replace('RECID', data.id);
481     return '';
482 }
483
484 function getAttrValue(rowIdx) {
485     var data = this.grid.model.getRow(rowIdx);
486     if(!data) return '';
487     var attrCode = this.field.split('.')[1];
488     var rec = queuedRecordsMap[data.id];
489     var attr = getRecAttrFromCode(rec, attrCode);
490     return (attr) ? attr.attr_value() : '';
491 }
492
493 function vlGetDateTimeField(rowIdx) {
494     data = this.grid.model.getRow(rowIdx);
495     if(!data) return '';
496     if(!data[this.field]) return '';
497     var date = dojo.date.stamp.fromISOString(data[this.field]);
498     return dojo.date.locale.format(date, {selector:'date'});
499 }
500
501 function vlGetCreator(rowIdx) {
502     data = this.grid.model.getRow(rowIdx);
503     if(!data) return '';
504     var id = data.creator;
505     if(userCache[id])
506         return userCache[id].usrname();
507     var user = fieldmapper.standardRequest(
508         ['open-ils.actor', 'open-ils.actor.user.retrieve'], [authtoken, id]);
509     if(e = openils.Event.parse(user))
510         return alert(e);
511     userCache[id] = user;
512     return user.usrname();
513 }
514
515 function vlGetViewMARC(rowIdx) {
516     data = this.grid.model.getRow(rowIdx);
517     if(data) 
518         return this.value.replace('RECID', data.id);
519 }
520
521 function vlGetOverlayTargetSelector(rowIdx) {
522     data = this.grid.model.getRow(rowIdx);
523     if(data) {
524         var value = this.value.replace(/GRIDID/g, data._id);
525         value = value.replace(/RECID/g, currentImportRecId);
526         value = value.replace(/ID/g, data.id);
527         if(data._id == currentOverlayRecordsMapGid[currentImportRecId])
528             return value.replace('/>', 'checked="checked"/>');
529         return value;
530     }
531 }
532
533 /**
534   * see if the user has enabled overlays for the current match set and, 
535   * if so, map the current import record to the overlay target.
536   */
537 function vlHandleOverlayTargetSelected(recId, gridId) {
538     var noneSelected = true;
539     var checkboxes = dojo.query('[name=vl-overlay-target-'+currentImportRecId+']');
540     for(var i = 0; i < checkboxes.length; i++) {
541         var checkbox = checkboxes[i];
542         var matchRecId = checkbox.getAttribute('match');
543         var gid = checkbox.getAttribute('gridid');
544         if(checkbox.checked) {
545             if(matchRecId == recId && gid == gridId) {
546                 noneSelected = false;
547                 currentOverlayRecordsMap[currentImportRecId] = matchRecId;
548                 currentOverlayRecordsMapGid[currentImportRecId] = gid;
549                 dojo.byId('vl-record-list-selected-' + currentImportRecId).checked = true;
550                 dojo.byId('vl-record-list-selected-' + currentImportRecId).parentNode.className = 'overlay_selected';
551             } else {
552                 checkbox.checked = false;
553             }
554         }
555     }
556
557     if(noneSelected) {
558         delete currentOverlayRecordsMap[currentImportRecId];
559         delete currentOverlayRecordsMapGid[currentImportRecId];
560         dojo.byId('vl-record-list-selected-' + currentImportRecId).checked = false;
561         dojo.byId('vl-record-list-selected-' + currentImportRecId).parentNode.className = '';
562     }
563 }
564
565 var vlQueueGridBuilt = false;
566 function buildRecordGrid(type) {
567     displayGlobalDiv('vl-queue-div');
568
569     currentOverlayRecordsMap = {};
570
571     if(!vlQueueGridBuilt) {
572         var defs = (type == 'bib') ? bibAttrDefs : authAttrDefs;
573         for(var i = 0; i < defs.length; i++) {
574             var def = defs[i]
575             attrDefMap[def.code()] = def.id();
576             var col = {
577                 name:def.description(), 
578                 field:'attr.' + def.code(),
579                 get: getAttrValue,
580                 selectableColumn:true
581             };
582             vlQueueGridLayout[0].cells[0].push(col);
583         }
584         vlQueueGridBuilt = true;
585     }
586
587     var storeData;
588     if(type == 'bib')
589         storeData = vqbr.toStoreData(queuedRecords);
590     else
591         storeData = vqar.toStoreData(queuedRecords);
592
593     var store = new dojo.data.ItemFileReadStore({data:storeData});
594     var model = new dojox.grid.data.DojoData(
595         null, store, {rowsPerPage: 100, clientSort: true, query:{id:'*'}});
596     vlQueueGrid.setModel(model);
597
598     if(vlQueueGridColumePicker) {
599         vlQueueGrid.update();
600     } else {
601         vlQueueGridColumePicker = 
602             new openils.GridColumnPicker(vlQueueGridColumePickerDialog, 
603                 vlQueueGrid, vlQueueGridLayout, authtoken, 'vandelay.queue');
604         vlQueueGridColumePicker.load();
605     }
606 }
607
608 function vlQueueGridPrevPage() {
609     var page = parseInt(vlQueueDisplayPage.getValue());
610     if(page < 2) return;
611     vlQueueDisplayPage.setValue(page - 1);
612     retrieveQueuedRecords(currentType, currentQueueId, handleRetrieveRecords);
613 }
614
615 function vlQueueGridNextPage() {
616     vlQueueDisplayPage.setValue(parseInt(vlQueueDisplayPage.getValue())+1);
617     retrieveQueuedRecords(currentType, currentQueueId, handleRetrieveRecords);
618 }
619
620 function vlDeleteQueue(type, queueId, onload) {
621     fieldmapper.standardRequest(
622         ['open-ils.vandelay', 'open-ils.vandelay.'+type+'_queue.delete'],
623         {   async: true,
624             params: [authtoken, queueId],
625             oncomplete: function(r) {
626                 var resp = r.recv().content();
627                 if(e = openils.Event.parse(resp))
628                     return alert(e);
629                 onload();
630             }
631         }
632     );
633 }
634
635
636 function vlQueueGridDrawSelectBox(rowIdx) {
637     var data = this.grid.model.getRow(rowIdx);
638     if(!data) return '';
639     var domId = 'vl-record-list-selected-' +data.id;
640     selectableGridRecords[domId] = data.id;
641     return "<div><input type='checkbox' id='"+domId+"'/></div>";
642 }
643
644 function vlSelectAllQueueGridRecords() {
645     for(var id in selectableGridRecords) 
646         dojo.byId(id).checked = true;
647 }
648 function vlSelectNoQueueGridRecords() {
649     for(var id in selectableGridRecords) 
650         dojo.byId(id).checked = false;
651 }
652 function vlToggleQueueGridSelect() {
653     if(dojo.byId('vl-queue-grid-row-selector').checked)
654         vlSelectAllQueueGridRecords();
655     else
656         vlSelectNoQueueGridRecords();
657 }
658
659 var handleRetrieveRecords = function() {
660     buildRecordGrid(currentType);
661 }
662
663 function vlImportSelectedRecords() {
664     displayGlobalDiv('vl-generic-progress-with-total');
665     var records = [];
666
667     for(var id in selectableGridRecords) {
668         if(dojo.byId(id).checked) {
669             var recId = selectableGridRecords[id];
670             var rec = queuedRecordsMap[recId];
671             if(!rec.import_time()) 
672                 records.push(recId);
673         }
674     }
675
676     fieldmapper.standardRequest(
677         ['open-ils.vandelay', 'open-ils.vandelay.'+currentType+'_record.list.import'],
678         {   async: true,
679             params: [authtoken, records, {overlay_map:currentOverlayRecordsMap}],
680             onresponse: function(r) {
681                 var resp = r.recv().content();
682                 if(e = openils.Event.parse(resp))
683                     return alert(e);
684                 vlControlledProgressBar.update({maximum:resp.total, progress:resp.progress});
685             },
686             oncomplete: function() {
687                 return retrieveQueuedRecords(currentType, currentQueueId, handleRetrieveRecords);
688             }
689         }
690     );
691 }
692
693 function vlImportRecordQueue(type, queueId, noMatchOnly, onload) {
694     displayGlobalDiv('vl-generic-progress-with-total');
695     var method = 'open-ils.vandelay.bib_queue.import';
696     if(noMatchOnly)
697         method = method.replace('import', 'nomatch.import');
698     if(type == 'auth')
699         method = method.replace('bib', 'auth');
700
701     fieldmapper.standardRequest(
702         ['open-ils.vandelay', method],
703         {   async: true,
704             params: [authtoken, queueId],
705             onresponse: function(r) {
706                 var resp = r.recv().content();
707                 if(e = openils.Event.parse(resp))
708                     return alert(e);
709                 vlControlledProgressBar.update({maximum:resp.total, progress:resp.progress});
710             },
711             oncomplete: function() {onload();}
712         }
713     );
714 }
715
716
717 /**
718   * Create queue, upload MARC, process spool, load the newly created queue 
719   */
720 function batchUpload() {
721     var queueName = dijit.byId('vl-queue-name').getValue();
722     currentType = dijit.byId('vl-record-type').getValue();
723
724     var handleProcessSpool = function() {
725         console.log('records uploaded and spooled');
726         if(vlUploadQueueAutoImport.checked) {
727             vlImportRecordQueue(currentType, currentQueueId, true,  
728                 function() {
729                     retrieveQueuedRecords(currentType, currentQueueId, handleRetrieveRecords);
730                 }
731             );
732         } else {
733             retrieveQueuedRecords(currentType, currentQueueId, handleRetrieveRecords);
734         }
735     }
736
737     var handleUploadMARC = function(key) {
738         console.log('marc uploaded');
739         dojo.style(dojo.byId('vl-upload-status-processing'), 'display', 'block');
740         processSpool(key, currentQueueId, currentType, handleProcessSpool);
741     };
742
743     var handleCreateQueue = function(queue) {
744         console.log('queue created ' + queue.name());
745         currentQueueId = queue.id();
746         uploadMARC(handleUploadMARC);
747     };
748     
749     if(vlUploadQueueSelector.getValue() && !queueName) {
750         currentQueueId = vlUploadQueueSelector.getValue();
751         console.log('adding records to existing queue ' + currentQueueId);
752         uploadMARC(handleUploadMARC);
753     } else {
754         createQueue(queueName, currentType, handleCreateQueue);
755     }
756 }
757
758
759 function vlFleshQueueSelect(selector, type) {
760     var data = (type == 'bib') ? vbq.toStoreData(allUserBibQueues) : vaq.toStoreData(allUserAuthQueues);
761     selector.store = new dojo.data.ItemFileReadStore({data:data});
762     selector.setValue(null);
763     selector.setDisplayedValue('');
764     if(data[0])
765         selector.setValue(data[0].id());
766 }
767
768 function vlShowUploadForm() {
769     displayGlobalDiv('vl-marc-upload-div');
770     vlFleshQueueSelect(vlUploadQueueSelector, vlUploadRecordType.getValue());
771 }
772
773 function vlShowQueueSelect() {
774     displayGlobalDiv('vl-queue-select-div');
775     vlFleshQueueSelect(vlQueueSelectQueueList, vlQueueSelectType.getValue());
776 }
777
778 function vlFetchQueueFromForm() {
779     currentType = vlQueueSelectType.getValue();
780     currentQueueId = vlQueueSelectQueueList.getValue();
781     retrieveQueuedRecords(currentType, currentQueueId, handleRetrieveRecords);
782 }
783
784 function vlOpenMarcEditWindow(rec, postReloadHTMLHandler) {
785     /*
786         To run in Firefox directly, must set signed.applets.codebase_principal_support
787         to true in about:config
788     */
789     netscape.security.PrivilegeManager.enablePrivilege('UniversalXPConnect');
790     win = window.open('/xul/server/cat/marcedit.xul'); // XXX version?
791
792     function onsave(r) {
793         // after the record is saved, reload the HTML display
794         var stat = r.recv().content();
795         if(e = openils.Event.parse(stat))
796             return alert(e);
797         alert(dojo.byId('vl-marc-edit-complete-label').innerHTML);
798         win.close();
799         vlLoadMARCHtml(rec.id(), false, postReloadHTMLHandler);
800     }
801
802     win.xulG = {
803         record : {marc : rec.marc()},
804         save : {
805             label: dojo.byId('vl-marc-edit-save-label').innerHTML,
806             func: function(xmlString) {
807                 var method = 'open-ils.permacrud.update.' + rec.classname;
808                 rec.marc(xmlString);
809                 fieldmapper.standardRequest(
810                     ['open-ils.permacrud', method],
811                     {   async: true,
812                         params: [authtoken, rec],
813                         oncomplete: onsave
814                     }
815                 );
816             },
817         }
818     };
819 }
820
821 function vlLoadMarcEditor(type, recId, postReloadHTMLHandler) {
822     var method = 'open-ils.permacrud.search.vqbr';
823     if(currentType != 'bib')
824         method = method.replace(/vqbr/,'vqar');
825
826     fieldmapper.standardRequest(
827         ['open-ils.permacrud', method],
828         {   async: true, 
829             params: [authtoken, {id : recId}],
830             oncomplete: function(r) {
831                 var rec = r.recv().content();
832                 if(e = openils.Event.parse(rec))
833                     return alert(e);
834                 vlOpenMarcEditWindow(rec, postReloadHTMLHandler);
835             }
836         }
837     );
838 }
839
840
841
842 //------------------------------------------------------------
843 // attribute editors
844
845 // attribute-editor global variables
846
847 var ATTR_EDITOR_IN_UPDATE_MODE = false; // true on 'edit', false on 'create'
848 var ATTR_EDIT_ID = null;                // id of current 'edit' attribute
849 var ATTR_EDIT_GROUP = 'bib';            // bib-attrs or auth-attrs
850
851 function vlAttrEditorInit() {
852     // set up tooltips on the edit form
853     connectTooltip('attr-editor-tags'); 
854     connectTooltip('attr-editor-subfields'); 
855 }
856
857 function vlShowAttrEditor() {
858     displayGlobalDiv('vl-attr-editor-div');
859     loadAttrEditorGrid();
860     idHide('vl-generic-progress');
861 }
862
863 function setAttrEditorGroup(groupName) {
864     // put us into 'bib'-attr or 'auth'-attr mode.
865     if (ATTR_EDIT_GROUP != groupName) {
866         ATTR_EDIT_GROUP = groupName;
867         loadAttrEditorGrid();
868     }
869 }
870
871 function onAttrEditorOpen() {
872     // the "bars" have the create/update/cancel/etc. buttons.
873     var create_bar = document.getElementById('attr-editor-create-bar');
874     var update_bar = document.getElementById('attr-editor-update-bar');
875     if (ATTR_EDITOR_IN_UPDATE_MODE) {
876         update_bar.style.display='table-row';
877         create_bar.style.display='none';
878         // hide the dropdown-button
879         idStyle('vl-create-attr-editor-button', 'visibility', 'hidden');
880     } else {
881         dijit.byId('attr-editor-dialog').reset();
882         create_bar.style.display='table-row';
883         update_bar.style.display='none';
884     }
885 }
886
887 function onAttrEditorClose() {
888     // reset the form to a "create" form. (We may have borrowed it for editing.)
889     ATTR_EDITOR_IN_UPDATE_MODE = false;
890     // show the dropdown-button
891     idStyle('vl-create-attr-editor-button', 'visibility', 'visible');
892 }
893
894 function loadAttrEditorGrid() {
895     var _data = (ATTR_EDIT_GROUP == 'auth') ? 
896         vqarad.toStoreData(authAttrDefs) : vqbrad.toStoreData(bibAttrDefs) ;
897                  
898     var store = new dojo.data.ItemFileReadStore({data:_data});
899     var model = new dojox.grid.data.DojoData(
900         null, store, {rowsPerPage: 100, clientSort: true, query:{id:'*'}});
901     attrEditorGrid.setModel(model);
902     attrEditorGrid.setStructure(vlAttrGridLayout);
903     attrEditorGrid.onRowClick = onAttrEditorClick;
904     attrEditorGrid.update();
905 }
906
907 function attrGridGetTag(n) {
908     // grid helper: return the tags from the row's xpath column.
909     var xp = this.grid.model.getRow(n);
910     return xp && xpathParser.parse(xp.xpath).tags;
911 }
912
913 function attrGridGetSubfield(n) {
914     // grid helper: return the subfields from the row's xpath column.
915     var xp = this.grid.model.getRow(n);
916     return xp && xpathParser.parse(xp.xpath).subfields;
917 }
918
919 function onAttrEditorClick(evt) {
920     var row = attrEditorGrid.model.getRow(evt.rowIndex);
921     ATTR_EDIT_ID = row.id;
922     ATTR_EDITOR_IN_UPDATE_MODE = true;
923
924     // populate the popup editor.
925     dojo.byId('attr-editor-code').value = row.code;
926     dojo.byId('attr-editor-description').value = row.description;
927     var parsed_xpath = xpathParser.parse(row.xpath);
928     dojo.byId('attr-editor-tags').value = parsed_xpath.tags;
929     dojo.byId('attr-editor-subfields').value = parsed_xpath.subfields;
930     dojo.byId('attr-editor-identifier').value = (row.ident ? 'True':'False');
931     dojo.byId('attr-editor-xpath').value = row.xpath;
932     dojo.byId('attr-editor-remove').value = row.remove;
933
934     // set up UI for editing
935     dojo.byId('vl-create-attr-editor-button').click();
936 }
937
938 function vlSaveAttrDefinition(data) {
939     idHide('vl-attr-editor-div');
940     idShow('vl-generic-progress');
941
942     data.id = ATTR_EDIT_ID;
943
944     // this ought to honour custom xpaths, but overwrite xpaths
945     // derived from tags/subfields.
946     if (data.xpath == '' || looksLikeDerivedXpath(data.xpath)) {
947         var _xpath = tagAndSubFieldsToXpath(data.tag, data.subfield);
948         data.xpath = _xpath;
949     }
950
951     // build up our permacrud params. Key variables here are
952     // "create or update" and "bib or auth".
953
954     var isAuth   = (ATTR_EDIT_GROUP == 'auth');
955     var isCreate = (ATTR_EDIT_ID == null);
956     var rad      = isAuth ? new vqarad() : new vqbrad() ;
957     var method   = 'open-ils.permacrud' + (isCreate ? '.create.' : '.update.') 
958         + (isAuth ? 'vqarad' : 'vqbrad');
959     var _data    = rad.fromStoreItem(data);
960
961     _data.ischanged(1);
962
963     fieldmapper.standardRequest(
964         ['open-ils.permacrud', method],
965         {   async: true,
966             params: [authtoken, _data ],
967             onresponse: function(r) { },
968             oncomplete: function(r) {
969                 attrEditorFetchAttrDefs(vlShowAttrEditor);
970                 ATTR_EDIT_ID = null;
971             },
972             onerror: function(r) {
973                 alert('vlSaveAttrDefinition comms error: ' + r);
974             }
975         }
976     );
977 }
978
979 function attrEditorFetchAttrDefs(callback) {
980     var fn = (ATTR_EDIT_GROUP == 'auth') ? vlFetchAuthAttrDefs : vlFetchBibAttrDefs;
981     return fn(callback);
982 }
983
984 function vlAttrDelete() {
985     idHide('vl-attr-editor-div');
986     idShow('vl-generic-progress');
987
988     var isAuth = (ATTR_EDIT_GROUP == 'auth');
989     var method = 'open-ils.permacrud.delete.' + (isAuth ? 'vqarad' : 'vqbrad');
990     var rad    = isAuth ? new vqarad() : new vqbrad() ;
991     fieldmapper.standardRequest(
992         ['open-ils.permacrud', method],
993         {   async: true,
994             params: [authtoken, rad.fromHash({ id : ATTR_EDIT_ID }), ],
995             oncomplete: function() {
996                 dijit.byId('attr-editor-dialog').onCancel(); // close the dialog
997                 attrEditorFetchAttrDefs(vlShowAttrEditor);
998                 ATTR_EDIT_ID = null;
999             },
1000             onerror: function(r) {
1001                 alert('vlAttrDelete comms error: ' + r);
1002             }
1003         }
1004     );
1005 }
1006
1007 // ------------------------------------------------------------
1008 // utilities for attribute editors
1009
1010 // dom utilities (maybe dojo does these, and these should be replaced)
1011
1012 function idStyle(obId, k, v)    { document.getElementById(obId).style[k] = v;   }
1013 function idShow(obId)           { idStyle(obId, 'display', 'block');            }
1014 function idHide(obId)           { idStyle(obId, 'display' , 'none');            }
1015
1016 function connectTooltip(fieldId) {
1017     // Given an element id, look up a tooltip element in the doc (same
1018     // id with a '-tip' suffix) and associate the two. Maybe dojo has
1019     // a better way to do this?
1020     var fld = dojo.byId(fieldId);
1021     var tip = dojo.byId(fieldId + '-tip');
1022     dojo.connect(fld, 'onfocus', function(evt) {
1023                      dijit.showTooltip(tip.innerHTML, fld, ['below', 'after']); });
1024     dojo.connect(fld, 'onblur', function(evt) { dijit.hideTooltip(fld); });
1025 }
1026
1027 // xpath utilities
1028
1029 var xpathParser = new openils.MarcXPathParser();
1030
1031 function tagAndSubFieldsToXpath(tags, subfields) {
1032     // given tags, and subfields, build up an XPath.
1033     try {
1034         var parts = {
1035             'tags':tags.match(/[\d]+/g), 
1036             'subfields':subfields.match(/[a-zA-z]/g) };
1037         return xpathParser.compile(parts);
1038     } catch (err) {
1039         return {'parts':null, 'tags':null, 'error':err};
1040     }
1041 }
1042
1043 function looksLikeDerivedXpath(path) {
1044     // Does this path look like it was derived from tags and subfields?
1045     var parsed = xpathParser.parse(path);
1046     if (parsed.tags == null) 
1047         return false;
1048     var compiled = xpathParser.compile(parsed);
1049     return (path == compiled);
1050 }
1051
1052 // amazing xpath-util unit-tests
1053 if (!looksLikeDerivedXpath('//*[@tag="901"]/*[@code="c"]'))     alert('vandelay xpath-utility error');
1054 if ( looksLikeDerivedXpath('ba-boo-ba-boo!'))                   alert('vandelay xpath-utility error');