]> git.evergreen-ils.org Git - working/Evergreen.git/blob - Open-ILS/web/js/ui/default/actor/user/register.js
in patron editor, prevent Save and Save & Clone from working with an invalid form...
[working/Evergreen.git] / Open-ILS / web / js / ui / default / actor / user / register.js
1 dojo.require('dojo.data.ItemFileReadStore');
2 dojo.require('dijit.form.Textarea');
3 dojo.require('dijit.form.FilteringSelect');
4 dojo.require('dijit.form.ComboBox');
5 dojo.require('dijit.form.NumberSpinner');
6 dojo.require('fieldmapper.IDL');
7 dojo.require('openils.PermaCrud');
8 dojo.require('openils.widget.AutoGrid');
9 dojo.require('openils.widget.AutoFieldWidget');
10 dojo.require('dijit.form.CheckBox');
11 dojo.require('dijit.form.Button');
12 dojo.require('dojo.date');
13 dojo.require('openils.CGI');
14 dojo.require('openils.XUL');
15 dojo.require('openils.Util');
16 dojo.require('openils.Event');
17
18 dojo.requireLocalization('openils.actor', 'register');
19 var localeStrings = dojo.i18n.getLocalization('openils.actor', 'register');
20
21
22 var pcrud;
23 var fmClasses = ['au', 'ac', 'aua', 'actsc', 'asv', 'asvq', 'asva'];
24 var fieldDoc = {};
25 var statCats;
26 var statCatTemplate;
27 var surveys;
28 var staff;
29 var patron;
30 var uEditUsePhonePw = false;
31 var widgetPile = [];
32 var uEditCardVirtId = -1;
33 var uEditAddrVirtId = -1;
34 var orgSettings = {};
35 var userSettings = {};
36 var userSettingsToUpdate = {};
37 var userSettingTypes;
38 var tbody;
39 var addrTemplateRows;
40 var cgi;
41 var cloneUser;
42 var cloneUserObj;
43 var stageUser;
44 var optInSettings;
45 var allCardsTemplate;
46
47 var dupeUsrname = false;
48 var dupeBarcode = false;
49
50 if(!window.xulG) var xulG = null;
51
52
53 function load() {
54     staff = new openils.User().user;
55     pcrud = new openils.PermaCrud();
56     cgi = new openils.CGI();
57     cloneUser = cgi.param('clone');
58     var userId = cgi.param('usr');
59     var stageUname = cgi.param('stage');
60
61     if(xulG) {
62             if(xulG.ses) openils.User.authtoken = xulG.ses;
63             if(typeof xulG.clone != 'undefined') cloneUser = xulG.clone;
64         if(typeof xulG.usr != 'undefined') userId = xulG.usr
65         if(typeof xulG.params != 'undefined') {
66             var parms = xulG.params;
67                 if(typeof parms.ses != 'undefined') 
68                 openils.User.authtoken = parms.ses;
69                 if(typeof parms.clone != 'undefined') 
70                 cloneUser = parms.clone;
71             if(typeof parms.usr != 'undefined')
72                 userId = parms.usr;
73             if(typeof parms.stage != 'undefined')
74                 stageUname = parms.stage
75         }
76     }
77
78     orgSettings = fieldmapper.aou.fetchOrgSettingBatch(staff.ws_ou(), [
79         'global.password_regex',
80         'global.juvenile_age_threshold',
81         'patron.password.use_phone',
82         'ui.patron.default_inet_access_level',
83         'circ.holds.behind_desk_pickup_supported'
84     ]);
85     for(k in orgSettings)
86         if(orgSettings[k])
87             orgSettings[k] = orgSettings[k].value;
88
89     uEditUsePhonePw = orgSettings['patron.password.use_phone'];
90     uEditFetchUserSettings(userId);
91
92     if(userId) {
93         patron = uEditLoadUser(userId);
94     } else {
95         if(stageUname) {
96             patron = uEditLoadStageUser(stageUname);
97         } else {
98             patron = uEditNewPatron();
99             if(cloneUser) 
100                 uEditCopyCloneData(patron);
101         }
102     }
103
104
105     var list = pcrud.search('fdoc', {fm_class:fmClasses});
106     for(var i in list) {
107         var doc = list[i];
108         if(!fieldDoc[doc.fm_class()])
109             fieldDoc[doc.fm_class()] = {};
110         fieldDoc[doc.fm_class()][doc.field()] = doc;
111     }
112
113     tbody = dojo.byId('uedit-tbody');
114
115     addrTemplateRows = dojo.query('tr[type=addr-template]', tbody);
116     dojo.forEach(addrTemplateRows, function(row) { row.parentNode.removeChild(row); } );
117     statCatTemplate = tbody.removeChild(dojo.byId('stat-cat-row-template'));
118     surveyTemplate = tbody.removeChild(dojo.byId('survey-row-template'));
119     surveyQuestionTemplate = tbody.removeChild(dojo.byId('survey-question-row-template'));
120
121     loadStaticFields();
122     if(patron.isnew() && patron.addresses().length == 0) 
123         uEditNewAddr(null, uEditAddrVirtId, true);
124     else loadAllAddrs();
125     loadStatCats();
126     loadSurveys();
127     checkClaimsReturnCountPerm();
128     checkClaimsNoCheckoutCountPerm();
129
130     dojo.connect(replaceBarcode, 'onClick', replaceCardHandler);
131     dojo.connect(allCards, 'onClick', drawAllCards);
132     if(patron.cards().length > 1)
133         dojo.removeClass(dojo.byId('uedit-all-barcodes'), 'hidden');
134 }
135
136
137 function drawAllCards() {
138
139     var tbody = dojo.byId('uedit-all-cards-tbody');
140     if(!allCardsTemplate) {
141         allCardsTemplate = tbody.removeChild(dojo.byId('uedit-all-cards-tr-template'));
142     } else {
143         while(tbody.childNodes[0])
144             tbody.removeChild(tbody.childNodes[0]);
145     }
146
147     var first = true;
148     dojo.forEach(
149         [patron.card()].concat(patron.cards()), // grab the main card first
150         function(card) {
151             if(!first) {
152                 if(card.id() == patron.card().id())
153                     return;
154             }
155             var row = allCardsTemplate.cloneNode(true);
156             getByName(row, 'barcode').innerHTML = card.barcode();
157             getByName(row, 'active').appendChild(
158                 openils.Util.isTrue(card.active()) ? 
159                     dojo.byId('true').cloneNode(true) :
160                     dojo.byId('false').cloneNode(true)
161             ); 
162
163             tbody.appendChild(row);
164             first = false;
165         }
166     );
167
168     allCardsDialog.show();
169 }
170
171 /**
172  * Mark the current card inactive, create a new primary card
173  */
174 function replaceCardHandler() {
175     var input = findWidget('ac', 'barcode');
176     input.widget.attr('value', null);
177     
178     // pull old car off the cards list so we don't have a dupe sitting in there
179     var old = patron.cards().filter(function(c){return (c.id() == patron.card().id())})[0];
180     old.active('f');
181     old.ischanged(1);
182
183     var newc = new fieldmapper.ac();
184     newc.id(uEditCardVirtId--);
185     newc.isnew(1);
186     newc.active('t');
187     patron.card(newc);
188     patron.cards().push(newc);
189 }
190
191
192 /**
193  * Loads a staged user and turns them into something the editor can understand
194  */
195 function uEditLoadStageUser(stageUname) {
196
197     var data = fieldmapper.standardRequest(
198         ['open-ils.actor', 'open-ils.actor.user.stage.retrieve.by_username'],
199         { params : [openils.User.authtoken, stageUname] }
200     );
201
202     stageUser = data.user;
203     patron = uEditNewPatron();
204
205     if(!stageUser) 
206         return patron;
207
208     // copy the data into our new user object
209     for(var key in fieldmapper.IDL.fmclasses.stgu.field_map) {
210         if(fieldmapper.IDL.fmclasses.au.field_map[key] && !fieldmapper.IDL.fmclasses.stgu.field_map[key].virtual) {
211             if(data.user[key]() !== null)
212                 patron[key]( data.user[key]() );
213         }
214     }
215
216     // copy the data into our new address objects
217     // TODO: uses the first mailing address only
218     if(data.mailing_addresses.length) {
219
220         var mail_addr = new fieldmapper.aua();
221         mail_addr.id(-1); // virtual ID
222         mail_addr.usr(-1);
223         mail_addr.isnew(1);
224         patron.mailing_address(mail_addr);
225         patron.addresses().push(mail_addr);
226
227         for(var key in fieldmapper.IDL.fmclasses.stgma.field_map) {
228             if(fieldmapper.IDL.fmclasses.aua.field_map[key] && !fieldmapper.IDL.fmclasses.stgma.field_map[key].virtual) {
229                 if(data.mailing_addresses[0][key]() !== null)
230                     mail_addr[key]( data.mailing_addresses[0][key]() );
231             }
232         }
233     }
234     
235     // copy the data into our new address objects
236     // TODO uses the first billing address only
237     if(data.billing_addresses.length) {
238
239         var bill_addr = new fieldmapper.aua();
240         bill_addr.id(-2); // virtual ID
241         bill_addr.usr(-1);
242         bill_addr.isnew(1);
243         patron.billing_address(bill_addr);
244         patron.addresses().push(bill_addr);
245
246         for(var key in fieldmapper.IDL.fmclasses.stgba.field_map) {
247             if(fieldmapper.IDL.fmclasses.aua.field_map[key] && !fieldmapper.IDL.fmclasses.stgba.field_map[key].virtual) {
248                 if(data.billing_addresses[0][key]() !== null)
249                     bill_addr[key]( data.billing_addresses[0][key]() );
250             }
251         }
252     }
253
254     // TODO: uses the first card only
255     if(data.cards.length) {
256         var card = new fieldmapper.ac();
257         card.id(-1); // virtual ID
258         patron.card().barcode(data.cards[0].barcode());
259     }
260
261     return patron;
262 }
263
264 /*
265  * clone the home org, phone numbers, and billing/mailing address
266  */
267 function uEditCopyCloneData(patron) {
268     cloneUserObj = uEditLoadUser(cloneUser);
269
270     dojo.forEach( [
271         'home_ou', 
272         'day_phone', 
273         'evening_phone', 
274         'other_phone',
275         'billing_address',
276         'usrgroup',
277         'mailing_address' ], 
278         function(field) {
279             patron[field](cloneUserObj[field]());
280         }
281     );
282
283     // don't grab all addresses().  the only ones we can link to are billing/mailing
284     if(patron.billing_address())
285         patron.addresses().push(patron.billing_address());
286
287     if(patron.mailing_address() && (
288             patron.addresses().length == 0 || 
289             patron.mailing_address().id() != patron.billing_address().id()) )
290         patron.addresses().push(patron.mailing_address());
291 }
292
293
294 function uEditFetchUserSettings(userId) {
295     
296     var baseNode = fieldmapper.aou.findOrgUnit(staff.ws_ou());
297     var orgs = fieldmapper.aou.orgNodeTrail(baseNode);
298     orgs = orgs.map(function(node) { return node.id(); });
299
300     /* fetch any user setting types we need + any that offer opt-in */
301     userSettingTypes = pcrud.search('cust', {
302         '-or' : [
303             {name:['circ.holds_behind_desk']}, 
304             {name : {
305                 'in': {
306                     select : {atevdef : ['opt_in_setting']}, 
307                     from : 'atevdef',
308                     // we only care about opt-in settings for event_defs our users encounter
309                     where : {'+atevdef' : {owner : orgs}}
310                 }
311             }}
312         ]
313     });
314
315     var names = userSettingTypes.map(function(obj) { return obj.name() });
316
317     /* fetch any values set for this user */
318     userSettings = fieldmapper.standardRequest(
319         ['open-ils.actor', 'open-ils.actor.patron.settings.retrieve'],
320         {params : [openils.User.authtoken, userId, names]});
321 }
322
323
324 function uEditLoadUser(userId) {
325     var patron = fieldmapper.standardRequest(
326         ['open-ils.actor', 'open-ils.actor.user.fleshed.retrieve'],
327         {params : [openils.User.authtoken, userId]}
328     );
329     openils.Event.parse_and_raise(patron);
330     return patron;
331 }
332
333 function loadStaticFields() {
334     for(var idx = 0; tbody.childNodes[idx]; idx++) {
335         var row = tbody.childNodes[idx];
336         if(row.nodeType != row.ELEMENT_NODE) continue;
337         var fmcls = row.getAttribute('fmclass');
338         if(fmcls) {
339             fleshFMRow(row, fmcls);
340         } else {
341
342             if(row.id == 'uedit-settings-divider') {
343
344                 var template = tbody.removeChild(dojo.byId('uedit-user-setting-template'));
345                 dojo.forEach(userSettingTypes, function(type) { uEditDrawSettingRow(tbody, row, template, type); } );
346
347                 if(userSettingTypes.length > 1 || orgSettings['circ.holds.behind_desk_pickup_supported']) {
348                     openils.Util.show('uedit-settings-divider', 'table-row');
349                 }
350             }
351         }
352     }
353 }
354
355 function uEditDrawSettingRow(tbody, dividerRow, template, stype) {
356     var row = template.cloneNode(true);
357     row.setAttribute('user_setting', stype.name());
358     getByName(row, 'label').innerHTML = stype.label();
359     var cb = new dijit.form.CheckBox({}, getByName(row, 'widget'));
360     cb.attr('value', userSettings[stype.name()]);
361     dojo.connect(cb, 'onChange', function(newVal) { userSettingsToUpdate[stype.name()] = newVal; });
362     tbody.insertBefore(row, dividerRow.nextSibling);
363     openils.Util.show(row, 'table-row');
364 }
365
366 function uEditUpdateUserSettings(userId) {
367     return fieldmapper.standardRequest(
368         ['open-ils.actor', 'open-ils.actor.patron.settings.update'],
369         {params : [openils.User.authtoken, userId, userSettingsToUpdate]});
370 }
371
372 function loadAllAddrs() {
373     dojo.forEach(patron.addresses(),
374         function(addr) {
375             uEditNewAddr(null, addr.id());
376         }
377     );
378 }
379
380 function loadStatCats() {
381
382     statCats = fieldmapper.standardRequest(
383         ['open-ils.circ', 'open-ils.circ.stat_cat.actor.retrieve.all'],
384         {params : [openils.User.authtoken, staff.ws_ou()]}
385     );
386
387     // draw stat cats
388     for(var idx in statCats) {
389         var stat = statCats[idx];
390         var row = statCatTemplate.cloneNode(true);
391         row.id = 'stat-cat-row-' + idx;
392         tbody.appendChild(row);
393         getByName(row, 'name').innerHTML = stat.name();
394         var valtd = getByName(row, 'widget');
395         var span = valtd.appendChild(document.createElement('span'));
396         var store = new dojo.data.ItemFileReadStore(
397                 {data:fieldmapper.actsc.toStoreData(stat.entries())});
398         var comboBox = new dijit.form.ComboBox({store:store}, span);
399         comboBox.labelAttr = 'value';
400         comboBox.searchAttr = 'value';
401
402         comboBox._wtype = 'statcat';
403         comboBox._statcat = stat.id();
404         widgetPile.push(comboBox); 
405
406         // populate existing cats
407         var map = patron.stat_cat_entries().filter(
408             function(mp) { return (mp.stat_cat() == stat.id()) })[0];
409         if(map) comboBox.attr('value', map.stat_cat_entry()); 
410
411     }
412 }
413
414 function loadSurveys() {
415
416     surveys = fieldmapper.standardRequest(
417         ['open-ils.circ', 'open-ils.circ.survey.retrieve.all'],
418         {params : [openils.User.authtoken]}
419     );
420
421     // draw surveys
422     for(var idx in surveys) {
423         var survey = surveys[idx];
424         var srow = surveyTemplate.cloneNode(true);
425         tbody.appendChild(srow);
426         getByName(srow, 'name').innerHTML = survey.name();
427
428         for(var q in survey.questions()) {
429             var quest = survey.questions()[q];
430             var qrow = surveyQuestionTemplate.cloneNode(true);
431             tbody.appendChild(qrow);
432             getByName(qrow, 'question').innerHTML = quest.question();
433
434             var span = getByName(qrow, 'answers').appendChild(document.createElement('span'));
435             var store = new dojo.data.ItemFileReadStore(
436                 {data:fieldmapper.asva.toStoreData(quest.answers())});
437             var select = new dijit.form.FilteringSelect({store:store}, span);
438             select.labelAttr = 'answer';
439             select.searchAttr = 'answer';
440
441             select._wtype = 'survey';
442             select._survey = survey.id();
443             select._question = quest.id();
444             widgetPile.push(select); 
445         }
446     }
447 }
448
449
450 function fleshFMRow(row, fmcls, args) {
451     var fmfield = row.getAttribute('fmfield');
452     var wclass = row.getAttribute('wclass');
453     var wstyle = row.getAttribute('wstyle');
454     var wconstraints = row.getAttribute('wconstraints');
455
456     var isPasswd2 = (fmfield == 'passwd2');
457     if(isPasswd2) fmfield = 'passwd';
458     var fieldIdl = fieldmapper.IDL.fmclasses[fmcls].field_map[fmfield];
459     if(!args) args = {};
460
461     var existing = dojo.query('td', row);
462     var htd = existing[0] || row.appendChild(document.createElement('td'));
463     var ltd = existing[1] || row.appendChild(document.createElement('td'));
464     var wtd = existing[2] || row.appendChild(document.createElement('td'));
465
466     openils.Util.addCSSClass(htd, 'uedit-help');
467     if(fieldDoc[fmcls] && fieldDoc[fmcls][fmfield]) {
468         var link = dojo.byId('uedit-help-template').cloneNode(true);
469         link.id = '';
470         link.onclick = function() { ueLoadContextHelp(fmcls, fmfield) };
471         openils.Util.removeCSSClass(link, 'hidden');
472         htd.appendChild(link);
473     }
474
475     if(!ltd.textContent) {
476         var span = document.createElement('span');
477         ltd.appendChild(document.createTextNode(fieldIdl.label));
478     }
479
480     span = document.createElement('span');
481     wtd.appendChild(span);
482
483     var fmObject = null;
484     var disabled = false;
485     switch(fmcls) {
486         case 'au' : fmObject = patron; break;
487         case 'ac' : fmObject = patron.card(); break;
488         case 'aua' : 
489             fmObject = patron.addresses().filter(
490                 function(i) { return (i.id() == args.addr) })[0];
491             if(fmObject && fmObject.usr() != patron.id())
492                 disabled = true;
493             break;
494     }
495
496     var required = row.getAttribute('required') == 'required';
497
498     // password data is not fetched/required/displayed for existing users
499     if(!patron.isnew() && 'passwd' == fmfield)
500         required = false;
501
502     var dijitArgs = {
503         style: wstyle, 
504         required : required,
505         constraints : (wconstraints) ? eval('('+wconstraints+')') : {}, // the ()'s prevent Invalid Label errors with eval
506         disabled : disabled
507     };
508
509     if(fmcls == 'au' && fmfield == 'passwd') {
510         if (orgSettings['global.password_regex']) {
511             dijitArgs.regExp = orgSettings['global.password_regex'];
512         }
513     }
514
515     // TODO RSN: Add Setting!
516     if(fmcls == 'au' && fmfield == 'dob')
517         dijitArgs.popupClass = "";
518
519     var value = row.getAttribute('wvalue');
520     if(value !== null)
521         dijitArgs.value = value;
522
523     // fetch profile groups non-async so existing expire_date is
524     // not overwritten when the profile groups arrive and update
525     var sync = (fmfield == 'profile') ? true : false;
526
527     var widget = new openils.widget.AutoFieldWidget({
528         forceSync : sync,
529         idlField : fieldIdl,
530         fmObject : fmObject,
531         fmClass : fmcls,
532         parentNode : span,
533         widgetClass : wclass,
534         dijitArgs : dijitArgs,
535         orgDefaultsToWs : true,
536         orgLimitPerms : ['UPDATE_USER'],
537     });
538
539     widget.build();
540
541     // now put it back before we register the widget
542     if(isPasswd2) fmfield = 'passwd2';
543
544     widget._wtype = fmcls;
545     widget._fmfield = fmfield;
546     widget._addr = args.addr;
547     widgetPile.push(widget);
548     attachWidgetEvents(fmcls, fmfield, widget);
549     return widget;
550 }
551
552 function findWidget(wtype, fmfield, callback) {
553     return widgetPile.filter(
554         function(i){
555             if(i._wtype == wtype && i._fmfield == fmfield) {
556                 if(callback) return callback(i);
557                 return true;
558             }
559         }
560     ).pop();
561 }
562
563 /**
564  * if the user does not have the UPDATE_PATRON_CLAIM_RETURN_COUNT, 
565  * they are not allowed to directly alter the claim return count. 
566  * This function checks the perm and disable/enables the widget.
567  */
568 function checkClaimsReturnCountPerm() {
569     new openils.User().getPermOrgList(
570         'UPDATE_PATRON_CLAIM_RETURN_COUNT',
571         function(orgList) { 
572             var cr = findWidget('au', 'claims_returned_count');
573             if(orgList.indexOf(patron.home_ou()) == -1) 
574                 cr.widget.attr('disabled', true);
575             else
576                 cr.widget.attr('disabled', false);
577         },
578         true, 
579         true
580     );
581 }
582
583
584 function checkClaimsNoCheckoutCountPerm() {
585     new openils.User().getPermOrgList(
586         'UPDATE_PATRON_CLAIM_NEVER_CHECKED_OUT_COUNT',
587         function(orgList) { 
588             var cr = findWidget('au', 'claims_never_checked_out_count');
589             if(orgList.indexOf(patron.home_ou()) == -1) 
590                 cr.widget.attr('disabled', true);
591             else
592                 cr.widget.attr('disabled', false);
593         },
594         true, 
595         true
596     );
597 }
598
599
600 function attachWidgetEvents(fmcls, fmfield, widget) {
601
602     if(fmcls == 'ac') {
603         if(fmfield == 'barcode') {
604             dojo.connect(widget.widget, 'onChange',
605                 function() {
606                     var barcode = this.attr('value');
607                     dupeBarcode = false;
608                     dojo.addClass(dojo.byId('uedit-dupe-barcode-warning'), 'hidden');
609                     fieldmapper.standardRequest(
610                         ['open-ils.actor', 'open-ils.actor.barcode.exists'],
611                         {
612                             params: [openils.User.authtoken, barcode],
613                             oncomplete : function(r) {
614                                 var res = openils.Util.readResponse(r);
615                                 if(res == '1') {
616                                     dupeBarcode = true;
617                                     dojo.removeClass(dojo.byId('uedit-dupe-barcode-warning'), 'hidden');
618                                 } else {
619                                     dupeBarcode = false;
620                                     dojo.addClass(dojo.byId('uedit-dupe-barcode-warning'), 'hidden');
621                                     var un = findWidget('au', 'usrname');
622                                     if(!un.widget.attr('value'))
623                                         un.widget.attr('value', barcode);
624                                 }
625                             }
626                         }
627                     );
628                 }
629             );
630             return;
631         }
632     }
633
634     if(fmcls == 'au') {
635         switch(fmfield) {
636
637             case 'usrname':
638                 dojo.connect(widget.widget, 'onChange', 
639                     function() {
640                         var input = findWidget('au', 'usrname');
641                         var usrname = input.widget.attr('value');
642
643                         if(!usrname) {
644                             dupeUsrname = false;
645                             dojo.addClass(dojo.byId('uedit-dupe-username-warning'), 'hidden');
646                             return;
647                         }
648
649                         fieldmapper.standardRequest(
650                             ['open-ils.actor', 'open-ils.actor.username.exists'],
651                             {
652                                 params: [openils.User.authtoken, usrname],
653                                 oncomplete : function(r) {
654                                     var res = openils.Util.readResponse(r);
655                                     if(res) {
656                                         dupeUsrname = true;
657                                         dojo.removeClass(dojo.byId('uedit-dupe-username-warning'), 'hidden');
658                                     } else {
659                                         dupeUsrname = false;
660                                         dojo.addClass(dojo.byId('uedit-dupe-username-warning'), 'hidden');
661                                     }
662                                 }
663                             }
664                         );
665                     }   
666                 );
667
668                 return;
669
670             case 'profile': // when the profile changes, update the expire date
671                 dojo.connect(widget.widget, 'onChange', 
672                     function() {
673                         var self = this;
674                         var expireWidget = findWidget('au', 'expire_date');
675                         function found(items) {
676                             if(items.length == 0) return;
677                             var item = items[0];
678                             var interval = self.store.getValue(item, 'perm_interval');
679                             expireWidget.widget.attr('value', dojo.date.add(new Date(), 
680                                 'second', openils.Util.intervalToSeconds(interval)));
681                         }
682                         this.store.fetch({onComplete:found, query:{id:this.attr('value')}});
683                     }
684                 );
685                 return;
686
687             case 'dob':
688                 dojo.connect(widget.widget, 'onChange',
689                     function(newDob) {
690                         if(!newDob) return;
691                         var oldDob = patron.dob();
692                         if(dojo.date.stamp.fromISOString(oldDob) == newDob) return;
693
694                         var juvInterval = orgSettings['global.juvenile_age_threshold'] || '18 years';
695                         var juvWidget = findWidget('au', 'juvenile');
696                         var base = new Date();
697                         base.setTime(base.getTime() - Number(openils.Util.intervalToSeconds(juvInterval) + '000'));
698
699                         if(newDob <= base) // older than global.juvenile_age_threshold
700                             juvWidget.widget.attr('value', false);
701                         else
702                             juvWidget.widget.attr('value', true);
703                     }
704                 );
705                 return;
706
707             case 'first_given_name':
708             case 'family_name':
709                 dojo.connect(widget.widget, 'onChange',
710                     function(newVal) { uEditDupeSearch('name', newVal); });
711                 return;
712
713             case 'email':
714                 dojo.connect(widget.widget, 'onChange',
715                     function(newVal) { uEditDupeSearch('email', newVal); });
716                 return;
717
718             case 'ident_value':
719             case 'ident_value2':
720                 dojo.connect(widget.widget, 'onChange',
721                     function(newVal) { uEditDupeSearch('ident', newVal); });
722                 return;
723
724             case 'day_phone':
725                 // if configured, use the last for digits of the day phone number as the password
726                 if(uEditUsePhonePw && patron.isnew()) {
727                     dojo.connect(widget.widget, 'onChange',
728                         function(newVal) {
729                             if(newVal && newVal.length >= 4) {
730                                 var pw1 = findWidget('au', 'passwd').widget;
731                                 var pw2 = findWidget('au', 'passwd2').widget;
732                                 pw1.attr('value', newVal.substring(newVal.length - 4));
733                                 pw2.attr('value', newVal.substring(newVal.length - 4));
734                             }
735                         }
736                     );
737                 }
738             case 'evening_phone':
739             case 'other_phone':
740                 dojo.connect(widget.widget, 'onChange',
741                     function(newVal) { uEditDupeSearch('phone', newVal); });
742                 return;
743
744             case 'home_ou':
745                 dojo.connect(widget.widget, 'onChange',
746                     function(newVal) { 
747                         checkClaimsReturnCountPerm(); 
748                         checkClaimsNoCheckoutCountPerm();
749                     }
750                 );
751                 return;
752
753             case 'passwd':
754                 dojo.connect(widget.widget, 'onChange',
755                     function(newVal) {
756                         var pw1 = findWidget('au', 'passwd').widget;
757                         var pw2 = findWidget('au', 'passwd2').widget;
758                         var preserved_value = pw2.attr('value');
759                         // Ensure that the pw2 field match the pw1 field to validate
760                         pw2.regExp = newVal.replace(/([.\\^$*+?\(\)\[\]\{\}])/g, '\\$1');
761                         pw2.reset();
762                         pw2.attr('value',preserved_value);
763                     });
764                 return;
765         }
766     }
767
768     if(fmclass = 'aua') {
769         switch(fmfield) {
770             case 'post_code':
771                 dojo.connect(widget.widget, 'onChange',
772                     function(e) { 
773                         fieldmapper.standardRequest(
774                             ['open-ils.search', 'open-ils.search.zip'],
775                             {   async: true,
776                                 params: [e],
777                                 oncomplete : function(r) {
778                                     var res = openils.Util.readResponse(r);
779                                     if(!res) return;
780                                     var callback = function(w) { return w._addr == widget._addr; };
781                                     if(res.city) findWidget('aua', 'city', callback).widget.attr('value', res.city);
782                                     if(res.state) findWidget('aua', 'state', callback).widget.attr('value', res.state);
783                                     if(res.county) findWidget('aua', 'county', callback).widget.attr('value', res.county);
784                                     if(res.alert) alert(res.alert);
785                                 }
786                             }
787                         );
788                     }
789                 );
790                 return;
791
792             case 'street1':
793             case 'street2':
794             case 'city':
795                 dojo.connect(widget.widget, 'onChange',
796                     function(e) {
797                         var callback = function(w) { return w._addr == widget._addr; };
798                         var args = {
799                             street1 : findWidget('aua', 'street1', callback).widget.attr('value'),
800                             street2 : findWidget('aua', 'street2', callback).widget.attr('value'),
801                             city : findWidget('aua', 'city', callback).widget.attr('value'),
802                             post_code : findWidget('aua', 'post_code', callback).widget.attr('value')
803                         };
804                         if(args.street1 && args.city && args.post_code)
805                             uEditDupeSearch('address', args); 
806                     }
807                 );
808                 return;
809         }
810     }
811 }
812
813 function uEditDupeSearch(type, value) {
814     if(!value) return;
815     var search;
816     switch(type) {
817
818         case 'name':
819             openils.Util.hide('uedit-dupe-names-link');
820             var fname = findWidget('au', 'first_given_name').widget.attr('value');
821             var lname = findWidget('au', 'family_name').widget.attr('value');
822             if( !(fname && lname) ) return;
823             search = {
824                 first_given_name : {value : fname, group : 0},
825                 family_name : {value : lname, group : 0},
826             };
827             break;
828
829         case 'email':
830             openils.Util.hide('uedit-dupe-email-link');
831             search = {email : {value : value, group : 0}};
832             break;
833
834         case 'ident':
835             openils.Util.hide('uedit-dupe-ident-link');
836             search = {ident : {value : value, group : 2}};
837             break;
838
839         case 'phone':
840             openils.Util.hide('uedit-dupe-phone-link');
841             search = {phone : {value : value, group : 2}};
842             break;
843
844         case 'address':
845             openils.Util.hide('uedit-dupe-address-link');
846             search = {};
847             dojo.forEach(['street1', 'street2', 'city', 'post_code'],
848                 function(field) {
849                     if(value[field])
850                         search[field] = {value : value[field], group: 1};
851                 }
852             );
853             break;
854     }
855
856     // find possible duplicate patrons
857     fieldmapper.standardRequest(
858         ['open-ils.actor', 'open-ils.actor.patron.search.advanced'],
859         {   async: true,
860             params: [openils.User.authtoken, search],
861             oncomplete : function(r) {
862                 var resp = openils.Util.readResponse(r);
863                 resp = resp.filter(function(id) { return (id != patron.id()); });
864
865                 if(resp && resp.length > 0) {
866
867                     openils.Util.hide('uedit-help-div');
868                     openils.Util.show('uedit-dupe-div');
869                     var link;
870
871                     switch(type) {
872                         case 'name':
873                             link = dojo.byId('uedit-dupe-names-link');
874                             link.innerHTML = dojo.string.substitute(localeStrings.DUPE_PATRON_NAME, [resp.length]);
875                             break;
876                         case 'email':
877                             link = dojo.byId('uedit-dupe-email-link');
878                             link.innerHTML = dojo.string.substitute(localeStrings.DUPE_PATRON_EMAIL, [resp.length]);
879                             break;
880                         case 'ident':
881                             link = dojo.byId('uedit-dupe-ident-link');
882                             link.innerHTML = dojo.string.substitute(localeStrings.DUPE_PATRON_IDENT, [resp.length]);
883                             break;
884                         case 'phone':
885                             link = dojo.byId('uedit-dupe-phone-link');
886                             link.innerHTML = dojo.string.substitute(localeStrings.DUPE_PATRON_PHONE, [resp.length]);
887                             break;
888                         case 'address':
889                             link = dojo.byId('uedit-dupe-address-link');
890                             link.innerHTML = dojo.string.substitute(localeStrings.DUPE_PATRON_ADDR, [resp.length]);
891                             break;
892                     }
893
894                     openils.Util.show(link);
895                     link.onclick = function() {
896                         search.search_sort = js2JSON(["penalties", "family_name", "first_given_name"]);
897                         if(window.xulG)
898                             window.xulG.spawn_search(search);
899                         else
900                             console.log("running XUL patron search " + js2JSON(search));
901                     }
902                 }
903             }
904         }
905     );
906 }
907
908 function getByName(node, name) {
909     return dojo.query('[name='+name+']', node)[0];
910 }
911
912
913 function ueLoadContextHelp(fmcls, fmfield) {
914     openils.Util.hide('uedit-dupe-div');
915     openils.Util.show('uedit-help-div');
916     dojo.byId('uedit-help-field').innerHTML = fieldmapper.IDL.fmclasses[fmcls].field_map[fmfield].label;
917     dojo.byId('uedit-help-text').innerHTML = fieldDoc[fmcls][fmfield].string();
918 }
919
920
921 /* creates a new patron object with card attached */
922 function uEditNewPatron() {
923     patron = new au();
924     patron.isnew(1);
925     patron.id(-1);
926     card = new ac();
927     card.id(uEditCardVirtId--);
928     card.isnew(1);
929     patron.active(1);
930     patron.card(card);
931     patron.cards([card]);
932     patron.net_access_level(orgSettings['ui.patron.default_inet_access_level'] || 1);
933     patron.stat_cat_entries([]);
934     patron.survey_responses([]);
935     patron.addresses([]);
936     uEditMakeRandomPw(patron);
937     return patron;
938 }
939
940 function uEditMakeRandomPw(patron) {
941     if(uEditUsePhonePw) return;
942     var rand  = Math.random();
943     rand = parseInt(rand * 10000) + '';
944     while(rand.length < 4) rand += '0';
945 /*
946     appendClear($('ue_password_plain'),text(rand));
947     unHideMe($('ue_password_gen'));
948 */
949     patron.passwd(rand);
950     return rand;
951 }
952
953 function uEditWidgetVal(w) {
954     var val = (w.getFormattedValue) ? w.getFormattedValue() : w.attr('value');
955     if(val === '') val = null;
956     return val;
957 }
958
959 function uEditSave() { _uEditSave(); }
960 function uEditSaveClone() { _uEditSave(true); }
961
962 function _uEditSave(doClone) {
963
964     if ( (! myForm.isValid()) || dupeUsrname || dupeBarcode ) {
965         alert('Form is invalid.  Please edit and try again.');
966         return;
967     }
968
969     for(var idx in widgetPile) {
970         var w = widgetPile[idx];
971         var val = uEditWidgetVal(w);
972
973         switch(w._wtype) {
974             case 'au':
975                 if(w._fmfield != 'passwd2')
976                     patron[w._fmfield](val);
977                 break;
978
979             case 'ac':
980                 patron.card()[w._fmfield](val);
981                 break;
982
983             case 'aua':
984                 var addr = patron.addresses().filter(function(i){return (i.id() == w._addr)})[0];
985                 if(!addr) {
986                     addr = new fieldmapper.aua();
987                     addr.id(w._addr);
988                     addr.isnew(1);
989                     addr.usr(patron.id());
990                     patron.addresses().push(addr);
991                 } else {
992                     if(addr[w._fmfield]() != val)
993                         addr.ischanged(1);
994                 }
995                 addr[w._fmfield](val);
996
997                 if(dojo.byId('uedit-billing-address-' + addr.id()).checked) 
998                     patron.billing_address(addr.id());
999
1000                 if(dojo.byId('uedit-mailing-address-' + addr.id()).checked)
1001                     patron.mailing_address(addr.id());
1002
1003                 break;
1004
1005             case 'survey':
1006                 if(val == null) break;
1007                 var resp = new fieldmapper.asvr();
1008                 resp.isnew(1);
1009                 resp.survey(w._survey)
1010                 resp.usr(patron.id());
1011                 resp.question(w._question)
1012                 resp.answer(val);
1013                 patron.survey_responses().push(resp);
1014                 break;
1015
1016             case 'statcat':
1017                 if(val == null) break;
1018
1019                 var map = patron.stat_cat_entries().filter(
1020                     function(m){
1021                         return (m.stat_cat() == w._statcat) })[0];
1022
1023                 if(map) {
1024                     if(map.stat_cat_entry() == val) 
1025                         break;
1026                     map.ischanged(1);
1027                 } else {
1028                     map = new fieldmapper.actscecm();
1029                     map.isnew(1);
1030                 }
1031
1032                 map.stat_cat(w._statcat);
1033                 map.stat_cat_entry(val);
1034                 map.target_usr(patron.id());
1035                 patron.stat_cat_entries().push(map);
1036                 break;
1037         }
1038     }
1039
1040     patron.ischanged(1);
1041     fieldmapper.standardRequest(
1042         ['open-ils.actor', 'open-ils.actor.patron.update'],
1043         {   async: true,
1044             params: [openils.User.authtoken, patron],
1045             oncomplete: function(r) {
1046                 newPatron = openils.Util.readResponse(r);
1047                 if(newPatron) {
1048                     uEditUpdateUserSettings(newPatron.id());
1049                     if(stageUser) uEditRemoveStage();
1050                     uEditFinishSave(newPatron, doClone);
1051                 }
1052             }
1053         }
1054     );
1055 }
1056
1057 function uEditRemoveStage() {
1058     var resp = fieldmapper.standardRequest(
1059         ['open-ils.actor', 'open-ils.actor.user.stage.delete'],
1060         { params : [openils.User.authtoken, stageUser.row_id()] }
1061     )
1062 }
1063
1064 function uEditFinishSave(newPatron, doClone) {
1065
1066     if(doClone && cloneUser == null)
1067         cloneUser = newPatron.id();
1068
1069         if( doClone ) {
1070
1071                 if(xulG && typeof xulG.spawn_editor == 'function' && !patron.isnew() ) {
1072             window.xulG.spawn_editor({ses:openils.User.authtoken,clone:cloneUser});
1073             uEditRefresh();
1074
1075                 } else {
1076                         location.href = location.href.replace(/\?.*/, '') + '?clone=' + cloneUser;
1077                 }
1078
1079         } else {
1080
1081                 uEditRefresh();
1082         }
1083
1084         uEditRefreshXUL(newPatron);
1085 }
1086
1087 function uEditRefresh() {
1088     var usr = cgi.param('usr');
1089     var href = location.href.replace(/\?.*/, '');
1090     href += ((usr) ? '?usr=' + usr : '');
1091     location.href = href;
1092 }
1093
1094 function uEditRefreshXUL(newuser) {
1095         if (window.xulG && typeof window.xulG.on_save == 'function') 
1096                 window.xulG.on_save(newuser);
1097 }
1098
1099
1100 /**
1101  * Create a new address and insert it into the DOM
1102  * @param evt ignored
1103  * @param id The address id
1104  * @param mkLinks If true, set the new address as the 
1105  *  mailing/billing address for the user
1106  */
1107 function uEditNewAddr(evt, id, mkLinks) {
1108
1109     if(id == null) 
1110         id = --uEditAddrVirtId; // new address
1111
1112     var addr =  patron.addresses().filter(
1113         function(i) { return (i.id() == id) })[0];
1114
1115     dojo.forEach(addrTemplateRows, 
1116         function(row) {
1117
1118             row = tbody.insertBefore(row.cloneNode(true), dojo.byId('new-addr-row'));
1119             row.setAttribute('type', '');
1120             row.setAttribute('addr', id+'');
1121
1122             if(row.getAttribute('fmclass')) {
1123                 var widget = fleshFMRow(row, 'aua', {addr:id});
1124
1125                 // make new addresses valid by default
1126                 if(id < 0 && row.getAttribute('fmfield') == 'valid') 
1127                     widget.widget.attr('value', true); 
1128
1129             } else if(row.getAttribute('name') == 'uedit-addr-pending-row') {
1130
1131                 // if it's a pending address, show the 'approve' button
1132                 if(addr && openils.Util.isTrue(addr.pending())) {
1133                     openils.Util.show(row, 'table-row');
1134                     dojo.query('[name=approve-button]', row)[0].onclick = 
1135                         function() { uEditApproveAddress(addr); };
1136
1137                     if(addr.replaces()) {
1138                         var div = dojo.query('[name=replaced-addr]', row)[0]
1139                         var replaced =  patron.addresses().filter(
1140                             function(i) { return (i.id() == addr.replaces()) })[0];
1141
1142                         div.innerHTML = dojo.string.substitute(localeStrings.REPLACED_ADDRESS, [
1143                             replaced.address_type() || '',
1144                             replaced.street1() || '',
1145                             replaced.street2() || '',
1146                             replaced.city() || '',
1147                             replaced.state() || '',
1148                             replaced.post_code() || ''
1149                         ]);
1150
1151                     } else {
1152                         openils.Util.hide(dojo.query('[name=replaced-addr-div]', row)[0]);
1153                     }
1154                 }
1155
1156             } else if(row.getAttribute('name') == 'uedit-addr-owner-row') {
1157                 // address is owned by someone else.  provide option to load the
1158                 // user in a different tab
1159                 
1160                 if(addr && addr.usr() != patron.id()) {
1161                     openils.Util.show(row, 'table-row');
1162                     var link = getByName(row, 'addr-owner');
1163
1164                     // fetch the linked user so we can present their name in the UI
1165                     var addrUser;
1166                     if(cloneUserObj && cloneUserObj.id() == addr.usr()) {
1167                         addrUser = [
1168                             cloneUserObj.first_given_name(), 
1169                             cloneUserObj.second_given_name(), 
1170                             cloneUserObj.family_name()
1171                         ];
1172                     } else {
1173                         addrUser = fieldmapper.standardRequest(
1174                             ['open-ils.actor', 'open-ils.actor.user.retrieve.parts'],
1175                             {params: [
1176                                 openils.User.authtoken, 
1177                                 addr.usr(), 
1178                                 ['first_given_name', 'second_given_name', 'family_name']
1179                             ]}
1180                         );
1181                     }
1182
1183                     link.innerHTML = (addrUser.map(function(name) { return (name) ? name+' ' : '' })+'').replace(/,/g,''); // TODO i18n
1184                     link.onclick = function() {
1185                         if(openils.XUL.isXUL()) { 
1186                             window.xulG.spawn_editor({ses:openils.User.authtoken, usr:addr.usr()})
1187                         } else {
1188                             parent.location.href = location.href.replace(/clone=\d+/, 'usr=' + addr.usr());
1189                         }
1190                     }
1191                 }
1192
1193             } else if(row.getAttribute('name') == 'uedit-addr-divider') {
1194                 // link up the billing/mailing address and give the inputs IDs so we can acces the later
1195                 
1196                 // billing address
1197                 var ba = getByName(row, 'billing_address');
1198                 ba.id = 'uedit-billing-address-' + id;
1199                 if(mkLinks || (patron.billing_address() && patron.billing_address().id() == id))
1200                     ba.checked = true;
1201
1202                 // mailing address
1203                 var ma = getByName(row, 'mailing_address');
1204                 ma.id = 'uedit-mailing-address-' + id;
1205                 if(mkLinks || (patron.mailing_address() && patron.mailing_address().id() == id))
1206                     ma.checked = true;
1207
1208             } else {
1209                 var btn = dojo.query('[name=delete-button]', row)[0];
1210                 if(btn) btn.onclick = function(){ uEditDeleteAddr(id) };
1211             }
1212         }
1213     );
1214 }
1215
1216 function uEditApproveAddress(addr) {
1217     fieldmapper.standardRequest(
1218         ['open-ils.actor', 'open-ils.actor.user.pending_address.approve'],
1219         {   async: true,
1220             params:  [openils.User.authtoken, addr],
1221
1222             oncomplete : function(r) {
1223                 var oldId = openils.Util.readResponse(r);
1224                     
1225                 // remove addrs from UI
1226                 dojo.forEach(
1227                     patron.addresses(), 
1228                     function(addr) { uEditDeleteAddr(addr.id(), true); }
1229                 );
1230
1231                 if(oldId != null) {
1232                     
1233                     // remove the replaced address 
1234                     if(oldId != addr.id()) {
1235                                 patron.addresses(
1236                             patron.addresses().filter(
1237                                                 function(i) { return (i.id() != oldId); }
1238                                         )
1239                                 );
1240                     }
1241                     
1242                     // fix the the new address
1243                     addr.id(oldId);
1244                     addr.replaces(null);
1245                     addr.pending('f');
1246
1247                 }
1248
1249                 // redraw addrs
1250                 loadAllAddrs();
1251             }
1252         }
1253     );
1254 }
1255
1256
1257 function uEditDeleteAddr(id, noAlert) {
1258     if(!noAlert) {
1259         if(!confirm('Delete address ' + id)) return; /* XXX i18n */
1260     }
1261     var rows = dojo.query('tr[addr='+id+']', tbody);
1262     for(var i = 0; i < rows.length; i++)
1263         rows[i].parentNode.removeChild(rows[i]);
1264     widgetPile = widgetPile.filter(function(w){return (w._addr != id)});
1265 }
1266
1267 function uEditToggleRequired() {
1268     if((tbody.className +'').match(/hide-non-required/)) 
1269         openils.Util.removeCSSClass(tbody, 'hide-non-required');
1270     else
1271         openils.Util.addCSSClass(tbody, 'hide-non-required');
1272     openils.Util.toggle('uedit-show-required');
1273     openils.Util.toggle('uedit-show-all');
1274 }
1275
1276
1277
1278 openils.Util.addOnLoad(load);