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