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