]> git.evergreen-ils.org Git - working/Evergreen.git/blob - Open-ILS/web/js/ui/default/actor/user/register.js
allow deletion of stat cat entries in the patron editor (or more accurately, rows...
[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(ev){
768             netscape.security.PrivilegeManager.enablePrivilege('UniversalXPConnect');
769             if (!(ev.altKey || ev.ctrlKey || ev.metaKey)) {
770                 if (lock_ready && xulG && typeof xulG.lock_tab == 'function') {
771                     if (! already_locked) {
772                         xulG.lock_tab();
773                         already_locked = true;
774                     }
775                 }
776             }
777         }
778     );
779     dojo.connect(
780         widget.widget,
781         'onChange',
782         function(){
783             if (lock_ready && xulG && typeof xulG.lock_tab == 'function') {
784                 if (! already_locked) {
785                     xulG.lock_tab();
786                     already_locked = true;
787                 }
788             }
789         }
790     );
791
792
793     if(fmcls == 'ac') {
794         if(fmfield == 'barcode') {
795             dojo.connect(widget.widget, 'onChange',
796                 function() {
797                     var barcode = this.attr('value');
798                     dupeBarcode = false;
799                     dojo.addClass(dojo.byId('uedit-dupe-barcode-warning'), 'hidden');
800                     fieldmapper.standardRequest(
801                         ['open-ils.actor', 'open-ils.actor.barcode.exists'],
802                         {
803                             params: [openils.User.authtoken, barcode],
804                             oncomplete : function(r) {
805                                 var res = openils.Util.readResponse(r);
806                                 if(res == '1') {
807                                     dupeBarcode = true;
808                                     dojo.removeClass(dojo.byId('uedit-dupe-barcode-warning'), 'hidden');
809                                 } else {
810                                     dupeBarcode = false;
811                                     dojo.addClass(dojo.byId('uedit-dupe-barcode-warning'), 'hidden');
812                                     var un = findWidget('au', 'usrname');
813                                     if(!un.widget.attr('value'))
814                                         un.widget.attr('value', barcode);
815                                 }
816                             }
817                         }
818                     );
819                 }
820             );
821             return;
822         }
823     }
824
825     if(fmcls == 'au') {
826         switch(fmfield) {
827
828             case 'usrname':
829                 dojo.connect(widget.widget, 'onChange', 
830                     function() {
831                         var input = findWidget('au', 'usrname');
832                         var usrname = input.widget.attr('value');
833
834                         if(!usrname) {
835                             dupeUsrname = false;
836                             dojo.addClass(dojo.byId('uedit-dupe-username-warning'), 'hidden');
837                             return;
838                         }
839
840                         fieldmapper.standardRequest(
841                             ['open-ils.actor', 'open-ils.actor.username.exists'],
842                             {
843                                 params: [openils.User.authtoken, usrname],
844                                 oncomplete : function(r) {
845                                     var res = openils.Util.readResponse(r);
846                                     if(res) {
847                                         dupeUsrname = true;
848                                         dojo.removeClass(dojo.byId('uedit-dupe-username-warning'), 'hidden');
849                                     } else {
850                                         dupeUsrname = false;
851                                         dojo.addClass(dojo.byId('uedit-dupe-username-warning'), 'hidden');
852                                     }
853                                 }
854                             }
855                         );
856                     }   
857                 );
858
859                 return;
860
861             case 'profile': // when the profile changes, update the expire date
862                 dojo.connect(widget.widget, 'onChange', 
863                     function() {
864                         var self = this;
865                         var expireWidget = findWidget('au', 'expire_date');
866                         function found(items) {
867                             if(items.length == 0) return;
868                             var item = items[0];
869                             var interval = self.store.getValue(item, 'perm_interval');
870                             expireWidget.widget.attr('value', dojo.date.add(new Date(), 
871                                 'second', openils.Util.intervalToSeconds(interval)));
872                         }
873                         this.store.fetch({onComplete:found, query:{id:this.attr('value')}});
874                     }
875                 );
876                 return;
877
878             case 'dob':
879                 dojo.connect(widget.widget, 'onChange',
880                     function(newDob) {
881                         if(!newDob) return;
882                         var oldDob = patron.dob();
883                         if(dojo.date.stamp.fromISOString(oldDob) == newDob) return;
884
885                         var juvInterval = orgSettings['global.juvenile_age_threshold'] || '18 years';
886                         var juvWidget = findWidget('au', 'juvenile');
887                         var base = new Date();
888                         base.setTime(base.getTime() - Number(openils.Util.intervalToSeconds(juvInterval) + '000'));
889
890                         if(newDob <= base) // older than global.juvenile_age_threshold
891                             juvWidget.widget.attr('value', false);
892                         else
893                             juvWidget.widget.attr('value', true);
894                     }
895                 );
896                 return;
897
898             case 'first_given_name':
899             case 'family_name':
900                 dojo.connect(widget.widget, 'onChange',
901                     function(newVal) { uEditDupeSearch('name', newVal); });
902                 return;
903
904             case 'email':
905                 dojo.connect(widget.widget, 'onChange',
906                     function(newVal) { uEditDupeSearch('email', newVal); });
907                 return;
908
909             case 'ident_value':
910             case 'ident_value2':
911                 dojo.connect(widget.widget, 'onChange',
912                     function(newVal) { uEditDupeSearch('ident', newVal); });
913                 return;
914
915             case 'day_phone':
916                 // if configured, use the last for digits of the day phone number as the password
917                 if(uEditUsePhonePw && patron.isnew()) {
918                     dojo.connect(widget.widget, 'onChange',
919                         function(newVal) {
920                             if(newVal && newVal.length >= 4) {
921                                 var pw1 = findWidget('au', 'passwd').widget;
922                                 var pw2 = findWidget('au', 'passwd2').widget;
923                                 pw1.attr('value', newVal.substring(newVal.length - 4));
924                                 pw2.attr('value', newVal.substring(newVal.length - 4));
925                             }
926                         }
927                     );
928                 }
929             case 'evening_phone':
930             case 'other_phone':
931                 dojo.connect(widget.widget, 'onChange',
932                     function(newVal) { uEditDupeSearch('phone', newVal); });
933                 return;
934
935             case 'home_ou':
936                 dojo.connect(widget.widget, 'onChange',
937                     function(newVal) { 
938                         checkClaimsReturnCountPerm(); 
939                         checkClaimsNoCheckoutCountPerm();
940                     }
941                 );
942                 return;
943
944             case 'passwd':
945                 dojo.connect(widget.widget, 'onChange',
946                     function(newVal) {
947                         var pw1 = findWidget('au', 'passwd').widget;
948                         var pw2 = findWidget('au', 'passwd2').widget;
949                         var preserved_value = pw2.attr('value');
950                         // Ensure that the pw2 field match the pw1 field to validate
951                         pw2.regExp = newVal.replace(/([.\\^$*+?\(\)\[\]\{\}])/g, '\\$1');
952                         pw2.reset();
953                         pw2.attr('value',preserved_value);
954                     });
955                 return;
956         }
957     }
958
959     if(fmclass = 'aua') {
960         switch(fmfield) {
961             case 'post_code':
962                 dojo.connect(widget.widget, 'onChange',
963                     function(e) { 
964                         fieldmapper.standardRequest(
965                             ['open-ils.search', 'open-ils.search.zip'],
966                             {   async: true,
967                                 params: [e],
968                                 oncomplete : function(r) {
969                                     var res = openils.Util.readResponse(r);
970                                     if(!res) return;
971                                     var callback = function(w) { return w._addr == widget._addr; };
972                                     if(res.city) findWidget('aua', 'city', callback).widget.attr('value', res.city);
973                                     if(res.state) findWidget('aua', 'state', callback).widget.attr('value', res.state);
974                                     if(res.county) findWidget('aua', 'county', callback).widget.attr('value', res.county);
975                                     if(res.alert) alert(res.alert);
976                                 }
977                             }
978                         );
979                     }
980                 );
981                 return;
982
983             case 'street1':
984             case 'street2':
985             case 'city':
986                 dojo.connect(widget.widget, 'onChange',
987                     function(e) {
988                         var callback = function(w) { return w._addr == widget._addr; };
989                         var args = {
990                             street1 : findWidget('aua', 'street1', callback).widget.attr('value'),
991                             street2 : findWidget('aua', 'street2', callback).widget.attr('value'),
992                             city : findWidget('aua', 'city', callback).widget.attr('value'),
993                             post_code : findWidget('aua', 'post_code', callback).widget.attr('value')
994                         };
995                         if(args.street1 && args.city && args.post_code)
996                             uEditDupeSearch('address', args); 
997                     }
998                 );
999                 return;
1000         }
1001     }
1002 }
1003
1004 function uEditDupeSearch(type, value) {
1005     if(!value) return;
1006     var search;
1007     switch(type) {
1008
1009         case 'name':
1010             openils.Util.hide('uedit-dupe-names-link');
1011             var fname = findWidget('au', 'first_given_name').widget.attr('value');
1012             var lname = findWidget('au', 'family_name').widget.attr('value');
1013             if( !(fname && lname) ) return;
1014             search = {
1015                 first_given_name : {value : fname, group : 0},
1016                 family_name : {value : lname, group : 0},
1017             };
1018             break;
1019
1020         case 'email':
1021             openils.Util.hide('uedit-dupe-email-link');
1022             search = {email : {value : value, group : 0}};
1023             break;
1024
1025         case 'ident':
1026             openils.Util.hide('uedit-dupe-ident-link');
1027             search = {ident : {value : value, group : 2}};
1028             break;
1029
1030         case 'phone':
1031             openils.Util.hide('uedit-dupe-phone-link');
1032             search = {phone : {value : value, group : 2}};
1033             break;
1034
1035         case 'address':
1036             openils.Util.hide('uedit-dupe-address-link');
1037             search = {};
1038             dojo.forEach(['street1', 'street2', 'city', 'post_code'],
1039                 function(field) {
1040                     if(value[field])
1041                         search[field] = {value : value[field], group: 1};
1042                 }
1043             );
1044             break;
1045     }
1046
1047     // find possible duplicate patrons
1048     fieldmapper.standardRequest(
1049         ['open-ils.actor', 'open-ils.actor.patron.search.advanced'],
1050         {   async: true,
1051             params: [openils.User.authtoken, search],
1052             oncomplete : function(r) {
1053                 var resp = openils.Util.readResponse(r);
1054                 resp = resp.filter(function(id) { return (id != patron.id()); });
1055
1056                 if(resp && resp.length > 0) {
1057
1058                     openils.Util.hide('uedit-help-div');
1059                     openils.Util.show('uedit-dupe-div');
1060                     var link;
1061
1062                     switch(type) {
1063                         case 'name':
1064                             link = dojo.byId('uedit-dupe-names-link');
1065                             link.innerHTML = dojo.string.substitute(localeStrings.DUPE_PATRON_NAME, [resp.length]);
1066                             break;
1067                         case 'email':
1068                             link = dojo.byId('uedit-dupe-email-link');
1069                             link.innerHTML = dojo.string.substitute(localeStrings.DUPE_PATRON_EMAIL, [resp.length]);
1070                             break;
1071                         case 'ident':
1072                             link = dojo.byId('uedit-dupe-ident-link');
1073                             link.innerHTML = dojo.string.substitute(localeStrings.DUPE_PATRON_IDENT, [resp.length]);
1074                             break;
1075                         case 'phone':
1076                             link = dojo.byId('uedit-dupe-phone-link');
1077                             link.innerHTML = dojo.string.substitute(localeStrings.DUPE_PATRON_PHONE, [resp.length]);
1078                             break;
1079                         case 'address':
1080                             link = dojo.byId('uedit-dupe-address-link');
1081                             link.innerHTML = dojo.string.substitute(localeStrings.DUPE_PATRON_ADDR, [resp.length]);
1082                             break;
1083                     }
1084
1085                     openils.Util.show(link);
1086                     link.onclick = function() {
1087                         search.search_sort = js2JSON(["penalties", "family_name", "first_given_name"]);
1088                         if(window.xulG)
1089                             window.xulG.spawn_search(search);
1090                         else
1091                             console.log("running XUL patron search " + js2JSON(search));
1092                     }
1093                 }
1094             }
1095         }
1096     );
1097 }
1098
1099 function getByName(node, name) {
1100     return dojo.query('[name='+name+']', node)[0];
1101 }
1102
1103
1104 function ueLoadContextHelp(fmcls, fmfield) {
1105     openils.Util.hide('uedit-dupe-div');
1106     openils.Util.show('uedit-help-div');
1107     dojo.byId('uedit-help-field').innerHTML = fieldmapper.IDL.fmclasses[fmcls].field_map[fmfield].label;
1108     dojo.byId('uedit-help-text').innerHTML = fieldDoc[fmcls][fmfield].string();
1109 }
1110
1111
1112 /* creates a new patron object with card attached */
1113 function uEditNewPatron() {
1114     patron = new au();
1115     patron.isnew(1);
1116     patron.id(-1);
1117     card = new ac();
1118     card.id(uEditCardVirtId--);
1119     card.isnew(1);
1120     patron.active(1);
1121     patron.card(card);
1122     patron.cards([card]);
1123     patron.net_access_level(orgSettings['ui.patron.default_inet_access_level'] || 1);
1124     patron.ident_type(orgSettings['ui.patron.default_ident_type']);
1125     patron.stat_cat_entries([]);
1126     patron.survey_responses([]);
1127     patron.addresses([]);
1128     uEditMakeRandomPw(patron);
1129     return patron;
1130 }
1131
1132 function uEditMakeRandomPw(patron) {
1133     if(uEditUsePhonePw) return;
1134     var rand  = Math.random();
1135     rand = parseInt(rand * 10000) + '';
1136     while(rand.length < 4) rand += '0';
1137 /*
1138     appendClear($('ue_password_plain'),text(rand));
1139     unHideMe($('ue_password_gen'));
1140 */
1141     patron.passwd(rand);
1142     return rand;
1143 }
1144
1145 function uEditWidgetVal(w) {
1146     var val = (w.getFormattedValue) ? w.getFormattedValue() : w.attr('value');
1147     if(val === '') val = null;
1148     return val;
1149 }
1150
1151 function uEditSave() { _uEditSave(); }
1152 function uEditSaveClone() { _uEditSave(true); }
1153
1154 function _uEditSave(doClone) {
1155
1156     if ( (! myForm.isValid()) || dupeUsrname || dupeBarcode ) {
1157         alert(localeStrings.INVALID_FORM);
1158         return;
1159     }
1160
1161     for(var idx in widgetPile) {
1162         var w = widgetPile[idx];
1163         var val = uEditWidgetVal(w);
1164
1165         switch(w._wtype) {
1166             case 'au':
1167                 if(w._fmfield != 'passwd2')
1168                     patron[w._fmfield](val);
1169                 break;
1170
1171             case 'ac':
1172                 patron.card()[w._fmfield](val);
1173                 break;
1174
1175             case 'aua':
1176                 var addr = patron.addresses().filter(function(i){return (i.id() == w._addr)})[0];
1177                 if(!addr) {
1178                     addr = new fieldmapper.aua();
1179                     addr.id(w._addr);
1180                     addr.isnew(1);
1181                     addr.usr(patron.id());
1182                     addr.country(orgSettings['ui.patron.default_country']);
1183                     var t = patron.addresses();
1184                         if (!t) { t = []; }
1185                         t.push(addr);
1186                         patron.addresses(t);
1187                 } else {
1188                     if(addr[w._fmfield]() != val)
1189                         addr.ischanged(1);
1190                 }
1191                 addr[w._fmfield](val);
1192
1193                 if(dojo.byId('uedit-billing-address-' + addr.id()).checked) 
1194                     patron.billing_address(addr.id());
1195
1196                 if(dojo.byId('uedit-mailing-address-' + addr.id()).checked)
1197                     patron.mailing_address(addr.id());
1198
1199                 break;
1200
1201             case 'survey':
1202                 if(val == null) break;
1203                 var resp = new fieldmapper.asvr();
1204                 resp.isnew(1);
1205                 resp.survey(w._survey)
1206                 resp.usr(patron.id());
1207                 resp.question(w._question)
1208                 resp.answer(val);
1209                 var t = patron.survey_responses();
1210                     if (!t) { t = []; }
1211                     t.push(resp);
1212                     patron.survey_responses(t);
1213                 break;
1214
1215             case 'statcat':
1216                 var map = patron.stat_cat_entries().filter(
1217                     function(m){
1218                         return (m.stat_cat() == w._statcat) })[0];
1219
1220                 if(map) {
1221                     if(map.stat_cat_entry() == val) 
1222                         break;
1223                     if(val == null) {
1224                         val = '';
1225                         map.isdeleted(1);
1226                     } else {
1227                         map.ischanged(1);
1228                     }
1229                 } else {
1230                     if(val == null)
1231                         break;
1232                     map = new fieldmapper.actscecm();
1233                     map.isnew(1);
1234                 }
1235
1236                 map.stat_cat(w._statcat);
1237                 map.stat_cat_entry(val);
1238                 map.target_usr(patron.id());
1239                 var t = patron.stat_cat_entries();
1240                     if (!t) { t = []; }
1241                     t.push(map);
1242                     patron.stat_cat_entries(t);
1243                 break;
1244         }
1245     }
1246
1247     patron.ischanged(1);
1248     fieldmapper.standardRequest(
1249         ['open-ils.actor', 'open-ils.actor.patron.update'],
1250         {   async: true,
1251             params: [openils.User.authtoken, patron],
1252             oncomplete: function(r) {
1253                 lock_ready = false;
1254                 if (xulG && typeof xulG.unlock_tab == 'function') {
1255                     xulG.unlock_tab();
1256                     already_locked = false;
1257                 }
1258                 newPatron = openils.Util.readResponse(r);
1259                 if(newPatron) {
1260                     uEditUpdateUserSettings(newPatron.id());
1261                     if(stageUser) uEditRemoveStage();
1262                     uEditFinishSave(newPatron, doClone);
1263                 }
1264             }
1265         }
1266     );
1267 }
1268
1269 function uEditRemoveStage() {
1270     var resp = fieldmapper.standardRequest(
1271         ['open-ils.actor', 'open-ils.actor.user.stage.delete'],
1272         { params : [openils.User.authtoken, stageUser.row_id()] }
1273     )
1274 }
1275
1276 function uEditFinishSave(newPatron, doClone) {
1277
1278     if(doClone && cloneUser == null)
1279         cloneUser = newPatron.id();
1280
1281         if( doClone ) {
1282
1283                 if(xulG && typeof xulG.spawn_editor == 'function' && !patron.isnew() ) {
1284             window.xulG.spawn_editor({ses:openils.User.authtoken,clone:cloneUser});
1285             uEditRefresh();
1286
1287                 } else {
1288                         location.href = location.href.replace(/\?.*/, '') + '?clone=' + cloneUser;
1289                 }
1290
1291         } else {
1292
1293                 uEditRefresh();
1294         }
1295
1296         uEditRefreshXUL(newPatron);
1297 }
1298
1299 function uEditRefresh() {
1300     var usr = cgi.param('usr');
1301     var href = location.href.replace(/\?.*/, '');
1302     href += ((usr) ? '?usr=' + usr : '');
1303     location.href = href;
1304 }
1305
1306 function uEditRefreshXUL(newuser) {
1307         if (window.xulG && typeof window.xulG.on_save == 'function') 
1308                 window.xulG.on_save(newuser);
1309 }
1310
1311
1312 /**
1313  * Create a new address and insert it into the DOM
1314  * @param evt ignored
1315  * @param id The address id
1316  * @param mkLinks If true, set the new address as the 
1317  *  mailing/billing address for the user
1318  */
1319 function uEditNewAddr(evt, id, mkLinks) {
1320
1321     if(id == null) 
1322         id = --uEditAddrVirtId; // new address
1323
1324     var addr =  patron.addresses().filter(
1325         function(i) { return (i.id() == id) })[0];
1326
1327     dojo.forEach(addrTemplateRows, 
1328         function(row) {
1329
1330             row = tbody.insertBefore(row.cloneNode(true), dojo.byId('new-addr-row'));
1331             row.setAttribute('type', '');
1332             row.setAttribute('addr', id+'');
1333
1334             if(row.getAttribute('fmclass')) {
1335                 var widget = fleshFMRow(row, 'aua', {addr:id});
1336
1337                 // make new addresses a default address type
1338                 if(id < 0 && row.getAttribute('fmfield') == 'address_type') 
1339                     widget.widget.attr('value', localeStrings.DEFAULT_ADDRESS_TYPE); 
1340
1341                 // make new addresses valid by default
1342                 if(id < 0 && row.getAttribute('fmfield') == 'valid') 
1343                     widget.widget.attr('value', true); 
1344
1345                 // make new addresses use the org setting for default country 
1346                 if(id < 0 && row.getAttribute('fmfield') == 'country') 
1347                     widget.widget.attr('value',orgSettings['ui.patron.default_country']);
1348
1349             } else if(row.getAttribute('name') == 'uedit-addr-pending-row') {
1350
1351                 // if it's a pending address, show the 'approve' button
1352                 if(addr && openils.Util.isTrue(addr.pending())) {
1353                     openils.Util.show(row, 'table-row');
1354                     dojo.query('[name=approve-button]', row)[0].onclick = 
1355                         function() { uEditApproveAddress(addr); };
1356
1357                     if(addr.replaces()) {
1358                         var div = dojo.query('[name=replaced-addr]', row)[0]
1359                         var replaced =  patron.addresses().filter(
1360                             function(i) { return (i.id() == addr.replaces()) })[0];
1361
1362                         div.innerHTML = dojo.string.substitute(localeStrings.REPLACED_ADDRESS, [
1363                             replaced.address_type() || '',
1364                             replaced.street1() || '',
1365                             replaced.street2() || '',
1366                             replaced.city() || '',
1367                             replaced.state() || '',
1368                             replaced.post_code() || ''
1369                         ]);
1370
1371                     } else {
1372                         openils.Util.hide(dojo.query('[name=replaced-addr-div]', row)[0]);
1373                     }
1374                 }
1375
1376             } else if(row.getAttribute('name') == 'uedit-addr-owner-row') {
1377                 // address is owned by someone else.  provide option to load the
1378                 // user in a different tab
1379                 
1380                 if(addr && addr.usr() != patron.id()) {
1381                     openils.Util.show(row, 'table-row');
1382                     var link = getByName(row, 'addr-owner');
1383
1384                     // fetch the linked user so we can present their name in the UI
1385                     var addrUser;
1386                     if(cloneUserObj && cloneUserObj.id() == addr.usr()) {
1387                         addrUser = [
1388                             cloneUserObj.first_given_name(), 
1389                             cloneUserObj.second_given_name(), 
1390                             cloneUserObj.family_name()
1391                         ];
1392                     } else {
1393                         addrUser = fieldmapper.standardRequest(
1394                             ['open-ils.actor', 'open-ils.actor.user.retrieve.parts'],
1395                             {params: [
1396                                 openils.User.authtoken, 
1397                                 addr.usr(), 
1398                                 ['first_given_name', 'second_given_name', 'family_name']
1399                             ]}
1400                         );
1401                     }
1402
1403                     link.innerHTML = (addrUser.map(function(name) { return (name) ? name+' ' : '' })+'').replace(/,/g,''); // TODO i18n
1404                     link.onclick = function() {
1405                         if(openils.XUL.isXUL()) { 
1406                             window.xulG.spawn_editor({ses:openils.User.authtoken, usr:addr.usr()})
1407                         } else {
1408                             parent.location.href = location.href.replace(/clone=\d+/, 'usr=' + addr.usr());
1409                         }
1410                     }
1411                 }
1412
1413             } else if(row.getAttribute('name') == 'uedit-addr-divider') {
1414                 // link up the billing/mailing address and give the inputs IDs so we can acces the later
1415                 
1416                 // billing address
1417                 var ba = getByName(row, 'billing_address');
1418                 ba.id = 'uedit-billing-address-' + id;
1419                 if(mkLinks || (patron.billing_address() && patron.billing_address().id() == id))
1420                     ba.checked = true;
1421
1422                 // mailing address
1423                 var ma = getByName(row, 'mailing_address');
1424                 ma.id = 'uedit-mailing-address-' + id;
1425                 if(mkLinks || (patron.mailing_address() && patron.mailing_address().id() == id))
1426                     ma.checked = true;
1427
1428                 var btn = dojo.query('[name=delete-button]', row)[0];
1429                 if(btn) btn.onclick = function(){ uEditDeleteAddr(id) };
1430             }
1431         }
1432     );
1433 }
1434
1435 function uEditApproveAddress(addr) {
1436     fieldmapper.standardRequest(
1437         ['open-ils.actor', 'open-ils.actor.user.pending_address.approve'],
1438         {   async: true,
1439             params:  [openils.User.authtoken, addr],
1440
1441             oncomplete : function(r) {
1442                 var oldId = openils.Util.readResponse(r);
1443                     
1444                 // remove addrs from UI
1445                 dojo.forEach(
1446                     patron.addresses(), 
1447                     function(addr) { uEditDeleteAddr(addr.id(), true); }
1448                 );
1449
1450                 if(oldId != null) {
1451                     
1452                     // remove the replaced address 
1453                     if(oldId != addr.id()) {
1454                                 patron.addresses(
1455                             patron.addresses().filter(
1456                                                 function(i) { return (i.id() != oldId); }
1457                                         )
1458                                 );
1459                     }
1460                     
1461                     // fix the the new address
1462                     addr.id(oldId);
1463                     addr.replaces(null);
1464                     addr.pending('f');
1465
1466                 }
1467
1468                 // redraw addrs
1469                 loadAllAddrs();
1470             }
1471         }
1472     );
1473 }
1474
1475
1476 function uEditDeleteAddr(id, noAlert) {
1477     if (patron.isnew() && orgSettings['ui.patron.registration.require_address']) {
1478         if (dojo.query('tr[name=uedit-addr-divider]').length < 2) {
1479             alert(localeStrings.NEED_ADDRESS);
1480             return;
1481         }
1482     }
1483     if(!noAlert) {
1484         if(!confirm(dojo.string.substitute(localeStrings.DELETE_ADDRESS, [id]))) return;
1485     }
1486     var addr = patron.addresses().filter(function(i){return (i.id() == id)})[0];
1487     if (addr) { addr.isdeleted(1); }
1488     var m_a = patron.mailing_address();
1489         if (typeof m_a == 'object' && m_a != null) { m_a = m_a.id(); }
1490         if (m_a == id) { patron.mailing_address(null); }
1491     var b_a = patron.billing_address();
1492         if (typeof b_a == 'object' && b_a != null) { b_a = b_a.id(); }
1493         if (b_a == id) { patron.billing_address(null); }
1494
1495     var rows = dojo.query('tr[addr='+id+']', tbody);
1496     for(var i = 0; i < rows.length; i++)
1497         rows[i].parentNode.removeChild(rows[i]);
1498     widgetPile = widgetPile.filter(function(w){return (w._addr != id)});
1499 }
1500
1501 function uEditToggleRequired() {
1502     if((tbody.className +'').match(/hide-non-required/)) 
1503         openils.Util.removeCSSClass(tbody, 'hide-non-required');
1504     else
1505         openils.Util.addCSSClass(tbody, 'hide-non-required');
1506     openils.Util.toggle('uedit-show-required');
1507     openils.Util.toggle('uedit-show-all');
1508 }
1509
1510 function printable_output() {
1511     var temp; var s = '=-=-=-=\r\n';
1512     for (var idx in widgetPile) {
1513         var w = widgetPile[idx];
1514         var val = uEditWidgetVal(w);
1515         var label;
1516         if (typeof w.idlField == 'undefined') {
1517             label = w._wtype;
1518             if (w._wtype == 'statcat') {
1519                 var stat = statCats.filter(
1520                     function(m){
1521                         return (m.id() == w._statcat) })[0];
1522                 label = stat.name();
1523             } else if (w._wtype == 'survey') {
1524                 var survey = surveys.filter(
1525                     function(m){
1526                         return (m.id() == w._survey) })[0];
1527                 var question = survey.questions().filter(
1528                     function(m){
1529                         return (m.id() == w._question) })[0];
1530                 label = survey.name() + ' : ' + question.question();
1531             } else {
1532                 label = 'FIXME';
1533             }
1534         } else {
1535             label = w.idlField.label;
1536         }
1537         if (temp != w._wtype) {
1538             temp = w._wtype;
1539             s += '-------\r\n';
1540         }
1541         s += label + ':\t' + (typeof val == 'object' ? '' : val) + '\r\n';
1542     }
1543     s += '=-=-=-=\r\n';
1544     return s;
1545 }
1546
1547 openils.Util.addOnLoad(load);