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