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