]> git.evergreen-ils.org Git - Evergreen.git/blob - Open-ILS/web/js/ui/default/actor/user/register.js
Active/Primary Editing for Patron Cards
[Evergreen.git] / Open-ILS / web / js / ui / default / actor / user / register.js
1 dojo.require('dojo.data.ItemFileReadStore');
2 dojo.require('dijit.form.Form');
3 dojo.require('dijit.form.Textarea');
4 dojo.require('dijit.form.FilteringSelect');
5 dojo.require('dijit.form.ComboBox');
6 dojo.require('dijit.form.NumberSpinner');
7 dojo.require('fieldmapper.IDL');
8 dojo.require('openils.PermaCrud');
9 dojo.require('openils.widget.AutoGrid');
10 dojo.require('openils.widget.AutoFieldWidget');
11 dojo.require('dijit.form.CheckBox');
12 dojo.require('dijit.form.Button');
13 dojo.require('dojo.date');
14 dojo.require('openils.CGI');
15 dojo.require('openils.XUL');
16 dojo.require('openils.Util');
17 dojo.require('openils.Event');
18
19 dojo.requireLocalization('openils.actor', 'register');
20 var localeStrings = dojo.i18n.getLocalization('openils.actor', 'register');
21
22
23 var pcrud;
24 var fmClasses = ['au', 'ac', 'aua', 'actsc', 'asv', 'asvq', 'asva'];
25 var fieldDoc = {};
26 var statCats;
27 var statCatTemplate;
28 var surveys;
29 var staff;
30 var patron;
31 var uEditUsePhonePw = false;
32 var widgetPile = [];
33 var uEditCardVirtId = -1;
34 var uEditAddrVirtId = -1;
35 var orgSettings = {};
36 var userSettings = {};
37 var userSettingsToUpdate = {};
38 var userSettingTypes;
39 var tbody;
40 var addrTemplateRows;
41 var cgi;
42 var cloneUser;
43 var cloneUserObj;
44 var stageUser;
45 var optInSettings;
46 var allCardsTemplate;
47 var uEditCloneCopyAddr; // if true, copy addrs on clone instead of link
48 var homeOuTypes = {};
49 var cardPerms = {};
50 var editCard;
51
52 var dupeUsrname = false;
53 var dupeBarcode = false;
54
55 if(!window.xulG) var xulG = null;
56 var lock_ready = false;
57 var already_locked = false;
58
59 function load() {
60     staff = new openils.User().user;
61     pcrud = new openils.PermaCrud();
62     cgi = new openils.CGI();
63     cloneUser = cgi.param('clone');
64     var userId = cgi.param('usr');
65     var stageUname = cgi.param('stage');
66
67     saveButton.attr("label", localeStrings.SAVE);
68     saveCloneButton.attr("label", localeStrings.SAVE_CLONE);
69     replaceBarcode.attr("label", localeStrings.REPLACE_BARCODE);
70     dojo.byId('uedit-show-required').innerHTML = localeStrings.SHOW_REQUIRED;
71     dojo.byId('uedit-show-suggested').innerHTML = localeStrings.SHOW_SUGGESTED;
72     dojo.byId('uedit-show-all').innerHTML = localeStrings.SHOW_ALL;
73     dojo.byId('uedit-dupe-barcode-warning').innerHTML = localeStrings.BARCODE_IN_USE;
74     allCards.attr("label", localeStrings.SEE_ALL);
75     dojo.byId('uedit-dupe-username-warning').innerHTML = localeStrings.DUPE_USERNAME;
76     generatePassword.attr("label", localeStrings.RESET_PASSWORD);
77     dojo.byId('verifyPassword').innerHTML = localeStrings.VERIFY_PASSWORD;
78     dojo.byId('parentGuardian').innerHTML = localeStrings.PARENT_OR_GUARDIAN;
79     dojo.byId('userSettings').innerHTML = localeStrings.USER_SETTINGS;
80     dojo.byId('statCats').innerHTML = localeStrings.STAT_CATS;
81     dojo.byId('uedit-all-cards-barcode').innerHTML = localeStrings.ALL_CARDS_BARCODE;
82     dojo.byId('uedit-all-cards-active').innerHTML = localeStrings.ALL_CARDS_ACTIVE;
83     dojo.byId('uedit-all-cards-primary').innerHTML = localeStrings.ALL_CARDS_PRIMARY;
84     allCardsClose.attr("label", localeStrings.ALL_CARDS_CLOSE);
85     allCardsApply.attr("label", localeStrings.ALL_CARDS_APPLY);
86
87     dojo.query("td[name='addressHeader']").forEach( function(item) { item.innerHTML = localeStrings.ADDRESS_HEADER; });
88     dojo.query("span[name='mailingAddress']").forEach( function(item) { item.innerHTML = localeStrings.ADDRESS_MAILING; });
89     dojo.query("span[name='billingAddress']").forEach( function(item) { item.innerHTML = localeStrings.ADDRESS_BILLING; });
90     dojo.query("span[name='addressPending']").forEach( function(item) { item.innerHTML = localeStrings.ADDRESS_PENDING; });
91     dojo.query("button[name='approve-button']").forEach( function(item) { item.innerHTML = localeStrings.ADDRESS_APPROVE; });
92     dojo.query("span[name='address-already-owned']").forEach( function(item) { item.innerHTML = localeStrings.ADDRESS_OWNED; });
93     dojo.query("button[name='addressNew']").forEach( function(item) { item.innerHTML = localeStrings.ADDRESS_NEW; });
94
95     if(xulG) {
96             if(xulG.ses) openils.User.authtoken = xulG.ses;
97             if(typeof xulG.clone != 'undefined') cloneUser = xulG.clone;
98         if(typeof xulG.usr != 'undefined') userId = xulG.usr
99         if(typeof xulG.params != 'undefined') {
100             var parms = xulG.params;
101                 if(typeof parms.ses != 'undefined') 
102                 openils.User.authtoken = parms.ses;
103                 if(typeof parms.clone != 'undefined') 
104                 cloneUser = parms.clone;
105             if(typeof parms.usr != 'undefined')
106                 userId = parms.usr;
107             if(typeof parms.stage != 'undefined')
108                 stageUname = parms.stage
109         }
110     }
111
112     orgSettings = fieldmapper.aou.fetchOrgSettingBatch(staff.ws_ou(), [
113         'global.password_regex',
114         'global.juvenile_age_threshold',
115         'patron.password.use_phone',
116         'ui.patron.default_inet_access_level',
117         'ui.patron.default_ident_type',
118         'ui.patron.default_country',
119         'ui.patron.registration.require_address',
120         'circ.holds.behind_desk_pickup_supported',
121         'circ.patron_edit.clone.copy_address',
122         'ui.patron.edit.au.second_given_name.show',
123         'ui.patron.edit.au.second_given_name.suggest',
124         'ui.patron.edit.au.suffix.show',
125         'ui.patron.edit.au.suffix.suggest',
126         'ui.patron.edit.au.alias.show',
127         'ui.patron.edit.au.alias.suggest',
128         'ui.patron.edit.au.dob.require',
129         'ui.patron.edit.au.dob.show',
130         'ui.patron.edit.au.dob.suggest',
131         'ui.patron.edit.au.dob.calendar',
132         'ui.patron.edit.au.juvenile.show',
133         'ui.patron.edit.au.juvenile.suggest',
134         'ui.patron.edit.au.ident_value.show',
135         'ui.patron.edit.au.ident_value.suggest',
136         'ui.patron.edit.au.ident_value2.show',
137         'ui.patron.edit.au.ident_value2.suggest',
138         'ui.patron.edit.au.email.require',
139         'ui.patron.edit.au.email.show',
140         'ui.patron.edit.au.email.suggest',
141         'ui.patron.edit.au.email.regex',
142         'ui.patron.edit.au.email.example',
143         'ui.patron.edit.au.day_phone.require',
144         'ui.patron.edit.au.day_phone.show',
145         'ui.patron.edit.au.day_phone.suggest',
146         'ui.patron.edit.au.day_phone.regex',
147         'ui.patron.edit.au.day_phone.example',
148         'ui.patron.edit.au.evening_phone.require',
149         'ui.patron.edit.au.evening_phone.show',
150         'ui.patron.edit.au.evening_phone.suggest',
151         'ui.patron.edit.au.evening_phone.regex',
152         'ui.patron.edit.au.evening_phone.example',
153         'ui.patron.edit.au.other_phone.require',
154         'ui.patron.edit.au.other_phone.show',
155         'ui.patron.edit.au.other_phone.suggest',
156         'ui.patron.edit.au.other_phone.regex',
157         'ui.patron.edit.au.other_phone.example',
158         'ui.patron.edit.phone.regex',
159         'ui.patron.edit.phone.example',
160         'ui.patron.edit.au.active.show',
161         'ui.patron.edit.au.active.suggest',
162         'ui.patron.edit.au.barred.show',
163         'ui.patron.edit.au.barred.suggest',
164         'ui.patron.edit.au.master_account.show',
165         'ui.patron.edit.au.master_account.suggest',
166         'ui.patron.edit.au.claims_returned_count.show',
167         'ui.patron.edit.au.claims_returned_count.suggest',
168         'ui.patron.edit.au.claims_never_checked_out_count.show',
169         'ui.patron.edit.au.claims_never_checked_out_count.suggest',
170         'ui.patron.edit.au.alert_message.show',
171         'ui.patron.edit.au.alert_message.suggest',
172         'ui.patron.edit.aua.post_code.regex',
173         'ui.patron.edit.aua.post_code.example',
174         'ui.patron.edit.aua.county.require',
175         'format.date',
176         'ui.patron.edit.default_suggested',
177         'opac.barcode_regex',
178         'opac.username_regex'
179     ]);
180
181     for(k in orgSettings)
182         if(orgSettings[k])
183             orgSettings[k] = orgSettings[k].value;
184
185     uEditCloneCopyAddr = orgSettings['circ.patron_edit.clone.copy_address'];
186     uEditUsePhonePw = orgSettings['patron.password.use_phone'];
187     uEditFetchUserSettings(userId);
188
189     if(userId) {
190         patron = uEditLoadUser(userId);
191     } else {
192         if(stageUname) {
193             patron = uEditLoadStageUser(stageUname);
194         } else {
195             patron = uEditNewPatron();
196             if(cloneUser) 
197                 uEditCopyCloneData(patron);
198         }
199     }
200
201
202     var list = pcrud.search('fdoc', {fm_class:fmClasses});
203     for(var i in list) {
204         var doc = list[i];
205         if(!fieldDoc[doc.fm_class()])
206             fieldDoc[doc.fm_class()] = {};
207         fieldDoc[doc.fm_class()][doc.field()] = doc;
208     }
209
210     list = pcrud.search('aout', {can_have_users: 'true'});
211     for(var i in list) {
212         var type = list[i];
213         homeOuTypes[type.id()] = true;
214     }
215
216     tbody = dojo.byId('uedit-tbody');
217
218     if(orgSettings['ui.patron.edit.default_suggested'])
219         uEditToggleRequired(2);
220
221     addrTemplateRows = dojo.query('tr[type=addr-template]', tbody);
222     dojo.forEach(addrTemplateRows, function(row) { row.parentNode.removeChild(row); } );
223     statCatTemplate = tbody.removeChild(dojo.byId('stat-cat-row-template'));
224     surveyTemplate = tbody.removeChild(dojo.byId('survey-row-template'));
225     surveyQuestionTemplate = tbody.removeChild(dojo.byId('survey-question-row-template'));
226
227     checkGrpAppPerm(); // to do the initial load
228     loadStaticFields();
229
230
231     if(patron.isnew() && patron.addresses().length == 0) 
232         uEditNewAddr(null, uEditAddrVirtId, true);
233     else loadAllAddrs();
234     loadStatCats();
235     loadSurveys();
236     checkClaimsReturnCountPerm();
237     checkClaimsNoCheckoutCountPerm();
238
239     dojo.connect(replaceBarcode, 'onClick', replaceCardHandler);
240     dojo.connect(allCards, 'onClick', drawAllCards);
241     if(patron.isnew()) {
242         dojo.addClass(dojo.byId('uedit-all-barcodes'), 'hidden');
243     } else {
244         new openils.User().getPermOrgList(
245             'UPDATE_PATRON_ACTIVE_CARD',
246             function(orgList) { 
247                 if(orgList.indexOf(patron.home_ou()) != -1) 
248                     cardPerms['UPDATE_PATRON_ACTIVE_CARD'] = true;
249             },
250             true, 
251             true
252         );
253         new openils.User().getPermOrgList(
254             'UPDATE_PATRON_PRIMARY_CARD',
255             function(orgList) { 
256                 if(orgList.indexOf(patron.home_ou()) != -1) 
257                     cardPerms['UPDATE_PATRON_PRIMARY_CARD'] = true;
258             },
259             true, 
260             true
261         );
262     }
263
264     var input = findWidget('ac', 'barcode');
265     if (patron.isnew()) {
266         replaceBarcode.attr('disabled', true);
267     } else {
268         input.widget.attr('disabled', true).attr('readOnly', true);
269     }
270
271         dojo.connect(generatePassword, 'onClick', generatePasswordHandler);
272
273     if(!patron.isnew() && !checkGrpAppPerm(patron.profile()) && patron.id() != openils.User.user.id()) {
274         // we are not allowed to edit this user, so disable the save option
275         saveButton.attr('disabled', true);
276         saveCloneButton.attr('disabled', true);
277     }
278         
279     lock_ready = true;
280 }
281
282 var permGroups;
283 var noPermGroups = [];
284 // Returns true if the user is allowed to edit the selected group
285 function checkGrpAppPerm(grpId) {
286
287     if(!permGroups) {
288
289         // get the groups
290         permGroups = new openils.PermaCrud().retrieveAll('pgt');
291         var permGroupPerms = []
292
293         // collect the group permissions
294         dojo.forEach(permGroups, 
295             function(grp) {
296                 if(grp.application_perm())
297                     permGroupPerms.push(grp.application_perm());
298             }
299         );
300
301         // see which of the group application perms I do not have
302         var myPerms = fieldmapper.standardRequest(
303             ['open-ils.actor', 'open-ils.actor.user.has_work_perm_at.batch'],
304             [openils.User.authtoken, permGroupPerms]
305         );
306
307         var failedPerms = [];
308         for(var p in myPerms) { 
309             if(myPerms[p].length == 0) 
310                 failedPerms.push(p); 
311         }
312
313         // identify which groups I cannot edit because I do not have permisssion
314
315         function checkTree(grp, failed) {
316             failed = failed || failedPerms.indexOf(grp.application_perm()) > -1;
317             if(failed) noPermGroups.push(grp.id()+'');
318             dojo.forEach(
319                 permGroups.filter(function(g) { return g.parent() == grp.id() } ),
320                 function(child) {
321                     checkTree(child, failed);
322                 }
323             );
324         }
325
326         checkTree(permGroups.filter(function(g) { return g.parent() == null })[0]);
327     }
328
329     return noPermGroups.indexOf(grpId+'') == -1;
330 }
331
332
333 function drawAllCards() {
334
335     var tbody = dojo.byId('uedit-all-cards-tbody');
336     if(!allCardsTemplate) {
337         allCardsTemplate = tbody.removeChild(dojo.byId('uedit-all-cards-tr-template'));
338     } else {
339         while(tbody.childNodes[0])
340             tbody.removeChild(tbody.childNodes[0]);
341     }
342
343     if(cardPerms['UPDATE_PATRON_ACTIVE_CARD'] || cardPerms['UPDATE_PATRON_PRIMARY_CARD']) {
344         dojo.removeClass(dojo.byId('uedit-apply-card-changes'), 'hidden');
345     } else {
346         dojo.addClass(dojo.byId('uedit-apply-card-changes'), 'hidden');
347     }
348
349     var first = true;
350     dojo.forEach(
351         patron.cards().filter(function(c) { return c.id() == patron.card().id(); }).concat(patron.cards()), // grab the main card first
352         function(card) {
353             if(!first) {
354                 if(card.id() == patron.card().id())
355                     return;
356             }
357             var row = allCardsTemplate.cloneNode(true);
358             row.setAttribute("cardid", card.id());
359             row.card = card;
360             getByName(row, 'barcode').innerHTML = card.barcode();
361             if(cardPerms['UPDATE_PATRON_ACTIVE_CARD']) {
362                 row.active_checkbox = new dijit.form.CheckBox({
363                     scrollOnFocus:false,
364                     checked: openils.Util.isTrue(card.active())
365                 }, getByName(row, 'active'));
366             } else {
367                 getByName(row, 'active').appendChild(
368                     openils.Util.isTrue(card.active()) ? 
369                         dojo.byId('true').cloneNode(true) :
370                         dojo.byId('false').cloneNode(true)
371                 );
372             }
373             if(cardPerms['UPDATE_PATRON_PRIMARY_CARD']) {
374                 row.primary_radiobutton = new dijit.form.RadioButton({
375                     scrollOnFocus:false,
376                     checked: card.id() == patron.card().id(),
377                     value: card.id(),
378                     name: 'card_primary'
379                 }, getByName(row, 'primary'));
380             } else {
381                 getByName(row, 'primary').appendChild(
382                     openils.Util.isTrue(card.id() == patron.card().id()) ? 
383                         dojo.byId('true').cloneNode(true) :
384                         dojo.byId('false').cloneNode(true)
385                 );
386             }
387             tbody.appendChild(row);
388             first = false;
389         }
390     );
391
392     allCardsDialog.show();
393 }
394
395 function applyCardChanges() {
396     var cardrows = dojo.query('[cardid]', allCardsDialog.domNode);
397     dojo.forEach(cardrows,
398         function(row) {
399             if(cardPerms['UPDATE_PATRON_ACTIVE_CARD']) {
400                 var active = row.active_checkbox.checked ? 't' : 'f'
401                 if(row.card.active() != active) {
402                     row.card.active(active);
403                     row.card.ischanged(1);
404                 }
405             }
406             if(cardPerms['UPDATE_PATRON_PRIMARY_CARD']) {
407                 if(row.primary_radiobutton.checked && row.card.id() != patron.card().id()) {
408                     patron.card(row.card);
409                 }
410             }
411         }
412     );
413     allCardsDialog.hide();
414 }
415
416 /**
417  * Mark the current card inactive, create a new primary card
418  */
419 function replaceCardHandler() {
420     var input = findWidget('ac', 'barcode');
421     input.widget.attr('disabled', false).attr('readOnly', false).attr('value', null).focus();
422     replaceBarcode.attr('disabled', true);
423     
424     // pull old card off the cards list so we don't have a dupe sitting in there
425     if (patron.cards().length > 0) {
426         var old = patron.cards().filter(function(c){return (c.id() == patron.card().id())})[0];
427         old.active('f');
428         old.ischanged(1);
429     }
430
431     var newc = new fieldmapper.ac();
432     newc.id(uEditCardVirtId--);
433     newc.isnew(1);
434     newc.active('t');
435     patron.card(newc);
436     editCard = newc;
437     var t = patron.cards();
438         if (!t) { t = []; }
439         t.push(newc);
440         patron.cards(t);
441 }
442
443 /**
444  * Generate a random password for the patron.
445  */
446 function generatePasswordHandler() {
447         uEditMakeRandomPw(patron);
448         var f = findWidget('au', 'passwd');
449         f.widget.attr('value', patron.passwd());
450         f = findWidget('au', 'passwd2');
451         f.widget.attr('value', patron.passwd());
452 }
453
454 /**
455  * Loads a staged user and turns them into something the editor can understand
456  */
457 function uEditLoadStageUser(stageUname) {
458
459     var data = fieldmapper.standardRequest(
460         ['open-ils.actor', 'open-ils.actor.user.stage.retrieve.by_username'],
461         { params : [openils.User.authtoken, stageUname] }
462     );
463
464     stageUser = data.user;
465     patron = uEditNewPatron();
466
467     if(!stageUser) 
468         return patron;
469
470     // copy the data into our new user object
471     for(var key in fieldmapper.IDL.fmclasses.stgu.field_map) {
472         if(fieldmapper.IDL.fmclasses.au.field_map[key] && !fieldmapper.IDL.fmclasses.stgu.field_map[key].virtual) {
473             if(data.user[key]() !== null)
474                 patron[key]( data.user[key]() );
475         }
476     }
477
478     // copy the data into our new address objects
479     // TODO: uses the first mailing address only
480     if(data.mailing_addresses.length) {
481
482         var mail_addr = new fieldmapper.aua();
483         mail_addr.id(-1); // virtual ID
484         mail_addr.usr(-1);
485         mail_addr.isnew(1);
486         patron.mailing_address(mail_addr);
487         var t = patron.addresses();
488             if (!t) { t = []; }
489             t.push(mail_addr);
490             patron.addresses(t);
491
492         for(var key in fieldmapper.IDL.fmclasses.stgma.field_map) {
493             if(fieldmapper.IDL.fmclasses.aua.field_map[key] && !fieldmapper.IDL.fmclasses.stgma.field_map[key].virtual) {
494                 if(data.mailing_addresses[0][key]() !== null)
495                     mail_addr[key]( data.mailing_addresses[0][key]() );
496             }
497         }
498     }
499     
500     // copy the data into our new address objects
501     // TODO uses the first billing address only
502     if(data.billing_addresses.length) {
503
504         var bill_addr = new fieldmapper.aua();
505         bill_addr.id(-2); // virtual ID
506         bill_addr.usr(-1);
507         bill_addr.isnew(1);
508         patron.billing_address(bill_addr);
509         var t = patron.addresses();
510             if (!t) { t = []; }
511             t.push(bill_addr);
512             patron.addresses(t);
513
514         for(var key in fieldmapper.IDL.fmclasses.stgba.field_map) {
515             if(fieldmapper.IDL.fmclasses.aua.field_map[key] && !fieldmapper.IDL.fmclasses.stgba.field_map[key].virtual) {
516                 if(data.billing_addresses[0][key]() !== null)
517                     bill_addr[key]( data.billing_addresses[0][key]() );
518             }
519         }
520     }
521
522     // TODO: uses the first card only
523     if(data.cards.length) {
524         var card = new fieldmapper.ac();
525         card.id(-1); // virtual ID
526         patron.card().barcode(data.cards[0].barcode());
527     }
528
529     return patron;
530 }
531
532 /*
533  * clone the home org, phone numbers, and billing/mailing address
534  */
535 function uEditCopyCloneData(patron) {
536     cloneUserObj = uEditLoadUser(cloneUser);
537
538     var cloneFields = [
539         'home_ou', 
540         'day_phone', 
541         'evening_phone', 
542         'other_phone',
543         'usrgroup'
544     ];
545
546     if(!uEditCloneCopyAddr) 
547         cloneFields = cloneFields.concat(['mailing_address', 'billing_address']);
548
549     dojo.forEach(
550         cloneFields, 
551         function(field) {
552             patron[field](cloneUserObj[field]());
553         }
554     );
555
556     if(uEditCloneCopyAddr) {
557         var billAddr, mailAddr;
558
559         // copy the billing and mailing addresses into new addresses
560         function cloneAddr(addr) {
561             var newAddr = addr.clone();
562             newAddr.isnew(true);
563             newAddr.id(uEditAddrVirtId--);
564             newAddr.usr(patron.id());
565             patron.addresses().push(newAddr);
566             return newAddr;
567         }
568
569         if(billAddr = cloneUserObj.billing_address()) 
570             patron.billing_address(cloneAddr(billAddr));
571
572         if(mailAddr = cloneUserObj.mailing_address()) {
573             if (billAddr && billAddr.id() == mailAddr.id()) {
574                 patron.mailing_address(patron.billing_address());
575             } else {
576                 patron.mailing_address(cloneAddr(mailAddr));
577             }
578         }
579
580         if(!billAddr) // if there was no billing addr, use the mailing addr
581             patron.billing_address(patron.mailing_address());
582
583     } else {
584
585         // link the billing and mailing addresses
586         if(patron.billing_address()) {
587             var t = patron.addresses();
588                 if (!t) { t = []; }
589                 t.push(patron.billing_address());
590                 patron.addresses(t);
591         }
592
593         if(patron.mailing_address() && (
594                 patron.addresses().length == 0 || 
595                 patron.mailing_address().id() != patron.billing_address().id()) ) {
596             var t = patron.addresses();
597                 if (!t) { t = []; }
598                 t.push(patron.mailing_address());
599                 patron.addresses(t);
600         }
601     }
602 }
603
604
605 function uEditFetchUserSettings(userId) {
606     
607     var baseNode = fieldmapper.aou.findOrgUnit(staff.ws_ou());
608     var orgs = fieldmapper.aou.orgNodeTrail(baseNode);
609     orgs = orgs.map(function(node) { return node.id(); });
610
611     /* fetch any user setting types we need + any that offer opt-in */
612     userSettingTypes = pcrud.search('cust', {
613         '-or' : [
614             {name:['circ.holds_behind_desk', 'circ.collections.exempt']}, 
615             {name : {
616                 'in': {
617                     select : {atevdef : ['opt_in_setting']}, 
618                     from : 'atevdef',
619                     // we only care about opt-in settings for event_defs our users encounter
620                     where : {'+atevdef' : {owner : orgs}}
621                 }
622             }}
623         ]
624     });
625
626     var names = userSettingTypes.map(function(obj) { return obj.name() });
627
628     /* fetch any values set for this user */
629     if(userId) {
630         userSettings = fieldmapper.standardRequest(
631             ['open-ils.actor', 'open-ils.actor.patron.settings.retrieve.authoritative'],
632             {params : [openils.User.authtoken, userId, names]});
633     }
634 }
635
636
637 function uEditLoadUser(userId) {
638     var patron = fieldmapper.standardRequest(
639         ['open-ils.actor', 'open-ils.actor.user.fleshed.retrieve.authoritative'],
640         {params : [openils.User.authtoken, userId]}
641     );
642     openils.Event.parse_and_raise(patron);
643     return patron;
644 }
645
646 function loadStaticFields() {
647     for(var idx = 0; tbody.childNodes[idx]; idx++) {
648         var row = tbody.childNodes[idx];
649         if(row.nodeType != row.ELEMENT_NODE) continue;
650         var fmcls = row.getAttribute('fmclass');
651         if(fmcls) {
652             fleshFMRow(row, fmcls);
653         } else {
654
655             if(row.id == 'uedit-settings-divider') {
656
657                 var template = tbody.removeChild(dojo.byId('uedit-user-setting-template'));
658                 dojo.forEach(userSettingTypes, function(type) { uEditDrawSettingRow(tbody, row, template, type); } );
659
660                 if(userSettingTypes.length > 1 || orgSettings['circ.holds.behind_desk_pickup_supported']) {
661                     openils.Util.show('uedit-settings-divider', 'table-row');
662                 }
663             }
664         }
665     }
666 }
667
668 function uEditDrawSettingRow(tbody, dividerRow, template, stype) {
669     var row = template.cloneNode(true);
670     row.setAttribute('user_setting', stype.name());
671     getByName(row, 'label').innerHTML = stype.label();
672     var cb = new dijit.form.CheckBox({scrollOnFocus:false}, getByName(row, 'widget'));
673     cb.attr('value', userSettings[stype.name()]);
674     dojo.connect(cb, 'onChange', function(newVal) { userSettingsToUpdate[stype.name()] = newVal; });
675     tbody.insertBefore(row, dividerRow.nextSibling);
676     openils.Util.show(row, 'table-row');
677
678     if(stype.name() == 'circ.collections.exempt') {
679         checkCollectionsExemptPerm(cb);
680     }
681 }
682
683 function uEditUpdateUserSettings(userId) {
684     return fieldmapper.standardRequest(
685         ['open-ils.actor', 'open-ils.actor.patron.settings.update'],
686         {params : [openils.User.authtoken, userId, userSettingsToUpdate]});
687 }
688
689 function loadAllAddrs() {
690     dojo.forEach(patron.addresses(),
691         function(addr) {
692             uEditNewAddr(null, addr.id());
693         }
694     );
695 }
696
697 function loadStatCats() {
698
699     statCats = fieldmapper.standardRequest(
700         ['open-ils.circ', 'open-ils.circ.stat_cat.actor.retrieve.all'],
701         {params : [openils.User.authtoken, staff.ws_ou()]}
702     );
703
704     // draw stat cats
705     for(var idx in statCats) {
706         var stat = statCats[idx];
707         var row = statCatTemplate.cloneNode(true);
708         row.id = 'stat-cat-row-' + idx;
709         row.setAttribute('stat_cat_owner',stat.owner());
710         row.setAttribute('stat_cat_name',stat.name());
711         row.setAttribute('stat_cat_id',stat.id());
712         tbody.appendChild(row);
713         getByName(row, 'name').innerHTML = stat.name();
714         var valtd = getByName(row, 'widget');
715         var span = valtd.appendChild(document.createElement('span'));
716         var store = new dojo.data.ItemFileReadStore(
717                 {data:fieldmapper.actsc.toStoreData(stat.entries())});
718         var comboBox = new dijit.form.ComboBox({store:store,scrollOnFocus:false,fetchProperties:{sort:[{attribute: 'value'}]}}, span);
719         comboBox.labelAttr = 'value';
720         comboBox.searchAttr = 'value';
721
722         comboBox._wtype = 'statcat';
723         comboBox._statcat = stat.id();
724         widgetPile.push(comboBox); 
725
726         // populate existing cats
727         var map = patron.stat_cat_entries().filter(
728             function(mp) { return (mp.stat_cat() == stat.id()) })[0];
729         if(map) comboBox.attr('value', map.stat_cat_entry()); 
730
731     }
732 }
733
734 function loadSurveys() {
735
736     surveys = fieldmapper.standardRequest(
737         ['open-ils.circ', 'open-ils.circ.survey.retrieve.all'],
738         {params : [openils.User.authtoken]}
739     );
740
741     // draw surveys
742     for(var idx in surveys) {
743         var survey = surveys[idx];
744         var required = openils.Util.isTrue(survey.required());
745         var srow = surveyTemplate.cloneNode(true);
746         if(required) srow.setAttribute('required','required');
747         tbody.appendChild(srow);
748         getByName(srow, 'name').innerHTML = survey.name();
749
750         for(var q in survey.questions()) {
751             var quest = survey.questions()[q];
752             var qrow = surveyQuestionTemplate.cloneNode(true);
753             if(required) qrow.setAttribute('required','required');
754             tbody.appendChild(qrow);
755             getByName(qrow, 'question').innerHTML = quest.question();
756
757             var span = getByName(qrow, 'answers').appendChild(document.createElement('span'));
758             var store = new dojo.data.ItemFileReadStore(
759                 {data:fieldmapper.asva.toStoreData(quest.answers())});
760             var select = new dijit.form.FilteringSelect({store:store,scrollOnFocus:false}, span);
761             if (! required ) {
762                 select.isValid = function() { return true; };
763             }
764             select.labelAttr = 'answer';
765             select.searchAttr = 'answer';
766
767             select._wtype = 'survey';
768             select._survey = survey.id();
769             select._question = quest.id();
770             widgetPile.push(select); 
771         }
772     }
773 }
774
775
776 function fleshFMRow(row, fmcls, args) {
777     var fmfield = row.getAttribute('fmfield');
778     var wclass = row.getAttribute('wclass');
779     var wstyle = row.getAttribute('wstyle');
780     var wconstraints = row.getAttribute('wconstraints');
781     /* use CSS to set the zindex for widgets you want to disable. */
782     var disabled = dojo.style(row, 'zIndex') == -1 ? true : false;
783     var isphone = (fmcls == 'au') && (fmfield.search('_phone') != -1);
784
785     var isPasswd2 = (fmfield == 'passwd2');
786     if(isPasswd2) fmfield = 'passwd';
787     var fieldIdl = fieldmapper.IDL.fmclasses[fmcls].field_map[fmfield];
788     if(!args) args = {};
789
790     var existing = dojo.query('td', row);
791     var htd = existing[0] || row.appendChild(document.createElement('td'));
792     var ltd = existing[1] || row.appendChild(document.createElement('td'));
793     var wtd = existing[2] || row.appendChild(document.createElement('td'));
794     var ftd = existing[3] || row.appendChild(document.createElement('td'));
795
796     openils.Util.addCSSClass(htd, 'uedit-help');
797     if(fieldDoc[fmcls] && fieldDoc[fmcls][fmfield]) {
798         var link = dojo.byId('uedit-help-template').cloneNode(true);
799         link.id = '';
800         link.onclick = function() { ueLoadContextHelp(fmcls, fmfield) };
801         openils.Util.removeCSSClass(link, 'hidden');
802         htd.appendChild(link);
803     }
804
805     if(!ltd.textContent) {
806         ltd.appendChild(document.createTextNode(fieldIdl.label));
807     }
808
809     if(!ftd.textContent) {
810         if(orgSettings['ui.patron.edit.' + fmcls + '.' + fmfield + '.example']) {
811             ftd.appendChild(document.createTextNode(localeStrings.EXAMPLE + orgSettings['ui.patron.edit.' + fmcls + '.' + fmfield + '.example']));
812         }
813         else if(isphone && orgSettings['ui.patron.edit.phone.example']) {
814             ftd.appendChild(document.createTextNode(localeStrings.EXAMPLE + orgSettings['ui.patron.edit.phone.example']));
815         }
816         else if(fieldIdl.datatype == 'timestamp') {
817             ftd.appendChild(document.createTextNode(localeStrings.EXAMPLE + dojo.date.locale.format(new Date(1970,0,31),{selector: "date", fullYear: true, datePattern: (orgSettings['format.date'] ? orgSettings['format.date'] : null)})));
818         }
819     }
820
821     var span = document.createElement('span');
822     wtd.appendChild(span);
823
824     var fmObject = null;
825     switch(fmcls) {
826         case 'au' : fmObject = patron; break;
827         case 'ac' : if(!editCard) editCard = patron.card(); fmObject = editCard; break;
828         case 'aua' : 
829             fmObject = patron.addresses().filter(
830                 function(i) { return (i.id() == args.addr) })[0];
831             if(fmObject && fmObject.usr() != patron.id())
832                 disabled = true;
833             break;
834     }
835
836     // Adjust required value by org settings
837     var curRequired = row.getAttribute('required');
838     var required = curRequired == 'required';
839     if(orgSettings['ui.patron.edit.' + fmcls + '.' + fmfield + '.require']) {
840         row.setAttribute('required', 'required');
841         required = true;
842     }
843     else if (curRequired != 'required' && orgSettings['ui.patron.edit.' + fmcls + '.' + fmfield + '.show']) {
844         row.setAttribute('required', 'show');
845     }
846     else if (curRequired != 'required' && curRequired != 'show' && orgSettings['ui.patron.edit.' + fmcls + '.' + fmfield + '.suggest']) {
847         row.setAttribute('required', 'suggested');
848     }
849
850     // password data is not fetched/required/displayed for existing users
851     if(!patron.isnew() && 'passwd' == fmfield)
852         required = false;
853
854     var dijitArgs = {
855         style: wstyle, 
856         required : required,
857         constraints : (wconstraints) ? eval('('+wconstraints+')') : {}, // the ()'s prevent Invalid Label errors with eval
858         disabled : disabled
859     };
860
861     // Org settings provided regex?
862     if(orgSettings['ui.patron.edit.' + fmcls + '.' + fmfield + '.regex']) {
863         dijitArgs.regExp = orgSettings['ui.patron.edit.' + fmcls + '.' + fmfield + '.regex'];
864     }
865     else if(isphone && orgSettings['ui.patron.edit.phone.regex']) {
866         dijitArgs.regExp = orgSettings['ui.patron.edit.phone.regex'];
867     }
868
869     if(fmcls == 'au' && fmfield == 'passwd') {
870         if (orgSettings['global.password_regex']) {
871             dijitArgs.regExp = orgSettings['global.password_regex'];
872         }
873     }
874
875     if(fmcls == 'au' && fmfield == 'dob' && !orgSettings['ui.patron.edit.au.dob.calendar'])
876         dijitArgs.popupClass = "";
877
878     var value = row.getAttribute('wvalue');
879     if(value !== null)
880         dijitArgs.value = value;
881
882     var wargs = {
883         idlField : fieldIdl,
884         fmObject : fmObject,
885         fmClass : fmcls,
886         parentNode : span,
887         widgetClass : wclass,
888         dijitArgs : dijitArgs,
889         orgDefaultsToWs : true,
890         orgLimitPerms : ['UPDATE_USER'],
891     };
892
893     if(fmfield == 'profile') {
894         // fetch profile groups non-async so existing expire_date is
895         // not overwritten when the profile groups arrive and update
896         wargs.forceSync = true;
897         wargs.disableQuery = {usergroup : 'f'};
898         if(!patron.isnew() && !checkGrpAppPerm(patron.profile()))
899             wargs.readOnly = true;
900     } else {
901         wargs.forceSync = false;
902     }
903
904     if(fmcls == 'au' && fmfield == 'home_ou'){
905         wargs.labelAttr = 'name';
906         wargs.searchAttr = 'name';
907     }
908
909     var widget = new openils.widget.AutoFieldWidget(wargs);
910     widget.build(
911         function(w, ww) {
912             if(fmfield == 'profile') { trimGrpTree(ww); }
913         }
914     );
915
916     // now put it back before we register the widget
917     if(isPasswd2) fmfield = 'passwd2';
918
919     widget._wtype = fmcls;
920     widget._fmfield = fmfield;
921     widget._addr = args.addr;
922     widgetPile.push(widget);
923     attachWidgetEvents(fmcls, fmfield, widget);
924     return widget;
925 }
926
927 function trimGrpTree(autoWidget) {
928     var store = autoWidget.widget.store;
929     if(!store) return;
930     // remove all groups that this user are not allowed to edit, 
931     // except the profile group of an existing user
932     store.fetch({onItem : 
933         function(item) {
934             if(!checkGrpAppPerm(item.id[0]) && patron.profile() != item.id[0])
935                 store.deleteItem(item);
936         }
937     });
938 }
939
940 function findWidget(wtype, fmfield, callback) {
941     return widgetPile.filter(
942         function(i){
943             if(i._wtype == wtype && i._fmfield == fmfield) {
944                 if(callback) return callback(i);
945                 return true;
946             }
947         }
948     ).pop();
949 }
950
951 /**
952  * if the user does not have the UPDATE_PATRON_CLAIM_RETURN_COUNT, 
953  * they are not allowed to directly alter the claim return count. 
954  * This function checks the perm and disable/enables the widget.
955  */
956 function checkClaimsReturnCountPerm() {
957     new openils.User().getPermOrgList(
958         'UPDATE_PATRON_CLAIM_RETURN_COUNT',
959         function(orgList) { 
960             var cr = findWidget('au', 'claims_returned_count');
961             if(orgList.indexOf(patron.home_ou()) == -1) 
962                 cr.widget.attr('disabled', true);
963             else
964                 cr.widget.attr('disabled', false);
965         },
966         true, 
967         true
968     );
969 }
970
971
972 function checkClaimsNoCheckoutCountPerm() {
973     new openils.User().getPermOrgList(
974         'UPDATE_PATRON_CLAIM_NEVER_CHECKED_OUT_COUNT',
975         function(orgList) { 
976             var cr = findWidget('au', 'claims_never_checked_out_count');
977             if(orgList.indexOf(patron.home_ou()) == -1) 
978                 cr.widget.attr('disabled', true);
979             else
980                 cr.widget.attr('disabled', false);
981         },
982         true, 
983         true
984     );
985 }
986
987 var collectExemptCBox;
988 function checkCollectionsExemptPerm(cbox) {
989     if(cbox) collectExemptCBox = cbox;
990     new openils.User().getPermOrgList(
991         'UPDATE_PATRON_COLLECTIONS_EXEMPT',
992         function(orgList) { 
993             if(orgList.indexOf(patron.home_ou()) == -1) 
994                 collectExemptCBox.attr('disabled', true);
995             else
996                 collectExemptCBox.attr('disabled', false);
997         },
998         true, 
999         true
1000     );
1001 }
1002
1003 function usePhonePw(newVal) {
1004     var newPw = false;
1005     if(this.regExp) {
1006         matches = RegExp(this.regExp).exec(newVal);
1007         if(matches.length > 1) newPw = matches[1];
1008     }
1009     if(!newPw && newVal && newVal.length >= 4) {
1010         newPw = newVal.substring(newVal.length - 4);
1011     }
1012     if(newPw) {
1013         var p1 = findWidget('au', 'passwd');
1014         var p2 = findWidget('au', 'passwd2');
1015         if (p1 && p2) {
1016             p1.widget.attr('value', newPw);
1017             p2.widget.attr('value', newPw);
1018         }
1019         return newPw;
1020     } else {
1021         return null;
1022     }
1023 }
1024
1025 function attachWidgetEvents(fmcls, fmfield, widget) {
1026
1027     dojo.connect(
1028         widget.widget,
1029         'onKeyPress',
1030         function(ev){
1031             netscape.security.PrivilegeManager.enablePrivilege('UniversalXPConnect');
1032             if (!(ev.altKey || ev.ctrlKey || ev.metaKey)) {
1033                 if (lock_ready && xulG && typeof xulG.lock_tab == 'function') {
1034                     if (! already_locked) {
1035                         xulG.lock_tab();
1036                         already_locked = true;
1037                     }
1038                 }
1039             }
1040         }
1041     );
1042     dojo.connect(
1043         widget.widget,
1044         'onChange',
1045         function(){
1046             if (lock_ready && xulG && typeof xulG.lock_tab == 'function') {
1047                 if (! already_locked) {
1048                     xulG.lock_tab();
1049                     already_locked = true;
1050                 }
1051             }
1052         }
1053     );
1054
1055
1056     if(fmcls == 'ac') {
1057         if(fmfield == 'barcode') {
1058             dojo.connect(widget.widget, 'onChange',
1059                 function() {
1060                     var barcode = this.attr('value');
1061                     dupeBarcode = false;
1062                     dojo.addClass(dojo.byId('uedit-dupe-barcode-warning'), 'hidden');
1063                     fieldmapper.standardRequest(
1064                         ['open-ils.actor', 'open-ils.actor.barcode.exists'],
1065                         {
1066                             params: [openils.User.authtoken, barcode],
1067                             oncomplete : function(r) {
1068                                 var res = openils.Util.readResponse(r);
1069                                 if(res == '1') {
1070                                     dupeBarcode = true;
1071                                     dojo.removeClass(dojo.byId('uedit-dupe-barcode-warning'), 'hidden');
1072                                 } else {
1073                                     dupeBarcode = false;
1074                                     dojo.addClass(dojo.byId('uedit-dupe-barcode-warning'), 'hidden');
1075                                     editCard.barcode(barcode); // Keep the "All" interface up to date
1076                                     var un = findWidget('au', 'usrname');
1077                                     if(!un.widget.attr('value'))
1078                                         un.widget.attr('value', barcode);
1079                                 }
1080                             }
1081                         }
1082                     );
1083                 }
1084             );
1085             return;
1086         }
1087     }
1088
1089     if(fmcls == 'au') {
1090         switch(fmfield) {
1091
1092             case 'usrname':
1093                 widget.widget.isValid = function() {
1094                     // No spaces
1095                     if(this.attr("value").match(/\s/)) {
1096                         return false;
1097                     }
1098                     // Can look like a barcode (for initial value)
1099                     if(orgSettings['opac.barcode_regex']) {
1100                         var test_regexp = new RegExp(orgSettings['opac.barcode_regex']);
1101                         if(test_regexp.test(this.attr("value"))) {
1102                             return true;
1103                         }
1104                     }
1105                     // Can look like a username
1106                     if(orgSettings['opac.username_regex']) {
1107                         var test_regexp = new RegExp(orgSettings['opac.username_regex']);
1108                         if(test_regexp.test(this.attr("value"))) {
1109                             return true;
1110                         }
1111                     }
1112                     // If we know what a barcode and username look like and we got here, reject
1113                     if(orgSettings['opac.barcode_regex'] && orgSettings['opac.username_regex'])
1114                         return false;
1115                     // Otherwise we don't have enough info to say either way, let it through.
1116                     return true;
1117                 }
1118                 dojo.connect(widget.widget, 'onChange', 
1119                     function() {
1120                         var input = findWidget('au', 'usrname');
1121                         var usrname = input.widget.attr('value');
1122
1123                         if(!usrname) {
1124                             dupeUsrname = false;
1125                             dojo.addClass(dojo.byId('uedit-dupe-username-warning'), 'hidden');
1126                             return;
1127                         }
1128
1129                         fieldmapper.standardRequest(
1130                             ['open-ils.actor', 'open-ils.actor.username.exists'],
1131                             {
1132                                 params: [openils.User.authtoken, usrname],
1133                                 oncomplete : function(r) {
1134                                     var res = openils.Util.readResponse(r);
1135                                     if(res) {
1136                                         dupeUsrname = true;
1137                                         dojo.removeClass(dojo.byId('uedit-dupe-username-warning'), 'hidden');
1138                                     } else {
1139                                         dupeUsrname = false;
1140                                         dojo.addClass(dojo.byId('uedit-dupe-username-warning'), 'hidden');
1141                                     }
1142                                 }
1143                             }
1144                         );
1145                     }   
1146                 );
1147
1148                 return;
1149
1150             case 'profile': // when the profile changes, update the expire date
1151                 dojo.connect(widget.widget, 'onChange', 
1152                     function() {
1153                         var self = this;
1154                         var expireWidget = findWidget('au', 'expire_date');
1155                         function found(items) {
1156                             if(items.length == 0) return;
1157                             var item = items[0];
1158                             var interval = self.store.getValue(item, 'perm_interval');
1159                             expireWidget.widget.attr('value', dojo.date.add(new Date(), 
1160                                 'second', openils.Util.intervalToSeconds(interval)));
1161                         }
1162                         this.store.fetch({onComplete:found, query:{id:this.attr('value')}});
1163                     }
1164                 );
1165                 return;
1166
1167             case 'dob':
1168                 widget.widget.isValid = function() {
1169                     return this.attr("value") < new Date();
1170                 };
1171                 dojo.connect(widget.widget, 'onChange',
1172                     function(newDob) {
1173                         if(!newDob) return;
1174                         var oldDob = patron.dob();
1175                         if(dojo.date.stamp.fromISOString(oldDob) == newDob) return;
1176
1177                         var juvInterval = orgSettings['global.juvenile_age_threshold'] || '18 years';
1178                         var juvWidget = findWidget('au', 'juvenile');
1179                         var base = new Date();
1180                         base.setTime(base.getTime() - Number(openils.Util.intervalToSeconds(juvInterval) + '000'));
1181
1182                         if(newDob <= base) // older than global.juvenile_age_threshold
1183                             juvWidget.widget.attr('value', false);
1184                         else
1185                             juvWidget.widget.attr('value', true);
1186                     }
1187                 );
1188                 return;
1189
1190             case 'first_given_name':
1191             case 'family_name':
1192                 dojo.connect(widget.widget, 'onChange',
1193                     function(newVal) { uEditDupeSearch('name', newVal); });
1194                 return;
1195
1196             case 'email':
1197                 dojo.connect(widget.widget, 'onChange',
1198                     function(newVal) { uEditDupeSearch('email', newVal); });
1199                 return;
1200
1201             case 'ident_value':
1202             case 'ident_value2':
1203                 dojo.connect(widget.widget, 'onChange',
1204                     function(newVal) { uEditDupeSearch('ident', newVal); });
1205                 return;
1206
1207             case 'day_phone':
1208                 // if configured, use the last four digits of the day phone number as the password
1209                 // Alt, use the first capture group of the validator regex
1210                 if(uEditUsePhonePw && patron.isnew()) {
1211                     dojo.connect(widget.widget, 'onChange', widget.widget, usePhonePw);
1212                     if (patron.day_phone()) {
1213                         usePhonePw(patron.day_phone());
1214                     }
1215                 }
1216             case 'evening_phone':
1217             case 'other_phone':
1218                 dojo.connect(widget.widget, 'onChange',
1219                     function(newVal) { uEditDupeSearch('phone', newVal); });
1220                 return;
1221
1222             case 'home_ou':
1223                 widget.widget.isValid = function() {
1224                     if(this.item) {
1225                         if(homeOuTypes[this.store.getValue(this.item, 'ou_type')]) {
1226                             return true;
1227                         }
1228                         return false;
1229                     }
1230                     return true;
1231                 };
1232                 dojo.connect(widget.widget, 'onChange',
1233                     function(newVal) { 
1234                         checkClaimsReturnCountPerm(); 
1235                         checkClaimsNoCheckoutCountPerm();
1236                         checkCollectionsExemptPerm();
1237                     }
1238                 );
1239                 return;
1240
1241             case 'passwd':
1242                 dojo.connect(widget.widget, 'onChange',
1243                     function(newVal) {
1244                         var pw1 = findWidget('au', 'passwd').widget;
1245                         var pw2 = findWidget('au', 'passwd2').widget;
1246                         var preserved_value = pw2.attr('value');
1247                         // Ensure that the pw2 field match the pw1 field to validate
1248                         pw2.regExp = newVal.replace(/([.\\^$*+?\(\)\[\]\{\}])/g, '\\$1');
1249                         pw2.reset();
1250                         pw2.attr('value',preserved_value);
1251                     });
1252                 return;
1253         }
1254     }
1255
1256     if(fmclass = 'aua') {
1257         switch(fmfield) {
1258             case 'post_code':
1259                 dojo.connect(widget.widget, 'onChange',
1260                     function(e) { 
1261                         fieldmapper.standardRequest(
1262                             ['open-ils.search', 'open-ils.search.zip'],
1263                             {   async: true,
1264                                 params: [e],
1265                                 oncomplete : function(r) {
1266                                     var res = openils.Util.readResponse(r);
1267                                     if(!res) return;
1268                                     var callback = function(w) { return w._addr == widget._addr; };
1269                                     if(res.city) findWidget('aua', 'city', callback).widget.attr('value', res.city);
1270                                     if(res.state) findWidget('aua', 'state', callback).widget.attr('value', res.state);
1271                                     if(res.county) findWidget('aua', 'county', callback).widget.attr('value', res.county);
1272                                     if(res.alert) alert(res.alert);
1273                                 }
1274                             }
1275                         );
1276                     }
1277                 );
1278                 return;
1279
1280             case 'street1':
1281             case 'street2':
1282             case 'city':
1283                 dojo.connect(widget.widget, 'onChange',
1284                     function(e) {
1285                         var callback = function(w) { return w._addr == widget._addr; };
1286                         var args = {
1287                             street1 : findWidget('aua', 'street1', callback).widget.attr('value'),
1288                             street2 : findWidget('aua', 'street2', callback).widget.attr('value'),
1289                             city : findWidget('aua', 'city', callback).widget.attr('value'),
1290                             post_code : findWidget('aua', 'post_code', callback).widget.attr('value')
1291                         };
1292                         if(args.street1 && args.city && args.post_code)
1293                             uEditDupeSearch('address', args); 
1294                     }
1295                 );
1296                 return;
1297         }
1298     }
1299 }
1300
1301 function uEditDupeSearch(type, value) {
1302     if(!value) return;
1303     var search;
1304     switch(type) {
1305
1306         case 'name':
1307             openils.Util.hide('uedit-dupe-names-link');
1308             var fname = findWidget('au', 'first_given_name').widget.attr('value');
1309             var lname = findWidget('au', 'family_name').widget.attr('value');
1310             if( !(fname && lname) ) return;
1311             search = {
1312                 first_given_name : {value : fname, group : 0},
1313                 family_name : {value : lname, group : 0},
1314             };
1315             break;
1316
1317         case 'email':
1318             openils.Util.hide('uedit-dupe-email-link');
1319             search = {email : {value : value, group : 0}};
1320             break;
1321
1322         case 'ident':
1323             openils.Util.hide('uedit-dupe-ident-link');
1324             search = {ident : {value : value, group : 2}};
1325             break;
1326
1327         case 'phone':
1328             openils.Util.hide('uedit-dupe-phone-link');
1329             search = {phone : {value : value, group : 2}};
1330             break;
1331
1332         case 'address':
1333             openils.Util.hide('uedit-dupe-address-link');
1334             search = {};
1335             dojo.forEach(['street1', 'street2', 'city', 'post_code'],
1336                 function(field) {
1337                     if(value[field])
1338                         search[field] = {value : value[field], group: 1};
1339                 }
1340             );
1341             break;
1342     }
1343
1344     // find possible duplicate patrons
1345     fieldmapper.standardRequest(
1346         ['open-ils.actor', 'open-ils.actor.patron.search.advanced'],
1347         {   async: true,
1348             params: [openils.User.authtoken, search],
1349             oncomplete : function(r) {
1350                 var resp = openils.Util.readResponse(r);
1351                 resp = resp.filter(function(id) { return (id != patron.id()); });
1352
1353                 if(resp && resp.length > 0) {
1354
1355                     openils.Util.hide('uedit-help-div');
1356                     openils.Util.show('uedit-dupe-div');
1357                     var link;
1358
1359                     switch(type) {
1360                         case 'name':
1361                             link = dojo.byId('uedit-dupe-names-link');
1362                             link.innerHTML = dojo.string.substitute(localeStrings.DUPE_PATRON_NAME, [resp.length]);
1363                             break;
1364                         case 'email':
1365                             link = dojo.byId('uedit-dupe-email-link');
1366                             link.innerHTML = dojo.string.substitute(localeStrings.DUPE_PATRON_EMAIL, [resp.length]);
1367                             break;
1368                         case 'ident':
1369                             link = dojo.byId('uedit-dupe-ident-link');
1370                             link.innerHTML = dojo.string.substitute(localeStrings.DUPE_PATRON_IDENT, [resp.length]);
1371                             break;
1372                         case 'phone':
1373                             link = dojo.byId('uedit-dupe-phone-link');
1374                             link.innerHTML = dojo.string.substitute(localeStrings.DUPE_PATRON_PHONE, [resp.length]);
1375                             break;
1376                         case 'address':
1377                             link = dojo.byId('uedit-dupe-address-link');
1378                             link.innerHTML = dojo.string.substitute(localeStrings.DUPE_PATRON_ADDR, [resp.length]);
1379                             break;
1380                     }
1381
1382                     openils.Util.show(link);
1383                     link.onclick = function() {
1384                         search.search_sort = js2JSON(["penalties", "family_name", "first_given_name"]);
1385                         if(window.xulG)
1386                             window.xulG.spawn_search(search);
1387                         else
1388                             console.log("running XUL patron search " + js2JSON(search));
1389                     }
1390                 }
1391             }
1392         }
1393     );
1394 }
1395
1396 function getByName(node, name) {
1397     return dojo.query('[name='+name+']', node)[0];
1398 }
1399
1400
1401 function ueLoadContextHelp(fmcls, fmfield) {
1402     openils.Util.hide('uedit-dupe-div');
1403     openils.Util.show('uedit-help-div');
1404     dojo.byId('uedit-help-field').innerHTML = fieldmapper.IDL.fmclasses[fmcls].field_map[fmfield].label;
1405     dojo.byId('uedit-help-text').innerHTML = fieldDoc[fmcls][fmfield].string();
1406 }
1407
1408
1409 /* creates a new patron object with card attached */
1410 function uEditNewPatron() {
1411     patron = new au();
1412     patron.isnew(1);
1413     patron.id(-1);
1414     card = new ac();
1415     card.id(uEditCardVirtId--);
1416     card.isnew(1);
1417     patron.active(1);
1418     patron.card(card);
1419     patron.cards([card]);
1420     patron.net_access_level(orgSettings['ui.patron.default_inet_access_level'] || 1);
1421     patron.ident_type(orgSettings['ui.patron.default_ident_type']);
1422     patron.stat_cat_entries([]);
1423     patron.survey_responses([]);
1424     patron.addresses([]);
1425     uEditMakeRandomPw(patron);
1426     return patron;
1427 }
1428
1429 function uEditMakeRandomPw(patron) {
1430     var rand  = Math.random();
1431     rand = parseInt(rand * 10000) + '';
1432     while(rand.length < 4) rand += '0';
1433 /*
1434     appendClear($('ue_password_plain'),text(rand));
1435     unHideMe($('ue_password_gen'));
1436 */
1437     patron.passwd(rand);
1438     return rand;
1439 }
1440
1441 function uEditWidgetVal(w) {
1442     var val = (w.getFormattedValue) ? w.getFormattedValue() : w.attr('value');
1443     if(val === '') val = null;
1444     return val;
1445 }
1446
1447 function uEditSave() { _uEditSave(); }
1448 function uEditSaveClone() { _uEditSave(true); }
1449
1450 function _uEditSave(doClone) {
1451
1452     if ( (! myForm.isValid()) || dupeUsrname || dupeBarcode ) {
1453         alert(localeStrings.INVALID_FORM);
1454         return;
1455     }
1456
1457     for(var idx in widgetPile) {
1458         var w = widgetPile[idx];
1459         var val = uEditWidgetVal(w);
1460
1461         switch(w._wtype) {
1462             case 'au':
1463                 if(w._fmfield != 'passwd2')
1464                     patron[w._fmfield](val);
1465                 break;
1466
1467             case 'ac':
1468                 if(!editCard) editCard = patron.card();
1469                 editCard[w._fmfield](val);
1470                 break;
1471
1472             case 'aua':
1473                 var addr = patron.addresses().filter(function(i){return (i.id() == w._addr)})[0];
1474                 if(!addr) {
1475                     addr = new fieldmapper.aua();
1476                     addr.id(w._addr);
1477                     addr.isnew(1);
1478                     addr.usr(patron.id());
1479                     addr.country(orgSettings['ui.patron.default_country']);
1480                     var t = patron.addresses();
1481                         if (!t) { t = []; }
1482                         t.push(addr);
1483                         patron.addresses(t);
1484                 } else {
1485                     if(addr[w._fmfield]() != val)
1486                         addr.ischanged(1);
1487                 }
1488                 addr[w._fmfield](val);
1489
1490                 if(dojo.byId('uedit-billing-address-' + addr.id()).checked) 
1491                     patron.billing_address(addr.id());
1492
1493                 if(dojo.byId('uedit-mailing-address-' + addr.id()).checked)
1494                     patron.mailing_address(addr.id());
1495
1496                 break;
1497
1498             case 'survey':
1499                 if(val == null) break;
1500                 var resp = new fieldmapper.asvr();
1501                 resp.isnew(1);
1502                 resp.survey(w._survey)
1503                 resp.usr(patron.id());
1504                 resp.question(w._question)
1505                 resp.answer(val);
1506                 var t = patron.survey_responses();
1507                     if (!t) { t = []; }
1508                     t.push(resp);
1509                     patron.survey_responses(t);
1510                 break;
1511
1512             case 'statcat':
1513                 var map = patron.stat_cat_entries().filter(
1514                     function(m){
1515                         return (m.stat_cat() == w._statcat) })[0];
1516
1517                 if(map) {
1518                     if(map.stat_cat_entry() == val) 
1519                         break;
1520                     if(val == null) {
1521                         val = '';
1522                         map.isdeleted(1);
1523                     } else {
1524                         map.ischanged(1);
1525                     }
1526                 } else {
1527                     if(val == null)
1528                         break;
1529                     map = new fieldmapper.actscecm();
1530                     map.isnew(1);
1531                 }
1532
1533                 map.stat_cat(w._statcat);
1534                 map.stat_cat_entry(val);
1535                 map.target_usr(patron.id());
1536                 var t = patron.stat_cat_entries();
1537                     if (!t) { t = []; }
1538                     t.push(map);
1539                     patron.stat_cat_entries(t);
1540                 break;
1541         }
1542     }
1543
1544     patron.ischanged(1);
1545     fieldmapper.standardRequest(
1546         ['open-ils.actor', 'open-ils.actor.patron.update'],
1547         {   async: true,
1548             params: [openils.User.authtoken, patron],
1549             oncomplete: function(r) {
1550                 lock_ready = false;
1551                 if (xulG && typeof xulG.unlock_tab == 'function') {
1552                     xulG.unlock_tab();
1553                     already_locked = false;
1554                 }
1555                 newPatron = openils.Util.readResponse(r);
1556                 if(newPatron) {
1557                     uEditUpdateUserSettings(newPatron.id());
1558                     if(stageUser) uEditRemoveStage();
1559                     uEditFinishSave(newPatron, doClone);
1560                 }
1561             }
1562         }
1563     );
1564 }
1565
1566 function uEditRemoveStage() {
1567     var resp = fieldmapper.standardRequest(
1568         ['open-ils.actor', 'open-ils.actor.user.stage.delete'],
1569         { params : [openils.User.authtoken, stageUser.row_id()] }
1570     )
1571 }
1572
1573 function uEditFinishSave(newPatron, doClone) {
1574
1575     if(doClone && cloneUser == null)
1576         cloneUser = newPatron.id();
1577
1578         if( doClone ) {
1579
1580                 if(xulG && typeof xulG.spawn_editor == 'function' && !patron.isnew() ) {
1581             window.xulG.spawn_editor({ses:openils.User.authtoken,clone:cloneUser});
1582             uEditRefresh();
1583
1584                 } else {
1585                         location.href = location.href.replace(/\?.*/, '') + '?clone=' + cloneUser;
1586                 }
1587
1588         } else {
1589
1590                 uEditRefresh();
1591         }
1592
1593         uEditRefreshXUL(newPatron);
1594 }
1595
1596 function uEditRefresh() {
1597     var usr = cgi.param('usr');
1598     var href = location.href.replace(/\?.*/, '');
1599     href += ((usr) ? '?usr=' + usr : '');
1600     location.href = href;
1601 }
1602
1603 function uEditRefreshXUL(newuser) {
1604         if (window.xulG && typeof window.xulG.on_save == 'function') 
1605                 window.xulG.on_save(newuser);
1606 }
1607
1608
1609 /**
1610  * Create a new address and insert it into the DOM
1611  * @param evt ignored
1612  * @param id The address id
1613  * @param mkLinks If true, set the new address as the 
1614  *  mailing/billing address for the user
1615  */
1616 function uEditNewAddr(evt, id, mkLinks) {
1617
1618     if(id == null) 
1619         id = --uEditAddrVirtId; // new address
1620
1621     var addr =  patron.addresses().filter(
1622         function(i) { return (i.id() == id) })[0];
1623
1624     dojo.forEach(addrTemplateRows, 
1625         function(row) {
1626
1627             row = tbody.insertBefore(row.cloneNode(true), dojo.byId('new-addr-row'));
1628             row.setAttribute('type', '');
1629             row.setAttribute('addr', id+'');
1630
1631             if(row.getAttribute('fmclass')) {
1632                 var widget = fleshFMRow(row, 'aua', {addr:id});
1633
1634                 // make new addresses a default address type
1635                 if(id < 0 && row.getAttribute('fmfield') == 'address_type') 
1636                     widget.widget.attr('value', localeStrings.DEFAULT_ADDRESS_TYPE); 
1637
1638                 // make new addresses valid by default
1639                 if(id < 0 && row.getAttribute('fmfield') == 'valid') 
1640                     widget.widget.attr('value', true); 
1641
1642                 // make new addresses use the org setting for default country 
1643                 if(id < 0 && row.getAttribute('fmfield') == 'country') 
1644                     widget.widget.attr('value',orgSettings['ui.patron.default_country']);
1645
1646             } else if(row.getAttribute('name') == 'uedit-addr-pending-row') {
1647
1648                 // if it's a pending address, show the 'approve' button
1649                 if(addr && openils.Util.isTrue(addr.pending())) {
1650                     openils.Util.show(row, 'table-row');
1651                     dojo.query('[name=approve-button]', row)[0].onclick = 
1652                         function() { uEditApproveAddress(addr); };
1653
1654                     if(addr.replaces()) {
1655                         var div = dojo.query('[name=replaced-addr]', row)[0]
1656                         var replaced =  patron.addresses().filter(
1657                             function(i) { return (i.id() == addr.replaces()) })[0];
1658
1659                         div.innerHTML = dojo.string.substitute(localeStrings.REPLACED_ADDRESS, [
1660                             replaced.address_type() || '',
1661                             replaced.street1() || '',
1662                             replaced.street2() || '',
1663                             replaced.city() || '',
1664                             replaced.state() || '',
1665                             replaced.post_code() || ''
1666                         ]);
1667
1668                     } else {
1669                         openils.Util.hide(dojo.query('[name=replaced-addr-div]', row)[0]);
1670                     }
1671                 }
1672
1673             } else if(row.getAttribute('name') == 'uedit-addr-owner-row') {
1674                 // address is owned by someone else.  provide option to load the
1675                 // user in a different tab
1676                 
1677                 if(addr && addr.usr() != patron.id()) {
1678                     openils.Util.show(row, 'table-row');
1679                     var link = getByName(row, 'addr-owner');
1680
1681                     // fetch the linked user so we can present their name in the UI
1682                     var addrUser;
1683                     if(cloneUserObj && cloneUserObj.id() == addr.usr()) {
1684                         addrUser = [
1685                             cloneUserObj.first_given_name(), 
1686                             cloneUserObj.second_given_name(), 
1687                             cloneUserObj.family_name()
1688                         ];
1689                     } else {
1690                         addrUser = fieldmapper.standardRequest(
1691                             ['open-ils.actor', 'open-ils.actor.user.retrieve.parts'],
1692                             {params: [
1693                                 openils.User.authtoken, 
1694                                 addr.usr(), 
1695                                 ['first_given_name', 'second_given_name', 'family_name']
1696                             ]}
1697                         );
1698                     }
1699
1700                     link.innerHTML = (addrUser.map(function(name) { return (name) ? name+' ' : '' })+'').replace(/,/g,''); // TODO i18n
1701                     link.onclick = function() {
1702                         if(openils.XUL.isXUL()) { 
1703                             window.xulG.spawn_editor({ses:openils.User.authtoken, usr:addr.usr()})
1704                         } else {
1705                             parent.location.href = location.href.replace(/clone=\d+/, 'usr=' + addr.usr());
1706                         }
1707                     }
1708                 }
1709
1710             } else if(row.getAttribute('name') == 'uedit-addr-divider') {
1711                 // link up the billing/mailing address and give the inputs IDs so we can access the later
1712                 
1713                 // billing address
1714                 var ba = getByName(row, 'billing_address');
1715                 ba.id = 'uedit-billing-address-' + id;
1716                 if(mkLinks || (patron.billing_address() && patron.billing_address().id() == id))
1717                     ba.checked = true;
1718
1719                 // mailing address
1720                 var ma = getByName(row, 'mailing_address');
1721                 ma.id = 'uedit-mailing-address-' + id;
1722                 if(mkLinks || (patron.mailing_address() && patron.mailing_address().id() == id))
1723                     ma.checked = true;
1724
1725                 var btn = dojo.query('[name=delete-button]', row)[0];
1726                 if(btn) btn.onclick = function(){ uEditDeleteAddr(id) };
1727             }
1728         }
1729     );
1730 }
1731
1732 function uEditApproveAddress(addr) {
1733     fieldmapper.standardRequest(
1734         ['open-ils.actor', 'open-ils.actor.user.pending_address.approve'],
1735         {   async: true,
1736             params:  [openils.User.authtoken, addr],
1737
1738             oncomplete : function(r) {
1739                 var oldId = openils.Util.readResponse(r);
1740                     
1741                 // remove addrs from UI
1742                 dojo.forEach(
1743                     patron.addresses(), 
1744                     function(addr) { uEditDeleteAddr(addr.id(), true); }
1745                 );
1746
1747                 if(oldId != null) {
1748                     
1749                     // remove the replaced address 
1750                     if(oldId != addr.id()) {
1751                                 patron.addresses(
1752                             patron.addresses().filter(
1753                                                 function(i) { return (i.id() != oldId); }
1754                                         )
1755                                 );
1756                     }
1757                     
1758                     // fix the the new address
1759                     addr.id(oldId);
1760                     addr.replaces(null);
1761                     addr.pending('f');
1762
1763                 }
1764
1765                 // redraw addrs
1766                 loadAllAddrs();
1767             }
1768         }
1769     );
1770 }
1771
1772
1773 function uEditDeleteAddr(id, noAlert) {
1774     if (patron.isnew() && orgSettings['ui.patron.registration.require_address']) {
1775         if (dojo.query('tr[name=uedit-addr-divider]').length < 2) {
1776             alert(localeStrings.NEED_ADDRESS);
1777             return;
1778         }
1779     }
1780     if(!noAlert) {
1781         if(!confirm(dojo.string.substitute(localeStrings.DELETE_ADDRESS, [id]))) return;
1782     }
1783     var addr = patron.addresses().filter(function(i){return (i.id() == id)})[0];
1784     if (addr) { addr.isdeleted(1); }
1785     var m_a = patron.mailing_address();
1786         if (typeof m_a == 'object' && m_a != null) { m_a = m_a.id(); }
1787         if (m_a == id) { patron.mailing_address(null); }
1788     var b_a = patron.billing_address();
1789         if (typeof b_a == 'object' && b_a != null) { b_a = b_a.id(); }
1790         if (b_a == id) { patron.billing_address(null); }
1791
1792     var rows = dojo.query('tr[addr='+id+']', tbody);
1793     for(var i = 0; i < rows.length; i++)
1794         rows[i].parentNode.removeChild(rows[i]);
1795     widgetPile = widgetPile.filter(function(w){return (w._addr != id)});
1796 }
1797
1798 function uEditToggleRequired(level) {
1799     openils.Util.removeCSSClass(tbody, 'hide-non-required');
1800     openils.Util.removeCSSClass(tbody, 'hide-non-suggested');
1801     openils.Util.show('uedit-show-required');
1802     openils.Util.show('uedit-show-required-br');
1803     openils.Util.show('uedit-show-suggested');
1804     openils.Util.show('uedit-show-suggested-br');
1805     openils.Util.show('uedit-show-all');
1806     switch(level) {
1807         case 1:
1808             openils.Util.hide('uedit-show-required');
1809             openils.Util.hide('uedit-show-required-br');
1810             openils.Util.addCSSClass(tbody, 'hide-non-required');
1811             break;
1812         case 2:
1813             openils.Util.hide('uedit-show-suggested');
1814             openils.Util.hide('uedit-show-suggested-br');
1815             openils.Util.addCSSClass(tbody, 'hide-non-suggested');
1816             break;
1817         default:
1818             openils.Util.hide('uedit-show-all');
1819             break;
1820     } 
1821 }
1822
1823 function printable_output() {
1824     var temp; var s = '=-=-=-=\r\n';
1825     for (var idx in widgetPile) {
1826         var w = widgetPile[idx];
1827         var val = uEditWidgetVal(w);
1828         var label;
1829         if (typeof w.idlField == 'undefined') {
1830             label = w._wtype;
1831             if (w._wtype == 'statcat') {
1832                 var stat = statCats.filter(
1833                     function(m){
1834                         return (m.id() == w._statcat) })[0];
1835                 label = stat.name();
1836             } else if (w._wtype == 'survey') {
1837                 var survey = surveys.filter(
1838                     function(m){
1839                         return (m.id() == w._survey) })[0];
1840                 var question = survey.questions().filter(
1841                     function(m){
1842                         return (m.id() == w._question) })[0];
1843                 label = survey.name() + ' : ' + question.question();
1844             } else {
1845                 label = 'FIXME';
1846             }
1847         } else {
1848             label = w.idlField.label;
1849         }
1850         if (temp != w._wtype) {
1851             temp = w._wtype;
1852             s += '-------\r\n';
1853         }
1854         s += label + ':\t' + (typeof val == 'object' ? '' : val) + '\r\n';
1855     }
1856     s += '=-=-=-=\r\n';
1857     return s;
1858 }
1859
1860 openils.Util.addOnLoad(load);