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