]> git.evergreen-ils.org Git - working/Evergreen.git/blob - Open-ILS/web/js/ui/default/vandelay/vandelay.js
slight mods to vandelay match set page to sync w/ updated bib/auth match table layout
[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']});
468                 dataStore.identifier = '_id';
469
470                 var matchSeenMap = {};
471
472                 // XXX much of this is no longer needed with changes to match_set
473                 for(var i = 0; i < dataStore.items.length; i++) {
474                     var item = dataStore.items[i];
475                     item._id = i; // just need something unique
476                     /*
477                     for(var j = 0; j < matches.length; j++) {
478                         var match = matches[j];
479                         if(match.eg_record() == item.id && !matchSeenMap[match.id()]) {
480                             var attr = getRecAttrFromMatch(queuedRecordsMap[recId], match);
481                             item.src_matchpoint = getRecAttrDefFromAttr(attr, currentType).code();
482                             matchSeenMap[match.id()] = 1;
483                             break;
484                         }
485                     }
486                     */
487                 }
488
489                 // now populate the grid
490                 vlPopulateMatchGrid(vlMatchGrid, dataStore);
491             }
492         }
493     );
494 }
495
496 function vlPopulateMatchGrid(grid, data) {
497     var store = new dojo.data.ItemFileReadStore({data:data});
498     grid.setStore(store);
499     grid.update();
500 }
501
502 function showMe(id) {
503     dojo.style(dojo.byId(id), 'display', 'block');
504 }
505 function hideMe(id) {
506     dojo.style(dojo.byId(id), 'display', 'none');
507 }
508
509
510 function vlLoadMARCHtml(recId, inCat, oncomplete) {
511     dijit.byId('vl-marc-html-done-button').onClick = oncomplete;
512     displayGlobalDiv('vl-generic-progress');
513     var api;
514     var params = [recId, 1];
515
516     if(inCat) {
517         hideMe('vl-marc-html-edit-button'); // don't show marc editor button
518         dijit.byId('vl-marc-html-edit-button').onClick = function(){}
519         api = ['open-ils.search', 'open-ils.search.biblio.record.html'];
520         if(currentType == 'auth')
521             api = ['open-ils.search', 'open-ils.search.authority.to_html'];
522     } else {
523         showMe('vl-marc-html-edit-button'); // plug in the marc editor button
524         dijit.byId('vl-marc-html-edit-button').onClick = 
525             function() {vlLoadMarcEditor(currentType, recId, oncomplete);};
526         params = [authtoken, recId];
527         api = ['open-ils.vandelay', 'open-ils.vandelay.queued_bib_record.html'];
528         if(currentType == 'auth')
529             api = ['open-ils.vandelay', 'open-ils.vandelay.queued_authority_record.html'];
530     }
531
532     fieldmapper.standardRequest(
533         api, 
534         {   async: true,
535             params: params,
536             oncomplete: function(r) {
537             displayGlobalDiv('vl-marc-html-div');
538                 var html = r.recv().content();
539                 dojo.byId('vl-marc-record-html').innerHTML = html;
540             }
541         }
542     );
543 }
544
545
546 /*
547 function getRecMatchesFromAttrCode(rec, attrCode) {
548     var matches = [];
549     var attr = getRecAttrFromCode(rec, attrCode);
550     for(var j = 0; j < rec.matches().length; j++) {
551         var match = rec.matches()[j];
552         if(match.matched_attr() == attr.id()) 
553             matches.push(match);
554     }
555     return matches;
556 }
557 */
558
559 /*
560 function getRecAttrFromMatch(rec, match) {
561     for(var i = 0; i < rec.attributes().length; i++) {
562         var attr = rec.attributes()[i];
563         if(attr.id() == match.matched_attr())
564             return attr;
565     }
566 }
567 */
568
569 function getRecAttrDefFromAttr(attr, type) {
570     var defs = (type == 'bib') ? bibAttrDefs : authAttrDefs;
571     for(var i = 0; i < defs.length; i++) {
572         var def = defs[i];
573         if(def.id() == attr.field())
574             return def;
575     }
576 }
577
578 function getRecAttrFromCode(rec, attrCode) {
579     var defId = attrDefMap[currentType][attrCode];
580     var attrs = rec.attributes();
581     for(var i = 0; i < attrs.length; i++) {
582         var attr = attrs[i];
583         if(attr.field() == defId) 
584             return attr;
585     }
586     return null;
587 }
588
589 function vlGetViewMatches(rowIdx, item) {
590     if(item) {
591         var id = this.grid.store.getValue(item, 'id');
592         var rec = queuedRecordsMap[id];
593         if(rec.matches().length > 0)
594             return id;
595     }
596     return -1
597 }
598
599 function vlFormatViewMatches(id) {
600     if(id == -1) return '';
601     return '<a href="javascript:void(0);" onclick="vlLoadMatchUI(' + id + ');">' + this.name + '</a>';
602 }
603
604 function vlGetViewErrors(rowIdx, item) {
605     if(item) {
606         var id = this.grid.store.getValue(item, 'id');
607         var rec = queuedRecordsMap[id];
608         // id:rec_error:item_import_error_count
609         return id + ':' + 
610             (rec.import_error() ? 1 : '') + ':' + 
611             rec.import_items().filter(function(i) {return i.import_error()}).length;
612     }
613     return -1
614 }
615
616 function vlFormatViewErrors(chunk) {
617     if(chunk == -1) return '';
618     var id = chunk.split(':')[0];
619     var rec = chunk.split(':')[1];
620     var count = chunk.split(':')[2];
621     var links = '';
622     if(rec) 
623         links += '<a href="javascript:void(0);" onclick="vlLoadErrorUI(' + id + ');">Record</a><br/>'; // TODO I18N
624     if(Number(count))
625         links += '<a href="javascript:void(0);" onclick="vlLoadErrorUI(' + id + ');">Items ('+count+')</a>'; // TODO I18N
626     return links;
627 }
628
629 //var vlItemErrorColumnPicker;
630 function vlLoadErrorUI(id) {
631
632     displayGlobalDiv('vl-import-error-div');
633     openils.Util.hide('vl-import-error-grid-all');
634     openils.Util.show('vl-import-error-record');
635
636     var rec = queuedRecordsMap[id];
637
638     dojo.byId('vl-error-id').innerHTML = rec.id();
639     dojo.forEach( // TODO sane authority rec. fields
640         ['title', 'author', 'isbn', 'issn', 'upc'],
641         function(field) {
642             var attr =  getRecAttrFromCode(rec, field);
643             var eid = 'vl-error-' + field;
644             if(attr) {
645                 openils.Util.show(dojo.byId(eid).parentNode, 'table-row');
646                 dojo.byId(eid).innerHTML = attr.attr_value();
647             } else {
648                 openils.Util.hide(dojo.byId(eid).parentNode);
649             }
650         }
651     );
652     var iediv = dojo.byId('vl-error-import-error');
653     var eddiv = dojo.byId('vl-error-error-detail');
654     if(rec.import_error()) {
655         openils.Util.show(iediv.parentNode, 'table-row');
656         openils.Util.show(eddiv.parentNode, 'table-row');
657         iediv.innerHTML = rec.import_error();
658         eddiv.innerHTML = rec.error_detail();
659     } else {
660         openils.Util.hide(iediv.parentNode);
661         openils.Util.hide(eddiv.parentNode);
662     }
663
664     var errorItems = rec.import_items().filter(function(i) {return i.import_error()});
665     if(errorItems.length) {
666         openils.Util.show('vl-import-error-grid-some');
667         storeData = vqbr.toStoreData(errorItems);
668         var store = new dojo.data.ItemFileReadStore({data:storeData});
669         vlImportErrorGrid.setStore(store);
670         vlImportErrorGrid.update();
671     } else {
672         openils.Util.hide('vl-import-error-grid-some');
673     }
674 }
675
676 function vlLoadErrorUIAll() {
677
678     displayGlobalDiv('vl-import-error-div');
679     openils.Util.hide('vl-import-error-grid-some');
680     openils.Util.hide('vl-import-error-record');
681     openils.Util.show('vl-import-error-grid-all');
682     vlAllImportErrorGrid.resetStore();
683
684     vlImportErrorGrid.displayOffset = 0;
685
686     vlAllImportErrorGrid.dataLoader = function() {
687
688         vlAllImportErrorGrid.showLoadProgressIndicator();
689
690         fieldmapper.standardRequest(
691             ['open-ils.vandelay', 'open-ils.vandelay.import_item.queue.retrieve'],
692             {
693                 async : true,
694                 params : [
695                     authtoken, currentQueueId, {   
696                         with_import_error: (vlImportItemsShowErrors.checked) ? 1 : null,
697                         offset : vlAllImportErrorGrid.displayOffset,
698                         limit : vlAllImportErrorGrid.displayLimit
699                     }
700                 ],
701                 onresponse : function(r) {
702                     var item = openils.Util.readResponse(r);
703                     if(!item) return;
704                     vlAllImportErrorGrid.store.newItem(vii.toStoreItem(item));
705                 },
706                 oncomplete : function() {
707                     vlAllImportErrorGrid.hideLoadProgressIndicator();
708                 }
709             }
710         );
711     };
712
713     vlAllImportErrorGrid.dataLoader();
714 }
715
716 function vlGetOrg(rowIdx, item) {
717     if(!item) return '';
718     var value = this.grid.store.getValue(item, this.field);
719     if(value) return fieldmapper.aou.findOrgUnit(value).shortname();
720     return '';
721 }
722
723 function vlFormatViewMatchMARC(id) {
724     return '<a href="javascript:void(0);" onclick="vlLoadMARCHtml(' + id + ', true, '+
725         'function(){displayGlobalDiv(\'vl-match-div\');});">' + this.name + '</a>';
726 }
727
728 function getAttrValue(rowIdx, item) {
729     if(!item) return '';
730     var attrCode = this.field.split('.')[1];
731     var rec = queuedRecordsMap[this.grid.store.getValue(item, 'id')];
732     var attr = getRecAttrFromCode(rec, attrCode);
733     return (attr) ? attr.attr_value() : '';
734 }
735
736 function vlGetDateTimeField(rowIdx, item) {
737     if(!item) return '';
738     var value = this.grid.store.getValue(item, this.field);
739     if(!value) return '';
740     var date = dojo.date.stamp.fromISOString(value);
741     return dojo.date.locale.format(date, {selector:'date'});
742 }
743
744 function vlGetCreator(rowIdx, item) {
745     if(!item) return '';
746     var id = this.grid.store.getValue(item, 'creator');
747     if(userCache[id])
748         return userCache[id].usrname();
749     var user = fieldmapper.standardRequest(
750         ['open-ils.actor', 'open-ils.actor.user.retrieve'], [authtoken, id]);
751     if(e = openils.Event.parse(user))
752         return alert(e);
753     userCache[id] = user;
754     return user.usrname();
755 }
756
757 function vlGetViewMARC(rowIdx, item) {
758     return item && this.grid.store.getValue(item, 'id');
759 }
760
761 function vlFormatViewMARC(id) {
762     return '<a href="javascript:void(0);" onclick="vlLoadMARCHtml(' + id + ', false, '+
763         'function(){displayGlobalDiv(\'vl-queue-div\');});">' + this.name + '</a>';
764 }
765
766 function vlGetOverlayTargetSelector(rowIdx, item) {
767     if(!item) return;
768     return this.grid.store.getValue(item, '_id') + ':' + this.grid.store.getValue(item, 'id');
769 }
770
771 function vlFormatOverlayTargetSelector(val) {
772     if(!val) return '';
773     var parts = val.split(':');
774     var _id = parts[0];
775     var id = parts[1];
776     var value = '<input type="checkbox" name="vl-overlay-target-RECID" '+
777         'onclick="vlHandleOverlayTargetSelected(ID, GRIDID);" gridid="GRIDID" match="ID"/>';
778     value = value.replace(/GRIDID/g, _id);
779     value = value.replace(/RECID/g, currentImportRecId);
780     value = value.replace(/ID/g, id);
781     if(_id == currentOverlayRecordsMapGid[currentImportRecId])
782         return value.replace('/>', 'checked="checked"/>');
783     return value;
784 }
785
786
787 /**
788   * see if the user has enabled overlays for the current match set and, 
789   * if so, map the current import record to the overlay target.
790   */
791 function vlHandleOverlayTargetSelected(recId, gridId) {
792     var noneSelected = true;
793     var checkboxes = dojo.query('[name=vl-overlay-target-'+currentImportRecId+']');
794     for(var i = 0; i < checkboxes.length; i++) {
795         var checkbox = checkboxes[i];
796         var matchRecId = checkbox.getAttribute('match');
797         var gid = checkbox.getAttribute('gridid');
798         if(checkbox.checked) {
799             if(matchRecId == recId && gid == gridId) {
800                 noneSelected = false;
801                 currentOverlayRecordsMap[currentImportRecId] = matchRecId;
802                 currentOverlayRecordsMapGid[currentImportRecId] = gid;
803                 dojo.byId('vl-record-list-selected-' + currentImportRecId).checked = true;
804                 dojo.byId('vl-record-list-selected-' + currentImportRecId).parentNode.className = 'overlay_selected';
805             } else {
806                 checkbox.checked = false;
807             }
808         }
809     }
810
811     if(noneSelected) {
812         delete currentOverlayRecordsMap[currentImportRecId];
813         delete currentOverlayRecordsMapGid[currentImportRecId];
814         dojo.byId('vl-record-list-selected-' + currentImportRecId).checked = false;
815         dojo.byId('vl-record-list-selected-' + currentImportRecId).parentNode.className = '';
816     }
817 }
818
819 var valLastQueueType = null;
820 var vlQueueGridLayout = null;
821 function buildRecordGrid(type) {
822     displayGlobalDiv('vl-queue-div');
823
824     if(type == 'bib') {
825         openils.Util.show('vl-bib-queue-grid-wrapper');
826         openils.Util.hide('vl-auth-queue-grid-wrapper');
827         vlQueueGrid = vlBibQueueGrid;
828     } else {
829         openils.Util.show('vl-auth-queue-grid-wrapper');
830         openils.Util.hide('vl-bib-queue-grid-wrapper');
831         vlQueueGrid = vlAuthQueueGrid;
832     }
833
834
835     if(valLastQueueType != type) {
836         valLastQueueType = type;
837         vlQueueGridLayout = vlQueueGrid.attr('structure');
838         var defs = (type == 'bib') ? bibAttrDefs : authAttrDefs;
839         attrDefMap[type] = {};
840         for(var i = 0; i < defs.length; i++) {
841             var def = defs[i]
842             attrDefMap[type][def.code()] = def.id();
843             var col = {
844                 name:def.description(), 
845                 field:'attr.' + def.code(),
846                 get: getAttrValue,
847                 selectableColumn:true
848             };
849             vlQueueGridLayout[0].cells[0].push(col);
850         }
851     }
852
853     dojo.forEach(vlQueueGridLayout[0].cells[0], 
854         function(cell) { 
855             if(cell.field.match(/^\+/)) 
856                 cell.nonSelectable=true;
857         }
858     );
859
860     var storeData;
861     if(type == 'bib')
862         storeData = vqbr.toStoreData(queuedRecords);
863     else
864         storeData = vqar.toStoreData(queuedRecords);
865
866     var store = new dojo.data.ItemFileReadStore({data:storeData});
867     vlQueueGrid.setStore(store);
868
869     if(vlQueueGridColumePicker[type]) {
870         vlQueueGrid.update();
871     } else {
872
873         vlQueueGridColumePicker[type] =
874             new openils.widget.GridColumnPicker(
875                 authtoken, 'vandelay.queue.'+type, vlQueueGrid, vlQueueGridLayout);
876         vlQueueGridColumePicker[type].load();
877     }
878 }
879
880 function vlQueueGridPrevPage() {
881     var page = parseInt(vlQueueDisplayPage.getValue());
882     if(page < 2) return;
883     vlQueueDisplayPage.setValue(page - 1);
884     retrieveQueuedRecords(currentType, currentQueueId, handleRetrieveRecords);
885 }
886
887 function vlQueueGridNextPage() {
888     vlQueueDisplayPage.setValue(parseInt(vlQueueDisplayPage.getValue())+1);
889     retrieveQueuedRecords(currentType, currentQueueId, handleRetrieveRecords);
890 }
891
892 function vlDeleteQueue(type, queueId, onload) {
893     fieldmapper.standardRequest(
894         ['open-ils.vandelay', 'open-ils.vandelay.'+type+'_queue.delete'],
895         {   async: true,
896             params: [authtoken, queueId],
897             oncomplete: function(r) {
898                 var resp = r.recv().content();
899                 if(e = openils.Event.parse(resp))
900                     return alert(e);
901                 onload();
902             }
903         }
904     );
905 }
906
907
908 function vlQueueGridDrawSelectBox(rowIdx, item) {
909     return item &&  this.grid.store.getValue(item, 'id');
910 }
911
912 function vlQueueGridFormatSelectBox(id) {
913     var domId = 'vl-record-list-selected-' + id;
914     if (id) { selectableGridRecords[domId] = id; }
915     return "<div><input type='checkbox' id='"+domId+"'/></div>";
916 }
917
918 function vlSelectAllQueueGridRecords() {
919     for(var id in selectableGridRecords) 
920         dojo.byId(id).checked = true;
921 }
922 function vlSelectNoQueueGridRecords() {
923     for(var id in selectableGridRecords) 
924         dojo.byId(id).checked = false;
925 }
926 function vlToggleQueueGridSelect() {
927     if(dojo.byId('vl-queue-grid-row-selector').checked)
928         vlSelectAllQueueGridRecords();
929     else
930         vlSelectNoQueueGridRecords();
931 }
932
933 var handleRetrieveRecords = function() {
934     buildRecordGrid(currentType);
935     vlFetchQueueSummary(currentQueueId, currentType, 
936         function(summary) {
937             dojo.byId('vl-queue-summary-name').innerHTML = summary.queue.name();
938             dojo.byId('vl-queue-summary-total-count').innerHTML = summary.total +'';
939             dojo.byId('vl-queue-summary-import-count').innerHTML = summary.imported + '';
940             dojo.byId('vl-queue-summary-import-item-count').innerHTML = summary.total_items + '';
941             dojo.byId('vl-queue-summary-rec-error-count').innerHTML = summary.rec_import_errors + '';
942             dojo.byId('vl-queue-summary-item-error-count').innerHTML = summary.item_import_errors + '';
943         }
944     );
945 }
946
947 function vlFetchQueueSummary(qId, type, onload) {
948     fieldmapper.standardRequest(
949         ['open-ils.vandelay', 'open-ils.vandelay.'+type+'_queue.summary.retrieve'],
950         {   async: true,
951             params: [authtoken, qId],
952             oncomplete : function(r) {
953                 var summary = r.recv().content();
954                 if(e = openils.Event.parse(summary))
955                     return alert(e);
956                 return onload(summary);
957             }
958         }
959     );
960 }
961
962 function vlHandleQueueItemsAction(action) {
963
964     dojo.connect(
965         queueItemsImportCancelButton, 
966         'onClick', 
967         function() {
968             queueItemsImportDialog.hide();
969         }
970     );
971
972     dojo.connect(
973         queueItemsImportGoButton,
974         'onClick', 
975         function() {
976             queueItemsImportDialog.hide();
977
978             // hack to set the widgets the import funcs will be looking at.  Reset them below.
979             vlUploadQueueAutoImport.attr('value',  vlUploadQueueAutoImport2.attr('value'));
980             vlUploadQueueAutoOverlayExact.attr('value',  vlUploadQueueAutoOverlayExact2.attr('value'));
981             vlUploadQueueAutoOverlay1Match.attr('value',  vlUploadQueueAutoOverlay1Match2.attr('value'));
982             vlUploadMergeProfile.attr('value',  vlUploadMergeProfile2.attr('value'));
983
984             if(action == 'import') {
985                 vlImportSelectedRecords();
986             } else if(action == 'import_all') {
987                 vlImportAllRecords();
988             }
989             
990             // reset the widgets to prevent accidental future actions
991             vlUploadQueueAutoImport.attr('value',  false);
992             vlUploadQueueAutoImport2.attr('value', false);
993             vlUploadQueueAutoOverlayExact.attr('value', false);
994             vlUploadQueueAutoOverlayExact2.attr('value', false);
995             vlUploadQueueAutoOverlay1Match.attr('value', false);
996             vlUploadQueueAutoOverlay1Match2.attr('value', false);
997             vlUploadMergeProfile.attr('value', '');
998             vlUploadMergeProfile2.attr('value', '');
999         }
1000     );
1001
1002     queueItemsImportDialog.show();
1003 }
1004     
1005
1006 function vlImportSelectedRecords() {
1007     displayGlobalDiv('vl-generic-progress-with-total');
1008     var records = [];
1009
1010     for(var id in selectableGridRecords) {
1011         if(dojo.byId(id).checked) {
1012             var recId = selectableGridRecords[id];
1013             var rec = queuedRecordsMap[recId];
1014             if(!rec.import_time()) 
1015                 records.push(recId);
1016         }
1017     }
1018
1019     var options = {overlay_map : currentOverlayRecordsMap};
1020
1021     if(vlUploadQueueAutoOverlayExact.checked) {
1022         options.auto_overlay_exact = true;
1023         vlUploadQueueAutoOverlayExact.checked = false;
1024     }
1025
1026     if(vlUploadQueueAutoOverlay1Match.checked) {
1027         options.auto_overlay_1match = true;
1028         vlUploadQueueAutoOverlay1Match.checked = false;
1029     }
1030     
1031     var profile = vlUploadMergeProfile.attr('value');
1032     if(profile != null && profile != '') {
1033         options.merge_profile = profile;
1034     }
1035
1036     fieldmapper.standardRequest(
1037         ['open-ils.vandelay', 'open-ils.vandelay.'+currentType+'_record.list.import'],
1038         {   async: true,
1039             params: [authtoken, records, options],
1040             onresponse: function(r) {
1041                 var resp = r.recv().content();
1042                 if(e = openils.Event.parse(resp))
1043                     return alert(e);
1044                 if(resp.complete) {
1045                     return retrieveQueuedRecords(currentType, currentQueueId, handleRetrieveRecords);
1046                 } else {
1047                     vlControlledProgressBar.update({maximum:resp.total, progress:resp.progress});
1048                 }
1049             }, 
1050         }
1051     );
1052 }
1053
1054 function vlImportAllRecords() {
1055     vlImportRecordQueue(currentType, currentQueueId, false,
1056         function(){displayGlobalDiv('vl-queue-div');});
1057 }
1058
1059 function vlImportRecordQueue(type, queueId, noMatchOnly, onload) {
1060     displayGlobalDiv('vl-generic-progress-with-total');
1061     var method = 'open-ils.vandelay.bib_queue.import';
1062     if(noMatchOnly)
1063         method = method.replace('import', 'nomatch.import');
1064     if(type == 'auth')
1065         method = method.replace('bib', 'auth');
1066
1067     var options = {};
1068     if(vlUploadQueueAutoOverlayExact.checked) {
1069         options.auto_overlay_exact = true;
1070         vlUploadQueueAutoOverlayExact.checked = false;
1071     }
1072
1073     if(vlUploadQueueAutoOverlay1Match.checked) {
1074         options.auto_overlay_1match = true;
1075         vlUploadQueueAutoOverlay1Match.checked = false;
1076     }
1077     
1078     var profile = vlUploadMergeProfile.attr('value');
1079     if(profile != null && profile != '') {
1080         options.merge_profile = profile;
1081     }
1082
1083     fieldmapper.standardRequest(
1084         ['open-ils.vandelay', method],
1085         {   async: true,
1086             params: [authtoken, queueId, options],
1087             onresponse: function(r) {
1088                 var resp = r.recv().content();
1089                 if(e = openils.Event.parse(resp))
1090                     return alert(e);
1091                 vlControlledProgressBar.update({maximum:resp.total, progress:resp.progress});
1092             },
1093             oncomplete: function() {onload();}
1094         }
1095     );
1096 }
1097
1098
1099 /**
1100   * Create queue, upload MARC, process spool, load the newly created queue 
1101   */
1102 function batchUpload() {
1103     var queueName = dijit.byId('vl-queue-name').getValue();
1104     currentType = dijit.byId('vl-record-type').getValue();
1105
1106     var handleProcessSpool = function() {
1107         if(vlUploadQueueAutoImport.checked || vlUploadQueueAutoOverlayExact.checked || vlUploadQueueAutoOverlay1Match.checked) {
1108             var noMatchOnly = !vlUploadQueueAutoOverlayExact.checked && !vlUploadQueueAutoOverlay1Match.checked;
1109             vlImportRecordQueue(
1110                 currentType, 
1111                 currentQueueId, 
1112                 noMatchOnly,
1113                 function() {
1114                     retrieveQueuedRecords(currentType, currentQueueId, handleRetrieveRecords);
1115                 }
1116             );
1117         } else {
1118             retrieveQueuedRecords(currentType, currentQueueId, handleRetrieveRecords);
1119         }
1120     }
1121
1122     var handleUploadMARC = function(key) {
1123         dojo.style(dojo.byId('vl-upload-status-processing'), 'display', 'block');
1124         processSpool(key, currentQueueId, currentType, handleProcessSpool);
1125     };
1126
1127     var handleCreateQueue = function(queue) {
1128         currentQueueId = queue.id();
1129         uploadMARC(handleUploadMARC);
1130     };
1131     
1132     if(vlUploadQueueSelector.getValue() && !queueName) {
1133         currentQueueId = vlUploadQueueSelector.getValue();
1134         uploadMARC(handleUploadMARC);
1135     } else {
1136         createQueue(queueName, currentType, handleCreateQueue, 
1137             vlUploadQueueHoldingsImportProfile.attr('value'),
1138             vlUploadQueueMatchSet.attr('value')
1139         );
1140     }
1141 }
1142
1143
1144 function vlFleshQueueSelect(selector, type) {
1145     var data = (type == 'bib') ? vbq.toStoreData(allUserBibQueues) : vaq.toStoreData(allUserAuthQueues);
1146     selector.store = new dojo.data.ItemFileReadStore({data:data});
1147     selector.setValue(null);
1148     selector.setDisplayedValue('');
1149     if(data[0])
1150         selector.setValue(data[0].id());
1151
1152     var qInput = dijit.byId('vl-queue-name');
1153
1154     var selChange = function(val) {
1155         console.log('selector onchange');
1156         // user selected a queue from the selector;  clear the input and 
1157         // set the item import profile already defined for the queue
1158         var queue = allUserBibQueues.filter(function(q) { return (q.id() == val) })[0];
1159         if(val) {
1160             vlUploadQueueHoldingsImportProfile.attr('value', queue.item_attr_def() || '');
1161             vlUploadQueueHoldingsImportProfile.attr('disabled', true);
1162             vlUploadQueueMatchSet.attr('value', queue.match_set() || '');
1163             vlUploadQueueMatchSet.attr('disabled', true);
1164         } else {
1165             vlUploadQueueHoldingsImportProfile.attr('value', '');
1166             vlUploadQueueHoldingsImportProfile.attr('disabled', false);
1167             vlUploadQueueMatchSet.attr('value', '');
1168             vlUploadQueueMatchSet.attr('disabled', false);
1169         }
1170         dojo.disconnect(qInput._onchange);
1171         qInput.attr('value', '');
1172         qInput._onchange = dojo.connect(qInput, 'onChange', inputChange);
1173     }
1174     
1175     var inputChange = function(val) {
1176         console.log('qinput onchange');
1177         // user entered a new queue name. clear the selector 
1178         vlUploadQueueHoldingsImportProfile.attr('value', '');
1179         vlUploadQueueHoldingsImportProfile.attr('disabled', false);
1180         vlUploadQueueMatchSet.attr('value', '');
1181         vlUploadQueueMatchSet.attr('disabled', false);
1182         dojo.disconnect(selector._onchange);
1183         selector.attr('value', '');
1184         selector._onchange = dojo.connect(selector, 'onChange', selChange);
1185     }
1186
1187     selector._onchange = dojo.connect(selector, 'onChange', selChange);
1188     qInput._onchange = dojo.connect(qInput, 'onChange', inputChange);
1189 }
1190
1191 function vlUpdateMatchSetSelector(type) {
1192     type = (type.match(/bib/)) ? 'biblio' : 'authority';
1193     vlUploadQueueMatchSet.store = 
1194         new dojo.data.ItemFileReadStore({data:vms.toStoreData(matchSets[type])});
1195 }
1196
1197 function vlShowUploadForm() {
1198     displayGlobalDiv('vl-marc-upload-div');
1199     vlFleshQueueSelect(vlUploadQueueSelector, vlUploadRecordType.getValue());
1200     vlUploadSourceSelector.store = 
1201         new dojo.data.ItemFileReadStore({data:cbs.toStoreData(vlBibSources, 'source')});
1202     vlUploadSourceSelector.setValue(vlBibSources[0].id());
1203     vlUploadQueueHoldingsImportProfile.store = 
1204         new dojo.data.ItemFileReadStore({data:viiad.toStoreData(importItemDefs)});
1205     vlUpdateMatchSetSelector(vlUploadRecordType.getValue());
1206 }
1207
1208 function vlShowQueueSelect() {
1209     displayGlobalDiv('vl-queue-select-div');
1210     vlFleshQueueSelect(vlQueueSelectQueueList, vlQueueSelectType.getValue());
1211 }
1212
1213 function vlShowMatchSetEditor() {
1214     displayGlobalDiv('vl-match-set-editor-div');
1215     dojo.byId('vl-match-set-editor-div').appendChild(
1216         dojo.create('iframe', {
1217             id : 'vl-match-set-iframe',
1218             src : oilsBasePath + '/eg/conify/global/vandelay/match_set',
1219             style : 'width:100%; height:500px; border:none; margin:0px;'
1220         })
1221     );
1222 }
1223
1224 function vlFetchQueueFromForm() {
1225     currentType = vlQueueSelectType.getValue();
1226     currentQueueId = vlQueueSelectQueueList.getValue();
1227     retrieveQueuedRecords(currentType, currentQueueId, handleRetrieveRecords);
1228 }
1229
1230 function vlOpenMarcEditWindow(rec, postReloadHTMLHandler) {
1231     /*
1232         To run in Firefox directly, must set signed.applets.codebase_principal_support
1233         to true in about:config
1234     */
1235     netscape.security.PrivilegeManager.enablePrivilege('UniversalXPConnect');
1236     win = window.open('/xul/server/cat/marcedit.xul'); // XXX version?
1237
1238     var type;
1239     if (currentType == 'bib') {
1240         type = 'bre';
1241     } else {
1242         type = 'are';
1243     }
1244
1245     function onsave(r) {
1246         // after the record is saved, reload the HTML display
1247         var stat = r.recv().content();
1248         if(e = openils.Event.parse(stat))
1249             return alert(e);
1250         alert(dojo.byId('vl-marc-edit-complete-label').innerHTML);
1251         win.close();
1252         vlLoadMARCHtml(rec.id(), false, postReloadHTMLHandler);
1253     }
1254
1255     win.xulG = {
1256         record : {marc : rec.marc(), "rtype": type},
1257         save : {
1258             label: dojo.byId('vl-marc-edit-save-label').innerHTML,
1259             func: function(xmlString) {
1260                 var method = 'open-ils.permacrud.update.' + rec.classname;
1261                 rec.marc(xmlString);
1262                 fieldmapper.standardRequest(
1263                     ['open-ils.permacrud', method],
1264                     {   async: true,
1265                         params: [authtoken, rec],
1266                         oncomplete: onsave
1267                     }
1268                 );
1269             },
1270         },
1271         'lock_tab' : typeof xulG != 'undefined' ? (typeof xulG['lock_tab'] != 'undefined' ? xulG.lock_tab : undefined) : undefined,
1272         'unlock_tab' : typeof xulG != 'undefined' ? (typeof xulG['unlock_tab'] != 'undefined' ? xulG.unlock_tab : undefined) : undefined
1273     };
1274 }
1275
1276 function vlLoadMarcEditor(type, recId, postReloadHTMLHandler) {
1277     var method = 'open-ils.permacrud.search.vqbr';
1278     if(currentType != 'bib')
1279         method = method.replace(/vqbr/,'vqar');
1280
1281     fieldmapper.standardRequest(
1282         ['open-ils.permacrud', method],
1283         {   async: true, 
1284             params: [authtoken, {id : recId}],
1285             oncomplete: function(r) {
1286                 var rec = r.recv().content();
1287                 if(e = openils.Event.parse(rec))
1288                     return alert(e);
1289                 vlOpenMarcEditWindow(rec, postReloadHTMLHandler);
1290             }
1291         }
1292     );
1293 }
1294
1295
1296
1297 //------------------------------------------------------------
1298 // attribute editors
1299
1300 // attribute-editor global variables
1301
1302 var ATTR_EDITOR_IN_UPDATE_MODE = false; // true on 'edit', false on 'create'
1303 var ATTR_EDIT_ID = null;                // id of current 'edit' attribute
1304 var ATTR_EDIT_GROUP = 'bib';            // bib-attrs or auth-attrs
1305
1306 function vlAttrEditorInit() {
1307     // set up tooltips on the edit form
1308     connectTooltip('attr-editor-tags'); 
1309     connectTooltip('attr-editor-subfields'); 
1310 }
1311
1312 function vlShowAttrEditor() {
1313     displayGlobalDiv('vl-attr-editor-div');
1314     loadAttrEditorGrid();
1315     idHide('vl-generic-progress');
1316 }
1317
1318 function setAttrEditorGroup(groupName) {
1319     // put us into 'bib'-attr or 'auth'-attr mode.
1320     if (ATTR_EDIT_GROUP != groupName) {
1321         ATTR_EDIT_GROUP = groupName;
1322         loadAttrEditorGrid();
1323     }
1324 }
1325
1326 function onAttrEditorOpen() {
1327     // the "bars" have the create/update/cancel/etc. buttons.
1328     var create_bar = document.getElementById('attr-editor-create-bar');
1329     var update_bar = document.getElementById('attr-editor-update-bar');
1330     if (ATTR_EDITOR_IN_UPDATE_MODE) {
1331         update_bar.style.display='table-row';
1332         create_bar.style.display='none';
1333         // hide the dropdown-button
1334         idStyle('vl-create-attr-editor-button', 'visibility', 'hidden');
1335     } else {
1336         dijit.byId('attr-editor-dialog').reset();
1337         create_bar.style.display='table-row';
1338         update_bar.style.display='none';
1339     }
1340 }
1341
1342 function onAttrEditorClose() {
1343     // reset the form to a "create" form. (We may have borrowed it for editing.)
1344     ATTR_EDITOR_IN_UPDATE_MODE = false;
1345     // show the dropdown-button
1346     idStyle('vl-create-attr-editor-button', 'visibility', 'visible');
1347 }
1348
1349 function loadAttrEditorGrid() {
1350     var _data = (ATTR_EDIT_GROUP == 'auth') ? 
1351         vqarad.toStoreData(authAttrDefs) : vqbrad.toStoreData(bibAttrDefs) ;
1352
1353     var store = new dojo.data.ItemFileReadStore({data:_data});
1354     attrEditorGrid.setStore(store);
1355     attrEditorGrid.onRowDblClick = onAttrEditorClick;
1356     attrEditorGrid.update();
1357 }
1358
1359 function attrGridGetTag(n, item) {
1360     // grid helper: return the tags from the row's xpath column.
1361     return item && xpathParser.parse(this.grid.store.getValue(item, 'xpath')).tags;
1362 }
1363
1364 function attrGridGetSubfield(n, item) {
1365     // grid helper: return the subfields from the row's xpath column.
1366     return item && xpathParser.parse(this.grid.store.getValue(item, 'xpath')).subfields;
1367 }
1368
1369 function onAttrEditorClick() {
1370     var row = this.getItem(this.focus.rowIndex);
1371     ATTR_EDIT_ID = this.store.getValue(row, 'id');
1372     ATTR_EDITOR_IN_UPDATE_MODE = true;
1373
1374     // populate the popup editor.
1375     dijit.byId('attr-editor-code').attr('value', this.store.getValue(row, 'code'));
1376     dijit.byId('attr-editor-description').attr('value', this.store.getValue(row, 'description'));
1377     var parsed_xpath = xpathParser.parse(this.store.getValue(row, 'xpath'));
1378     dijit.byId('attr-editor-tags').attr('value', parsed_xpath.tags);
1379     dijit.byId('attr-editor-subfields').attr('value', parsed_xpath.subfields);
1380     dijit.byId('attr-editor-xpath').attr('value', this.store.getValue(row, 'xpath'));
1381     dijit.byId('attr-editor-remove').attr('value', this.store.getValue(row, 'remove'));
1382
1383     // set up UI for editing
1384     dojo.byId('vl-create-attr-editor-button').click();
1385 }
1386
1387 function vlSaveAttrDefinition(data) {
1388     idHide('vl-attr-editor-div');
1389     idShow('vl-generic-progress');
1390
1391     data.id = ATTR_EDIT_ID;
1392
1393     // this ought to honour custom xpaths, but overwrite xpaths
1394     // derived from tags/subfields.
1395     if (data.xpath == '' || looksLikeDerivedXpath(data.xpath)) {
1396         var _xpath = tagAndSubFieldsToXpath(data.tag, data.subfield);
1397         data.xpath = _xpath;
1398     }
1399
1400     // build up our permacrud params. Key variables here are
1401     // "create or update" and "bib or auth".
1402
1403     var isAuth   = (ATTR_EDIT_GROUP == 'auth');
1404     var isCreate = (ATTR_EDIT_ID == null);
1405     var rad      = isAuth ? new vqarad() : new vqbrad() ;
1406     var method   = 'open-ils.permacrud' + (isCreate ? '.create.' : '.update.') 
1407         + (isAuth ? 'vqarad' : 'vqbrad');
1408     var _data    = rad.fromStoreItem(data);
1409
1410     _data.ischanged(1);
1411
1412     fieldmapper.standardRequest(
1413         ['open-ils.permacrud', method],
1414         {   async: true,
1415             params: [authtoken, _data ],
1416             onresponse: function(r) { },
1417             oncomplete: function(r) {
1418                 attrEditorFetchAttrDefs(vlShowAttrEditor);
1419                 ATTR_EDIT_ID = null;
1420             },
1421             onerror: function(r) {
1422                 alert('vlSaveAttrDefinition comms error: ' + r);
1423             }
1424         }
1425     );
1426 }
1427
1428 function attrEditorFetchAttrDefs(callback) {
1429     var fn = (ATTR_EDIT_GROUP == 'auth') ? vlFetchAuthAttrDefs : vlFetchBibAttrDefs;
1430     return fn(callback);
1431 }
1432
1433 function vlAttrDelete() {
1434     idHide('vl-attr-editor-div');
1435     idShow('vl-generic-progress');
1436
1437     var isAuth = (ATTR_EDIT_GROUP == 'auth');
1438     var method = 'open-ils.permacrud.delete.' + (isAuth ? 'vqarad' : 'vqbrad');
1439     var rad    = isAuth ? new vqarad() : new vqbrad() ;
1440     fieldmapper.standardRequest(
1441         ['open-ils.permacrud', method],
1442         {   async: true,
1443             params: [authtoken, rad.fromHash({ id : ATTR_EDIT_ID }), ],
1444             oncomplete: function() {
1445                 dijit.byId('attr-editor-dialog').onCancel(); // close the dialog
1446                 attrEditorFetchAttrDefs(vlShowAttrEditor);
1447                 ATTR_EDIT_ID = null;
1448             },
1449             onerror: function(r) {
1450                 alert('vlAttrDelete comms error: ' + r);
1451             }
1452         }
1453     );
1454 }
1455
1456 // ------------------------------------------------------------
1457 // utilities for attribute editors
1458
1459 // dom utilities (maybe dojo does these, and these should be replaced)
1460
1461 function idStyle(obId, k, v)    { document.getElementById(obId).style[k] = v;   }
1462 function idShow(obId)           { idStyle(obId, 'display', 'block');            }
1463 function idHide(obId)           { idStyle(obId, 'display' , 'none');            }
1464
1465 function connectTooltip(fieldId) {
1466     // Given an element id, look up a tooltip element in the doc (same
1467     // id with a '-tip' suffix) and associate the two. Maybe dojo has
1468     // a better way to do this?
1469     var fld = dojo.byId(fieldId);
1470     var tip = dojo.byId(fieldId + '-tip');
1471     dojo.connect(fld, 'onfocus', function(evt) {
1472                      dijit.showTooltip(tip.innerHTML, fld, ['below', 'after']); });
1473     dojo.connect(fld, 'onblur', function(evt) { dijit.hideTooltip(fld); });
1474 }
1475
1476 // xpath utilities
1477
1478 var xpathParser = new openils.MarcXPathParser();
1479
1480 function tagAndSubFieldsToXpath(tags, subfields) {
1481     // given tags, and subfields, build up an XPath.
1482     try {
1483         var parts = {
1484             'tags':tags.match(/[\d]+/g), 
1485             'subfields':subfields.match(/[a-zA-z]/g) };
1486         return xpathParser.compile(parts);
1487     } catch (err) {
1488         return {'parts':null, 'tags':null, 'error':err};
1489     }
1490 }
1491
1492 function looksLikeDerivedXpath(path) {
1493     // Does this path look like it was derived from tags and subfields?
1494     var parsed = xpathParser.parse(path);
1495     if (parsed.tags == null) 
1496         return false;
1497     var compiled = xpathParser.compile(parsed);
1498     return (path == compiled);
1499 }
1500
1501 // amazing xpath-util unit-tests
1502 if (!looksLikeDerivedXpath('//*[@tag="901"]/*[@code="c"]'))     alert('vandelay xpath-utility error');
1503 if ( looksLikeDerivedXpath('ba-boo-ba-boo!'))                   alert('vandelay xpath-utility error');
1504
1505
1506
1507 var profileContextOrg
1508 function vlShowProfileEditor() {
1509     displayGlobalDiv('vl-profile-editor-div');
1510     buildProfileGrid();
1511
1512     var connect = function() {
1513         dojo.connect(profileContextOrgSelector, 'onChange',
1514             function() {
1515                 profileContextOrg = this.attr('value');
1516                 pGrid.resetStore();
1517                 buildProfileGrid();
1518             }
1519         );
1520     };
1521
1522     new openils.User().buildPermOrgSelector(
1523         'ADMIN_MERGE_PROFILE', profileContextOrgSelector, null, connect);
1524 }
1525
1526 function buildProfileGrid() {
1527
1528     if(profileContextOrg == null)
1529         profileContextOrg = openils.User.user.ws_ou();
1530
1531     pGrid.loadAll( 
1532         {order_by : {vmp : 'name'}}, 
1533         {owner : fieldmapper.aou.fullPath(profileContextOrg, true)}
1534     );
1535 }
1536
1537 /* --- Import Item Attr Grid --------------- */
1538
1539 var itemAttrContextOrg;
1540 function vlShowImportItemAttrEditor() {
1541     displayGlobalDiv('vl-item-attr-editor-div');
1542     buildImportItemAttrGrid();
1543
1544     var connect = function() {
1545         dojo.connect(itemAttrContextOrgSelector, 'onChange',
1546             function() {
1547                 itemAttrContextOrg = this.attr('value');
1548                 itemAttrGrid.resetStore();
1549                 vlShowImportItemAttrEditor();
1550             }
1551         );
1552     };
1553
1554     new openils.User().buildPermOrgSelector(
1555         'ADMIN_IMPORT_ITEM_ATTR_DEF', 
1556             itemAttrContextOrgSelector, null, connect);
1557 }
1558
1559 function buildImportItemAttrGrid() {
1560
1561     if(itemAttrContextOrg == null)
1562         itemAttrContextOrg = openils.User.user.ws_ou();
1563
1564     itemAttrGrid.loadAll( 
1565         {order_by : {viiad : 'name'}}, 
1566         {owner : fieldmapper.aou.fullPath(itemAttrContextOrg, true)}
1567     );
1568 }
1569