LP#1706148 - Hide "Hold is behind Circ Desk" checkbox in XUL patron registration.
[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     // Clear the usrname if it looks like a UUID
686     if (patron['usrname']().replace(/-/g,'').match(/[0-9a-f]{32}/)) {
687         patron['usrname']('');
688     }
689
690     // copy the data into our new address objects
691     // TODO: uses the first mailing address only
692     if(data.mailing_addresses.length) {
693
694         var mail_addr = new fieldmapper.aua();
695         mail_addr.id(-1); // virtual ID
696         mail_addr.usr(-1);
697         mail_addr.isnew(1);
698         patron.mailing_address(mail_addr);
699         var t = patron.addresses();
700             if (!t) { t = []; }
701             t.push(mail_addr);
702             patron.addresses(t);
703
704         for(var key in fieldmapper.IDL.fmclasses.stgma.field_map) {
705             if(fieldmapper.IDL.fmclasses.aua.field_map[key] && !fieldmapper.IDL.fmclasses.stgma.field_map[key].virtual) {
706                 if(data.mailing_addresses[0][key]() !== null)
707                     mail_addr[key]( data.mailing_addresses[0][key]() );
708             }
709         }
710     }
711     
712     // copy the data into our new address objects
713     // TODO uses the first billing address only
714     if(data.billing_addresses.length) {
715
716         var bill_addr = new fieldmapper.aua();
717         bill_addr.id(-2); // virtual ID
718         bill_addr.usr(-1);
719         bill_addr.isnew(1);
720         patron.billing_address(bill_addr);
721         var t = patron.addresses();
722             if (!t) { t = []; }
723             t.push(bill_addr);
724             patron.addresses(t);
725
726         for(var key in fieldmapper.IDL.fmclasses.stgba.field_map) {
727             if(fieldmapper.IDL.fmclasses.aua.field_map[key] && !fieldmapper.IDL.fmclasses.stgba.field_map[key].virtual) {
728                 if(data.billing_addresses[0][key]() !== null)
729                     bill_addr[key]( data.billing_addresses[0][key]() );
730             }
731         }
732     }
733
734     // TODO: uses the first card only
735     if(data.cards.length) {
736         var card = new fieldmapper.ac();
737         card.id(-1); // virtual ID
738         patron.card().barcode(data.cards[0].barcode());
739         // Set usrname to barcode if usrname is empty
740         if (patron.usrname() == '') {
741             patron.usrname(card.barcode());
742         }
743     }
744
745     return patron;
746 }
747
748 /*
749  * clone the home org, phone numbers, and billing/mailing address
750  */
751 function uEditCopyCloneData(patron) {
752     cloneUserObj = uEditLoadUser(cloneUser);
753
754     var cloneFields = [
755         'home_ou', 
756         'day_phone', 
757         'evening_phone', 
758         'other_phone',
759         'usrgroup'
760     ];
761
762     if(!uEditCloneCopyAddr) 
763         cloneFields = cloneFields.concat(['mailing_address', 'billing_address']);
764
765     dojo.forEach(
766         cloneFields, 
767         function(field) {
768             patron[field](cloneUserObj[field]());
769         }
770     );
771
772     if(uEditCloneCopyAddr) {
773         var billAddr, mailAddr;
774
775         // copy the billing and mailing addresses into new addresses
776         function cloneAddr(addr) {
777             var newAddr = addr.clone();
778             newAddr.isnew(true);
779             newAddr.id(uEditAddrVirtId--);
780             newAddr.usr(patron.id());
781             patron.addresses().push(newAddr);
782             return newAddr;
783         }
784
785         if(billAddr = cloneUserObj.billing_address()) 
786             patron.billing_address(cloneAddr(billAddr));
787
788         if(mailAddr = cloneUserObj.mailing_address()) {
789             if (billAddr && billAddr.id() == mailAddr.id()) {
790                 patron.mailing_address(patron.billing_address());
791             } else {
792                 patron.mailing_address(cloneAddr(mailAddr));
793             }
794         }
795
796         if(!billAddr) // if there was no billing addr, use the mailing addr
797             patron.billing_address(patron.mailing_address());
798
799     } else {
800
801         // link the billing and mailing addresses
802         if(patron.billing_address()) {
803             var t = patron.addresses();
804                 if (!t) { t = []; }
805                 t.push(patron.billing_address());
806                 patron.addresses(t);
807         }
808
809         if(patron.mailing_address() && (
810                 patron.addresses().length == 0 || 
811                 patron.mailing_address().id() != patron.billing_address().id()) ) {
812             var t = patron.addresses();
813                 if (!t) { t = []; }
814                 t.push(patron.mailing_address());
815                 patron.addresses(t);
816         }
817     }
818 }
819
820
821 function uEditFetchUserSettings(userId) {
822     
823     var baseNode = fieldmapper.aou.findOrgUnit(staff.ws_ou());
824     var orgs = fieldmapper.aou.orgNodeTrail(baseNode);
825     orgs = orgs.map(function(node) { return node.id(); });
826
827     /* fetch any user setting types we need + any that offer opt-in */
828     userSettingTypes = pcrud.search('cust', {
829         '-or' : [
830             {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']}, 
831             {name : {
832                 'in': {
833                     select : {atevdef : ['opt_in_setting']}, 
834                     from : 'atevdef',
835                     // we only care about opt-in settings for event_defs our users encounter
836                     where : {'+atevdef' : {owner : orgs}}
837                 }
838             }}
839         ]
840     });
841
842     var names = userSettingTypes.map(function(obj) { return obj.name() });
843
844     /* fetch any values set for this user */
845     if(userId) {
846         userSettings = fieldmapper.standardRequest(
847             ['open-ils.actor', 'open-ils.actor.patron.settings.retrieve.authoritative'],
848             {params : [openils.User.authtoken, userId, names]});
849     } else {
850         // Defaults!
851         userSettingTypes.forEach(function(setting, index, array) {
852             if(setting.reg_default() != undefined) {
853                 userSettings[setting.name()] = setting.reg_default();
854                 userSettingsToUpdate[setting.name()] = setting.reg_default();
855             }
856         });
857     }
858 }
859
860
861 function uEditLoadUser(userId) {
862     var patron = fieldmapper.standardRequest(
863         ['open-ils.actor', 'open-ils.actor.user.fleshed.retrieve.authoritative'],
864         {params : [openils.User.authtoken, userId]}
865     );
866     openils.Event.parse_and_raise(patron);
867     return patron;
868 }
869
870 function loadStaticFields() {
871     for(var idx = 0; tbody.childNodes[idx]; idx++) {
872         var row = tbody.childNodes[idx];
873         if(row.nodeType != row.ELEMENT_NODE) continue;
874         var fmcls = row.getAttribute('fmclass');
875         if(fmcls) {
876             fleshFMRow(row, fmcls);
877         } else {
878
879             if(row.id == 'uedit-settings-divider') {
880
881                 var template = tbody.removeChild(dojo.byId('uedit-user-setting-template'));
882                 dojo.forEach(userSettingTypes, function(type) { uEditDrawSettingRow(tbody, row, template, type); } );
883
884                 if(userSettingTypes.length > 1 || orgSettings['circ.holds.behind_desk_pickup_supported']) {
885                     openils.Util.show('uedit-settings-divider', 'table-row');
886                 }
887             }
888         }
889     }
890 }
891
892 function uEditDrawSettingRow(tbody, dividerRow, template, stype) {
893     var row = template.cloneNode(true);
894     row.setAttribute('user_setting', stype.name());
895     getByName(row, 'label').innerHTML = stype.label();
896     switch(stype.name()) {
897         case 'opac.hold_notify':
898             var template = localeStrings.HOLD_NOTIFY_PHONE + '<span name="hold_phone"></span>&nbsp;'
899                 + localeStrings.HOLD_NOTIFY_EMAIL + '<span name="hold_email"></span>';
900             if(orgSettings['sms.enable']) {
901                 template += '&nbsp;' + localeStrings.HOLD_NOTIFY_SMS + '<span name="hold_sms"></span>';
902             }
903             getByName(row, 'widget').innerHTML = template;
904             var setting = userSettings['opac.hold_notify'];
905             if(setting == null) setting = 'phone:email';
906             var cb_phone = new dijit.form.CheckBox({scrollOnFocus:false}, getByName(row, 'hold_phone'));
907             cb_phone.attr('value', setting.indexOf('phone') != -1);
908             var cb_email = new dijit.form.CheckBox({scrollOnFocus:false}, getByName(row, 'hold_email'));
909             cb_email.attr('value', setting.indexOf('email') != -1);
910             var cb_sms = null;
911             if(orgSettings['sms.enable']) {
912                 cb_sms = new dijit.form.CheckBox({scrollOnFocus:false}, getByName(row, 'hold_sms'));
913                 cb_sms.attr('value', setting.indexOf('sms') != -1);
914             }
915             var func = function() {
916                 var newVal = '';
917                 var splitter = '';
918                 if(cb_phone.checked) {
919                     newVal+= splitter + 'phone';
920                     splitter = ':';
921                 }
922                 if(cb_email.checked) {
923                     newVal+= splitter + 'email';
924                     splitter = ':';
925                 }
926                 if(orgSettings['sms.enable'] && cb_sms.checked) {
927                     newVal+= splitter + 'sms';
928                     splitter = ':';
929                 }
930                 userSettingsToUpdate['opac.hold_notify'] = newVal;
931             };
932             dojo.connect(cb_phone, 'onChange', func);
933             dojo.connect(cb_email, 'onChange', func);
934             if(cb_sms) dojo.connect(cb_sms, 'onChange', func);
935             break;
936         case 'opac.default_pickup_location':
937             var sb = new openils.widget.FilteringTreeSelect({
938                 scrollOnFocus: false,
939                 labelAttr: 'name',
940                 searchAttr: 'name',
941                 parentField: 'parent_ou',
942                 }, getByName(row, 'widget'));
943             sb.tree = fieldmapper.aou.globalOrgTree;
944             sb.startup();
945             sb.attr('value', userSettings[stype.name()]);
946
947             sb.isValid = function() {
948                 if(this.item) {
949                     if(holdPickupTypes[this.store.getValue(this.item, 'ou_type')]) {
950                         return true;
951                     }
952                     return false;
953                 }
954                 return true;
955             };
956
957             dojo.connect(sb, 'onChange', function(newVal) { userSettingsToUpdate[stype.name()] = newVal; });
958             break;
959         case 'opac.default_sms_carrier':
960             if(!orgSettings['sms.enable']) return; // Skip when SMS is disabled
961             var carriers = pcrud.search('csc', {active: 'true'}, {'order_by':[{'class':'csc', 'field':'name'},{'class':'csc', 'field':'region'}]});
962             var storedata = fieldmapper.csc.toStoreData(carriers);
963             for(var i in storedata.items) storedata.items[i].label = storedata.items[i].name + ' (' + storedata.items[i].region + ')';
964             var store = new dojo.data.ItemFileReadStore({data:storedata});
965             var select = new dijit.form.FilteringSelect({store:store,scrollOnFocus:false,labelAttr:'label',searchAttr:'label'}, getByName(row, 'widget'));
966             select.attr('value', userSettings[stype.name()]);
967             select.isValid = function() { return true; };
968             dojo.connect(select, 'onChange', function(newVal) { userSettingsToUpdate[stype.name()] = newVal; });
969             break;
970         case 'opac.default_sms_notify':
971             if(!orgSettings['sms.enable']) return; // Skip when SMS is disabled
972         case 'opac.default_phone':
973             var tb = new dijit.form.TextBox({scrollOnFocus:false}, getByName(row, 'widget'));
974             tb.attr('value', userSettings[stype.name()]);
975             dojo.connect(tb, 'onChange', function(newVal) { userSettingsToUpdate[stype.name()] = newVal; });
976             break;
977         case 'circ.holds_behind_desk':
978             // Skip when hold is behind circ desk is not enabled
979             if(!orgSettings['circ.holds.behind_desk_pickup_supported']) return;
980             var cb = new dijit.form.CheckBox({scrollOnFocus:false}, getByName(row, 'widget'));
981             cb.attr('value', userSettings[stype.name()]);
982             dojo.connect(cb, 'onChange', function(newVal) { userSettingsToUpdate[stype.name()] = newVal; });
983             break;
984         default:
985             var cb = new dijit.form.CheckBox({scrollOnFocus:false}, getByName(row, 'widget'));
986             cb.attr('value', userSettings[stype.name()]);
987             dojo.connect(cb, 'onChange', function(newVal) { userSettingsToUpdate[stype.name()] = newVal; });
988             if(stype.name() == 'circ.collections.exempt') {
989                 checkCollectionsExemptPerm(cb);
990             }
991     }
992     tbody.insertBefore(row, dividerRow.nextSibling);
993     openils.Util.show(row, 'table-row');
994 }
995
996 function uEditUpdateUserSettings(userId) {
997     return fieldmapper.standardRequest(
998         ['open-ils.actor', 'open-ils.actor.patron.settings.update'],
999         {params : [openils.User.authtoken, userId, userSettingsToUpdate]});
1000 }
1001
1002 function loadAllAddrs() {
1003     dojo.forEach(patron.addresses(),
1004         function(addr) {
1005             uEditNewAddr(null, addr.id());
1006         }
1007     );
1008 }
1009
1010 function loadStatCats() {
1011     var sc_widget;
1012
1013     statCats = fieldmapper.standardRequest(
1014         ['open-ils.circ', 'open-ils.circ.stat_cat.actor.retrieve.all'],
1015         {params : [openils.User.authtoken, staff.ws_ou()]}
1016     );
1017
1018     // draw stat cats
1019     for(var idx in statCats) {
1020         var stat = statCats[idx];
1021         var required = openils.Util.isTrue(stat.required());
1022         var allow_freetext = openils.Util.isTrue(stat.allow_freetext());
1023         var default_entry = null;
1024         if(stat.default_entries()[0])
1025             default_entry = stat.default_entries()[0].stat_cat_entry();
1026         
1027         var row = statCatTemplate.cloneNode(true);
1028         row.id = 'stat-cat-row-' + idx;
1029         row.setAttribute('stat_cat_owner',stat.owner());
1030         row.setAttribute('stat_cat_name',stat.name());
1031         row.setAttribute('stat_cat_id',stat.id());
1032         if(required) {
1033             row.setAttribute('required','required');
1034             dividerRow = dojo.byId('stat-cat-divider');
1035             dividerRow.setAttribute('required','required');
1036         }
1037         tbody.appendChild(row);
1038         getByName(row, 'name').innerHTML = stat.name();
1039         var valtd = getByName(row, 'widget');
1040         var span = valtd.appendChild(document.createElement('span'));
1041         var store = new dojo.data.ItemFileReadStore(
1042                 {data:fieldmapper.actsc.toStoreData(stat.entries())});
1043         var p_opt, e_field;
1044
1045         var patmap = patron.stat_cat_entries().filter(
1046             function(mp) { return (mp.stat_cat() == stat.id()) })[0];
1047         var entrymap = stat.entries().filter(
1048                 function(mp) { return (mp.id() == default_entry) })[0];
1049         
1050         if(allow_freetext) {
1051             sc_widget = new dijit.form.ComboBox({store:store,scrollOnFocus:false,fetchProperties:{sort:[{attribute: 'value'}]}}, span);
1052             e_field = entrymap ? entrymap.value() : null;
1053             p_opt = 'value';
1054         } else {
1055             sc_widget = new dijit.form.FilteringSelect({store:store,scrollOnFocus:false,fetchProperties:{sort:[{attribute: 'value'}]}}, span);
1056             sc_widget.attr('required', false);
1057             e_field = entrymap ? entrymap.id() : null;
1058             p_opt = 'displayedValue';
1059         }
1060
1061         sc_widget.labelAttr = 'value';
1062         sc_widget.searchAttr = 'value';
1063
1064         sc_widget._wtype = 'statcat';
1065         sc_widget._statcat = stat.id();
1066
1067         // set value:  first choice is patron table entry,
1068         // then the default entry for the stat_cat if new patron
1069         if(patmap) {
1070             sc_widget.attr(p_opt, patmap.stat_cat_entry()); 
1071         } else if(entrymap && patron.isnew()) {
1072             sc_widget.attr('value', e_field); 
1073         }
1074
1075         if(required) {
1076             sc_widget.attr('required', true);
1077             sc_widget._hasBeenBlurred = true;
1078             if(sc_widget.validate)
1079                 sc_widget.validate();
1080         }
1081
1082         widgetPile.push(sc_widget); 
1083     }
1084 }
1085
1086 function loadSurveys() {
1087
1088     surveys = fieldmapper.standardRequest(
1089         ['open-ils.circ', 'open-ils.circ.survey.retrieve.all'],
1090         {params : [openils.User.authtoken]}
1091     );
1092
1093     // draw surveys
1094     for(var idx in surveys) {
1095         var survey = surveys[idx];
1096         var required = openils.Util.isTrue(survey.required());
1097         var srow = surveyTemplate.cloneNode(true);
1098         if(required) srow.setAttribute('required','required');
1099         tbody.appendChild(srow);
1100         getByName(srow, 'name').innerHTML = survey.name();
1101
1102         for(var q in survey.questions()) {
1103             var quest = survey.questions()[q];
1104             var qrow = surveyQuestionTemplate.cloneNode(true);
1105             if(required) qrow.setAttribute('required','required');
1106             tbody.appendChild(qrow);
1107             getByName(qrow, 'question').innerHTML = quest.question();
1108
1109             var span = getByName(qrow, 'answers').appendChild(document.createElement('span'));
1110             var store = new dojo.data.ItemFileReadStore(
1111                 {data:fieldmapper.asva.toStoreData(quest.answers())});
1112             var select = new dijit.form.FilteringSelect({store:store,scrollOnFocus:false}, span);
1113             if (! required ) {
1114                 select.isValid = function() { return true; };
1115             }
1116             select.labelAttr = 'answer';
1117             select.searchAttr = 'answer';
1118
1119             select._wtype = 'survey';
1120             select._survey = survey.id();
1121             select._question = quest.id();
1122             widgetPile.push(select); 
1123         }
1124     }
1125 }
1126
1127
1128 function fleshFMRow(row, fmcls, args) {
1129     var fmfield = row.getAttribute('fmfield');
1130     var wclass = row.getAttribute('wclass');
1131     var wstyle = row.getAttribute('wstyle');
1132     var wconstraints = row.getAttribute('wconstraints');
1133     /* use CSS to set the zindex for widgets you want to disable. */
1134     var disabled = dojo.style(row, 'zIndex') == -1 ? true : false;
1135     var isphone = (fmcls == 'au') && (fmfield.search('_phone') != -1);
1136
1137     var isPasswd2 = (fmfield == 'passwd2');
1138     if(isPasswd2) fmfield = 'passwd';
1139     var fieldIdl = fieldmapper.IDL.fmclasses[fmcls].field_map[fmfield];
1140     if(!args) args = {};
1141
1142     var existing = dojo.query('td', row);
1143     var htd = existing[0] || row.appendChild(document.createElement('td'));
1144     var ltd = existing[1] || row.appendChild(document.createElement('td'));
1145     var wtd = existing[2] || row.appendChild(document.createElement('td'));
1146     var ftd = existing[3] || row.appendChild(document.createElement('td'));
1147
1148     openils.Util.addCSSClass(htd, 'uedit-help');
1149     if(fieldDoc[fmcls] && fieldDoc[fmcls][fmfield]) {
1150         var link = dojo.byId('uedit-help-template').cloneNode(true);
1151         link.id = '';
1152         link.onclick = function() { ueLoadContextHelp(fmcls, fmfield) };
1153         openils.Util.removeCSSClass(link, 'hidden');
1154         htd.appendChild(link);
1155     }
1156
1157     if(!ltd.textContent) {
1158         ltd.appendChild(document.createTextNode(fieldIdl.label));
1159     }
1160
1161     if(!ftd.textContent) {
1162         if(orgSettings['ui.patron.edit.' + fmcls + '.' + fmfield + '.example']) {
1163             ftd.appendChild(document.createTextNode(localeStrings.EXAMPLE + orgSettings['ui.patron.edit.' + fmcls + '.' + fmfield + '.example']));
1164         }
1165         else if(isphone && orgSettings['ui.patron.edit.phone.example']) {
1166             ftd.appendChild(document.createTextNode(localeStrings.EXAMPLE + orgSettings['ui.patron.edit.phone.example']));
1167         }
1168         else if(fieldIdl.datatype == 'timestamp') {
1169             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)})));
1170         }
1171
1172         if (fmcls == "au" && (isphone || fmfield == "email")) {
1173             var span = dojo.create(
1174                 "span", {
1175                     "className": "hidden",
1176                     "id": "wrap_invalidate_" + fmfield
1177                 }
1178             );
1179             uGenerateInvalidatorWidget(span, fmfield);
1180             ftd.appendChild(span);
1181         }
1182     }
1183
1184     var span = document.createElement('span');
1185     wtd.appendChild(span);
1186
1187     var fmObject = null;
1188     switch(fmcls) {
1189         case 'au' :
1190             fmObject = patron;
1191             if(fmfield == 'barred') {
1192                 // Are we allowed to touch the barred state?
1193                 var permission = 'BAR_PATRON';
1194                 if(fmObject.barred() == 't') {
1195                     permission = 'UNBAR_PATRON';
1196                 }
1197                 var ou = staff.ws_ou();
1198                 if(fmObject.home_ou() != null) {
1199                     ou = fmObject.home_ou();
1200                 }
1201                 var resp = fieldmapper.standardRequest(
1202                     ['open-ils.actor', 'open-ils.actor.user.perm.check'],
1203                     { params : [openils.User.authtoken, staff.id(), ou, [permission] ] }
1204                 );
1205                 if(resp[0]) { // No permission to adjust barred state from current
1206                     disabled = true;
1207                 }
1208             }
1209             break;
1210         case 'ac' : if(!editCard) editCard = patron.card(); fmObject = editCard; break;
1211         case 'aua' : 
1212             fmObject = patron.addresses().filter(
1213                 function(i) { return (i.id() == args.addr) })[0];
1214             if(fmObject && fmObject.usr() != patron.id())
1215                 disabled = true;
1216             break;
1217     }
1218
1219     // Adjust required value by org settings
1220     var curRequired = row.getAttribute('required');
1221     var required = curRequired == 'required';
1222     if(orgSettings['ui.patron.edit.' + fmcls + '.' + fmfield + '.require']) {
1223         row.setAttribute('required', 'required');
1224         required = true;
1225     }
1226     else if (curRequired != 'required' && orgSettings['ui.patron.edit.' + fmcls + '.' + fmfield + '.show']) {
1227         row.setAttribute('required', 'show');
1228     }
1229     else if (curRequired != 'required' && curRequired != 'show' && orgSettings['ui.patron.edit.' + fmcls + '.' + fmfield + '.suggest']) {
1230         row.setAttribute('required', 'suggested');
1231     }
1232
1233     // password data is not fetched/required/displayed for existing users
1234     if(!patron.isnew() && 'passwd' == fmfield)
1235         required = false;
1236
1237     var dijitArgs = {
1238         style: wstyle, 
1239         required : required,
1240         constraints : (wconstraints) ? eval('('+wconstraints+')') : {}, // the ()'s prevent Invalid Label errors with eval
1241         disabled : disabled
1242     };
1243
1244     // Org settings provided regex?
1245     if(orgSettings['ui.patron.edit.' + fmcls + '.' + fmfield + '.regex']) {
1246         dijitArgs.regExp = orgSettings['ui.patron.edit.' + fmcls + '.' + fmfield + '.regex'];
1247     }
1248     else if(isphone && orgSettings['ui.patron.edit.phone.regex']) {
1249         dijitArgs.regExp = orgSettings['ui.patron.edit.phone.regex'];
1250     }
1251
1252     if(fmcls == 'au' && fmfield == 'passwd') {
1253         if (orgSettings['global.password_regex']) {
1254             dijitArgs.regExp = orgSettings['global.password_regex'];
1255         }
1256     }
1257
1258     if(fmcls == 'au' && fmfield == 'dob' && !orgSettings['ui.patron.edit.au.dob.calendar'])
1259         dijitArgs.popupClass = "";
1260
1261     if(fmcls == 'au' && fmfield == 'ident_type')
1262         dijitArgs.fetchProperties = { sort: [{attribute:"name",descending:false}] };
1263
1264     var value = row.getAttribute('wvalue');
1265     if(value !== null)
1266         dijitArgs.value = value;
1267
1268     var wargs = {
1269         idlField : fieldIdl,
1270         fmObject : fmObject,
1271         fmClass : fmcls,
1272         parentNode : span,
1273         widgetClass : wclass,
1274         dijitArgs : dijitArgs,
1275         orgDefaultsToWs : true,
1276         orgLimitPerms : ['UPDATE_USER'],
1277     };
1278
1279     if(fmfield == 'profile') {
1280         // fetch profile groups non-async so existing expire_date is
1281         // not overwritten when the profile groups arrive and update
1282         wargs.forceSync = true;
1283         wargs.disableQuery = {usergroup : 'f'};
1284     } else {
1285         wargs.forceSync = false;
1286     }
1287
1288     if(fmcls == 'au' && fmfield == 'home_ou'){
1289         wargs.labelAttr = 'name';
1290         wargs.searchAttr = 'name';
1291     }
1292
1293     var widget = new openils.widget.AutoFieldWidget(wargs);
1294     widget.build(
1295         function(w, ww) {
1296             if(fmfield == 'profile') {
1297                 trimGrpTree(ww);
1298                 if(!patron.isnew() && !checkGrpAppPerm(patron.profile())){
1299                     w.attr('disabled', true);
1300                 }
1301             }
1302         }
1303     );
1304
1305     // now put it back before we register the widget
1306     if(isPasswd2) fmfield = 'passwd2';
1307
1308     widget._wtype = fmcls;
1309     widget._fmfield = fmfield;
1310     widget._addr = args.addr;
1311     widgetPile.push(widget);
1312     attachWidgetEvents(fmcls, fmfield, widget);
1313     return widget;
1314 }
1315
1316 function trimGrpTree(autoWidget) {
1317     var store = autoWidget.widget.store;
1318     if(!store) return;
1319     // remove all groups that this user are not allowed to edit, 
1320     // except the profile group of an existing user
1321     store.fetch({onItem : 
1322         function(item) {
1323             if(!checkGrpAppPerm(item.id[0]) && patron.profile() != item.id[0])
1324                 store.deleteItem(item);
1325         }
1326     });
1327 }
1328
1329 function findWidget(wtype, fmfield, callback) {
1330     return widgetPile.filter(
1331         function(i){
1332             if(i._wtype == wtype && i._fmfield == fmfield) {
1333                 if(callback) return callback(i);
1334                 return true;
1335             }
1336         }
1337     ).pop();
1338 }
1339
1340 /**
1341  * if the user does not have the UPDATE_PATRON_CLAIM_RETURN_COUNT, 
1342  * they are not allowed to directly alter the claim return count. 
1343  * This function checks the perm and disable/enables the widget.
1344  */
1345 function checkClaimsReturnCountPerm() {
1346     new openils.User().getPermOrgList(
1347         'UPDATE_PATRON_CLAIM_RETURN_COUNT',
1348         function(orgList) { 
1349             var cr = findWidget('au', 'claims_returned_count');
1350             if (!cr) return;
1351             if(orgList.indexOf(patron.home_ou()) == -1) 
1352                 cr.widget.attr('disabled', true);
1353             else
1354                 cr.widget.attr('disabled', false);
1355         },
1356         true, 
1357         true
1358     );
1359 }
1360
1361 function checkSecondaryGroupsPerm() {
1362     new openils.User().getPermOrgList(
1363         'CREATE_USER_GROUP_LINK',
1364         function(orgList) {
1365             if(orgList.indexOf(patron.home_ou()) == -1) {
1366                 dojo.addClass(dojo.byId('ueditSecondaryGrpButton'), 'hidden');
1367                 secondaryGroupsChanged = false;
1368             } else {
1369                 dojo.removeClass(dojo.byId('ueditSecondaryGrpButton'), 'hidden');
1370             }
1371         },
1372         true,
1373         true
1374     );
1375 }
1376
1377 function checkClaimsNoCheckoutCountPerm() {
1378     new openils.User().getPermOrgList(
1379         'UPDATE_PATRON_CLAIM_NEVER_CHECKED_OUT_COUNT',
1380         function(orgList) { 
1381             var cr = findWidget('au', 'claims_never_checked_out_count');
1382             if (!cr) return;
1383             if(orgList.indexOf(patron.home_ou()) == -1) 
1384                 cr.widget.attr('disabled', true);
1385             else
1386                 cr.widget.attr('disabled', false);
1387         },
1388         true, 
1389         true
1390     );
1391 }
1392
1393 var collectExemptCBox;
1394 function checkCollectionsExemptPerm(cbox) {
1395     if(cbox) collectExemptCBox = cbox;
1396     new openils.User().getPermOrgList(
1397         'UPDATE_PATRON_COLLECTIONS_EXEMPT',
1398         function(orgList) { 
1399             if (!collectExemptCBox) return;
1400             if(orgList.indexOf(patron.home_ou()) == -1) 
1401                 collectExemptCBox.attr('disabled', true);
1402             else
1403                 collectExemptCBox.attr('disabled', false);
1404         },
1405         true, 
1406         true
1407     );
1408 }
1409
1410 function usePhonePw(newVal) {
1411     var newPw = false;
1412     if(this.regExp) {
1413         matches = RegExp(this.regExp).exec(newVal);
1414         if(matches.length > 1) newPw = matches[1];
1415     }
1416     if(!newPw && newVal && newVal.length >= 4) {
1417         newPw = newVal.substring(newVal.length - 4);
1418     }
1419     if(newPw) {
1420         var p1 = findWidget('au', 'passwd');
1421         var p2 = findWidget('au', 'passwd2');
1422         if (p1 && p2) {
1423             p1.widget.attr('value', newPw);
1424             p2.widget.attr('value', newPw);
1425         }
1426         return newPw;
1427     } else {
1428         return null;
1429     }
1430 }
1431
1432 function attachWidgetEvents(fmcls, fmfield, widget) {
1433
1434     dojo.connect(
1435         widget.widget,
1436         'onKeyPress',
1437         function(ev){
1438             if (!(ev.altKey || ev.ctrlKey || ev.metaKey)) {
1439                 if (lock_ready && xulG && typeof xulG.lock_tab == 'function') {
1440                     if (! already_locked) {
1441                         xulG.lock_tab();
1442                         already_locked = true;
1443                     }
1444                 }
1445             }
1446         }
1447     );
1448     dojo.connect(
1449         widget.widget,
1450         'onChange',
1451         function(){
1452             if (lock_ready && xulG && typeof xulG.lock_tab == 'function') {
1453                 if (! already_locked) {
1454                     xulG.lock_tab();
1455                     already_locked = true;
1456                 }
1457             }
1458         }
1459     );
1460
1461
1462     if(fmcls == 'ac') {
1463         if(fmfield == 'barcode') {
1464             widget.widget.isValid = function() {
1465                 if(this.attr('disabled') || this.attr('readOnly')) {
1466                     return true;
1467                 }
1468                 if(orgSettings['ui.patron.edit.ac.barcode.regex']) { // This serves as a master "on" for these checks
1469                     // No spaces
1470                     if(this.attr("value").match(/\s/)) {
1471                         return false;
1472                     }
1473                     var test_regexp = new RegExp(orgSettings['ui.patron.edit.ac.barcode.regex']);
1474                     if(test_regexp.test(this.attr("value"))) {
1475                         return true;
1476                     }
1477                     return false;
1478                 }
1479
1480                 return true;
1481             }
1482             dojo.connect(widget.widget, 'onChange',
1483                 function() {
1484                     var barcode = this.attr('value');
1485                     dupeBarcode = false;
1486                     dojo.addClass(dojo.byId('uedit-dupe-barcode-warning'), 'hidden');
1487                     fieldmapper.standardRequest(
1488                         ['open-ils.actor', 'open-ils.actor.barcode.exists'],
1489                         {
1490                             params: [openils.User.authtoken, barcode],
1491                             oncomplete : function(r) {
1492                                 var res = openils.Util.readResponse(r);
1493                                 if(res == '1') {
1494                                     dupeBarcode = true;
1495                                     dojo.removeClass(dojo.byId('uedit-dupe-barcode-warning'), 'hidden');
1496                                 } else {
1497                                     dupeBarcode = false;
1498                                     dojo.addClass(dojo.byId('uedit-dupe-barcode-warning'), 'hidden');
1499                                     editCard.barcode(barcode); // Keep the "All" interface up to date
1500                                     var un = findWidget('au', 'usrname');
1501                                     if(!un.widget.attr('value'))
1502                                         un.widget.attr('value', barcode);
1503                                 }
1504                             }
1505                         }
1506                     );
1507                 }
1508             );
1509             return;
1510         }
1511     }
1512
1513     if(fmcls == 'au') {
1514         switch(fmfield) {
1515
1516             case 'usrname':
1517                 widget.widget.isValid = function() {
1518                     // Not empty
1519                     if(this.attr("value") == '') {
1520                         return false;
1521                     }
1522                     // No spaces
1523                     if(this.attr("value").match(/\s/)) {
1524                         return false;
1525                     }
1526                     // Can look like a barcode (for initial value)
1527                     if(orgSettings['opac.barcode_regex']) {
1528                         var test_regexp = new RegExp(orgSettings['opac.barcode_regex']);
1529                         if(test_regexp.test(this.attr("value"))) {
1530                             return true;
1531                         }
1532                     }
1533                     // Can look like a username
1534                     if(orgSettings['opac.username_regex']) {
1535                         var test_regexp = new RegExp(orgSettings['opac.username_regex']);
1536                         if(test_regexp.test(this.attr("value"))) {
1537                             return true;
1538                         }
1539                     }
1540                     // If we know what a barcode and username look like and we got here, reject
1541                     if(orgSettings['opac.barcode_regex'] && orgSettings['opac.username_regex'])
1542                         return false;
1543                     // Otherwise we don't have enough info to say either way, let it through.
1544                     return true;
1545                 }
1546                 dojo.connect(widget.widget, 'onChange', 
1547                     function() {
1548                         var input = findWidget('au', 'usrname');
1549                         var usrname = input.widget.attr('value');
1550
1551                         // Skip username check if the value is not yet present, or if this
1552                         // is a patron which already existed and the usrname value is unchanged
1553                         if(!usrname || (!patron.isnew() && usrname == patron.usrname())) {
1554                             dupeUsrname = false;
1555                             dojo.addClass(dojo.byId('uedit-dupe-username-warning'), 'hidden');
1556                             return;
1557                         }
1558
1559                         fieldmapper.standardRequest(
1560                             ['open-ils.actor', 'open-ils.actor.username.exists'],
1561                             {
1562                                 params: [openils.User.authtoken, usrname],
1563                                 oncomplete : function(r) {
1564                                     var res = openils.Util.readResponse(r);
1565                                     if(res) {
1566                                         dupeUsrname = true;
1567                                         dojo.removeClass(dojo.byId('uedit-dupe-username-warning'), 'hidden');
1568                                     } else {
1569                                         dupeUsrname = false;
1570                                         dojo.addClass(dojo.byId('uedit-dupe-username-warning'), 'hidden');
1571                                     }
1572                                 }
1573                             }
1574                         );
1575                     }   
1576                 );
1577
1578                 return;
1579
1580             case 'profile': // when the profile changes, update the expire date
1581                 dojo.connect(widget.widget, 'onChange', 
1582                     function() {
1583                         var self = this;
1584                         var expireWidget = findWidget('au', 'expire_date');
1585                         function found(items) {
1586                             if(items.length == 0) return;
1587                             var item = items[0];
1588                             var interval = self.store.getValue(item, 'perm_interval');
1589                             expireWidget.widget.attr('value', dojo.date.add(new Date(), 
1590                                 'second', openils.Util.intervalToSeconds(interval)));
1591                         }
1592                         this.store.fetch({onComplete:found, query:{id:this.attr('value')}});
1593                     }
1594                 );
1595                 return;
1596
1597             case 'dob':
1598                 widget.widget.isValid = function() {
1599                     return this.attr("value") < new Date();
1600                 };
1601                 dojo.connect(widget.widget, 'onChange',
1602                     function(newDob) {
1603                         if(!newDob) return;
1604                         var oldDob = patron.dob();
1605                         if(dojo.date.stamp.fromISOString(oldDob) == newDob) return;
1606
1607                         var juvInterval = orgSettings['global.juvenile_age_threshold'] || '18 years';
1608                         var juvWidget = findWidget('au', 'juvenile');
1609                         var base = new Date();
1610                         base.setTime(base.getTime() - Number(openils.Util.intervalToSeconds(juvInterval) + '000'));
1611
1612                         if(newDob <= base) // older than global.juvenile_age_threshold
1613                             juvWidget.widget.attr('value', false);
1614                         else
1615                             juvWidget.widget.attr('value', true);
1616                     }
1617                 );
1618                 return;
1619
1620             case 'first_given_name':
1621             case 'family_name':
1622                 dojo.connect(widget.widget, 'onChange',
1623                     function(newVal) { uEditDupeSearch('name', newVal); });
1624                 return;
1625
1626             case 'email':
1627                 dojo.connect(widget.widget, 'onChange',
1628                     function(newVal) { uEditDupeSearch('email', newVal); });
1629                 return;
1630
1631             case 'ident_value':
1632             case 'ident_value2':
1633                 dojo.connect(widget.widget, 'onChange',
1634                     function(newVal) { uEditDupeSearch('ident', newVal); });
1635                 return;
1636
1637             case 'day_phone':
1638                 // if configured, use the last four digits of the day phone number as the password
1639                 // Alt, use the first capture group of the validator regex
1640                 if(uEditUsePhonePw && patron.isnew()) {
1641                     dojo.connect(widget.widget, 'onChange', widget.widget, usePhonePw);
1642                     if (patron.day_phone()) {
1643                         usePhonePw(patron.day_phone());
1644                     }
1645                 }
1646             case 'evening_phone':
1647             case 'other_phone':
1648                 dojo.connect(widget.widget, 'onChange',
1649                     function(newVal) { uEditDupeSearch('phone', newVal); });
1650                 return;
1651
1652             case 'home_ou':
1653                 widget.widget.isValid = function() {
1654                     if(this.item) {
1655                         if(homeOuTypes[this.store.getValue(this.item, 'ou_type')]) {
1656                             return true;
1657                         }
1658                         return false;
1659                     }
1660                     return true;
1661                 };
1662                 dojo.connect(widget.widget, 'onChange',
1663                     function(newVal) { 
1664                         checkClaimsReturnCountPerm(); 
1665                         checkClaimsNoCheckoutCountPerm();
1666                         checkCollectionsExemptPerm();
1667                     }
1668                 );
1669                 return;
1670
1671             case 'passwd':
1672                 dojo.connect(widget.widget, 'onChange',
1673                     function(newVal) {
1674                         var pw1 = findWidget('au', 'passwd').widget;
1675                         var pw2 = findWidget('au', 'passwd2').widget;
1676                         var preserved_value = pw2.attr('value');
1677                         // Ensure that the pw2 field match the pw1 field to validate
1678                         pw2.regExp = newVal.replace(/([.\\^$*+?\(\)\[\]\{\}])/g, '\\$1');
1679                         pw2.reset();
1680                         pw2.attr('value',preserved_value);
1681                     });
1682                 return;
1683         }
1684     }
1685
1686     if(fmclass = 'aua') {
1687
1688         // map post code to city, state, and county
1689         if (fmfield == 'post_code') {
1690             dojo.connect(widget.widget, 'onChange',
1691                 function(e) { 
1692                     fieldmapper.standardRequest(
1693                         ['open-ils.search', 'open-ils.search.zip'],
1694                         {   async: true,
1695                             params: [e],
1696                             oncomplete : function(r) {
1697                                 var res = openils.Util.readResponse(r);
1698                                 if(!res) return;
1699                                 var callback = function(w) { return w._addr == widget._addr; };
1700                                 if(res.city) findWidget('aua', 'city', callback).widget.attr('value', res.city);
1701                                 if(res.state) findWidget('aua', 'state', callback).widget.attr('value', res.state);
1702                                 if(res.county) findWidget('aua', 'county', callback).widget.attr('value', res.county);
1703                                 if(res.alert) alert(res.alert);
1704                             }
1705                         }
1706                     );
1707                 }
1708             );
1709         }
1710
1711         // duplicate address search
1712         if (['street1', 'street2', 'city'].indexOf(fmfield) > -1) {
1713             dojo.connect(widget.widget, 'onChange',
1714                 function(e) {
1715                     var callback = function(w) { return w._addr == widget._addr; };
1716                     var args = {
1717                         street1 : findWidget('aua', 'street1', callback).widget.attr('value'),
1718                         street2 : findWidget('aua', 'street2', callback).widget.attr('value'),
1719                         city : findWidget('aua', 'city', callback).widget.attr('value'),
1720                         post_code : findWidget('aua', 'post_code', callback).widget.attr('value')
1721                     };
1722                     if(args.street1 && args.city && args.post_code)
1723                         uEditDupeSearch('address', args); 
1724                 }
1725             ); 
1726         }
1727
1728         if (addressAlertFields.indexOf(fmfield) > -1) {
1729             dojo.connect(
1730                 widget.widget, 'onChange', 
1731                 function() { uEditAddressAlertMarshal(widget._addr) }
1732             );
1733         }
1734     }
1735 }
1736
1737 function uEditAddressAlertMarshal(addrId, changeBilling, changeMailing) {
1738
1739     if (changeBilling) {
1740         uEditAddressAlertMarshal(prevBillingAddress);
1741         prevBillingAddress = addrId;
1742     }
1743     
1744     if (changeMailing) {
1745         uEditAddressAlertMarshal(prevMailingAddress);
1746         prevMailingAddress = addrId;
1747     }
1748
1749     var callback = function(w) { return w._addr == addrId; };
1750     var args = {};
1751     dojo.forEach(addressAlertFields,
1752         function(field) {
1753             args[field] = findWidget('aua', field, callback).widget.attr('value')
1754         }
1755     );
1756     args.mailing_address = dojo.byId('uedit-mailing-address-' + addrId).checked;
1757     args.billing_address = dojo.byId('uedit-billing-address-' + addrId).checked;
1758     uEditAddressAlertSearch(args, addrId);
1759 }
1760
1761 var _addrAlertTimeout = {};
1762 function uEditAddressAlertSearch(args, addrId) {
1763
1764     _addrAlertTimeout[addrId] = setTimeout(
1765         function() {
1766             if (_addrAlertTimeout[addrId]) 
1767                 clearTimeout(_addrAlertTimeout[addrId]);
1768
1769             console.log('creating addr alert search for ' + addrId);
1770
1771             fieldmapper.standardRequest(
1772                 ['open-ils.actor', 'open-ils.actor.address_alert.test'],
1773                 {   async: true,
1774                     params: [openils.User.authtoken, staff.ws_ou(), args],
1775                     oncomplete : function(r) {
1776                         var alerts = openils.Util.readResponse(r);
1777                         var msgNode = dojo.byId('uedit-address-alert-message');
1778                         var headerRow = dojo.filter(
1779                             dojo.query('[name=uedit-addr-divider]'),
1780                             function(row) { return row.getAttribute('addr') == addrId })[0]
1781
1782                         msgNode.innerHTML = '';
1783
1784                         if (alerts.length) {
1785
1786                             // show the alert box
1787                             openils.Util.hide('uedit-help-div');
1788                             openils.Util.hide('uedit-dupe-div');
1789                             openils.Util.show('uedit-address-alert');
1790
1791                             // style the address header row
1792                             openils.Util.addCSSClass(headerRow, 'uedit-address-alert-divider');
1793
1794                             dojo.forEach(alerts,
1795                                 function(addr) {
1796                                     msgNode.innerHTML += addr.alert_message() + '<br/>';
1797                                 }
1798                             );
1799
1800                         } else { 
1801                             openils.Util.hide('uedit-address-alert');
1802                             openils.Util.removeCSSClass(headerRow, 'uedit-address-alert-divider');
1803                         }
1804                     }
1805                 }
1806             );
1807         }, 
1808         addressAlertTimeout
1809     );
1810 }
1811
1812 function uEditDupeSearch(type, value) {
1813     if(!value) return;
1814     var search;
1815     switch(type) {
1816
1817         case 'name':
1818             openils.Util.hide('uedit-dupe-names-link');
1819             var fname = findWidget('au', 'first_given_name').widget.attr('value');
1820             var lname = findWidget('au', 'family_name').widget.attr('value');
1821             if( !(fname && lname) ) return;
1822             search = {
1823                 first_given_name : {value : fname, group : 0},
1824                 family_name : {value : lname, group : 0},
1825             };
1826             break;
1827
1828         case 'email':
1829             openils.Util.hide('uedit-dupe-email-link');
1830             search = {email : {value : value, group : 0}};
1831             break;
1832
1833         case 'ident':
1834             openils.Util.hide('uedit-dupe-ident-link');
1835             search = {ident : {value : value, group : 2}};
1836             break;
1837
1838         case 'phone':
1839             openils.Util.hide('uedit-dupe-phone-link');
1840             search = {phone : {value : value, group : 2}};
1841             break;
1842
1843         case 'address':
1844             openils.Util.hide('uedit-dupe-address-link');
1845             search = {};
1846             dojo.forEach(['street1', 'street2', 'city', 'post_code'],
1847                 function(field) {
1848                     if(value[field])
1849                         search[field] = {value : value[field], group: 1};
1850                 }
1851             );
1852             break;
1853     }
1854
1855     // find possible duplicate patrons
1856     fieldmapper.standardRequest(
1857         ['open-ils.actor', 'open-ils.actor.patron.search.advanced'],
1858         {   async: true,
1859             params: [openils.User.authtoken, search, null, null, 1],
1860             oncomplete : function(r) {
1861                 var resp = openils.Util.readResponse(r);
1862                 resp = resp.filter(function(id) { return (id != patron.id()); });
1863
1864                 if(resp && resp.length > 0) {
1865
1866                     openils.Util.hide('uedit-help-div');
1867                     openils.Util.hide('uedit-address-alert');
1868                     openils.Util.show('uedit-dupe-div');
1869                     var link;
1870
1871                     switch(type) {
1872                         case 'name':
1873                             link = dojo.byId('uedit-dupe-names-link');
1874                             link.innerHTML = dojo.string.substitute(localeStrings.DUPE_PATRON_NAME, [resp.length]);
1875                             break;
1876                         case 'email':
1877                             link = dojo.byId('uedit-dupe-email-link');
1878                             link.innerHTML = dojo.string.substitute(localeStrings.DUPE_PATRON_EMAIL, [resp.length]);
1879                             break;
1880                         case 'ident':
1881                             link = dojo.byId('uedit-dupe-ident-link');
1882                             link.innerHTML = dojo.string.substitute(localeStrings.DUPE_PATRON_IDENT, [resp.length]);
1883                             break;
1884                         case 'phone':
1885                             link = dojo.byId('uedit-dupe-phone-link');
1886                             link.innerHTML = dojo.string.substitute(localeStrings.DUPE_PATRON_PHONE, [resp.length]);
1887                             break;
1888                         case 'address':
1889                             link = dojo.byId('uedit-dupe-address-link');
1890                             link.innerHTML = dojo.string.substitute(localeStrings.DUPE_PATRON_ADDR, [resp.length]);
1891                             break;
1892                     }
1893
1894                     openils.Util.show(link);
1895                     link.onclick = function() {
1896                         search.search_sort = js2JSON(["penalties", "family_name", "first_given_name"]);
1897                         search.include_inactive = "true";
1898                         if(window.xulG)
1899                             window.xulG.spawn_search(search);
1900                         else
1901                             console.log("running XUL patron search " + js2JSON(search));
1902                     }
1903                 }
1904             }
1905         }
1906     );
1907 }
1908
1909 function getByName(node, name) {
1910     return dojo.query('[name='+name+']', node)[0];
1911 }
1912
1913
1914 function ueLoadContextHelp(fmcls, fmfield) {
1915     openils.Util.hide('uedit-dupe-div');
1916     openils.Util.hide('uedit-dupe-div');
1917     openils.Util.show('uedit-help-div');
1918     dojo.byId('uedit-help-field').innerHTML = fieldmapper.IDL.fmclasses[fmcls].field_map[fmfield].label;
1919     dojo.byId('uedit-help-text').innerHTML = fieldDoc[fmcls][fmfield].string();
1920 }
1921
1922
1923 /* creates a new patron object with card attached */
1924 function uEditNewPatron() {
1925     patron = new au();
1926     patron.isnew(1);
1927     patron.id(-1);
1928     card = new ac();
1929     card.id(uEditCardVirtId--);
1930     card.isnew(1);
1931     patron.active(1);
1932     patron.card(card);
1933     patron.cards([card]);
1934     patron.net_access_level(orgSettings['ui.patron.default_inet_access_level'] || 1);
1935     patron.ident_type(orgSettings['ui.patron.default_ident_type']);
1936     patron.stat_cat_entries([]);
1937     patron.survey_responses([]);
1938     patron.addresses([]);
1939     uEditMakeRandomPw(patron);
1940     return patron;
1941 }
1942
1943 function uEditMakeRandomPw(patron) {
1944     var rand  = Math.random();
1945     rand = parseInt(rand * 10000) + '';
1946     while(rand.length < 4) rand += '0';
1947 /*
1948     appendClear($('ue_password_plain'),text(rand));
1949     unHideMe($('ue_password_gen'));
1950 */
1951     patron.passwd(rand);
1952     return rand;
1953 }
1954
1955 function uEditWidgetVal(w) {
1956     var val = (w.getFormattedValue) ? w.getFormattedValue() : w.attr('value');
1957     if(val === '') val = null;
1958     return val;
1959 }
1960
1961 function uEditSave() { _uEditSave(); }
1962 function uEditSaveClone() { _uEditSave(true); }
1963
1964 function _uEditSave(doClone) {
1965
1966     if ( (! myForm.isValid()) || dupeUsrname || dupeBarcode ) {
1967         alert(localeStrings.INVALID_FORM);
1968         return;
1969     }
1970
1971     for(var idx in widgetPile) {
1972         var w = widgetPile[idx];
1973         var val = uEditWidgetVal(w);
1974
1975         switch(w._wtype) {
1976             case 'au':
1977                 if(w._fmfield != 'passwd2')
1978                     patron[w._fmfield](val);
1979                 break;
1980
1981             case 'ac':
1982                 if(!editCard) editCard = patron.card();
1983                 editCard[w._fmfield](val);
1984                 break;
1985
1986             case 'aua':
1987                 var addr = patron.addresses().filter(function(i){return (i.id() == w._addr)})[0];
1988                 if(!addr) {
1989                     addr = new fieldmapper.aua();
1990                     addr.id(w._addr);
1991                     addr.isnew(1);
1992                     addr.usr(patron.id());
1993                     addr.country(orgSettings['ui.patron.default_country']);
1994                     var t = patron.addresses();
1995                         if (!t) { t = []; }
1996                         t.push(addr);
1997                         patron.addresses(t);
1998                 } else {
1999                     if(addr[w._fmfield]() != val)
2000                         addr.ischanged(1);
2001                 }
2002                 addr[w._fmfield](val);
2003
2004                 if(dojo.byId('uedit-billing-address-' + addr.id()).checked) 
2005                     patron.billing_address(addr.id());
2006
2007                 if(dojo.byId('uedit-mailing-address-' + addr.id()).checked)
2008                     patron.mailing_address(addr.id());
2009
2010                 break;
2011
2012             case 'survey':
2013                 if(val == null) break;
2014                 var resp = new fieldmapper.asvr();
2015                 resp.isnew(1);
2016                 resp.survey(w._survey)
2017                 resp.usr(patron.id());
2018                 resp.question(w._question)
2019                 resp.answer(val);
2020                 var t = patron.survey_responses();
2021                     if (!t) { t = []; }
2022                     t.push(resp);
2023                     patron.survey_responses(t);
2024                 break;
2025
2026             case 'statcat':
2027                 var map = patron.stat_cat_entries().filter(
2028                     function(m){
2029                         return (m.stat_cat() == w._statcat) })[0];
2030
2031                 if(w.declaredClass == 'dijit.form.FilteringSelect') {
2032                     val = w.attr('displayedValue');
2033                 }
2034
2035                 if(map) {
2036                     if(map.stat_cat_entry() == val) 
2037                         break;
2038                     if(val == null) {
2039                         val = '';
2040                         map.isdeleted(1);
2041                     } else {
2042                         map.ischanged(1);
2043                     }
2044                 } else {
2045                     if(val == null)
2046                         break;
2047                     map = new fieldmapper.actscecm();
2048                     map.isnew(1);
2049                 }
2050
2051                 map.stat_cat(w._statcat);
2052                 map.stat_cat_entry(val);
2053                 map.target_usr(patron.id());
2054                 var t = patron.stat_cat_entries();
2055                     if (!t) { t = []; }
2056                     t.push(map);
2057                     patron.stat_cat_entries(t);
2058                 break;
2059         }
2060     }
2061
2062     patron.ischanged(1);
2063     fieldmapper.standardRequest(
2064         ['open-ils.actor', 'open-ils.actor.patron.update'],
2065         {   async: true,
2066             params: [openils.User.authtoken, patron],
2067             oncomplete: function(r) {
2068                 lock_ready = false;
2069                 if (xulG && typeof xulG.unlock_tab == 'function') {
2070                     xulG.unlock_tab();
2071                     already_locked = false;
2072                 }
2073                 /* There's something that seems to just make the form reload
2074                  * on all saves, so this uUpdate... isn't needed here after
2075                  * all. */
2076                 //uUpdateContactInvalidators();
2077
2078                 newPatron = openils.Util.readResponse(r);
2079                 if(newPatron) {
2080                     uEditUpdateUserSettings(newPatron.id());
2081                     if(stageUser) uEditRemoveStage();
2082                     uEditFinishSave(newPatron, doClone);
2083                 }
2084             },
2085             onmethoderror: function(req, status, status_text) {
2086                 alert("Method error: " + status + ": " + status_text);
2087             }
2088         }
2089     );
2090     if(secondaryGroupsChanged){
2091         saveSecondaryGroups();
2092     }
2093 }
2094
2095 function uUpdateContactInvalidators() {
2096     /* show invalidator buttons for fields that having anything in them */
2097     ["email", "day_phone", "evening_phone", "other_phone"].forEach(
2098         function(f) {
2099             openils.Util[patron[f]() ? "show" : "hide"]("wrap_invalidate_" + f);
2100         }
2101     );
2102 }
2103
2104 function uGenerateInvalidatorWidget(container_node, field) {
2105     new dijit.form.Button(
2106         {
2107             "label": localeStrings.INVALIDATE,
2108             "scrollOnFocus": false,
2109             "onClick": function() {
2110                 progressDialog.show(true);
2111                 fieldmapper.standardRequest(
2112                     ["open-ils.actor", "open-ils.actor.invalidate." + field], {
2113                         "async": true,
2114                         "params": [openils.User.authtoken, patron.id(), null, patron.home_ou()],
2115                         "oncomplete": function(r) {
2116                             progressDialog.hide();
2117                             // alerts on non-success event
2118                             var res = openils.Util.readResponse(r);
2119
2120                             if (res.payload.last_xact_id) {
2121                                 for (var id in res.payload.last_xact_id) {
2122                                     if (patron.id() == id)
2123                                         patron.last_xact_id(
2124                                             res.payload.last_xact_id[id]
2125                                         );
2126                                 }
2127
2128                                 findWidget("au",field).widget.attr("value","");
2129                                 openils.Util.hide(container_node);
2130                             }
2131                         }
2132                     }
2133                 );
2134             }
2135         }, dojo.create("span", null, container_node, "only")
2136     );
2137 }
2138
2139 function uEditRemoveStage() {
2140     var resp = fieldmapper.standardRequest(
2141         ['open-ils.actor', 'open-ils.actor.user.stage.delete'],
2142         { params : [openils.User.authtoken, stageUser.row_id()] }
2143     )
2144 }
2145
2146 function uEditFinishSave(newPatron, doClone) {
2147
2148     if(doClone && cloneUser == null)
2149         cloneUser = newPatron.id();
2150
2151         if( doClone ) {
2152
2153                 if(xulG && typeof xulG.spawn_editor == 'function' && !patron.isnew() ) {
2154             window.xulG.spawn_editor({ses:openils.User.authtoken,clone:cloneUser});
2155             uEditRefresh();
2156
2157                 } else {
2158                         location.href = location.href.replace(/\?.*/, '') + '?clone=' + cloneUser;
2159                 }
2160
2161         } else {
2162
2163                 uEditRefresh();
2164         }
2165
2166         uEditRefreshXUL(newPatron);
2167 }
2168
2169 function uEditRefresh() {
2170     var usr = cgi.param('usr');
2171     var href = location.href.replace(/\?.*/, '');
2172     href += ((usr) ? '?usr=' + usr : '');
2173     location.href = href;
2174 }
2175
2176 function uEditRefreshXUL(newuser) {
2177         if (window.xulG && typeof window.xulG.on_save == 'function') 
2178                 window.xulG.on_save(newuser);
2179 }
2180
2181
2182 /**
2183  * Create a new address and insert it into the DOM
2184  * @param evt ignored
2185  * @param id The address id
2186  * @param mkLinks If true, set the new address as the 
2187  *  mailing/billing address for the user
2188  */
2189 function uEditNewAddr(evt, id, mkLinks) {
2190
2191     if(id == null) 
2192         id = --uEditAddrVirtId; // new address
2193
2194     var addr =  patron.addresses().filter(
2195         function(i) { return (i.id() == id) })[0];
2196
2197     dojo.forEach(addrTemplateRows, 
2198         function(row) {
2199
2200             row = tbody.insertBefore(row.cloneNode(true), dojo.byId('new-addr-row'));
2201             row.setAttribute('type', '');
2202             row.setAttribute('addr', id+'');
2203
2204             if(row.getAttribute('fmclass')) {
2205                 var widget = fleshFMRow(row, 'aua', {addr:id});
2206
2207                 // make new addresses a default address type
2208                 if(id < 0 && row.getAttribute('fmfield') == 'address_type') 
2209                     widget.widget.attr('value', localeStrings.DEFAULT_ADDRESS_TYPE); 
2210
2211                 // make new addresses valid by default
2212                 if(id < 0 && row.getAttribute('fmfield') == 'valid') 
2213                     widget.widget.attr('value', true); 
2214
2215                 // make new addresses use the org setting for default country 
2216                 if(id < 0 && row.getAttribute('fmfield') == 'country') 
2217                     widget.widget.attr('value',orgSettings['ui.patron.default_country']);
2218
2219             } else if(row.getAttribute('name') == 'uedit-addr-pending-row') {
2220
2221                 // if it's a pending address, show the 'approve' button
2222                 if(addr && openils.Util.isTrue(addr.pending())) {
2223                     openils.Util.show(row, 'table-row');
2224                     dojo.query('[name=approve-button]', row)[0].onclick = 
2225                         function() { uEditApproveAddress(addr); };
2226
2227                     if(addr.replaces()) {
2228                         var div = dojo.query('[name=replaced-addr]', row)[0]
2229                         var replaced =  patron.addresses().filter(
2230                             function(i) { return (i.id() == addr.replaces()) })[0];
2231
2232                         div.innerHTML = '<div>' + dojo.string.substitute(localeStrings.REPLACED_ADDRESS, [
2233                             '<b>' + replaced.address_type() + '</b>' || '',
2234                             replaced.street1() || '',
2235                             replaced.street2() || '',
2236                             replaced.city() || '',
2237                             replaced.state() || '',
2238                             replaced.post_code() || ''
2239                         ]) + '</div>';
2240
2241                     } else {
2242                         openils.Util.hide(dojo.query('[name=replaced-addr-div]', row)[0]);
2243                     }
2244                 }
2245
2246             } else if(row.getAttribute('name') == 'uedit-addr-owner-row') {
2247                 // address is owned by someone else.  provide option to load the
2248                 // user in a different tab
2249                 
2250                 if(addr && addr.usr() != patron.id()) {
2251                     openils.Util.show(row, 'table-row');
2252                     var link = getByName(row, 'addr-owner');
2253
2254                     // fetch the linked user so we can present their name in the UI
2255                     var addrUser;
2256                     if(cloneUserObj && cloneUserObj.id() == addr.usr()) {
2257                         addrUser = [
2258                             cloneUserObj.first_given_name(), 
2259                             cloneUserObj.second_given_name(), 
2260                             cloneUserObj.family_name()
2261                         ];
2262                     } else {
2263                         addrUser = fieldmapper.standardRequest(
2264                             ['open-ils.actor', 'open-ils.actor.user.retrieve.parts'],
2265                             {params: [
2266                                 openils.User.authtoken, 
2267                                 addr.usr(), 
2268                                 ['first_given_name', 'second_given_name', 'family_name']
2269                             ]}
2270                         );
2271                     }
2272
2273                     link.innerHTML = (addrUser.map(function(name) { return (name) ? name+' ' : '' })+'').replace(/,/g,''); // TODO i18n
2274                     link.onclick = function() {
2275                         if(openils.XUL.isXUL()) { 
2276                             window.xulG.spawn_editor({ses:openils.User.authtoken, usr:addr.usr()})
2277                         } else {
2278                             parent.location.href = location.href.replace(/clone=\d+/, 'usr=' + addr.usr());
2279                         }
2280                     }
2281                 }
2282
2283             } else if(row.getAttribute('name') == 'uedit-addr-divider') {
2284                 // link up the billing/mailing address and give the inputs IDs so we can access the later
2285                 
2286                 // billing address
2287                 var ba = getByName(row, 'billing_address');
2288                 ba.id = 'uedit-billing-address-' + id;
2289                 if(mkLinks || (patron.billing_address() && patron.billing_address().id() == id)) {
2290                     ba.checked = true;
2291                     prevBillingAddress = id;
2292                 }
2293
2294                 // mailing address
2295                 var ma = getByName(row, 'mailing_address');
2296                 ma.id = 'uedit-mailing-address-' + id;
2297                 if(mkLinks || (patron.mailing_address() && patron.mailing_address().id() == id)) {
2298                     ma.checked = true;
2299                     prevMailingAddress = id;
2300                 }
2301
2302                 ba.onclick = function() { console.log('ba.onchange ' + id); uEditAddressAlertMarshal(id, true) };
2303                 ma.onclick = function() { uEditAddressAlertMarshal(id, false, true) };
2304                 
2305                 var btn = dojo.query('[name=delete-button]', row)[0];
2306                 if(btn) btn.onclick = function(){ uEditDeleteAddr(id) };
2307             }
2308         }
2309     );
2310 }
2311
2312 function uEditApproveAddress(addr) {
2313     fieldmapper.standardRequest(
2314         ['open-ils.actor', 'open-ils.actor.user.pending_address.approve'],
2315         {   async: true,
2316             params:  [openils.User.authtoken, addr],
2317
2318             oncomplete : function(r) {
2319                 var oldId = openils.Util.readResponse(r);
2320                     
2321                 // remove addrs from UI
2322                 dojo.forEach(
2323                     patron.addresses(), 
2324                     function(addr) { uEditDeleteAddr(addr.id(), true); }
2325                 );
2326
2327                 if(oldId != null) {
2328                     
2329                     // remove the replaced address 
2330                     if(oldId != addr.id()) {
2331                                 patron.addresses(
2332                             patron.addresses().filter(
2333                                                 function(i) { return (i.id() != oldId); }
2334                                         )
2335                                 );
2336                     }
2337                     
2338                     // fix the the new address
2339                     addr.id(oldId);
2340                     addr.replaces(null);
2341                     addr.pending('f');
2342
2343                 }
2344
2345                 // redraw addrs
2346                 loadAllAddrs();
2347             }
2348         }
2349     );
2350 }
2351
2352
2353 function uEditDeleteAddr(id, noAlert) {
2354     if (patron.isnew() && orgSettings['ui.patron.registration.require_address']) {
2355         if (dojo.query('tr[name=uedit-addr-divider]').length < 2) {
2356             alert(localeStrings.NEED_ADDRESS);
2357             return;
2358         }
2359     }
2360     if(!noAlert) {
2361         if(!confirm(dojo.string.substitute(localeStrings.DELETE_ADDRESS, [id]))) return;
2362     }
2363     var addr = patron.addresses().filter(function(i){return (i.id() == id)})[0];
2364     if (addr) { addr.isdeleted(1); }
2365     var m_a = patron.mailing_address();
2366         if (typeof m_a == 'object' && m_a != null) { m_a = m_a.id(); }
2367         if (m_a == id) { patron.mailing_address(null); }
2368     var b_a = patron.billing_address();
2369         if (typeof b_a == 'object' && b_a != null) { b_a = b_a.id(); }
2370         if (b_a == id) { patron.billing_address(null); }
2371
2372     var rows = dojo.query('tr[addr='+id+']', tbody);
2373     for(var i = 0; i < rows.length; i++)
2374         rows[i].parentNode.removeChild(rows[i]);
2375     widgetPile = widgetPile.filter(function(w){return (w._addr != id)});
2376 }
2377
2378 function uEditToggleRequired(level) {
2379     openils.Util.removeCSSClass(tbody, 'hide-non-required');
2380     openils.Util.removeCSSClass(tbody, 'hide-non-suggested');
2381     openils.Util.show('uedit-show-required');
2382     openils.Util.show('uedit-show-required-br');
2383     openils.Util.show('uedit-show-suggested');
2384     openils.Util.show('uedit-show-suggested-br');
2385     openils.Util.show('uedit-show-all');
2386     switch(level) {
2387         case 1:
2388             openils.Util.hide('uedit-show-required');
2389             openils.Util.hide('uedit-show-required-br');
2390             openils.Util.addCSSClass(tbody, 'hide-non-required');
2391             break;
2392         case 2:
2393             openils.Util.hide('uedit-show-suggested');
2394             openils.Util.hide('uedit-show-suggested-br');
2395             openils.Util.addCSSClass(tbody, 'hide-non-suggested');
2396             break;
2397         default:
2398             openils.Util.hide('uedit-show-all');
2399             break;
2400     } 
2401 }
2402
2403 function printable_output() {
2404     var temp; var s = '=-=-=-=\r\n';
2405     for (var idx in widgetPile) {
2406         var w = widgetPile[idx];
2407         var val = uEditWidgetVal(w);
2408         var label;
2409         if (typeof w.idlField == 'undefined') {
2410             label = w._wtype;
2411             if (w._wtype == 'statcat') {
2412                 var stat = statCats.filter(
2413                     function(m){
2414                         return (m.id() == w._statcat) })[0];
2415                 label = stat.name();
2416             } else if (w._wtype == 'survey') {
2417                 var survey = surveys.filter(
2418                     function(m){
2419                         return (m.id() == w._survey) })[0];
2420                 var question = survey.questions().filter(
2421                     function(m){
2422                         return (m.id() == w._question) })[0];
2423                 label = survey.name() + ' : ' + question.question();
2424             } else {
2425                 label = 'FIXME';
2426             }
2427         } else {
2428             label = w.idlField.label;
2429         }
2430         if (temp != w._wtype) {
2431             temp = w._wtype;
2432             s += '-------\r\n';
2433         }
2434         s += label + ':\t' + (typeof val == 'object' ? '' : val) + '\r\n';
2435     }
2436     s += '=-=-=-=\r\n';
2437     return s;
2438 }
2439
2440 openils.Util.addOnLoad(load);