]> git.evergreen-ils.org Git - working/Evergreen.git/blob - Open-ILS/web/js/ui/default/actor/user/register.js
Merge branch 'master' of git.evergreen-ils.org:Evergreen into template-toolkit-opac
[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                 dojo.connect(widget.widget, 'onChange',
1009                     function(newDob) {
1010                         if(!newDob) return;
1011                         var oldDob = patron.dob();
1012                         if(dojo.date.stamp.fromISOString(oldDob) == newDob) return;
1013
1014                         var juvInterval = orgSettings['global.juvenile_age_threshold'] || '18 years';
1015                         var juvWidget = findWidget('au', 'juvenile');
1016                         var base = new Date();
1017                         base.setTime(base.getTime() - Number(openils.Util.intervalToSeconds(juvInterval) + '000'));
1018
1019                         if(newDob <= base) // older than global.juvenile_age_threshold
1020                             juvWidget.widget.attr('value', false);
1021                         else
1022                             juvWidget.widget.attr('value', true);
1023                     }
1024                 );
1025                 return;
1026
1027             case 'first_given_name':
1028             case 'family_name':
1029                 dojo.connect(widget.widget, 'onChange',
1030                     function(newVal) { uEditDupeSearch('name', newVal); });
1031                 return;
1032
1033             case 'email':
1034                 dojo.connect(widget.widget, 'onChange',
1035                     function(newVal) { uEditDupeSearch('email', newVal); });
1036                 return;
1037
1038             case 'ident_value':
1039             case 'ident_value2':
1040                 dojo.connect(widget.widget, 'onChange',
1041                     function(newVal) { uEditDupeSearch('ident', newVal); });
1042                 return;
1043
1044             case 'day_phone':
1045                 // if configured, use the last four digits of the day phone number as the password
1046                 if(uEditUsePhonePw && patron.isnew()) {
1047                     dojo.connect(widget.widget, 'onChange',
1048                         function(newVal) {
1049                             if(newVal && newVal.length >= 4) {
1050                                 var pw1 = findWidget('au', 'passwd').widget;
1051                                 var pw2 = findWidget('au', 'passwd2').widget;
1052                                 pw1.attr('value', newVal.substring(newVal.length - 4));
1053                                 pw2.attr('value', newVal.substring(newVal.length - 4));
1054                             }
1055                         }
1056                     );
1057                 }
1058             case 'evening_phone':
1059             case 'other_phone':
1060                 dojo.connect(widget.widget, 'onChange',
1061                     function(newVal) { uEditDupeSearch('phone', newVal); });
1062                 return;
1063
1064             case 'home_ou':
1065                 dojo.connect(widget.widget, 'onChange',
1066                     function(newVal) { 
1067                         checkClaimsReturnCountPerm(); 
1068                         checkClaimsNoCheckoutCountPerm();
1069                     }
1070                 );
1071                 return;
1072
1073             case 'passwd':
1074                 dojo.connect(widget.widget, 'onChange',
1075                     function(newVal) {
1076                         var pw1 = findWidget('au', 'passwd').widget;
1077                         var pw2 = findWidget('au', 'passwd2').widget;
1078                         var preserved_value = pw2.attr('value');
1079                         // Ensure that the pw2 field match the pw1 field to validate
1080                         pw2.regExp = newVal.replace(/([.\\^$*+?\(\)\[\]\{\}])/g, '\\$1');
1081                         pw2.reset();
1082                         pw2.attr('value',preserved_value);
1083                     });
1084                 return;
1085         }
1086     }
1087
1088     if(fmclass = 'aua') {
1089         switch(fmfield) {
1090             case 'post_code':
1091                 dojo.connect(widget.widget, 'onChange',
1092                     function(e) { 
1093                         fieldmapper.standardRequest(
1094                             ['open-ils.search', 'open-ils.search.zip'],
1095                             {   async: true,
1096                                 params: [e],
1097                                 oncomplete : function(r) {
1098                                     var res = openils.Util.readResponse(r);
1099                                     if(!res) return;
1100                                     var callback = function(w) { return w._addr == widget._addr; };
1101                                     if(res.city) findWidget('aua', 'city', callback).widget.attr('value', res.city);
1102                                     if(res.state) findWidget('aua', 'state', callback).widget.attr('value', res.state);
1103                                     if(res.county) findWidget('aua', 'county', callback).widget.attr('value', res.county);
1104                                     if(res.alert) alert(res.alert);
1105                                 }
1106                             }
1107                         );
1108                     }
1109                 );
1110                 return;
1111
1112             case 'street1':
1113             case 'street2':
1114             case 'city':
1115                 dojo.connect(widget.widget, 'onChange',
1116                     function(e) {
1117                         var callback = function(w) { return w._addr == widget._addr; };
1118                         var args = {
1119                             street1 : findWidget('aua', 'street1', callback).widget.attr('value'),
1120                             street2 : findWidget('aua', 'street2', callback).widget.attr('value'),
1121                             city : findWidget('aua', 'city', callback).widget.attr('value'),
1122                             post_code : findWidget('aua', 'post_code', callback).widget.attr('value')
1123                         };
1124                         if(args.street1 && args.city && args.post_code)
1125                             uEditDupeSearch('address', args); 
1126                     }
1127                 );
1128                 return;
1129         }
1130     }
1131 }
1132
1133 function uEditDupeSearch(type, value) {
1134     if(!value) return;
1135     var search;
1136     switch(type) {
1137
1138         case 'name':
1139             openils.Util.hide('uedit-dupe-names-link');
1140             var fname = findWidget('au', 'first_given_name').widget.attr('value');
1141             var lname = findWidget('au', 'family_name').widget.attr('value');
1142             if( !(fname && lname) ) return;
1143             search = {
1144                 first_given_name : {value : fname, group : 0},
1145                 family_name : {value : lname, group : 0},
1146             };
1147             break;
1148
1149         case 'email':
1150             openils.Util.hide('uedit-dupe-email-link');
1151             search = {email : {value : value, group : 0}};
1152             break;
1153
1154         case 'ident':
1155             openils.Util.hide('uedit-dupe-ident-link');
1156             search = {ident : {value : value, group : 2}};
1157             break;
1158
1159         case 'phone':
1160             openils.Util.hide('uedit-dupe-phone-link');
1161             search = {phone : {value : value, group : 2}};
1162             break;
1163
1164         case 'address':
1165             openils.Util.hide('uedit-dupe-address-link');
1166             search = {};
1167             dojo.forEach(['street1', 'street2', 'city', 'post_code'],
1168                 function(field) {
1169                     if(value[field])
1170                         search[field] = {value : value[field], group: 1};
1171                 }
1172             );
1173             break;
1174     }
1175
1176     // find possible duplicate patrons
1177     fieldmapper.standardRequest(
1178         ['open-ils.actor', 'open-ils.actor.patron.search.advanced'],
1179         {   async: true,
1180             params: [openils.User.authtoken, search],
1181             oncomplete : function(r) {
1182                 var resp = openils.Util.readResponse(r);
1183                 resp = resp.filter(function(id) { return (id != patron.id()); });
1184
1185                 if(resp && resp.length > 0) {
1186
1187                     openils.Util.hide('uedit-help-div');
1188                     openils.Util.show('uedit-dupe-div');
1189                     var link;
1190
1191                     switch(type) {
1192                         case 'name':
1193                             link = dojo.byId('uedit-dupe-names-link');
1194                             link.innerHTML = dojo.string.substitute(localeStrings.DUPE_PATRON_NAME, [resp.length]);
1195                             break;
1196                         case 'email':
1197                             link = dojo.byId('uedit-dupe-email-link');
1198                             link.innerHTML = dojo.string.substitute(localeStrings.DUPE_PATRON_EMAIL, [resp.length]);
1199                             break;
1200                         case 'ident':
1201                             link = dojo.byId('uedit-dupe-ident-link');
1202                             link.innerHTML = dojo.string.substitute(localeStrings.DUPE_PATRON_IDENT, [resp.length]);
1203                             break;
1204                         case 'phone':
1205                             link = dojo.byId('uedit-dupe-phone-link');
1206                             link.innerHTML = dojo.string.substitute(localeStrings.DUPE_PATRON_PHONE, [resp.length]);
1207                             break;
1208                         case 'address':
1209                             link = dojo.byId('uedit-dupe-address-link');
1210                             link.innerHTML = dojo.string.substitute(localeStrings.DUPE_PATRON_ADDR, [resp.length]);
1211                             break;
1212                     }
1213
1214                     openils.Util.show(link);
1215                     link.onclick = function() {
1216                         search.search_sort = js2JSON(["penalties", "family_name", "first_given_name"]);
1217                         if(window.xulG)
1218                             window.xulG.spawn_search(search);
1219                         else
1220                             console.log("running XUL patron search " + js2JSON(search));
1221                     }
1222                 }
1223             }
1224         }
1225     );
1226 }
1227
1228 function getByName(node, name) {
1229     return dojo.query('[name='+name+']', node)[0];
1230 }
1231
1232
1233 function ueLoadContextHelp(fmcls, fmfield) {
1234     openils.Util.hide('uedit-dupe-div');
1235     openils.Util.show('uedit-help-div');
1236     dojo.byId('uedit-help-field').innerHTML = fieldmapper.IDL.fmclasses[fmcls].field_map[fmfield].label;
1237     dojo.byId('uedit-help-text').innerHTML = fieldDoc[fmcls][fmfield].string();
1238 }
1239
1240
1241 /* creates a new patron object with card attached */
1242 function uEditNewPatron() {
1243     patron = new au();
1244     patron.isnew(1);
1245     patron.id(-1);
1246     card = new ac();
1247     card.id(uEditCardVirtId--);
1248     card.isnew(1);
1249     patron.active(1);
1250     patron.card(card);
1251     patron.cards([card]);
1252     patron.net_access_level(orgSettings['ui.patron.default_inet_access_level'] || 1);
1253     patron.ident_type(orgSettings['ui.patron.default_ident_type']);
1254     patron.stat_cat_entries([]);
1255     patron.survey_responses([]);
1256     patron.addresses([]);
1257     uEditMakeRandomPw(patron);
1258     return patron;
1259 }
1260
1261 function uEditMakeRandomPw(patron) {
1262     var rand  = Math.random();
1263     rand = parseInt(rand * 10000) + '';
1264     while(rand.length < 4) rand += '0';
1265 /*
1266     appendClear($('ue_password_plain'),text(rand));
1267     unHideMe($('ue_password_gen'));
1268 */
1269     patron.passwd(rand);
1270     return rand;
1271 }
1272
1273 function uEditWidgetVal(w) {
1274     var val = (w.getFormattedValue) ? w.getFormattedValue() : w.attr('value');
1275     if(val === '') val = null;
1276     return val;
1277 }
1278
1279 function uEditSave() { _uEditSave(); }
1280 function uEditSaveClone() { _uEditSave(true); }
1281
1282 function _uEditSave(doClone) {
1283
1284     if ( (! myForm.isValid()) || dupeUsrname || dupeBarcode ) {
1285         alert(localeStrings.INVALID_FORM);
1286         return;
1287     }
1288
1289     for(var idx in widgetPile) {
1290         var w = widgetPile[idx];
1291         var val = uEditWidgetVal(w);
1292
1293         switch(w._wtype) {
1294             case 'au':
1295                 if(w._fmfield != 'passwd2')
1296                     patron[w._fmfield](val);
1297                 break;
1298
1299             case 'ac':
1300                 patron.card()[w._fmfield](val);
1301                 break;
1302
1303             case 'aua':
1304                 var addr = patron.addresses().filter(function(i){return (i.id() == w._addr)})[0];
1305                 if(!addr) {
1306                     addr = new fieldmapper.aua();
1307                     addr.id(w._addr);
1308                     addr.isnew(1);
1309                     addr.usr(patron.id());
1310                     addr.country(orgSettings['ui.patron.default_country']);
1311                     var t = patron.addresses();
1312                         if (!t) { t = []; }
1313                         t.push(addr);
1314                         patron.addresses(t);
1315                 } else {
1316                     if(addr[w._fmfield]() != val)
1317                         addr.ischanged(1);
1318                 }
1319                 addr[w._fmfield](val);
1320
1321                 if(dojo.byId('uedit-billing-address-' + addr.id()).checked) 
1322                     patron.billing_address(addr.id());
1323
1324                 if(dojo.byId('uedit-mailing-address-' + addr.id()).checked)
1325                     patron.mailing_address(addr.id());
1326
1327                 break;
1328
1329             case 'survey':
1330                 if(val == null) break;
1331                 var resp = new fieldmapper.asvr();
1332                 resp.isnew(1);
1333                 resp.survey(w._survey)
1334                 resp.usr(patron.id());
1335                 resp.question(w._question)
1336                 resp.answer(val);
1337                 var t = patron.survey_responses();
1338                     if (!t) { t = []; }
1339                     t.push(resp);
1340                     patron.survey_responses(t);
1341                 break;
1342
1343             case 'statcat':
1344                 var map = patron.stat_cat_entries().filter(
1345                     function(m){
1346                         return (m.stat_cat() == w._statcat) })[0];
1347
1348                 if(map) {
1349                     if(map.stat_cat_entry() == val) 
1350                         break;
1351                     if(val == null) {
1352                         val = '';
1353                         map.isdeleted(1);
1354                     } else {
1355                         map.ischanged(1);
1356                     }
1357                 } else {
1358                     if(val == null)
1359                         break;
1360                     map = new fieldmapper.actscecm();
1361                     map.isnew(1);
1362                 }
1363
1364                 map.stat_cat(w._statcat);
1365                 map.stat_cat_entry(val);
1366                 map.target_usr(patron.id());
1367                 var t = patron.stat_cat_entries();
1368                     if (!t) { t = []; }
1369                     t.push(map);
1370                     patron.stat_cat_entries(t);
1371                 break;
1372         }
1373     }
1374
1375     patron.ischanged(1);
1376     fieldmapper.standardRequest(
1377         ['open-ils.actor', 'open-ils.actor.patron.update'],
1378         {   async: true,
1379             params: [openils.User.authtoken, patron],
1380             oncomplete: function(r) {
1381                 lock_ready = false;
1382                 if (xulG && typeof xulG.unlock_tab == 'function') {
1383                     xulG.unlock_tab();
1384                     already_locked = false;
1385                 }
1386                 newPatron = openils.Util.readResponse(r);
1387                 if(newPatron) {
1388                     uEditUpdateUserSettings(newPatron.id());
1389                     if(stageUser) uEditRemoveStage();
1390                     uEditFinishSave(newPatron, doClone);
1391                 }
1392             }
1393         }
1394     );
1395 }
1396
1397 function uEditRemoveStage() {
1398     var resp = fieldmapper.standardRequest(
1399         ['open-ils.actor', 'open-ils.actor.user.stage.delete'],
1400         { params : [openils.User.authtoken, stageUser.row_id()] }
1401     )
1402 }
1403
1404 function uEditFinishSave(newPatron, doClone) {
1405
1406     if(doClone && cloneUser == null)
1407         cloneUser = newPatron.id();
1408
1409         if( doClone ) {
1410
1411                 if(xulG && typeof xulG.spawn_editor == 'function' && !patron.isnew() ) {
1412             window.xulG.spawn_editor({ses:openils.User.authtoken,clone:cloneUser});
1413             uEditRefresh();
1414
1415                 } else {
1416                         location.href = location.href.replace(/\?.*/, '') + '?clone=' + cloneUser;
1417                 }
1418
1419         } else {
1420
1421                 uEditRefresh();
1422         }
1423
1424         uEditRefreshXUL(newPatron);
1425 }
1426
1427 function uEditRefresh() {
1428     var usr = cgi.param('usr');
1429     var href = location.href.replace(/\?.*/, '');
1430     href += ((usr) ? '?usr=' + usr : '');
1431     location.href = href;
1432 }
1433
1434 function uEditRefreshXUL(newuser) {
1435         if (window.xulG && typeof window.xulG.on_save == 'function') 
1436                 window.xulG.on_save(newuser);
1437 }
1438
1439
1440 /**
1441  * Create a new address and insert it into the DOM
1442  * @param evt ignored
1443  * @param id The address id
1444  * @param mkLinks If true, set the new address as the 
1445  *  mailing/billing address for the user
1446  */
1447 function uEditNewAddr(evt, id, mkLinks) {
1448
1449     if(id == null) 
1450         id = --uEditAddrVirtId; // new address
1451
1452     var addr =  patron.addresses().filter(
1453         function(i) { return (i.id() == id) })[0];
1454
1455     dojo.forEach(addrTemplateRows, 
1456         function(row) {
1457
1458             row = tbody.insertBefore(row.cloneNode(true), dojo.byId('new-addr-row'));
1459             row.setAttribute('type', '');
1460             row.setAttribute('addr', id+'');
1461
1462             if(row.getAttribute('fmclass')) {
1463                 var widget = fleshFMRow(row, 'aua', {addr:id});
1464
1465                 // make new addresses a default address type
1466                 if(id < 0 && row.getAttribute('fmfield') == 'address_type') 
1467                     widget.widget.attr('value', localeStrings.DEFAULT_ADDRESS_TYPE); 
1468
1469                 // make new addresses valid by default
1470                 if(id < 0 && row.getAttribute('fmfield') == 'valid') 
1471                     widget.widget.attr('value', true); 
1472
1473                 // make new addresses use the org setting for default country 
1474                 if(id < 0 && row.getAttribute('fmfield') == 'country') 
1475                     widget.widget.attr('value',orgSettings['ui.patron.default_country']);
1476
1477             } else if(row.getAttribute('name') == 'uedit-addr-pending-row') {
1478
1479                 // if it's a pending address, show the 'approve' button
1480                 if(addr && openils.Util.isTrue(addr.pending())) {
1481                     openils.Util.show(row, 'table-row');
1482                     dojo.query('[name=approve-button]', row)[0].onclick = 
1483                         function() { uEditApproveAddress(addr); };
1484
1485                     if(addr.replaces()) {
1486                         var div = dojo.query('[name=replaced-addr]', row)[0]
1487                         var replaced =  patron.addresses().filter(
1488                             function(i) { return (i.id() == addr.replaces()) })[0];
1489
1490                         div.innerHTML = dojo.string.substitute(localeStrings.REPLACED_ADDRESS, [
1491                             replaced.address_type() || '',
1492                             replaced.street1() || '',
1493                             replaced.street2() || '',
1494                             replaced.city() || '',
1495                             replaced.state() || '',
1496                             replaced.post_code() || ''
1497                         ]);
1498
1499                     } else {
1500                         openils.Util.hide(dojo.query('[name=replaced-addr-div]', row)[0]);
1501                     }
1502                 }
1503
1504             } else if(row.getAttribute('name') == 'uedit-addr-owner-row') {
1505                 // address is owned by someone else.  provide option to load the
1506                 // user in a different tab
1507                 
1508                 if(addr && addr.usr() != patron.id()) {
1509                     openils.Util.show(row, 'table-row');
1510                     var link = getByName(row, 'addr-owner');
1511
1512                     // fetch the linked user so we can present their name in the UI
1513                     var addrUser;
1514                     if(cloneUserObj && cloneUserObj.id() == addr.usr()) {
1515                         addrUser = [
1516                             cloneUserObj.first_given_name(), 
1517                             cloneUserObj.second_given_name(), 
1518                             cloneUserObj.family_name()
1519                         ];
1520                     } else {
1521                         addrUser = fieldmapper.standardRequest(
1522                             ['open-ils.actor', 'open-ils.actor.user.retrieve.parts'],
1523                             {params: [
1524                                 openils.User.authtoken, 
1525                                 addr.usr(), 
1526                                 ['first_given_name', 'second_given_name', 'family_name']
1527                             ]}
1528                         );
1529                     }
1530
1531                     link.innerHTML = (addrUser.map(function(name) { return (name) ? name+' ' : '' })+'').replace(/,/g,''); // TODO i18n
1532                     link.onclick = function() {
1533                         if(openils.XUL.isXUL()) { 
1534                             window.xulG.spawn_editor({ses:openils.User.authtoken, usr:addr.usr()})
1535                         } else {
1536                             parent.location.href = location.href.replace(/clone=\d+/, 'usr=' + addr.usr());
1537                         }
1538                     }
1539                 }
1540
1541             } else if(row.getAttribute('name') == 'uedit-addr-divider') {
1542                 // link up the billing/mailing address and give the inputs IDs so we can access the later
1543                 
1544                 // billing address
1545                 var ba = getByName(row, 'billing_address');
1546                 ba.id = 'uedit-billing-address-' + id;
1547                 if(mkLinks || (patron.billing_address() && patron.billing_address().id() == id))
1548                     ba.checked = true;
1549
1550                 // mailing address
1551                 var ma = getByName(row, 'mailing_address');
1552                 ma.id = 'uedit-mailing-address-' + id;
1553                 if(mkLinks || (patron.mailing_address() && patron.mailing_address().id() == id))
1554                     ma.checked = true;
1555
1556                 var btn = dojo.query('[name=delete-button]', row)[0];
1557                 if(btn) btn.onclick = function(){ uEditDeleteAddr(id) };
1558             }
1559         }
1560     );
1561 }
1562
1563 function uEditApproveAddress(addr) {
1564     fieldmapper.standardRequest(
1565         ['open-ils.actor', 'open-ils.actor.user.pending_address.approve'],
1566         {   async: true,
1567             params:  [openils.User.authtoken, addr],
1568
1569             oncomplete : function(r) {
1570                 var oldId = openils.Util.readResponse(r);
1571                     
1572                 // remove addrs from UI
1573                 dojo.forEach(
1574                     patron.addresses(), 
1575                     function(addr) { uEditDeleteAddr(addr.id(), true); }
1576                 );
1577
1578                 if(oldId != null) {
1579                     
1580                     // remove the replaced address 
1581                     if(oldId != addr.id()) {
1582                                 patron.addresses(
1583                             patron.addresses().filter(
1584                                                 function(i) { return (i.id() != oldId); }
1585                                         )
1586                                 );
1587                     }
1588                     
1589                     // fix the the new address
1590                     addr.id(oldId);
1591                     addr.replaces(null);
1592                     addr.pending('f');
1593
1594                 }
1595
1596                 // redraw addrs
1597                 loadAllAddrs();
1598             }
1599         }
1600     );
1601 }
1602
1603
1604 function uEditDeleteAddr(id, noAlert) {
1605     if (patron.isnew() && orgSettings['ui.patron.registration.require_address']) {
1606         if (dojo.query('tr[name=uedit-addr-divider]').length < 2) {
1607             alert(localeStrings.NEED_ADDRESS);
1608             return;
1609         }
1610     }
1611     if(!noAlert) {
1612         if(!confirm(dojo.string.substitute(localeStrings.DELETE_ADDRESS, [id]))) return;
1613     }
1614     var addr = patron.addresses().filter(function(i){return (i.id() == id)})[0];
1615     if (addr) { addr.isdeleted(1); }
1616     var m_a = patron.mailing_address();
1617         if (typeof m_a == 'object' && m_a != null) { m_a = m_a.id(); }
1618         if (m_a == id) { patron.mailing_address(null); }
1619     var b_a = patron.billing_address();
1620         if (typeof b_a == 'object' && b_a != null) { b_a = b_a.id(); }
1621         if (b_a == id) { patron.billing_address(null); }
1622
1623     var rows = dojo.query('tr[addr='+id+']', tbody);
1624     for(var i = 0; i < rows.length; i++)
1625         rows[i].parentNode.removeChild(rows[i]);
1626     widgetPile = widgetPile.filter(function(w){return (w._addr != id)});
1627 }
1628
1629 function uEditToggleRequired(level) {
1630     openils.Util.removeCSSClass(tbody, 'hide-non-required');
1631     openils.Util.removeCSSClass(tbody, 'hide-non-suggested');
1632     openils.Util.show('uedit-show-required');
1633     openils.Util.show('uedit-show-required-br');
1634     openils.Util.show('uedit-show-suggested');
1635     openils.Util.show('uedit-show-suggested-br');
1636     openils.Util.show('uedit-show-all');
1637     switch(level) {
1638         case 1:
1639             openils.Util.hide('uedit-show-required');
1640             openils.Util.hide('uedit-show-required-br');
1641             openils.Util.addCSSClass(tbody, 'hide-non-required');
1642             break;
1643         case 2:
1644             openils.Util.hide('uedit-show-suggested');
1645             openils.Util.hide('uedit-show-suggested-br');
1646             openils.Util.addCSSClass(tbody, 'hide-non-suggested');
1647             break;
1648         default:
1649             openils.Util.hide('uedit-show-all');
1650             break;
1651     } 
1652 }
1653
1654 function printable_output() {
1655     var temp; var s = '=-=-=-=\r\n';
1656     for (var idx in widgetPile) {
1657         var w = widgetPile[idx];
1658         var val = uEditWidgetVal(w);
1659         var label;
1660         if (typeof w.idlField == 'undefined') {
1661             label = w._wtype;
1662             if (w._wtype == 'statcat') {
1663                 var stat = statCats.filter(
1664                     function(m){
1665                         return (m.id() == w._statcat) })[0];
1666                 label = stat.name();
1667             } else if (w._wtype == 'survey') {
1668                 var survey = surveys.filter(
1669                     function(m){
1670                         return (m.id() == w._survey) })[0];
1671                 var question = survey.questions().filter(
1672                     function(m){
1673                         return (m.id() == w._question) })[0];
1674                 label = survey.name() + ' : ' + question.question();
1675             } else {
1676                 label = 'FIXME';
1677             }
1678         } else {
1679             label = w.idlField.label;
1680         }
1681         if (temp != w._wtype) {
1682             temp = w._wtype;
1683             s += '-------\r\n';
1684         }
1685         s += label + ':\t' + (typeof val == 'object' ? '' : val) + '\r\n';
1686     }
1687     s += '=-=-=-=\r\n';
1688     return s;
1689 }
1690
1691 openils.Util.addOnLoad(load);