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