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