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