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