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