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