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