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