]> git.evergreen-ils.org Git - working/Evergreen.git/blob - Open-ILS/web/js/ui/default/vandelay/vandelay.js
show match score/quality in VL record match grid
[working/Evergreen.git] / Open-ILS / web / js / ui / default / 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.FilteringSelect"); 
19 dojo.require("dijit.layout.ContentPane");
20 dojo.require("dijit.layout.TabContainer");
21 dojo.require("dijit.layout.LayoutContainer");
22 dojo.require('dijit.form.Button');
23 dojo.require('dijit.form.CheckBox');
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.DataGrid');
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("fieldmapper.OrgUtils");
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.widget.GridColumnPicker');
42 dojo.require('openils.PermaCrud');
43 dojo.require('openils.widget.OrgUnitFilteringSelect');
44 dojo.require('openils.widget.AutoGrid');
45 dojo.require('openils.widget.AutoFieldWidget');
46
47
48 var globalDivs = [
49     'vl-generic-progress',
50     'vl-generic-progress-with-total',
51     'vl-marc-upload-div',
52     'vl-queue-div',
53     'vl-match-div',
54     'vl-marc-html-div',
55     'vl-queue-select-div',
56     'vl-marc-upload-status-div',
57     'vl-attr-editor-div',
58     'vl-marc-export-div',
59     'vl-profile-editor-div',
60     'vl-item-attr-editor-div',
61     'vl-import-error-div'
62 ];
63
64 var authtoken;
65 var VANDELAY_URL = '/vandelay-upload';
66 var bibAttrDefs = [];
67 var authAttrDefs = [];
68 var queuedRecords = [];
69 var queuedRecordsMap = {};
70 var bibAttrsFetched = false;
71 var authAttrsFetched = false;
72 var attrDefMap = {}; // maps attr def code names to attr def ids
73 var currentType;
74 var currentQueueId = null;
75 var userCache = {};
76 var currentMatchedRecords; // set of loaded matched bib records
77 var currentOverlayRecordsMap; // map of import record to overlay record
78 var currentOverlayRecordsMapGid; // map of import record to overlay record grid id
79 var currentImportRecId; // when analyzing matches, this is the current import record
80 var userBibQueues = []; // only non-complete queues
81 var userAuthQueues = []; // only non-complete queues
82 var allUserBibQueues;
83 var allUserAuthQueues;
84 var selectableGridRecords;
85 var cgi = new openils.CGI();
86 var vlQueueGridColumePicker = {};
87 var vlBibSources = [];
88 var importItemDefs = [];
89 var matchSets = {};
90
91 /**
92   * Grab initial data
93   */
94 function vlInit() {
95     authtoken = openils.User.authtoken;
96     var initNeeded = 7; // how many async responses do we need before we're init'd 
97     var initCount = 0; // how many async reponses we've received
98
99     openils.Util.registerEnterHandler(
100         vlQueueDisplayPage.domNode, function(){retrieveQueuedRecords();});
101     openils.Util.addCSSClass(dojo.byId('vl-menu-marc-upload'), 'toolbar_selected');
102
103     function checkInitDone() {
104         initCount++;
105         if(initCount == initNeeded)
106             runStartupCommands();
107     }
108
109     var profiles = new openils.PermaCrud().retrieveAll('vmp');
110     vlUploadMergeProfile.store = new dojo.data.ItemFileReadStore({data:fieldmapper.vmp.toStoreData(profiles)});
111     vlUploadMergeProfile.labelAttr = 'name';
112     vlUploadMergeProfile.searchAttr = 'name';
113     vlUploadMergeProfile.startup();
114
115     vlUploadMergeProfile2.store = new dojo.data.ItemFileReadStore({data:fieldmapper.vmp.toStoreData(profiles)});
116     vlUploadMergeProfile2.labelAttr = 'name';
117     vlUploadMergeProfile2.searchAttr = 'name';
118     vlUploadMergeProfile2.startup();
119
120
121     // Fetch the bib and authority attribute definitions 
122     vlFetchBibAttrDefs(function () { checkInitDone(); });
123     vlFetchAuthAttrDefs(function () { checkInitDone(); });
124
125     vlRetrieveQueueList('bib', null, 
126         function(list) {
127             allUserBibQueues = list;
128             for(var i = 0; i < allUserBibQueues.length; i++) {
129                 if(allUserBibQueues[i].complete() == 'f')
130                     userBibQueues.push(allUserBibQueues[i]);
131             }
132             checkInitDone();
133         }
134     );
135
136     vlRetrieveQueueList('auth', null, 
137         function(list) {
138             allUserAuthQueues = list;
139             for(var i = 0; i < allUserAuthQueues.length; i++) {
140                 if(allUserAuthQueues[i].complete() == 'f')
141                     userAuthQueues.push(allUserAuthQueues[i]);
142             }
143             checkInitDone();
144         }
145     );
146
147     fieldmapper.standardRequest(
148         ['open-ils.permacrud', 'open-ils.permacrud.search.cbs.atomic'],
149         {   async: true,
150             params: [authtoken, {id:{"!=":null}}, {order_by:{cbs:'id'}}],
151             oncomplete : function(r) {
152                 vlBibSources = openils.Util.readResponse(r, false, true);
153                 checkInitDone();
154             }
155         }
156     );
157
158     var owner = fieldmapper.aou.orgNodeTrail(fieldmapper.aou.findOrgUnit(new openils.User().user.ws_ou()));
159     new openils.PermaCrud().search('viiad', 
160         {owner: owner.map(function(org) { return org.id(); })},
161         {   async: true,
162             oncomplete: function(r) {
163                 importItemDefs = openils.Util.readResponse(r);
164                 checkInitDone();
165             }
166         }
167     );
168
169     new openils.PermaCrud().search('vms',
170         {owner: owner.map(function(org) { return org.id(); })},
171         {   async: true,
172             oncomplete: function(r) {
173                 var sets = openils.Util.readResponse(r);
174                 dojo.forEach(sets, 
175                     function(set) {
176                         if(!matchSets[set.mtype()])
177                             matchSets[set.mtype()] = [];
178                         matchSets[set.mtype()].push(set);
179                     }
180                 );
181                 checkInitDone();
182             }
183         }
184     );
185
186     vlAttrEditorInit();
187 }
188
189
190 openils.Util.addOnLoad(vlInit);
191
192
193 // fetch the bib and authority attribute definitions
194
195 function vlFetchBibAttrDefs(postcomplete) {
196     bibAttrDefs = [];
197     fieldmapper.standardRequest(
198         ['open-ils.permacrud', 'open-ils.permacrud.search.vqbrad'],
199         {   async: true,
200             params: [authtoken, {id:{'!=':null}}],
201             onresponse: function(r) {
202                 var def = r.recv().content(); 
203                 if(e = openils.Event.parse(def[0])) 
204                     return alert(e);
205                 bibAttrDefs.push(def);
206             },
207             oncomplete: function() {
208                 bibAttrDefs = bibAttrDefs.sort(
209                     function(a, b) {
210                         if(a.id() > b.id()) return 1;
211                         if(a.id() < b.id()) return -1;
212                         return 0;
213                     }
214                 );
215                 postcomplete();
216             }
217         }
218     );
219 }
220
221 function vlFetchAuthAttrDefs(postcomplete) {
222     authAttrDefs = [];
223     fieldmapper.standardRequest(
224         ['open-ils.permacrud', 'open-ils.permacrud.search.vqarad'],
225         {   async: true,
226             params: [authtoken, {id:{'!=':null}}],
227             onresponse: function(r) {
228                 var def = r.recv().content(); 
229                 if(e = openils.Event.parse(def[0])) 
230                     return alert(e);
231                 authAttrDefs.push(def);
232             },
233             oncomplete: function() {
234                 authAttrDefs = authAttrDefs.sort(
235                     function(a, b) {
236                         if(a.id() > b.id()) return 1;
237                         if(a.id() < b.id()) return -1;
238                         return 0;
239                     }
240                 );
241                 postcomplete();
242             }
243         }
244     );
245 }
246
247 function vlRetrieveQueueList(type, filter, onload) {
248     type = (type == 'bib') ? type : 'authority';
249     fieldmapper.standardRequest(
250         ['open-ils.vandelay', 'open-ils.vandelay.'+type+'_queue.owner.retrieve.atomic'],
251         {   async: true,
252             params: [authtoken, null, filter],
253             oncomplete: function(r) {
254                 var list = r.recv().content();
255                 if(e = openils.Event.parse(list[0]))
256                     return alert(e);
257                 onload(list);
258             }
259         }
260     );
261
262 }
263
264 function displayGlobalDiv(id) {
265     for(var i = 0; i < globalDivs.length; i++) {
266         try {
267             dojo.style(dojo.byId(globalDivs[i]), 'display', 'none');
268         } catch(e) {
269             alert('please define div ' + globalDivs[i]);
270         }
271     }
272     dojo.style(dojo.byId(id),'display','block');
273
274     openils.Util.removeCSSClass(dojo.byId('vl-menu-marc-export'), 'toolbar_selected');
275     openils.Util.removeCSSClass(dojo.byId('vl-menu-marc-upload'), 'toolbar_selected');
276     openils.Util.removeCSSClass(dojo.byId('vl-menu-queue-select'), 'toolbar_selected');
277     openils.Util.removeCSSClass(dojo.byId('vl-menu-attr-editor'), 'toolbar_selected');
278     openils.Util.removeCSSClass(dojo.byId('vl-menu-profile-editor'), 'toolbar_selected');
279     openils.Util.removeCSSClass(dojo.byId('vl-menu-match-set-editor'), 'toolbar_selected');
280
281     if(dojo.byId('vl-match-set-iframe'))
282         dojo.byId('vl-match-set-editor-div').removeChild(dojo.byId('vl-match-set-iframe'));
283
284     switch(id) {
285         case 'vl-marc-export-div':
286             openils.Util.addCSSClass(dojo.byId('vl-menu-marc-export'), 'toolbar_selected');
287             break;
288         case 'vl-marc-upload-div':
289             openils.Util.addCSSClass(dojo.byId('vl-menu-marc-upload'), 'toolbar_selected');
290             break;
291         case 'vl-queue-select-div':
292             openils.Util.addCSSClass(dojo.byId('vl-menu-queue-select'), 'toolbar_selected');
293             break;
294         case 'vl-attr-editor-div':
295             openils.Util.addCSSClass(dojo.byId('vl-menu-attr-editor'), 'toolbar_selected');
296             break;
297         case 'vl-profile-editor-div':
298             openils.Util.addCSSClass(dojo.byId('vl-menu-profile-editor'), 'toolbar_selected');
299             break;
300         case 'vl-item-attr-editor-div':
301             openils.Util.addCSSClass(dojo.byId('vl-menu-import-item-attr-editor'), 'toolbar_selected');
302             break;
303         case 'vl-match-set-editor-div':
304             openils.Util.addCSSClass(dojo.byId('vl-menu-match-set-editor'), 'toolbar_selected');
305             break;
306     }
307 }
308
309 function runStartupCommands() {
310     currentQueueId = cgi.param('qid');
311     currentType = cgi.param('qtype');
312     dojo.style('vl-nav-bar', 'visibility', 'visible');
313     if(currentQueueId)
314         return retrieveQueuedRecords(currentType, currentQueueId, handleRetrieveRecords);
315     vlShowUploadForm();
316 }
317
318 /**
319   * asynchronously upload a file of MARC records
320   */
321 function uploadMARC(onload){
322     dojo.byId('vl-upload-status-count').innerHTML = '0';
323     dojo.byId('vl-ses-input').value = authtoken;
324     displayGlobalDiv('vl-marc-upload-status-div');
325     dojo.io.iframe.send({
326         url: VANDELAY_URL,
327         method: "post",
328         handleAs: "html",
329         form: dojo.byId('vl-marc-upload-form'),
330         handle: function(data,ioArgs){
331             var content = data.documentElement.textContent;
332             onload(content);
333         }
334     });
335 }       
336
337 /**
338   * Creates a new vandelay queue
339   */
340 function createQueue(queueName, type, onload, importDefId, matchSet) {
341     var name = (type=='bib') ? 'bib' : 'authority';
342     var method = 'open-ils.vandelay.'+ name +'_queue.create'
343     fieldmapper.standardRequest(
344         ['open-ils.vandelay', method],
345         {   async: true,
346             params: [authtoken, queueName, null, name, matchSet, importDefId],
347             oncomplete : function(r) {
348                 var queue = r.recv().content();
349                 if(e = openils.Event.parse(queue)) 
350                     return alert(e);
351                 onload(queue);
352             }
353         }
354     );
355 }
356
357 /**
358   * Tells vandelay to pull a batch of records from the cache and explode them
359   * out into the vandelay tables
360   */
361 function processSpool(key, queueId, type, onload) {
362     fieldmapper.standardRequest(
363         ['open-ils.vandelay', 'open-ils.vandelay.'+type+'.process_spool'],
364         {   async: true,
365             params: [authtoken, key, queueId],
366             onresponse : function(r) {
367                 var resp = r.recv().content();
368                 if(e = openils.Event.parse(resp)) 
369                     return alert(e);
370                 dojo.byId('vl-upload-status-count').innerHTML = resp;
371             },
372             oncomplete : function(r) {onload();}
373         }
374     );
375 }
376
377 function retrieveQueuedRecords(type, queueId, onload) {
378     displayGlobalDiv('vl-generic-progress');
379     queuedRecords = [];
380     queuedRecordsMap = {};
381     currentOverlayRecordsMap = {};
382     currentOverlayRecordsMapGid = {};
383     selectableGridRecords = {};
384     //resetVlQueueGridLayout();
385
386     if(!type) type = currentType;
387     if(!queueId) queueId = currentQueueId;
388     if(!onload) onload = handleRetrieveRecords;
389
390     var method = 'open-ils.vandelay.'+type+'_queue.records.retrieve.atomic';
391     if(vlQueueGridShowMatches.checked)
392         method = method.replace('records', 'records.matches');
393
394     var sel = dojo.byId('vl-queue-display-limit-selector');
395     var limit = parseInt(sel.options[sel.selectedIndex].value);
396     var offset = limit * parseInt(vlQueueDisplayPage.attr('value')-1);
397
398     var params =  [authtoken, queueId, {clear_marc: 1, offset: offset, limit: limit, flesh_import_items:1}];
399     if(vlQueueGridShowNonImport.checked)
400         params[2].non_imported = 1;
401
402     if(vlQueueGridShowImportErrors.checked)
403         params[2].with_import_error = 1;
404
405     fieldmapper.standardRequest(
406         ['open-ils.vandelay', method],
407         {   async: true,
408             params: params,
409             /*
410             onresponse: function(r) {
411                 console.log("ONREPONSE");
412                 var rec = r.recv().content();
413                 if(e = openils.Event.parse(rec))
414                     return alert(e);
415                 console.log("got record " + rec.id());
416                 queuedRecords.push(rec);
417                 queuedRecordsMap[rec.id()] = rec;
418             },
419             */
420             oncomplete: function(r){
421                 var recs = r.recv().content();
422                 if(e = openils.Event.parse(recs[0]))
423                     return alert(e);
424                 for(var i = 0; i < recs.length; i++) {
425                     var rec = recs[i];
426                     queuedRecords.push(rec);
427                     queuedRecordsMap[rec.id()] = rec;
428                 }
429                 onload();
430             }
431         }
432     );
433 }
434
435 function vlLoadMatchUI(recId) {
436     displayGlobalDiv('vl-generic-progress');
437     var matches = queuedRecordsMap[recId].matches();
438     var records = [];
439     currentImportRecId = recId;
440     for(var i = 0; i < matches.length; i++)
441         records.push(matches[i].eg_record());
442
443     var retrieve = ['open-ils.search', 'open-ils.search.biblio.record_entry.slim.retrieve'];
444     var params = [records];
445     if(currentType == 'auth') {
446         retrieve = ['open-ils.cat', 'open-ils.cat.authority.record.retrieve'];
447         params = [authtoken, records, {clear_marc:1}];
448     }
449
450     fieldmapper.standardRequest(
451         retrieve,
452         {   async: true,
453             params:params,
454             oncomplete: function(r) {
455                 var recs = r.recv().content();
456                 if(e = openils.Event.parse(recs))
457                     return alert(e);
458
459                 /* ui mangling */
460                 displayGlobalDiv('vl-match-div');
461                 resetVlMatchGridLayout();
462                 currentMatchedRecords = recs;
463                 vlMatchGrid.setStructure(vlMatchGridLayout);
464
465                 // build the data store of records with match information
466                 var dataStore = bre.toStoreData(recs, null, 
467                     {virtualFields:['_id', 'match_score', 'match_quality']});
468                 dataStore.identifier = '_id';
469
470                 var matchSeenMap = {};
471
472                 for(var i = 0; i < dataStore.items.length; i++) {
473                     var item = dataStore.items[i];
474                     item._id = i; // just need something unique
475                     for(var j = 0; j < matches.length; j++) {
476                         var match = matches[j];
477                         if(match.eg_record() == item.id && !matchSeenMap[match.id()]) {
478                             if(match.match_score)
479                                 item.match_score = match.match_score();
480                             item.match_quality = match.quality();
481                             matchSeenMap[match.id()] = 1;
482                             break;
483                         }
484                     }
485                 }
486
487                 // now populate the grid
488                 vlPopulateMatchGrid(vlMatchGrid, dataStore);
489             }
490         }
491     );
492 }
493
494 function vlPopulateMatchGrid(grid, data) {
495     var store = new dojo.data.ItemFileReadStore({data:data});
496     grid.setStore(store);
497     grid.update();
498 }
499
500 function showMe(id) {
501     dojo.style(dojo.byId(id), 'display', 'block');
502 }
503 function hideMe(id) {
504     dojo.style(dojo.byId(id), 'display', 'none');
505 }
506
507
508 function vlLoadMARCHtml(recId, inCat, oncomplete) {
509     dijit.byId('vl-marc-html-done-button').onClick = oncomplete;
510     displayGlobalDiv('vl-generic-progress');
511     var api;
512     var params = [recId, 1];
513
514     if(inCat) {
515         hideMe('vl-marc-html-edit-button'); // don't show marc editor button
516         dijit.byId('vl-marc-html-edit-button').onClick = function(){}
517         api = ['open-ils.search', 'open-ils.search.biblio.record.html'];
518         if(currentType == 'auth')
519             api = ['open-ils.search', 'open-ils.search.authority.to_html'];
520     } else {
521         showMe('vl-marc-html-edit-button'); // plug in the marc editor button
522         dijit.byId('vl-marc-html-edit-button').onClick = 
523             function() {vlLoadMarcEditor(currentType, recId, oncomplete);};
524         params = [authtoken, recId];
525         api = ['open-ils.vandelay', 'open-ils.vandelay.queued_bib_record.html'];
526         if(currentType == 'auth')
527             api = ['open-ils.vandelay', 'open-ils.vandelay.queued_authority_record.html'];
528     }
529
530     fieldmapper.standardRequest(
531         api, 
532         {   async: true,
533             params: params,
534             oncomplete: function(r) {
535             displayGlobalDiv('vl-marc-html-div');
536                 var html = r.recv().content();
537                 dojo.byId('vl-marc-record-html').innerHTML = html;
538             }
539         }
540     );
541 }
542
543
544 /*
545 function getRecMatchesFromAttrCode(rec, attrCode) {
546     var matches = [];
547     var attr = getRecAttrFromCode(rec, attrCode);
548     for(var j = 0; j < rec.matches().length; j++) {
549         var match = rec.matches()[j];
550         if(match.matched_attr() == attr.id()) 
551             matches.push(match);
552     }
553     return matches;
554 }
555 */
556
557 /*
558 function getRecAttrFromMatch(rec, match) {
559     for(var i = 0; i < rec.attributes().length; i++) {
560         var attr = rec.attributes()[i];
561         if(attr.id() == match.matched_attr())
562             return attr;
563     }
564 }
565 */
566
567 function getRecAttrDefFromAttr(attr, type) {
568     var defs = (type == 'bib') ? bibAttrDefs : authAttrDefs;
569     for(var i = 0; i < defs.length; i++) {
570         var def = defs[i];
571         if(def.id() == attr.field())
572             return def;
573     }
574 }
575
576 function getRecAttrFromCode(rec, attrCode) {
577     var defId = attrDefMap[currentType][attrCode];
578     var attrs = rec.attributes();
579     for(var i = 0; i < attrs.length; i++) {
580         var attr = attrs[i];
581         if(attr.field() == defId) 
582             return attr;
583     }
584     return null;
585 }
586
587 function vlGetViewMatches(rowIdx, item) {
588     if(item) {
589         var id = this.grid.store.getValue(item, 'id');
590         var rec = queuedRecordsMap[id];
591         if(rec.matches().length > 0)
592             return id;
593     }
594     return -1
595 }
596
597 function vlFormatViewMatches(id) {
598     if(id == -1) return '';
599     return '<a href="javascript:void(0);" onclick="vlLoadMatchUI(' + id + ');">' + this.name + '</a>';
600 }
601
602 function vlGetViewErrors(rowIdx, item) {
603     if(item) {
604         var id = this.grid.store.getValue(item, 'id');
605         var rec = queuedRecordsMap[id];
606         // id:rec_error:item_import_error_count
607         return id + ':' + 
608             (rec.import_error() ? 1 : '') + ':' + 
609             rec.import_items().filter(function(i) {return i.import_error()}).length;
610     }
611     return -1
612 }
613
614 function vlFormatViewErrors(chunk) {
615     if(chunk == -1) return '';
616     var id = chunk.split(':')[0];
617     var rec = chunk.split(':')[1];
618     var count = chunk.split(':')[2];
619     var links = '';
620     if(rec) 
621         links += '<a href="javascript:void(0);" onclick="vlLoadErrorUI(' + id + ');">Record</a><br/>'; // TODO I18N
622     if(Number(count))
623         links += '<a href="javascript:void(0);" onclick="vlLoadErrorUI(' + id + ');">Items ('+count+')</a>'; // TODO I18N
624     return links;
625 }
626
627 //var vlItemErrorColumnPicker;
628 function vlLoadErrorUI(id) {
629
630     displayGlobalDiv('vl-import-error-div');
631     openils.Util.hide('vl-import-error-grid-all');
632     openils.Util.show('vl-import-error-record');
633
634     var rec = queuedRecordsMap[id];
635
636     dojo.byId('vl-error-id').innerHTML = rec.id();
637     dojo.forEach( // TODO sane authority rec. fields
638         ['title', 'author', 'isbn', 'issn', 'upc'],
639         function(field) {
640             var attr =  getRecAttrFromCode(rec, field);
641             var eid = 'vl-error-' + field;
642             if(attr) {
643                 openils.Util.show(dojo.byId(eid).parentNode, 'table-row');
644                 dojo.byId(eid).innerHTML = attr.attr_value();
645             } else {
646                 openils.Util.hide(dojo.byId(eid).parentNode);
647             }
648         }
649     );
650     var iediv = dojo.byId('vl-error-import-error');
651     var eddiv = dojo.byId('vl-error-error-detail');
652     if(rec.import_error()) {
653         openils.Util.show(iediv.parentNode, 'table-row');
654         openils.Util.show(eddiv.parentNode, 'table-row');
655         iediv.innerHTML = rec.import_error();
656         eddiv.innerHTML = rec.error_detail();
657     } else {
658         openils.Util.hide(iediv.parentNode);
659         openils.Util.hide(eddiv.parentNode);
660     }
661
662     var errorItems = rec.import_items().filter(function(i) {return i.import_error()});
663     if(errorItems.length) {
664         openils.Util.show('vl-import-error-grid-some');
665         storeData = vqbr.toStoreData(errorItems);
666         var store = new dojo.data.ItemFileReadStore({data:storeData});
667         vlImportErrorGrid.setStore(store);
668         vlImportErrorGrid.update();
669     } else {
670         openils.Util.hide('vl-import-error-grid-some');
671     }
672 }
673
674 function vlLoadErrorUIAll() {
675
676     displayGlobalDiv('vl-import-error-div');
677     openils.Util.hide('vl-import-error-grid-some');
678     openils.Util.hide('vl-import-error-record');
679     openils.Util.show('vl-import-error-grid-all');
680     vlAllImportErrorGrid.resetStore();
681
682     vlImportErrorGrid.displayOffset = 0;
683
684     vlAllImportErrorGrid.dataLoader = function() {
685
686         vlAllImportErrorGrid.showLoadProgressIndicator();
687
688         fieldmapper.standardRequest(
689             ['open-ils.vandelay', 'open-ils.vandelay.import_item.queue.retrieve'],
690             {
691                 async : true,
692                 params : [
693                     authtoken, currentQueueId, {   
694                         with_import_error: (vlImportItemsShowErrors.checked) ? 1 : null,
695                         offset : vlAllImportErrorGrid.displayOffset,
696                         limit : vlAllImportErrorGrid.displayLimit
697                     }
698                 ],
699                 onresponse : function(r) {
700                     var item = openils.Util.readResponse(r);
701                     if(!item) return;
702                     vlAllImportErrorGrid.store.newItem(vii.toStoreItem(item));
703                 },
704                 oncomplete : function() {
705                     vlAllImportErrorGrid.hideLoadProgressIndicator();
706                 }
707             }
708         );
709     };
710
711     vlAllImportErrorGrid.dataLoader();
712 }
713
714 function vlGetOrg(rowIdx, item) {
715     if(!item) return '';
716     var value = this.grid.store.getValue(item, this.field);
717     if(value) return fieldmapper.aou.findOrgUnit(value).shortname();
718     return '';
719 }
720
721 function vlFormatViewMatchMARC(id) {
722     return '<a href="javascript:void(0);" onclick="vlLoadMARCHtml(' + id + ', true, '+
723         'function(){displayGlobalDiv(\'vl-match-div\');});">' + this.name + '</a>';
724 }
725
726 function getAttrValue(rowIdx, item) {
727     if(!item) return '';
728     var attrCode = this.field.split('.')[1];
729     var rec = queuedRecordsMap[this.grid.store.getValue(item, 'id')];
730     var attr = getRecAttrFromCode(rec, attrCode);
731     return (attr) ? attr.attr_value() : '';
732 }
733
734 function vlGetDateTimeField(rowIdx, item) {
735     if(!item) return '';
736     var value = this.grid.store.getValue(item, this.field);
737     if(!value) return '';
738     var date = dojo.date.stamp.fromISOString(value);
739     return dojo.date.locale.format(date, {selector:'date'});
740 }
741
742 function vlGetCreator(rowIdx, item) {
743     if(!item) return '';
744     var id = this.grid.store.getValue(item, 'creator');
745     if(userCache[id])
746         return userCache[id].usrname();
747     var user = fieldmapper.standardRequest(
748         ['open-ils.actor', 'open-ils.actor.user.retrieve'], [authtoken, id]);
749     if(e = openils.Event.parse(user))
750         return alert(e);
751     userCache[id] = user;
752     return user.usrname();
753 }
754
755 function vlGetViewMARC(rowIdx, item) {
756     return item && this.grid.store.getValue(item, 'id');
757 }
758
759 function vlFormatViewMARC(id) {
760     return '<a href="javascript:void(0);" onclick="vlLoadMARCHtml(' + id + ', false, '+
761         'function(){displayGlobalDiv(\'vl-queue-div\');});">' + this.name + '</a>';
762 }
763
764 function vlGetOverlayTargetSelector(rowIdx, item) {
765     if(!item) return;
766     return this.grid.store.getValue(item, '_id') + ':' + this.grid.store.getValue(item, 'id');
767 }
768
769 function vlFormatOverlayTargetSelector(val) {
770     if(!val) return '';
771     var parts = val.split(':');
772     var _id = parts[0];
773     var id = parts[1];
774     var value = '<input type="checkbox" name="vl-overlay-target-RECID" '+
775         'onclick="vlHandleOverlayTargetSelected(ID, GRIDID);" gridid="GRIDID" match="ID"/>';
776     value = value.replace(/GRIDID/g, _id);
777     value = value.replace(/RECID/g, currentImportRecId);
778     value = value.replace(/ID/g, id);
779     if(_id == currentOverlayRecordsMapGid[currentImportRecId])
780         return value.replace('/>', 'checked="checked"/>');
781     return value;
782 }
783
784
785 /**
786   * see if the user has enabled overlays for the current match set and, 
787   * if so, map the current import record to the overlay target.
788   */
789 function vlHandleOverlayTargetSelected(recId, gridId) {
790     var noneSelected = true;
791     var checkboxes = dojo.query('[name=vl-overlay-target-'+currentImportRecId+']');
792     for(var i = 0; i < checkboxes.length; i++) {
793         var checkbox = checkboxes[i];
794         var matchRecId = checkbox.getAttribute('match');
795         var gid = checkbox.getAttribute('gridid');
796         if(checkbox.checked) {
797             if(matchRecId == recId && gid == gridId) {
798                 noneSelected = false;
799                 currentOverlayRecordsMap[currentImportRecId] = matchRecId;
800                 currentOverlayRecordsMapGid[currentImportRecId] = gid;
801                 dojo.byId('vl-record-list-selected-' + currentImportRecId).checked = true;
802                 dojo.byId('vl-record-list-selected-' + currentImportRecId).parentNode.className = 'overlay_selected';
803             } else {
804                 checkbox.checked = false;
805             }
806         }
807     }
808
809     if(noneSelected) {
810         delete currentOverlayRecordsMap[currentImportRecId];
811         delete currentOverlayRecordsMapGid[currentImportRecId];
812         dojo.byId('vl-record-list-selected-' + currentImportRecId).checked = false;
813         dojo.byId('vl-record-list-selected-' + currentImportRecId).parentNode.className = '';
814     }
815 }
816
817 var valLastQueueType = null;
818 var vlQueueGridLayout = null;
819 function buildRecordGrid(type) {
820     displayGlobalDiv('vl-queue-div');
821
822     if(type == 'bib') {
823         openils.Util.show('vl-bib-queue-grid-wrapper');
824         openils.Util.hide('vl-auth-queue-grid-wrapper');
825         vlQueueGrid = vlBibQueueGrid;
826     } else {
827         openils.Util.show('vl-auth-queue-grid-wrapper');
828         openils.Util.hide('vl-bib-queue-grid-wrapper');
829         vlQueueGrid = vlAuthQueueGrid;
830     }
831
832
833     if(valLastQueueType != type) {
834         valLastQueueType = type;
835         vlQueueGridLayout = vlQueueGrid.attr('structure');
836         var defs = (type == 'bib') ? bibAttrDefs : authAttrDefs;
837         attrDefMap[type] = {};
838         for(var i = 0; i < defs.length; i++) {
839             var def = defs[i]
840             attrDefMap[type][def.code()] = def.id();
841             var col = {
842                 name:def.description(), 
843                 field:'attr.' + def.code(),
844                 get: getAttrValue,
845                 selectableColumn:true
846             };
847             vlQueueGridLayout[0].cells[0].push(col);
848         }
849     }
850
851     dojo.forEach(vlQueueGridLayout[0].cells[0], 
852         function(cell) { 
853             if(cell.field.match(/^\+/)) 
854                 cell.nonSelectable=true;
855         }
856     );
857
858     var storeData;
859     if(type == 'bib')
860         storeData = vqbr.toStoreData(queuedRecords);
861     else
862         storeData = vqar.toStoreData(queuedRecords);
863
864     var store = new dojo.data.ItemFileReadStore({data:storeData});
865     vlQueueGrid.setStore(store);
866
867     if(vlQueueGridColumePicker[type]) {
868         vlQueueGrid.update();
869     } else {
870
871         vlQueueGridColumePicker[type] =
872             new openils.widget.GridColumnPicker(
873                 authtoken, 'vandelay.queue.'+type, vlQueueGrid, vlQueueGridLayout);
874         vlQueueGridColumePicker[type].load();
875     }
876 }
877
878 function vlQueueGridPrevPage() {
879     var page = parseInt(vlQueueDisplayPage.getValue());
880     if(page < 2) return;
881     vlQueueDisplayPage.setValue(page - 1);
882     retrieveQueuedRecords(currentType, currentQueueId, handleRetrieveRecords);
883 }
884
885 function vlQueueGridNextPage() {
886     vlQueueDisplayPage.setValue(parseInt(vlQueueDisplayPage.getValue())+1);
887     retrieveQueuedRecords(currentType, currentQueueId, handleRetrieveRecords);
888 }
889
890 function vlDeleteQueue(type, queueId, onload) {
891     fieldmapper.standardRequest(
892         ['open-ils.vandelay', 'open-ils.vandelay.'+type+'_queue.delete'],
893         {   async: true,
894             params: [authtoken, queueId],
895             oncomplete: function(r) {
896                 var resp = r.recv().content();
897                 if(e = openils.Event.parse(resp))
898                     return alert(e);
899                 onload();
900             }
901         }
902     );
903 }
904
905
906 function vlQueueGridDrawSelectBox(rowIdx, item) {
907     return item &&  this.grid.store.getValue(item, 'id');
908 }
909
910 function vlQueueGridFormatSelectBox(id) {
911     var domId = 'vl-record-list-selected-' + id;
912     if (id) { selectableGridRecords[domId] = id; }
913     return "<div><input type='checkbox' id='"+domId+"'/></div>";
914 }
915
916 function vlSelectAllQueueGridRecords() {
917     for(var id in selectableGridRecords) 
918         dojo.byId(id).checked = true;
919 }
920 function vlSelectNoQueueGridRecords() {
921     for(var id in selectableGridRecords) 
922         dojo.byId(id).checked = false;
923 }
924 function vlToggleQueueGridSelect() {
925     if(dojo.byId('vl-queue-grid-row-selector').checked)
926         vlSelectAllQueueGridRecords();
927     else
928         vlSelectNoQueueGridRecords();
929 }
930
931 var handleRetrieveRecords = function() {
932     buildRecordGrid(currentType);
933     vlFetchQueueSummary(currentQueueId, currentType, 
934         function(summary) {
935             dojo.byId('vl-queue-summary-name').innerHTML = summary.queue.name();
936             dojo.byId('vl-queue-summary-total-count').innerHTML = summary.total +'';
937             dojo.byId('vl-queue-summary-import-count').innerHTML = summary.imported + '';
938             dojo.byId('vl-queue-summary-import-item-count').innerHTML = summary.total_items + '';
939             dojo.byId('vl-queue-summary-rec-error-count').innerHTML = summary.rec_import_errors + '';
940             dojo.byId('vl-queue-summary-item-error-count').innerHTML = summary.item_import_errors + '';
941         }
942     );
943 }
944
945 function vlFetchQueueSummary(qId, type, onload) {
946     fieldmapper.standardRequest(
947         ['open-ils.vandelay', 'open-ils.vandelay.'+type+'_queue.summary.retrieve'],
948         {   async: true,
949             params: [authtoken, qId],
950             oncomplete : function(r) {
951                 var summary = r.recv().content();
952                 if(e = openils.Event.parse(summary))
953                     return alert(e);
954                 return onload(summary);
955             }
956         }
957     );
958 }
959
960 function vlHandleQueueItemsAction(action) {
961
962     dojo.connect(
963         queueItemsImportCancelButton, 
964         'onClick', 
965         function() {
966             queueItemsImportDialog.hide();
967         }
968     );
969
970     dojo.connect(
971         queueItemsImportGoButton,
972         'onClick', 
973         function() {
974             queueItemsImportDialog.hide();
975
976             // hack to set the widgets the import funcs will be looking at.  Reset them below.
977             vlUploadQueueAutoImport.attr('value',  vlUploadQueueAutoImport2.attr('value'));
978             vlUploadQueueAutoOverlayExact.attr('value',  vlUploadQueueAutoOverlayExact2.attr('value'));
979             vlUploadQueueAutoOverlay1Match.attr('value',  vlUploadQueueAutoOverlay1Match2.attr('value'));
980             vlUploadMergeProfile.attr('value',  vlUploadMergeProfile2.attr('value'));
981
982             if(action == 'import') {
983                 vlImportSelectedRecords();
984             } else if(action == 'import_all') {
985                 vlImportAllRecords();
986             }
987             
988             // reset the widgets to prevent accidental future actions
989             vlUploadQueueAutoImport.attr('value',  false);
990             vlUploadQueueAutoImport2.attr('value', false);
991             vlUploadQueueAutoOverlayExact.attr('value', false);
992             vlUploadQueueAutoOverlayExact2.attr('value', false);
993             vlUploadQueueAutoOverlay1Match.attr('value', false);
994             vlUploadQueueAutoOverlay1Match2.attr('value', false);
995             vlUploadMergeProfile.attr('value', '');
996             vlUploadMergeProfile2.attr('value', '');
997         }
998     );
999
1000     queueItemsImportDialog.show();
1001 }
1002     
1003
1004 function vlImportSelectedRecords() {
1005     displayGlobalDiv('vl-generic-progress-with-total');
1006     var records = [];
1007
1008     for(var id in selectableGridRecords) {
1009         if(dojo.byId(id).checked) {
1010             var recId = selectableGridRecords[id];
1011             var rec = queuedRecordsMap[recId];
1012             if(!rec.import_time()) 
1013                 records.push(recId);
1014         }
1015     }
1016
1017     var options = {overlay_map : currentOverlayRecordsMap};
1018
1019     if(vlUploadQueueAutoOverlayExact.checked) {
1020         options.auto_overlay_exact = true;
1021         vlUploadQueueAutoOverlayExact.checked = false;
1022     }
1023
1024     if(vlUploadQueueAutoOverlay1Match.checked) {
1025         options.auto_overlay_1match = true;
1026         vlUploadQueueAutoOverlay1Match.checked = false;
1027     }
1028     
1029     var profile = vlUploadMergeProfile.attr('value');
1030     if(profile != null && profile != '') {
1031         options.merge_profile = profile;
1032     }
1033
1034     fieldmapper.standardRequest(
1035         ['open-ils.vandelay', 'open-ils.vandelay.'+currentType+'_record.list.import'],
1036         {   async: true,
1037             params: [authtoken, records, options],
1038             onresponse: function(r) {
1039                 var resp = r.recv().content();
1040                 if(e = openils.Event.parse(resp))
1041                     return alert(e);
1042                 if(resp.complete) {
1043                     return retrieveQueuedRecords(currentType, currentQueueId, handleRetrieveRecords);
1044                 } else {
1045                     vlControlledProgressBar.update({maximum:resp.total, progress:resp.progress});
1046                 }
1047             }, 
1048         }
1049     );
1050 }
1051
1052 function vlImportAllRecords() {
1053     vlImportRecordQueue(currentType, currentQueueId, false,
1054         function(){displayGlobalDiv('vl-queue-div');});
1055 }
1056
1057 function vlImportRecordQueue(type, queueId, noMatchOnly, onload) {
1058     displayGlobalDiv('vl-generic-progress-with-total');
1059     var method = 'open-ils.vandelay.bib_queue.import';
1060     if(noMatchOnly)
1061         method = method.replace('import', 'nomatch.import');
1062     if(type == 'auth')
1063         method = method.replace('bib', 'auth');
1064
1065     var options = {};
1066     if(vlUploadQueueAutoOverlayExact.checked) {
1067         options.auto_overlay_exact = true;
1068         vlUploadQueueAutoOverlayExact.checked = false;
1069     }
1070
1071     if(vlUploadQueueAutoOverlay1Match.checked) {
1072         options.auto_overlay_1match = true;
1073         vlUploadQueueAutoOverlay1Match.checked = false;
1074     }
1075     
1076     var profile = vlUploadMergeProfile.attr('value');
1077     if(profile != null && profile != '') {
1078         options.merge_profile = profile;
1079     }
1080
1081     fieldmapper.standardRequest(
1082         ['open-ils.vandelay', method],
1083         {   async: true,
1084             params: [authtoken, queueId, options],
1085             onresponse: function(r) {
1086                 var resp = r.recv().content();
1087                 if(e = openils.Event.parse(resp))
1088                     return alert(e);
1089                 vlControlledProgressBar.update({maximum:resp.total, progress:resp.progress});
1090             },
1091             oncomplete: function() {onload();}
1092         }
1093     );
1094 }
1095
1096
1097 /**
1098   * Create queue, upload MARC, process spool, load the newly created queue 
1099   */
1100 function batchUpload() {
1101     var queueName = dijit.byId('vl-queue-name').getValue();
1102     currentType = dijit.byId('vl-record-type').getValue();
1103
1104     var handleProcessSpool = function() {
1105         if(vlUploadQueueAutoImport.checked || vlUploadQueueAutoOverlayExact.checked || vlUploadQueueAutoOverlay1Match.checked) {
1106             var noMatchOnly = !vlUploadQueueAutoOverlayExact.checked && !vlUploadQueueAutoOverlay1Match.checked;
1107             vlImportRecordQueue(
1108                 currentType, 
1109                 currentQueueId, 
1110                 noMatchOnly,
1111                 function() {
1112                     retrieveQueuedRecords(currentType, currentQueueId, handleRetrieveRecords);
1113                 }
1114             );
1115         } else {
1116             retrieveQueuedRecords(currentType, currentQueueId, handleRetrieveRecords);
1117         }
1118     }
1119
1120     var handleUploadMARC = function(key) {
1121         dojo.style(dojo.byId('vl-upload-status-processing'), 'display', 'block');
1122         processSpool(key, currentQueueId, currentType, handleProcessSpool);
1123     };
1124
1125     var handleCreateQueue = function(queue) {
1126         currentQueueId = queue.id();
1127         uploadMARC(handleUploadMARC);
1128     };
1129     
1130     if(vlUploadQueueSelector.getValue() && !queueName) {
1131         currentQueueId = vlUploadQueueSelector.getValue();
1132         uploadMARC(handleUploadMARC);
1133     } else {
1134         createQueue(queueName, currentType, handleCreateQueue, 
1135             vlUploadQueueHoldingsImportProfile.attr('value'),
1136             vlUploadQueueMatchSet.attr('value')
1137         );
1138     }
1139 }
1140
1141
1142 function vlFleshQueueSelect(selector, type) {
1143     var data = (type == 'bib') ? vbq.toStoreData(allUserBibQueues) : vaq.toStoreData(allUserAuthQueues);
1144     selector.store = new dojo.data.ItemFileReadStore({data:data});
1145     selector.setValue(null);
1146     selector.setDisplayedValue('');
1147     if(data[0])
1148         selector.setValue(data[0].id());
1149
1150     var qInput = dijit.byId('vl-queue-name');
1151
1152     var selChange = function(val) {
1153         console.log('selector onchange');
1154         // user selected a queue from the selector;  clear the input and 
1155         // set the item import profile already defined for the queue
1156         var queue = allUserBibQueues.filter(function(q) { return (q.id() == val) })[0];
1157         if(val) {
1158             vlUploadQueueHoldingsImportProfile.attr('value', queue.item_attr_def() || '');
1159             vlUploadQueueHoldingsImportProfile.attr('disabled', true);
1160             vlUploadQueueMatchSet.attr('value', queue.match_set() || '');
1161             vlUploadQueueMatchSet.attr('disabled', true);
1162         } else {
1163             vlUploadQueueHoldingsImportProfile.attr('value', '');
1164             vlUploadQueueHoldingsImportProfile.attr('disabled', false);
1165             vlUploadQueueMatchSet.attr('value', '');
1166             vlUploadQueueMatchSet.attr('disabled', false);
1167         }
1168         dojo.disconnect(qInput._onchange);
1169         qInput.attr('value', '');
1170         qInput._onchange = dojo.connect(qInput, 'onChange', inputChange);
1171     }
1172     
1173     var inputChange = function(val) {
1174         console.log('qinput onchange');
1175         // user entered a new queue name. clear the selector 
1176         vlUploadQueueHoldingsImportProfile.attr('value', '');
1177         vlUploadQueueHoldingsImportProfile.attr('disabled', false);
1178         vlUploadQueueMatchSet.attr('value', '');
1179         vlUploadQueueMatchSet.attr('disabled', false);
1180         dojo.disconnect(selector._onchange);
1181         selector.attr('value', '');
1182         selector._onchange = dojo.connect(selector, 'onChange', selChange);
1183     }
1184
1185     selector._onchange = dojo.connect(selector, 'onChange', selChange);
1186     qInput._onchange = dojo.connect(qInput, 'onChange', inputChange);
1187 }
1188
1189 function vlUpdateMatchSetSelector(type) {
1190     type = (type.match(/bib/)) ? 'biblio' : 'authority';
1191     vlUploadQueueMatchSet.store = 
1192         new dojo.data.ItemFileReadStore({data:vms.toStoreData(matchSets[type])});
1193 }
1194
1195 function vlShowUploadForm() {
1196     displayGlobalDiv('vl-marc-upload-div');
1197     vlFleshQueueSelect(vlUploadQueueSelector, vlUploadRecordType.getValue());
1198     vlUploadSourceSelector.store = 
1199         new dojo.data.ItemFileReadStore({data:cbs.toStoreData(vlBibSources, 'source')});
1200     vlUploadSourceSelector.setValue(vlBibSources[0].id());
1201     vlUploadQueueHoldingsImportProfile.store = 
1202         new dojo.data.ItemFileReadStore({data:viiad.toStoreData(importItemDefs)});
1203     vlUpdateMatchSetSelector(vlUploadRecordType.getValue());
1204 }
1205
1206 function vlShowQueueSelect() {
1207     displayGlobalDiv('vl-queue-select-div');
1208     vlFleshQueueSelect(vlQueueSelectQueueList, vlQueueSelectType.getValue());
1209 }
1210
1211 function vlShowMatchSetEditor() {
1212     displayGlobalDiv('vl-match-set-editor-div');
1213     dojo.byId('vl-match-set-editor-div').appendChild(
1214         dojo.create('iframe', {
1215             id : 'vl-match-set-iframe',
1216             src : oilsBasePath + '/eg/conify/global/vandelay/match_set',
1217             style : 'width:100%; height:500px; border:none; margin:0px;'
1218         })
1219     );
1220 }
1221
1222 function vlFetchQueueFromForm() {
1223     currentType = vlQueueSelectType.getValue();
1224     currentQueueId = vlQueueSelectQueueList.getValue();
1225     retrieveQueuedRecords(currentType, currentQueueId, handleRetrieveRecords);
1226 }
1227
1228 function vlOpenMarcEditWindow(rec, postReloadHTMLHandler) {
1229     /*
1230         To run in Firefox directly, must set signed.applets.codebase_principal_support
1231         to true in about:config
1232     */
1233     netscape.security.PrivilegeManager.enablePrivilege('UniversalXPConnect');
1234     win = window.open('/xul/server/cat/marcedit.xul'); // XXX version?
1235
1236     var type;
1237     if (currentType == 'bib') {
1238         type = 'bre';
1239     } else {
1240         type = 'are';
1241     }
1242
1243     function onsave(r) {
1244         // after the record is saved, reload the HTML display
1245         var stat = r.recv().content();
1246         if(e = openils.Event.parse(stat))
1247             return alert(e);
1248         alert(dojo.byId('vl-marc-edit-complete-label').innerHTML);
1249         win.close();
1250         vlLoadMARCHtml(rec.id(), false, postReloadHTMLHandler);
1251     }
1252
1253     win.xulG = {
1254         record : {marc : rec.marc(), "rtype": type},
1255         save : {
1256             label: dojo.byId('vl-marc-edit-save-label').innerHTML,
1257             func: function(xmlString) {
1258                 var method = 'open-ils.permacrud.update.' + rec.classname;
1259                 rec.marc(xmlString);
1260                 fieldmapper.standardRequest(
1261                     ['open-ils.permacrud', method],
1262                     {   async: true,
1263                         params: [authtoken, rec],
1264                         oncomplete: onsave
1265                     }
1266                 );
1267             },
1268         },
1269         'lock_tab' : typeof xulG != 'undefined' ? (typeof xulG['lock_tab'] != 'undefined' ? xulG.lock_tab : undefined) : undefined,
1270         'unlock_tab' : typeof xulG != 'undefined' ? (typeof xulG['unlock_tab'] != 'undefined' ? xulG.unlock_tab : undefined) : undefined
1271     };
1272 }
1273
1274 function vlLoadMarcEditor(type, recId, postReloadHTMLHandler) {
1275     var method = 'open-ils.permacrud.search.vqbr';
1276     if(currentType != 'bib')
1277         method = method.replace(/vqbr/,'vqar');
1278
1279     fieldmapper.standardRequest(
1280         ['open-ils.permacrud', method],
1281         {   async: true, 
1282             params: [authtoken, {id : recId}],
1283             oncomplete: function(r) {
1284                 var rec = r.recv().content();
1285                 if(e = openils.Event.parse(rec))
1286                     return alert(e);
1287                 vlOpenMarcEditWindow(rec, postReloadHTMLHandler);
1288             }
1289         }
1290     );
1291 }
1292
1293
1294
1295 //------------------------------------------------------------
1296 // attribute editors
1297
1298 // attribute-editor global variables
1299
1300 var ATTR_EDITOR_IN_UPDATE_MODE = false; // true on 'edit', false on 'create'
1301 var ATTR_EDIT_ID = null;                // id of current 'edit' attribute
1302 var ATTR_EDIT_GROUP = 'bib';            // bib-attrs or auth-attrs
1303
1304 function vlAttrEditorInit() {
1305     // set up tooltips on the edit form
1306     connectTooltip('attr-editor-tags'); 
1307     connectTooltip('attr-editor-subfields'); 
1308 }
1309
1310 function vlShowAttrEditor() {
1311     displayGlobalDiv('vl-attr-editor-div');
1312     loadAttrEditorGrid();
1313     idHide('vl-generic-progress');
1314 }
1315
1316 function setAttrEditorGroup(groupName) {
1317     // put us into 'bib'-attr or 'auth'-attr mode.
1318     if (ATTR_EDIT_GROUP != groupName) {
1319         ATTR_EDIT_GROUP = groupName;
1320         loadAttrEditorGrid();
1321     }
1322 }
1323
1324 function onAttrEditorOpen() {
1325     // the "bars" have the create/update/cancel/etc. buttons.
1326     var create_bar = document.getElementById('attr-editor-create-bar');
1327     var update_bar = document.getElementById('attr-editor-update-bar');
1328     if (ATTR_EDITOR_IN_UPDATE_MODE) {
1329         update_bar.style.display='table-row';
1330         create_bar.style.display='none';
1331         // hide the dropdown-button
1332         idStyle('vl-create-attr-editor-button', 'visibility', 'hidden');
1333     } else {
1334         dijit.byId('attr-editor-dialog').reset();
1335         create_bar.style.display='table-row';
1336         update_bar.style.display='none';
1337     }
1338 }
1339
1340 function onAttrEditorClose() {
1341     // reset the form to a "create" form. (We may have borrowed it for editing.)
1342     ATTR_EDITOR_IN_UPDATE_MODE = false;
1343     // show the dropdown-button
1344     idStyle('vl-create-attr-editor-button', 'visibility', 'visible');
1345 }
1346
1347 function loadAttrEditorGrid() {
1348     var _data = (ATTR_EDIT_GROUP == 'auth') ? 
1349         vqarad.toStoreData(authAttrDefs) : vqbrad.toStoreData(bibAttrDefs) ;
1350
1351     var store = new dojo.data.ItemFileReadStore({data:_data});
1352     attrEditorGrid.setStore(store);
1353     attrEditorGrid.onRowDblClick = onAttrEditorClick;
1354     attrEditorGrid.update();
1355 }
1356
1357 function attrGridGetTag(n, item) {
1358     // grid helper: return the tags from the row's xpath column.
1359     return item && xpathParser.parse(this.grid.store.getValue(item, 'xpath')).tags;
1360 }
1361
1362 function attrGridGetSubfield(n, item) {
1363     // grid helper: return the subfields from the row's xpath column.
1364     return item && xpathParser.parse(this.grid.store.getValue(item, 'xpath')).subfields;
1365 }
1366
1367 function onAttrEditorClick() {
1368     var row = this.getItem(this.focus.rowIndex);
1369     ATTR_EDIT_ID = this.store.getValue(row, 'id');
1370     ATTR_EDITOR_IN_UPDATE_MODE = true;
1371
1372     // populate the popup editor.
1373     dijit.byId('attr-editor-code').attr('value', this.store.getValue(row, 'code'));
1374     dijit.byId('attr-editor-description').attr('value', this.store.getValue(row, 'description'));
1375     var parsed_xpath = xpathParser.parse(this.store.getValue(row, 'xpath'));
1376     dijit.byId('attr-editor-tags').attr('value', parsed_xpath.tags);
1377     dijit.byId('attr-editor-subfields').attr('value', parsed_xpath.subfields);
1378     dijit.byId('attr-editor-xpath').attr('value', this.store.getValue(row, 'xpath'));
1379     dijit.byId('attr-editor-remove').attr('value', this.store.getValue(row, 'remove'));
1380
1381     // set up UI for editing
1382     dojo.byId('vl-create-attr-editor-button').click();
1383 }
1384
1385 function vlSaveAttrDefinition(data) {
1386     idHide('vl-attr-editor-div');
1387     idShow('vl-generic-progress');
1388
1389     data.id = ATTR_EDIT_ID;
1390
1391     // this ought to honour custom xpaths, but overwrite xpaths
1392     // derived from tags/subfields.
1393     if (data.xpath == '' || looksLikeDerivedXpath(data.xpath)) {
1394         var _xpath = tagAndSubFieldsToXpath(data.tag, data.subfield);
1395         data.xpath = _xpath;
1396     }
1397
1398     // build up our permacrud params. Key variables here are
1399     // "create or update" and "bib or auth".
1400
1401     var isAuth   = (ATTR_EDIT_GROUP == 'auth');
1402     var isCreate = (ATTR_EDIT_ID == null);
1403     var rad      = isAuth ? new vqarad() : new vqbrad() ;
1404     var method   = 'open-ils.permacrud' + (isCreate ? '.create.' : '.update.') 
1405         + (isAuth ? 'vqarad' : 'vqbrad');
1406     var _data    = rad.fromStoreItem(data);
1407
1408     _data.ischanged(1);
1409
1410     fieldmapper.standardRequest(
1411         ['open-ils.permacrud', method],
1412         {   async: true,
1413             params: [authtoken, _data ],
1414             onresponse: function(r) { },
1415             oncomplete: function(r) {
1416                 attrEditorFetchAttrDefs(vlShowAttrEditor);
1417                 ATTR_EDIT_ID = null;
1418             },
1419             onerror: function(r) {
1420                 alert('vlSaveAttrDefinition comms error: ' + r);
1421             }
1422         }
1423     );
1424 }
1425
1426 function attrEditorFetchAttrDefs(callback) {
1427     var fn = (ATTR_EDIT_GROUP == 'auth') ? vlFetchAuthAttrDefs : vlFetchBibAttrDefs;
1428     return fn(callback);
1429 }
1430
1431 function vlAttrDelete() {
1432     idHide('vl-attr-editor-div');
1433     idShow('vl-generic-progress');
1434
1435     var isAuth = (ATTR_EDIT_GROUP == 'auth');
1436     var method = 'open-ils.permacrud.delete.' + (isAuth ? 'vqarad' : 'vqbrad');
1437     var rad    = isAuth ? new vqarad() : new vqbrad() ;
1438     fieldmapper.standardRequest(
1439         ['open-ils.permacrud', method],
1440         {   async: true,
1441             params: [authtoken, rad.fromHash({ id : ATTR_EDIT_ID }), ],
1442             oncomplete: function() {
1443                 dijit.byId('attr-editor-dialog').onCancel(); // close the dialog
1444                 attrEditorFetchAttrDefs(vlShowAttrEditor);
1445                 ATTR_EDIT_ID = null;
1446             },
1447             onerror: function(r) {
1448                 alert('vlAttrDelete comms error: ' + r);
1449             }
1450         }
1451     );
1452 }
1453
1454 // ------------------------------------------------------------
1455 // utilities for attribute editors
1456
1457 // dom utilities (maybe dojo does these, and these should be replaced)
1458
1459 function idStyle(obId, k, v)    { document.getElementById(obId).style[k] = v;   }
1460 function idShow(obId)           { idStyle(obId, 'display', 'block');            }
1461 function idHide(obId)           { idStyle(obId, 'display' , 'none');            }
1462
1463 function connectTooltip(fieldId) {
1464     // Given an element id, look up a tooltip element in the doc (same
1465     // id with a '-tip' suffix) and associate the two. Maybe dojo has
1466     // a better way to do this?
1467     var fld = dojo.byId(fieldId);
1468     var tip = dojo.byId(fieldId + '-tip');
1469     dojo.connect(fld, 'onfocus', function(evt) {
1470                      dijit.showTooltip(tip.innerHTML, fld, ['below', 'after']); });
1471     dojo.connect(fld, 'onblur', function(evt) { dijit.hideTooltip(fld); });
1472 }
1473
1474 // xpath utilities
1475
1476 var xpathParser = new openils.MarcXPathParser();
1477
1478 function tagAndSubFieldsToXpath(tags, subfields) {
1479     // given tags, and subfields, build up an XPath.
1480     try {
1481         var parts = {
1482             'tags':tags.match(/[\d]+/g), 
1483             'subfields':subfields.match(/[a-zA-z]/g) };
1484         return xpathParser.compile(parts);
1485     } catch (err) {
1486         return {'parts':null, 'tags':null, 'error':err};
1487     }
1488 }
1489
1490 function looksLikeDerivedXpath(path) {
1491     // Does this path look like it was derived from tags and subfields?
1492     var parsed = xpathParser.parse(path);
1493     if (parsed.tags == null) 
1494         return false;
1495     var compiled = xpathParser.compile(parsed);
1496     return (path == compiled);
1497 }
1498
1499 // amazing xpath-util unit-tests
1500 if (!looksLikeDerivedXpath('//*[@tag="901"]/*[@code="c"]'))     alert('vandelay xpath-utility error');
1501 if ( looksLikeDerivedXpath('ba-boo-ba-boo!'))                   alert('vandelay xpath-utility error');
1502
1503
1504
1505 var profileContextOrg
1506 function vlShowProfileEditor() {
1507     displayGlobalDiv('vl-profile-editor-div');
1508     buildProfileGrid();
1509
1510     var connect = function() {
1511         dojo.connect(profileContextOrgSelector, 'onChange',
1512             function() {
1513                 profileContextOrg = this.attr('value');
1514                 pGrid.resetStore();
1515                 buildProfileGrid();
1516             }
1517         );
1518     };
1519
1520     new openils.User().buildPermOrgSelector(
1521         'ADMIN_MERGE_PROFILE', profileContextOrgSelector, null, connect);
1522 }
1523
1524 function buildProfileGrid() {
1525
1526     if(profileContextOrg == null)
1527         profileContextOrg = openils.User.user.ws_ou();
1528
1529     pGrid.loadAll( 
1530         {order_by : {vmp : 'name'}}, 
1531         {owner : fieldmapper.aou.fullPath(profileContextOrg, true)}
1532     );
1533 }
1534
1535 /* --- Import Item Attr Grid --------------- */
1536
1537 var itemAttrContextOrg;
1538 function vlShowImportItemAttrEditor() {
1539     displayGlobalDiv('vl-item-attr-editor-div');
1540     buildImportItemAttrGrid();
1541
1542     var connect = function() {
1543         dojo.connect(itemAttrContextOrgSelector, 'onChange',
1544             function() {
1545                 itemAttrContextOrg = this.attr('value');
1546                 itemAttrGrid.resetStore();
1547                 vlShowImportItemAttrEditor();
1548             }
1549         );
1550     };
1551
1552     new openils.User().buildPermOrgSelector(
1553         'ADMIN_IMPORT_ITEM_ATTR_DEF', 
1554             itemAttrContextOrgSelector, null, connect);
1555 }
1556
1557 function buildImportItemAttrGrid() {
1558
1559     if(itemAttrContextOrg == null)
1560         itemAttrContextOrg = openils.User.user.ws_ou();
1561
1562     itemAttrGrid.loadAll( 
1563         {order_by : {viiad : 'name'}}, 
1564         {owner : fieldmapper.aou.fullPath(itemAttrContextOrg, true)}
1565     );
1566 }
1567