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