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