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