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