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