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