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