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