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