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