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