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