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