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