Followup patch to the first listed in https://bugs.launchpad.net/evergreen/+bug/745123
[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 required = openils.Util.isTrue(survey.required());
656         var srow = surveyTemplate.cloneNode(true);
657         if(required) srow.setAttribute('required','required');
658         tbody.appendChild(srow);
659         getByName(srow, 'name').innerHTML = survey.name();
660
661         for(var q in survey.questions()) {
662             var quest = survey.questions()[q];
663             var qrow = surveyQuestionTemplate.cloneNode(true);
664             if(required) qrow.setAttribute('required','required');
665             tbody.appendChild(qrow);
666             getByName(qrow, 'question').innerHTML = quest.question();
667
668             var span = getByName(qrow, 'answers').appendChild(document.createElement('span'));
669             var store = new dojo.data.ItemFileReadStore(
670                 {data:fieldmapper.asva.toStoreData(quest.answers())});
671             var select = new dijit.form.FilteringSelect({store:store,scrollOnFocus:false}, span);
672             if (! required ) {
673                 select.isValid = function() { return true; };
674             }
675             select.labelAttr = 'answer';
676             select.searchAttr = 'answer';
677
678             select._wtype = 'survey';
679             select._survey = survey.id();
680             select._question = quest.id();
681             widgetPile.push(select); 
682         }
683     }
684 }
685
686
687 function fleshFMRow(row, fmcls, args) {
688     var fmfield = row.getAttribute('fmfield');
689     var wclass = row.getAttribute('wclass');
690     var wstyle = row.getAttribute('wstyle');
691     var wconstraints = row.getAttribute('wconstraints');
692     /* use CSS to set the zindex for widgets you want to disable. */
693     var disabled = dojo.style(row, 'zIndex') == -1 ? true : false;
694     var isphone = (fmcls == 'au') && (fmfield.search('_phone') != -1);
695
696     var isPasswd2 = (fmfield == 'passwd2');
697     if(isPasswd2) fmfield = 'passwd';
698     var fieldIdl = fieldmapper.IDL.fmclasses[fmcls].field_map[fmfield];
699     if(!args) args = {};
700
701     var existing = dojo.query('td', row);
702     var htd = existing[0] || row.appendChild(document.createElement('td'));
703     var ltd = existing[1] || row.appendChild(document.createElement('td'));
704     var wtd = existing[2] || row.appendChild(document.createElement('td'));
705     var ftd = existing[3] || row.appendChild(document.createElement('td'));
706
707     openils.Util.addCSSClass(htd, 'uedit-help');
708     if(fieldDoc[fmcls] && fieldDoc[fmcls][fmfield]) {
709         var link = dojo.byId('uedit-help-template').cloneNode(true);
710         link.id = '';
711         link.onclick = function() { ueLoadContextHelp(fmcls, fmfield) };
712         openils.Util.removeCSSClass(link, 'hidden');
713         htd.appendChild(link);
714     }
715
716     if(!ltd.textContent) {
717         ltd.appendChild(document.createTextNode(fieldIdl.label));
718     }
719
720     if(!ftd.textContent) {
721         if(orgSettings['ui.patron.edit.' + fmcls + '.' + fmfield + '.example']) {
722             ftd.appendChild(document.createTextNode(localeStrings.EXAMPLE + orgSettings['ui.patron.edit.' + fmcls + '.' + fmfield + '.example']));
723         }
724         else if(isphone && orgSettings['ui.patron.edit.phone.example']) {
725             ftd.appendChild(document.createTextNode(localeStrings.EXAMPLE + orgSettings['ui.patron.edit.phone.example']));
726         }
727         else if(fieldIdl.datatype == 'timestamp') {
728             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)})));
729         }
730     }
731
732     var span = document.createElement('span');
733     wtd.appendChild(span);
734
735     var fmObject = null;
736     switch(fmcls) {
737         case 'au' : fmObject = patron; break;
738         case 'ac' : fmObject = patron.card(); break;
739         case 'aua' : 
740             fmObject = patron.addresses().filter(
741                 function(i) { return (i.id() == args.addr) })[0];
742             if(fmObject && fmObject.usr() != patron.id())
743                 disabled = true;
744             break;
745     }
746
747     // Adjust required value by org settings
748     var curRequired = row.getAttribute('required');
749     var required = curRequired == 'required';
750     if(orgSettings['ui.patron.edit.' + fmcls + '.' + fmfield + '.require']) {
751         row.setAttribute('required', 'required');
752         required = true;
753     }
754     else if (curRequired != 'required' && orgSettings['ui.patron.edit.' + fmcls + '.' + fmfield + '.show']) {
755         row.setAttribute('required', 'show');
756     }
757     else if (curRequired != 'required' && curRequired != 'show' && orgSettings['ui.patron.edit.' + fmcls + '.' + fmfield + '.suggest']) {
758         row.setAttribute('required', 'suggested');
759     }
760
761     // password data is not fetched/required/displayed for existing users
762     if(!patron.isnew() && 'passwd' == fmfield)
763         required = false;
764
765     var dijitArgs = {
766         style: wstyle, 
767         required : required,
768         constraints : (wconstraints) ? eval('('+wconstraints+')') : {}, // the ()'s prevent Invalid Label errors with eval
769         disabled : disabled
770     };
771
772     // Org settings provided regex?
773     if(orgSettings['ui.patron.edit.' + fmcls + '.' + fmfield + '.regex']) {
774         dijitArgs.regExp = orgSettings['ui.patron.edit.' + fmcls + '.' + fmfield + '.regex'];
775     }
776     else if(isphone && orgSettings['ui.patron.edit.phone.regex']) {
777         dijitArgs.regExp = orgSettings['ui.patron.edit.phone.regex'];
778     }
779
780     if(fmcls == 'au' && fmfield == 'passwd') {
781         if (orgSettings['global.password_regex']) {
782             dijitArgs.regExp = orgSettings['global.password_regex'];
783         }
784     }
785
786     if(fmcls == 'au' && fmfield == 'dob' && !orgSettings['ui.patron.edit.au.dob.calendar'])
787         dijitArgs.popupClass = "";
788
789     var value = row.getAttribute('wvalue');
790     if(value !== null)
791         dijitArgs.value = value;
792
793     var wargs = {
794         idlField : fieldIdl,
795         fmObject : fmObject,
796         fmClass : fmcls,
797         parentNode : span,
798         widgetClass : wclass,
799         dijitArgs : dijitArgs,
800         orgDefaultsToWs : true,
801         orgLimitPerms : ['UPDATE_USER'],
802     };
803
804     if(fmfield == 'profile') {
805         // fetch profile groups non-async so existing expire_date is
806         // not overwritten when the profile groups arrive and update
807         wargs.forceSync = true;
808         wargs.disableQuery = {usergroup : 'f'};
809         if(!patron.isnew() && !checkGrpAppPerm(patron.profile()))
810             wargs.readOnly = true;
811     } else {
812         wargs.forceSync = false;
813     }
814
815     var widget = new openils.widget.AutoFieldWidget(wargs);
816     widget.build(
817         function(w, ww) {
818             if(fmfield == 'profile') { trimGrpTree(ww); }
819         }
820     );
821
822     // now put it back before we register the widget
823     if(isPasswd2) fmfield = 'passwd2';
824
825     widget._wtype = fmcls;
826     widget._fmfield = fmfield;
827     widget._addr = args.addr;
828     widgetPile.push(widget);
829     attachWidgetEvents(fmcls, fmfield, widget);
830     return widget;
831 }
832
833 function trimGrpTree(autoWidget) {
834     var store = autoWidget.widget.store;
835     if(!store) return;
836     // remove all groups that this user are not allowed to edit, 
837     // except the profile group of an existing user
838     store.fetch({onItem : 
839         function(item) {
840             if(!checkGrpAppPerm(item.id[0]) && patron.profile() != item.id[0])
841                 store.deleteItem(item);
842         }
843     });
844 }
845
846 function findWidget(wtype, fmfield, callback) {
847     return widgetPile.filter(
848         function(i){
849             if(i._wtype == wtype && i._fmfield == fmfield) {
850                 if(callback) return callback(i);
851                 return true;
852             }
853         }
854     ).pop();
855 }
856
857 /**
858  * if the user does not have the UPDATE_PATRON_CLAIM_RETURN_COUNT, 
859  * they are not allowed to directly alter the claim return count. 
860  * This function checks the perm and disable/enables the widget.
861  */
862 function checkClaimsReturnCountPerm() {
863     new openils.User().getPermOrgList(
864         'UPDATE_PATRON_CLAIM_RETURN_COUNT',
865         function(orgList) { 
866             var cr = findWidget('au', 'claims_returned_count');
867             if(orgList.indexOf(patron.home_ou()) == -1) 
868                 cr.widget.attr('disabled', true);
869             else
870                 cr.widget.attr('disabled', false);
871         },
872         true, 
873         true
874     );
875 }
876
877
878 function checkClaimsNoCheckoutCountPerm() {
879     new openils.User().getPermOrgList(
880         'UPDATE_PATRON_CLAIM_NEVER_CHECKED_OUT_COUNT',
881         function(orgList) { 
882             var cr = findWidget('au', 'claims_never_checked_out_count');
883             if(orgList.indexOf(patron.home_ou()) == -1) 
884                 cr.widget.attr('disabled', true);
885             else
886                 cr.widget.attr('disabled', false);
887         },
888         true, 
889         true
890     );
891 }
892
893
894 function attachWidgetEvents(fmcls, fmfield, widget) {
895
896     dojo.connect(
897         widget.widget,
898         'onKeyPress',
899         function(ev){
900             netscape.security.PrivilegeManager.enablePrivilege('UniversalXPConnect');
901             if (!(ev.altKey || ev.ctrlKey || ev.metaKey)) {
902                 if (lock_ready && xulG && typeof xulG.lock_tab == 'function') {
903                     if (! already_locked) {
904                         xulG.lock_tab();
905                         already_locked = true;
906                     }
907                 }
908             }
909         }
910     );
911     dojo.connect(
912         widget.widget,
913         'onChange',
914         function(){
915             if (lock_ready && xulG && typeof xulG.lock_tab == 'function') {
916                 if (! already_locked) {
917                     xulG.lock_tab();
918                     already_locked = true;
919                 }
920             }
921         }
922     );
923
924
925     if(fmcls == 'ac') {
926         if(fmfield == 'barcode') {
927             dojo.connect(widget.widget, 'onChange',
928                 function() {
929                     var barcode = this.attr('value');
930                     dupeBarcode = false;
931                     dojo.addClass(dojo.byId('uedit-dupe-barcode-warning'), 'hidden');
932                     fieldmapper.standardRequest(
933                         ['open-ils.actor', 'open-ils.actor.barcode.exists'],
934                         {
935                             params: [openils.User.authtoken, barcode],
936                             oncomplete : function(r) {
937                                 var res = openils.Util.readResponse(r);
938                                 if(res == '1') {
939                                     dupeBarcode = true;
940                                     dojo.removeClass(dojo.byId('uedit-dupe-barcode-warning'), 'hidden');
941                                 } else {
942                                     dupeBarcode = false;
943                                     dojo.addClass(dojo.byId('uedit-dupe-barcode-warning'), 'hidden');
944                                     var un = findWidget('au', 'usrname');
945                                     if(!un.widget.attr('value'))
946                                         un.widget.attr('value', barcode);
947                                 }
948                             }
949                         }
950                     );
951                 }
952             );
953             return;
954         }
955     }
956
957     if(fmcls == 'au') {
958         switch(fmfield) {
959
960             case 'usrname':
961                 dojo.connect(widget.widget, 'onChange', 
962                     function() {
963                         var input = findWidget('au', 'usrname');
964                         var usrname = input.widget.attr('value');
965
966                         if(!usrname) {
967                             dupeUsrname = false;
968                             dojo.addClass(dojo.byId('uedit-dupe-username-warning'), 'hidden');
969                             return;
970                         }
971
972                         fieldmapper.standardRequest(
973                             ['open-ils.actor', 'open-ils.actor.username.exists'],
974                             {
975                                 params: [openils.User.authtoken, usrname],
976                                 oncomplete : function(r) {
977                                     var res = openils.Util.readResponse(r);
978                                     if(res) {
979                                         dupeUsrname = true;
980                                         dojo.removeClass(dojo.byId('uedit-dupe-username-warning'), 'hidden');
981                                     } else {
982                                         dupeUsrname = false;
983                                         dojo.addClass(dojo.byId('uedit-dupe-username-warning'), 'hidden');
984                                     }
985                                 }
986                             }
987                         );
988                     }   
989                 );
990
991                 return;
992
993             case 'profile': // when the profile changes, update the expire date
994                 dojo.connect(widget.widget, 'onChange', 
995                     function() {
996                         var self = this;
997                         var expireWidget = findWidget('au', 'expire_date');
998                         function found(items) {
999                             if(items.length == 0) return;
1000                             var item = items[0];
1001                             var interval = self.store.getValue(item, 'perm_interval');
1002                             expireWidget.widget.attr('value', dojo.date.add(new Date(), 
1003                                 'second', openils.Util.intervalToSeconds(interval)));
1004                         }
1005                         this.store.fetch({onComplete:found, query:{id:this.attr('value')}});
1006                     }
1007                 );
1008                 return;
1009
1010             case 'dob':
1011                 dojo.connect(widget.widget, 'onChange',
1012                     function(newDob) {
1013                         if(!newDob) return;
1014                         var oldDob = patron.dob();
1015                         if(dojo.date.stamp.fromISOString(oldDob) == newDob) return;
1016
1017                         var juvInterval = orgSettings['global.juvenile_age_threshold'] || '18 years';
1018                         var juvWidget = findWidget('au', 'juvenile');
1019                         var base = new Date();
1020                         base.setTime(base.getTime() - Number(openils.Util.intervalToSeconds(juvInterval) + '000'));
1021
1022                         if(newDob <= base) // older than global.juvenile_age_threshold
1023                             juvWidget.widget.attr('value', false);
1024                         else
1025                             juvWidget.widget.attr('value', true);
1026                     }
1027                 );
1028                 return;
1029
1030             case 'first_given_name':
1031             case 'family_name':
1032                 dojo.connect(widget.widget, 'onChange',
1033                     function(newVal) { uEditDupeSearch('name', newVal); });
1034                 return;
1035
1036             case 'email':
1037                 dojo.connect(widget.widget, 'onChange',
1038                     function(newVal) { uEditDupeSearch('email', newVal); });
1039                 return;
1040
1041             case 'ident_value':
1042             case 'ident_value2':
1043                 dojo.connect(widget.widget, 'onChange',
1044                     function(newVal) { uEditDupeSearch('ident', newVal); });
1045                 return;
1046
1047             case 'day_phone':
1048                 // if configured, use the last four digits of the day phone number as the password
1049                 if(uEditUsePhonePw && patron.isnew()) {
1050                     dojo.connect(widget.widget, 'onChange',
1051                         function(newVal) {
1052                             if(newVal && newVal.length >= 4) {
1053                                 var pw1 = findWidget('au', 'passwd').widget;
1054                                 var pw2 = findWidget('au', 'passwd2').widget;
1055                                 pw1.attr('value', newVal.substring(newVal.length - 4));
1056                                 pw2.attr('value', newVal.substring(newVal.length - 4));
1057                             }
1058                         }
1059                     );
1060                 }
1061             case 'evening_phone':
1062             case 'other_phone':
1063                 dojo.connect(widget.widget, 'onChange',
1064                     function(newVal) { uEditDupeSearch('phone', newVal); });
1065                 return;
1066
1067             case 'home_ou':
1068                 dojo.connect(widget.widget, 'onChange',
1069                     function(newVal) { 
1070                         checkClaimsReturnCountPerm(); 
1071                         checkClaimsNoCheckoutCountPerm();
1072                     }
1073                 );
1074                 return;
1075
1076             case 'passwd':
1077                 dojo.connect(widget.widget, 'onChange',
1078                     function(newVal) {
1079                         var pw1 = findWidget('au', 'passwd').widget;
1080                         var pw2 = findWidget('au', 'passwd2').widget;
1081                         var preserved_value = pw2.attr('value');
1082                         // Ensure that the pw2 field match the pw1 field to validate
1083                         pw2.regExp = newVal.replace(/([.\\^$*+?\(\)\[\]\{\}])/g, '\\$1');
1084                         pw2.reset();
1085                         pw2.attr('value',preserved_value);
1086                     });
1087                 return;
1088         }
1089     }
1090
1091     if(fmclass = 'aua') {
1092         switch(fmfield) {
1093             case 'post_code':
1094                 dojo.connect(widget.widget, 'onChange',
1095                     function(e) { 
1096                         fieldmapper.standardRequest(
1097                             ['open-ils.search', 'open-ils.search.zip'],
1098                             {   async: true,
1099                                 params: [e],
1100                                 oncomplete : function(r) {
1101                                     var res = openils.Util.readResponse(r);
1102                                     if(!res) return;
1103                                     var callback = function(w) { return w._addr == widget._addr; };
1104                                     if(res.city) findWidget('aua', 'city', callback).widget.attr('value', res.city);
1105                                     if(res.state) findWidget('aua', 'state', callback).widget.attr('value', res.state);
1106                                     if(res.county) findWidget('aua', 'county', callback).widget.attr('value', res.county);
1107                                     if(res.alert) alert(res.alert);
1108                                 }
1109                             }
1110                         );
1111                     }
1112                 );
1113                 return;
1114
1115             case 'street1':
1116             case 'street2':
1117             case 'city':
1118                 dojo.connect(widget.widget, 'onChange',
1119                     function(e) {
1120                         var callback = function(w) { return w._addr == widget._addr; };
1121                         var args = {
1122                             street1 : findWidget('aua', 'street1', callback).widget.attr('value'),
1123                             street2 : findWidget('aua', 'street2', callback).widget.attr('value'),
1124                             city : findWidget('aua', 'city', callback).widget.attr('value'),
1125                             post_code : findWidget('aua', 'post_code', callback).widget.attr('value')
1126                         };
1127                         if(args.street1 && args.city && args.post_code)
1128                             uEditDupeSearch('address', args); 
1129                     }
1130                 );
1131                 return;
1132         }
1133     }
1134 }
1135
1136 function uEditDupeSearch(type, value) {
1137     if(!value) return;
1138     var search;
1139     switch(type) {
1140
1141         case 'name':
1142             openils.Util.hide('uedit-dupe-names-link');
1143             var fname = findWidget('au', 'first_given_name').widget.attr('value');
1144             var lname = findWidget('au', 'family_name').widget.attr('value');
1145             if( !(fname && lname) ) return;
1146             search = {
1147                 first_given_name : {value : fname, group : 0},
1148                 family_name : {value : lname, group : 0},
1149             };
1150             break;
1151
1152         case 'email':
1153             openils.Util.hide('uedit-dupe-email-link');
1154             search = {email : {value : value, group : 0}};
1155             break;
1156
1157         case 'ident':
1158             openils.Util.hide('uedit-dupe-ident-link');
1159             search = {ident : {value : value, group : 2}};
1160             break;
1161
1162         case 'phone':
1163             openils.Util.hide('uedit-dupe-phone-link');
1164             search = {phone : {value : value, group : 2}};
1165             break;
1166
1167         case 'address':
1168             openils.Util.hide('uedit-dupe-address-link');
1169             search = {};
1170             dojo.forEach(['street1', 'street2', 'city', 'post_code'],
1171                 function(field) {
1172                     if(value[field])
1173                         search[field] = {value : value[field], group: 1};
1174                 }
1175             );
1176             break;
1177     }
1178
1179     // find possible duplicate patrons
1180     fieldmapper.standardRequest(
1181         ['open-ils.actor', 'open-ils.actor.patron.search.advanced'],
1182         {   async: true,
1183             params: [openils.User.authtoken, search],
1184             oncomplete : function(r) {
1185                 var resp = openils.Util.readResponse(r);
1186                 resp = resp.filter(function(id) { return (id != patron.id()); });
1187
1188                 if(resp && resp.length > 0) {
1189
1190                     openils.Util.hide('uedit-help-div');
1191                     openils.Util.show('uedit-dupe-div');
1192                     var link;
1193
1194                     switch(type) {
1195                         case 'name':
1196                             link = dojo.byId('uedit-dupe-names-link');
1197                             link.innerHTML = dojo.string.substitute(localeStrings.DUPE_PATRON_NAME, [resp.length]);
1198                             break;
1199                         case 'email':
1200                             link = dojo.byId('uedit-dupe-email-link');
1201                             link.innerHTML = dojo.string.substitute(localeStrings.DUPE_PATRON_EMAIL, [resp.length]);
1202                             break;
1203                         case 'ident':
1204                             link = dojo.byId('uedit-dupe-ident-link');
1205                             link.innerHTML = dojo.string.substitute(localeStrings.DUPE_PATRON_IDENT, [resp.length]);
1206                             break;
1207                         case 'phone':
1208                             link = dojo.byId('uedit-dupe-phone-link');
1209                             link.innerHTML = dojo.string.substitute(localeStrings.DUPE_PATRON_PHONE, [resp.length]);
1210                             break;
1211                         case 'address':
1212                             link = dojo.byId('uedit-dupe-address-link');
1213                             link.innerHTML = dojo.string.substitute(localeStrings.DUPE_PATRON_ADDR, [resp.length]);
1214                             break;
1215                     }
1216
1217                     openils.Util.show(link);
1218                     link.onclick = function() {
1219                         search.search_sort = js2JSON(["penalties", "family_name", "first_given_name"]);
1220                         if(window.xulG)
1221                             window.xulG.spawn_search(search);
1222                         else
1223                             console.log("running XUL patron search " + js2JSON(search));
1224                     }
1225                 }
1226             }
1227         }
1228     );
1229 }
1230
1231 function getByName(node, name) {
1232     return dojo.query('[name='+name+']', node)[0];
1233 }
1234
1235
1236 function ueLoadContextHelp(fmcls, fmfield) {
1237     openils.Util.hide('uedit-dupe-div');
1238     openils.Util.show('uedit-help-div');
1239     dojo.byId('uedit-help-field').innerHTML = fieldmapper.IDL.fmclasses[fmcls].field_map[fmfield].label;
1240     dojo.byId('uedit-help-text').innerHTML = fieldDoc[fmcls][fmfield].string();
1241 }
1242
1243
1244 /* creates a new patron object with card attached */
1245 function uEditNewPatron() {
1246     patron = new au();
1247     patron.isnew(1);
1248     patron.id(-1);
1249     card = new ac();
1250     card.id(uEditCardVirtId--);
1251     card.isnew(1);
1252     patron.active(1);
1253     patron.card(card);
1254     patron.cards([card]);
1255     patron.net_access_level(orgSettings['ui.patron.default_inet_access_level'] || 1);
1256     patron.ident_type(orgSettings['ui.patron.default_ident_type']);
1257     patron.stat_cat_entries([]);
1258     patron.survey_responses([]);
1259     patron.addresses([]);
1260     uEditMakeRandomPw(patron);
1261     return patron;
1262 }
1263
1264 function uEditMakeRandomPw(patron) {
1265     if(uEditUsePhonePw) return;
1266     var rand  = Math.random();
1267     rand = parseInt(rand * 10000) + '';
1268     while(rand.length < 4) rand += '0';
1269 /*
1270     appendClear($('ue_password_plain'),text(rand));
1271     unHideMe($('ue_password_gen'));
1272 */
1273     patron.passwd(rand);
1274     return rand;
1275 }
1276
1277 function uEditWidgetVal(w) {
1278     var val = (w.getFormattedValue) ? w.getFormattedValue() : w.attr('value');
1279     if(val === '') val = null;
1280     return val;
1281 }
1282
1283 function uEditSave() { _uEditSave(); }
1284 function uEditSaveClone() { _uEditSave(true); }
1285
1286 function _uEditSave(doClone) {
1287
1288     if ( (! myForm.isValid()) || dupeUsrname || dupeBarcode ) {
1289         alert(localeStrings.INVALID_FORM);
1290         return;
1291     }
1292
1293     for(var idx in widgetPile) {
1294         var w = widgetPile[idx];
1295         var val = uEditWidgetVal(w);
1296
1297         switch(w._wtype) {
1298             case 'au':
1299                 if(w._fmfield != 'passwd2')
1300                     patron[w._fmfield](val);
1301                 break;
1302
1303             case 'ac':
1304                 patron.card()[w._fmfield](val);
1305                 break;
1306
1307             case 'aua':
1308                 var addr = patron.addresses().filter(function(i){return (i.id() == w._addr)})[0];
1309                 if(!addr) {
1310                     addr = new fieldmapper.aua();
1311                     addr.id(w._addr);
1312                     addr.isnew(1);
1313                     addr.usr(patron.id());
1314                     addr.country(orgSettings['ui.patron.default_country']);
1315                     var t = patron.addresses();
1316                         if (!t) { t = []; }
1317                         t.push(addr);
1318                         patron.addresses(t);
1319                 } else {
1320                     if(addr[w._fmfield]() != val)
1321                         addr.ischanged(1);
1322                 }
1323                 addr[w._fmfield](val);
1324
1325                 if(dojo.byId('uedit-billing-address-' + addr.id()).checked) 
1326                     patron.billing_address(addr.id());
1327
1328                 if(dojo.byId('uedit-mailing-address-' + addr.id()).checked)
1329                     patron.mailing_address(addr.id());
1330
1331                 break;
1332
1333             case 'survey':
1334                 if(val == null) break;
1335                 var resp = new fieldmapper.asvr();
1336                 resp.isnew(1);
1337                 resp.survey(w._survey)
1338                 resp.usr(patron.id());
1339                 resp.question(w._question)
1340                 resp.answer(val);
1341                 var t = patron.survey_responses();
1342                     if (!t) { t = []; }
1343                     t.push(resp);
1344                     patron.survey_responses(t);
1345                 break;
1346
1347             case 'statcat':
1348                 var map = patron.stat_cat_entries().filter(
1349                     function(m){
1350                         return (m.stat_cat() == w._statcat) })[0];
1351
1352                 if(map) {
1353                     if(map.stat_cat_entry() == val) 
1354                         break;
1355                     if(val == null) {
1356                         val = '';
1357                         map.isdeleted(1);
1358                     } else {
1359                         map.ischanged(1);
1360                     }
1361                 } else {
1362                     if(val == null)
1363                         break;
1364                     map = new fieldmapper.actscecm();
1365                     map.isnew(1);
1366                 }
1367
1368                 map.stat_cat(w._statcat);
1369                 map.stat_cat_entry(val);
1370                 map.target_usr(patron.id());
1371                 var t = patron.stat_cat_entries();
1372                     if (!t) { t = []; }
1373                     t.push(map);
1374                     patron.stat_cat_entries(t);
1375                 break;
1376         }
1377     }
1378
1379     patron.ischanged(1);
1380     fieldmapper.standardRequest(
1381         ['open-ils.actor', 'open-ils.actor.patron.update'],
1382         {   async: true,
1383             params: [openils.User.authtoken, patron],
1384             oncomplete: function(r) {
1385                 lock_ready = false;
1386                 if (xulG && typeof xulG.unlock_tab == 'function') {
1387                     xulG.unlock_tab();
1388                     already_locked = false;
1389                 }
1390                 newPatron = openils.Util.readResponse(r);
1391                 if(newPatron) {
1392                     uEditUpdateUserSettings(newPatron.id());
1393                     if(stageUser) uEditRemoveStage();
1394                     uEditFinishSave(newPatron, doClone);
1395                 }
1396             }
1397         }
1398     );
1399 }
1400
1401 function uEditRemoveStage() {
1402     var resp = fieldmapper.standardRequest(
1403         ['open-ils.actor', 'open-ils.actor.user.stage.delete'],
1404         { params : [openils.User.authtoken, stageUser.row_id()] }
1405     )
1406 }
1407
1408 function uEditFinishSave(newPatron, doClone) {
1409
1410     if(doClone && cloneUser == null)
1411         cloneUser = newPatron.id();
1412
1413         if( doClone ) {
1414
1415                 if(xulG && typeof xulG.spawn_editor == 'function' && !patron.isnew() ) {
1416             window.xulG.spawn_editor({ses:openils.User.authtoken,clone:cloneUser});
1417             uEditRefresh();
1418
1419                 } else {
1420                         location.href = location.href.replace(/\?.*/, '') + '?clone=' + cloneUser;
1421                 }
1422
1423         } else {
1424
1425                 uEditRefresh();
1426         }
1427
1428         uEditRefreshXUL(newPatron);
1429 }
1430
1431 function uEditRefresh() {
1432     var usr = cgi.param('usr');
1433     var href = location.href.replace(/\?.*/, '');
1434     href += ((usr) ? '?usr=' + usr : '');
1435     location.href = href;
1436 }
1437
1438 function uEditRefreshXUL(newuser) {
1439         if (window.xulG && typeof window.xulG.on_save == 'function') 
1440                 window.xulG.on_save(newuser);
1441 }
1442
1443
1444 /**
1445  * Create a new address and insert it into the DOM
1446  * @param evt ignored
1447  * @param id The address id
1448  * @param mkLinks If true, set the new address as the 
1449  *  mailing/billing address for the user
1450  */
1451 function uEditNewAddr(evt, id, mkLinks) {
1452
1453     if(id == null) 
1454         id = --uEditAddrVirtId; // new address
1455
1456     var addr =  patron.addresses().filter(
1457         function(i) { return (i.id() == id) })[0];
1458
1459     dojo.forEach(addrTemplateRows, 
1460         function(row) {
1461
1462             row = tbody.insertBefore(row.cloneNode(true), dojo.byId('new-addr-row'));
1463             row.setAttribute('type', '');
1464             row.setAttribute('addr', id+'');
1465
1466             if(row.getAttribute('fmclass')) {
1467                 var widget = fleshFMRow(row, 'aua', {addr:id});
1468
1469                 // make new addresses a default address type
1470                 if(id < 0 && row.getAttribute('fmfield') == 'address_type') 
1471                     widget.widget.attr('value', localeStrings.DEFAULT_ADDRESS_TYPE); 
1472
1473                 // make new addresses valid by default
1474                 if(id < 0 && row.getAttribute('fmfield') == 'valid') 
1475                     widget.widget.attr('value', true); 
1476
1477                 // make new addresses use the org setting for default country 
1478                 if(id < 0 && row.getAttribute('fmfield') == 'country') 
1479                     widget.widget.attr('value',orgSettings['ui.patron.default_country']);
1480
1481             } else if(row.getAttribute('name') == 'uedit-addr-pending-row') {
1482
1483                 // if it's a pending address, show the 'approve' button
1484                 if(addr && openils.Util.isTrue(addr.pending())) {
1485                     openils.Util.show(row, 'table-row');
1486                     dojo.query('[name=approve-button]', row)[0].onclick = 
1487                         function() { uEditApproveAddress(addr); };
1488
1489                     if(addr.replaces()) {
1490                         var div = dojo.query('[name=replaced-addr]', row)[0]
1491                         var replaced =  patron.addresses().filter(
1492                             function(i) { return (i.id() == addr.replaces()) })[0];
1493
1494                         div.innerHTML = dojo.string.substitute(localeStrings.REPLACED_ADDRESS, [
1495                             replaced.address_type() || '',
1496                             replaced.street1() || '',
1497                             replaced.street2() || '',
1498                             replaced.city() || '',
1499                             replaced.state() || '',
1500                             replaced.post_code() || ''
1501                         ]);
1502
1503                     } else {
1504                         openils.Util.hide(dojo.query('[name=replaced-addr-div]', row)[0]);
1505                     }
1506                 }
1507
1508             } else if(row.getAttribute('name') == 'uedit-addr-owner-row') {
1509                 // address is owned by someone else.  provide option to load the
1510                 // user in a different tab
1511                 
1512                 if(addr && addr.usr() != patron.id()) {
1513                     openils.Util.show(row, 'table-row');
1514                     var link = getByName(row, 'addr-owner');
1515
1516                     // fetch the linked user so we can present their name in the UI
1517                     var addrUser;
1518                     if(cloneUserObj && cloneUserObj.id() == addr.usr()) {
1519                         addrUser = [
1520                             cloneUserObj.first_given_name(), 
1521                             cloneUserObj.second_given_name(), 
1522                             cloneUserObj.family_name()
1523                         ];
1524                     } else {
1525                         addrUser = fieldmapper.standardRequest(
1526                             ['open-ils.actor', 'open-ils.actor.user.retrieve.parts'],
1527                             {params: [
1528                                 openils.User.authtoken, 
1529                                 addr.usr(), 
1530                                 ['first_given_name', 'second_given_name', 'family_name']
1531                             ]}
1532                         );
1533                     }
1534
1535                     link.innerHTML = (addrUser.map(function(name) { return (name) ? name+' ' : '' })+'').replace(/,/g,''); // TODO i18n
1536                     link.onclick = function() {
1537                         if(openils.XUL.isXUL()) { 
1538                             window.xulG.spawn_editor({ses:openils.User.authtoken, usr:addr.usr()})
1539                         } else {
1540                             parent.location.href = location.href.replace(/clone=\d+/, 'usr=' + addr.usr());
1541                         }
1542                     }
1543                 }
1544
1545             } else if(row.getAttribute('name') == 'uedit-addr-divider') {
1546                 // link up the billing/mailing address and give the inputs IDs so we can access the later
1547                 
1548                 // billing address
1549                 var ba = getByName(row, 'billing_address');
1550                 ba.id = 'uedit-billing-address-' + id;
1551                 if(mkLinks || (patron.billing_address() && patron.billing_address().id() == id))
1552                     ba.checked = true;
1553
1554                 // mailing address
1555                 var ma = getByName(row, 'mailing_address');
1556                 ma.id = 'uedit-mailing-address-' + id;
1557                 if(mkLinks || (patron.mailing_address() && patron.mailing_address().id() == id))
1558                     ma.checked = true;
1559
1560                 var btn = dojo.query('[name=delete-button]', row)[0];
1561                 if(btn) btn.onclick = function(){ uEditDeleteAddr(id) };
1562             }
1563         }
1564     );
1565 }
1566
1567 function uEditApproveAddress(addr) {
1568     fieldmapper.standardRequest(
1569         ['open-ils.actor', 'open-ils.actor.user.pending_address.approve'],
1570         {   async: true,
1571             params:  [openils.User.authtoken, addr],
1572
1573             oncomplete : function(r) {
1574                 var oldId = openils.Util.readResponse(r);
1575                     
1576                 // remove addrs from UI
1577                 dojo.forEach(
1578                     patron.addresses(), 
1579                     function(addr) { uEditDeleteAddr(addr.id(), true); }
1580                 );
1581
1582                 if(oldId != null) {
1583                     
1584                     // remove the replaced address 
1585                     if(oldId != addr.id()) {
1586                                 patron.addresses(
1587                             patron.addresses().filter(
1588                                                 function(i) { return (i.id() != oldId); }
1589                                         )
1590                                 );
1591                     }
1592                     
1593                     // fix the the new address
1594                     addr.id(oldId);
1595                     addr.replaces(null);
1596                     addr.pending('f');
1597
1598                 }
1599
1600                 // redraw addrs
1601                 loadAllAddrs();
1602             }
1603         }
1604     );
1605 }
1606
1607
1608 function uEditDeleteAddr(id, noAlert) {
1609     if (patron.isnew() && orgSettings['ui.patron.registration.require_address']) {
1610         if (dojo.query('tr[name=uedit-addr-divider]').length < 2) {
1611             alert(localeStrings.NEED_ADDRESS);
1612             return;
1613         }
1614     }
1615     if(!noAlert) {
1616         if(!confirm(dojo.string.substitute(localeStrings.DELETE_ADDRESS, [id]))) return;
1617     }
1618     var addr = patron.addresses().filter(function(i){return (i.id() == id)})[0];
1619     if (addr) { addr.isdeleted(1); }
1620     var m_a = patron.mailing_address();
1621         if (typeof m_a == 'object' && m_a != null) { m_a = m_a.id(); }
1622         if (m_a == id) { patron.mailing_address(null); }
1623     var b_a = patron.billing_address();
1624         if (typeof b_a == 'object' && b_a != null) { b_a = b_a.id(); }
1625         if (b_a == id) { patron.billing_address(null); }
1626
1627     var rows = dojo.query('tr[addr='+id+']', tbody);
1628     for(var i = 0; i < rows.length; i++)
1629         rows[i].parentNode.removeChild(rows[i]);
1630     widgetPile = widgetPile.filter(function(w){return (w._addr != id)});
1631 }
1632
1633 function uEditToggleRequired(level) {
1634     openils.Util.removeCSSClass(tbody, 'hide-non-required');
1635     openils.Util.removeCSSClass(tbody, 'hide-non-suggested');
1636     openils.Util.show('uedit-show-required');
1637     openils.Util.show('uedit-show-required-br');
1638     openils.Util.show('uedit-show-suggested');
1639     openils.Util.show('uedit-show-suggested-br');
1640     openils.Util.show('uedit-show-all');
1641     switch(level) {
1642         case 1:
1643             openils.Util.hide('uedit-show-required');
1644             openils.Util.hide('uedit-show-required-br');
1645             openils.Util.addCSSClass(tbody, 'hide-non-required');
1646             break;
1647         case 2:
1648             openils.Util.hide('uedit-show-suggested');
1649             openils.Util.hide('uedit-show-suggested-br');
1650             openils.Util.addCSSClass(tbody, 'hide-non-suggested');
1651             break;
1652         default:
1653             openils.Util.hide('uedit-show-all');
1654             break;
1655     } 
1656 }
1657
1658 function printable_output() {
1659     var temp; var s = '=-=-=-=\r\n';
1660     for (var idx in widgetPile) {
1661         var w = widgetPile[idx];
1662         var val = uEditWidgetVal(w);
1663         var label;
1664         if (typeof w.idlField == 'undefined') {
1665             label = w._wtype;
1666             if (w._wtype == 'statcat') {
1667                 var stat = statCats.filter(
1668                     function(m){
1669                         return (m.id() == w._statcat) })[0];
1670                 label = stat.name();
1671             } else if (w._wtype == 'survey') {
1672                 var survey = surveys.filter(
1673                     function(m){
1674                         return (m.id() == w._survey) })[0];
1675                 var question = survey.questions().filter(
1676                     function(m){
1677                         return (m.id() == w._question) })[0];
1678                 label = survey.name() + ' : ' + question.question();
1679             } else {
1680                 label = 'FIXME';
1681             }
1682         } else {
1683             label = w.idlField.label;
1684         }
1685         if (temp != w._wtype) {
1686             temp = w._wtype;
1687             s += '-------\r\n';
1688         }
1689         s += label + ':\t' + (typeof val == 'object' ? '' : val) + '\r\n';
1690     }
1691     s += '=-=-=-=\r\n';
1692     return s;
1693 }
1694
1695 openils.Util.addOnLoad(load);