File: CardDialogOverlay.js

package info (click to toggle)
gcontactsync 1.0.0-1
  • links: PTS, VCS
  • area: main
  • in suites: jessie, jessie-kfreebsd
  • size: 1,536 kB
  • ctags: 396
  • sloc: makefile: 6
file content (686 lines) | stat: -rw-r--r-- 30,685 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
/* ***** BEGIN LICENSE BLOCK *****
 * Version: MPL 1.1/GPL 2.0/LGPL 2.1
 *
 * The contents of this file are subject to the Mozilla Public License Version
 * 1.1 (the "License"); you may not use this file except in compliance with
 * the License. You may obtain a copy of the License at
 * http://www.mozilla.org/MPL/
 *
 * Software distributed under the License is distributed on an "AS IS" basis,
 * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
 * for the specific language governing rights and limitations under the
 * License.
 *
 * The Original Code is gContactSync.
 *
 * The Initial Developer of the Original Code is
 * Josh Geenen <gcontactsync@pirules.org>.
 * Portions created by the Initial Developer are Copyright (C) 2008-2012
 * the Initial Developer. All Rights Reserved.
 *
 * Contributor(s):
 *
 * Alternatively, the contents of this file may be used under the terms of
 * either the GNU General Public License Version 2 or later (the "GPL"), or
 * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
 * in which case the provisions of the GPL or the LGPL are applicable instead
 * of those above. If you wish to allow use of your version of this file only
 * under the terms of either the GPL or the LGPL, and not to allow others to
 * use your version of this file under the terms of the MPL, indicate your
 * decision by deleting the provisions above and replace them with the notice
 * and other provisions required by the GPL or the LGPL. If you do not delete
 * the provisions above, a recipient may use your version of this file under
 * the terms of any one of the MPL, the GPL or the LGPL.
 *
 * ***** END LICENSE BLOCK ***** */

if (!com) var com = {}; // A generic wrapper variable
// A wrapper for all GCS functions and variables
if (!com.gContactSync) com.gContactSync = {};

window.addEventListener("load",
  /** Initializes the CardDialogOverlay when the window has finished loading. */
  function gCS_CardDialogOverlayLoadListener(e) {
    com.gContactSync.CardDialogOverlay.init();
  },
false);
/**
 * Attributes added to TB by gContactSync AND present in the card dialog overlay
 */
com.gContactSync.gAttributes = {
  "ThirdEmail":           {}, 
  "FourthEmail":          {},
  "HomeFaxNumber":        {},
  "OtherNumber":          {},
  "PrimaryEmailType":     {},
  "SecondEmailType":      {},
  "ThirdEmailType":       {},
  "FourthEmailType":      {},
  "WorkPhoneType":        {},
  "HomePhoneType":        {},
  "FaxNumberType":        {},
  "CellularNumberType":   {},
  "PagerNumberType":      {},
  "HomeFaxNumberType":    {},
  "OtherNumberType":      {},
  "WebPage1Type":         {},
  "WebPage2Type":         {}
};
/**
 * Adds a tab to the tab box in the New and Edit Card Dialogs.  Using JavaScript
 * is necessary because the tab box doesn't have an ID.
 * @class
 */
com.gContactSync.CardDialogOverlay = {
  /** The XUL namespace */
  mNamespace:  "http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul",
  /** The number of times an attempt was made to initialize the dialog */
  mLoadNumber: 0,
  /** This stores whether the contact is read-only (ie from LDAP or the Mac AB) */
  mDisabled:   false,
  /**
   * Adds a tab to the tab box, if possible.  Waits until the abCardOverlay is
   * loaded.
   */
  init: function CardDialogOverlay_init() {
    // if it isn't finished loading yet wait another 200 ms and try again
    if (!document.getElementById("abTabs")) {
      // if it has tried to load more than 50 times something is wrong, so quit
      if (com.gContactSync.CardDialogOverlay.mLoadNumber < 50)
        setTimeout(com.gContactSync.CardDialogOverlay.init, 200);
      com.gContactSync.CardDialogOverlay.mLoadNumber++;
      return;
    }
    for (var i = 0; i < com.gContactSync.Preferences.mSyncPrefs.numRelations.value; ++i) {
      com.gContactSync.gAttributes["Relation" + i] = "";
      com.gContactSync.gAttributes["Relation" + i + "Type"] = "";
    }

    try {
      // QI the card if it doesn't have the getProperty method
      // if the card cannot accept custom attributes, quit and do not add the
      // extra tabs
      if (!gEditCard.card.getProperty)
        gEditCard.card.QueryInterface(Components.interfaces.nsIAbMDBCard);
    }
    catch (e) {
      document.getElementById("gContactSyncTab").collapsed = true;
      return;
    }
    // some contacts are read-only so extra attributes should be disabled for
    // those cards (see Mozdev Bug 20169)
    try {
      com.gContactSync.CardDialogOverlay.mDisabled = document.getElementById("PreferMailFormatPopup").disabled;
    }
    catch (ex) {
      com.gContactSync.alertError("Error while determining if contact is read-only: " + ex);
      com.gContactSync.CardDialogOverlay.mDisabled = true;
    }
    // add the email type drop down menus
    try {
      // add the type for Postbox (this does nothing for TB or Seamonkey)
      if (!this.addPostboxEmailType(document.getElementById("PrimaryEmail"))) {
        var emailTypes       = com.gContactSync.gdata.contacts.EMAIL_TYPES,
            primaryEmailBox  = this.getBox("PrimaryEmail"),
            secondEmailBox   = this.getBox("SecondEmail"),
            thirdEmailBox    = this.getBox("ThirdEmail"),
            fourthEmailBox   = this.getBox("FourthEmail");
        // add the type menulist to e-mail elements if this isn't Postbox
        this.addMenuItems(primaryEmailBox, emailTypes, "PrimaryEmailType", "other");
        this.addMenuItems(secondEmailBox,  emailTypes, "SecondEmailType",  "other");
        this.addMenuItems(thirdEmailBox,   emailTypes, "ThirdEmailType",   "other");
        this.addMenuItems(fourthEmailBox,  emailTypes, "FourthEmailType",  "other");
      }
      else {
        document.getElementById("additionalEmailBox").collapsed = true;
      }
    }
    catch (ex0) {
      com.gContactSync.alertError("Unable to setup email types: " + ex0);
    }
    var newDialog      = false, // post-Mailnews Core Bug 63941 - TODO - can this be removed (Postbox?)
        showPhoneTypes = com.gContactSync.Preferences.mSyncPrefs.phoneTypes.value,
        swap           = com.gContactSync.Preferences.mSyncPrefs.swapMobilePager.value,
        work           = document.getElementById("WorkPhone"),
        home           = document.getElementById("HomePhone"),
        fax            = document.getElementById("FaxNumber"),
        pager          = document.getElementById("PagerNumber"),
        mobile         = document.getElementById("CellularNumber"),
        workLabel      = work.parentNode.previousSibling;
    // then replace all phone labels and remove the access keys
    if (!workLabel) {
      newDialog = true;
      workLabel = work.previousSibling;
    }
    if (showPhoneTypes) {
      if (swap) {
        try {
          // swap pager and mobile phone textboxes and values
          pager = document.getElementById("PagerNumber");
          pager.setAttribute("id", "tmp");
          var pagerValue = pager.value,
              mobile     = document.getElementById("CellularNumber");
          mobile.setAttribute("id", "PagerNumber");
          pager.setAttribute("id", "CellularNumber");
          pager.value = mobile.value;
          mobile.value = pagerValue;
        }
        catch (e1) {
          com.gContactSync.alertError("Unable to swap pager and mobile number values\n" + e1);
        }
      }

      try {
        workLabel.value = com.gContactSync.StringBundle.getStr("first");
        workLabel.setAttribute("accesskey", "");
        var homeLabel = newDialog ? home.previousSibling
                                  : home.parentNode.previousSibling;
        homeLabel.value = com.gContactSync.StringBundle.getStr("second");
        homeLabel.setAttribute("accesskey", "");
        var faxLabel = newDialog ? fax.previousSibling
                                 : fax.parentNode.previousSibling;
        faxLabel.value = com.gContactSync.StringBundle.getStr("third");
        faxLabel.setAttribute("accesskey", "");
        pager = document.getElementById("PagerNumber");
        var pagerLabel = newDialog ? pager.previousSibling
                                   : pager.parentNode.previousSibling;
        pagerLabel.value = com.gContactSync.StringBundle.getStr(swap ? "fifth" : "fourth");
        pagerLabel.setAttribute("accesskey", "");
        mobile = document.getElementById("CellularNumber");
        var mobileLabel = newDialog ? mobile.previousSibling
                                    : mobile.parentNode.previousSibling;
        mobileLabel.value = com.gContactSync.StringBundle.getStr(swap ? "fourth" : "fifth");
        mobileLabel.setAttribute("accesskey", "");
      }
      catch (ex2) {
        com.gContactSync.alertError("Unable to replace phone labels and remove access keys\n" + ex2);
      }
    }
    else {
      // TODO - replace the Sixth and Seventh labels
    }
    var phoneTypes = com.gContactSync.gdata.contacts.PHONE_TYPES;
    try {
      // Add a Google Voice menuitem
      phoneTypes.push("grandcentral");
      
      // setup the types for the phone numbers
      var workBox = work.parentNode;
      this.addMenuItems(workBox, phoneTypes, "WorkPhoneType", "work")
          .collapsed = !showPhoneTypes;
      var homeBox = home.parentNode;
      this.addMenuItems(homeBox, phoneTypes, "HomePhoneType", "home")
          .collapsed = !showPhoneTypes;
      var faxBox = fax.parentNode;
      this.addMenuItems(faxBox, phoneTypes, "FaxNumberType", "work_fax")
          .collapsed = !showPhoneTypes;
      var mobileBox = mobile.parentNode;
      this.addMenuItems(mobileBox, phoneTypes, "CellularNumberType", "mobile")
          .collapsed = !showPhoneTypes;
      var pagerBox = pager.parentNode;
      this.addMenuItems(pagerBox, phoneTypes, "PagerNumberType", "pager")
          .collapsed = !showPhoneTypes;
      var homeFaxBox = document.getElementById("HomeFaxNumber").parentNode;
      this.addMenuItems(homeFaxBox, phoneTypes, "HomeFaxNumberType", "home_fax")
          .collapsed = !showPhoneTypes;
      var otherNumberBox = document.getElementById("OtherNumber").parentNode;
      this.addMenuItems(otherNumberBox, phoneTypes, "OtherNumberType", "other")
          .collapsed = !showPhoneTypes;
    }
    catch (ex3) {
      com.gContactSync.alertError("Unable to setup phone number types\n" + ex3);
    }
    
    // Add the website types
    var websiteTypes = com.gContactSync.gdata.contacts.WEBSITE_TYPES;
    var site1Box = document.getElementById("WebPage1").parentNode;
    this.addMenuItems(site1Box, websiteTypes, "WebPage1Type", "work");
    var site2Box = document.getElementById("WebPage2").parentNode;
    this.addMenuItems(site2Box, websiteTypes, "WebPage2Type", "home");
    if (newDialog) {
      // rename the hidden phone number field IDs
      try {
        document.getElementById("HomeFaxNumber").id     = "OldHomeFaxNumber";
        document.getElementById("HomeFaxNumberType").id = "OldHomeFaxNumberType";
        document.getElementById("OtherNumber").id       = "OldOtherNumber";
        document.getElementById("OtherNumberType").id   = "OldOtherNumberType";
      }
      catch (e) {}
      try {
        // change the width of the phone numbers
        var phoneIDs = ["HomePhone", "WorkPhone", "CellularNumber", "FaxNumber",
                        "PagerNumber"];
        for (var i = 0; i < phoneIDs.length; i++) {
          var elem = document.getElementById(phoneIDs[i]);
          if (!elem) continue;
          elem.setAttribute("width", "150px");
        }
        // add the sixth and seventh numbers below 1 - 5
        var sixthNum   = this.setupNumBox("HomeFaxNumber",
                                          com.gContactSync.StringBundle.getStr("sixth")),
            seventhNum = this.setupNumBox("OtherNumber",
                                     com.gContactSync.StringBundle.getStr("seventh"));
        pager.parentNode.parentNode.appendChild(sixthNum);
        this.addMenuItems(sixthNum, phoneTypes, "HomeFaxNumberType", "home_fax")
          .collapsed = !showPhoneTypes;
        pager.parentNode.parentNode.appendChild(seventhNum);
        this.addMenuItems(seventhNum, phoneTypes, "OtherNumberType", "other")
          .collapsed = !showPhoneTypes;
        
        // Add the relation fields
        try {
          document.getElementById("relationFields").removeAttribute("hidden");
          var relationTypes = [""];
          // copy the relation types over
          for (i in com.gContactSync.gdata.contacts.RELATION_TYPES) {
            relationTypes.push(i);
          }
          var groupbox = document.getElementById("relationsGroupBox");
          for (var i = 0; i < com.gContactSync.Preferences.mSyncPrefs.numRelations.value; i++) {
            var relationBox = document.createElement("hbox");
            var spacer = document.createElement("spacer");
            spacer.setAttribute("flex", 1);
            relationBox.appendChild(spacer);
            var relationText = document.createElement("textbox");
            relationText.id = "Relation" + i;
            relationText.setAttribute("class", "uri-element");
            relationText.setAttribute("width", "180px");
            relationBox.appendChild(relationText);
            groupbox.appendChild(relationBox);
            this.addMenuItems(relationBox, relationTypes, "Relation" + i + "Type", "", com.gContactSync.StringBundle.getStr("relationWidth"));
          }
        }
        catch (ex5) {
          com.gContactSync.LOGGER.LOG_WARNING("Could not add the relation fields.", ex5);
        }
      }
      catch (ex6) {
        com.gContactSync.alertError("Unable to setup the extra tabs\n" + ex6);
      }
    }
    // if this is the old dialog, show the extra phone numbers
    else {
      try {
        // move the address descriptions below the addresses (rather than beside)
        var gbox = document.getElementById("addressDescGroupBox");
        if (gbox) {
          var parent = gbox.parentNode;
          parent.removeChild(gbox);
          parent.parentNode.firstChild.appendChild(gbox);
        }
        document.getElementById("numbersGroupBox").removeAttribute("hidden");
      }
      catch (e) {
        com.gContactSync.LOGGER.LOG_WARNING("Unable to move addressDescGroupBox" +
                                            " or remove hidden from numbersGB", e);
      }
    }
    
    // if this is a read-only card, make added elements disabled
    // the menulists are already taken care of
    // TODO update CardDialogOverlay...
    if (com.gContactSync.CardDialogOverlay.mDisabled) {
      document.getElementById("ThirdEmail").readOnly       = true;
      document.getElementById("FourthEmail").readOnly      = true;
      document.getElementById("HomeFaxNumber").readOnly    = true;
      document.getElementById("OtherNumber").readOnly      = true;
      document.getElementById("Relation").readOnly         = true;
      document.getElementById("Anniversary").readOnly      = true;
    }

    // Copy certain functions from the birthday datepicker (but show the year element)
    var anniversaryElem = document.getElementById("Anniversary");
    var birthdayElem    = document.getElementById("Birthday");
    anniversaryElem._constrainValue = birthdayElem._constrainValue;
    anniversaryElem._setFieldValue = birthdayElem._setFieldValue;

    // fix the width of the dialog
    window.sizeToContent();

    // override the check and set card values function
    com.gContactSync.originalCheckAndSetCardValues = CheckAndSetCardValues;
    CheckAndSetCardValues = com.gContactSync.CardDialogOverlay.CheckAndSetCardValues;
    // get the extra card values
    this.GetCardValues(gEditCard.card, document);
  },
  /**
   * Gets the parent node of an element with the given ID.
   * If there is no element with the given ID then this function will return
   * null.
   * @param aID The ID of the element whose parent node is returned.
   * @returns {XULElement} The parentNode of the element with the given ID.
   */
  getBox: function CardDialogOverlay_getBox(aID) {
    var elem = document.getElementById(aID);
    if (elem && elem.tagName === "emailaddress-input") { // Postbox
      return elem;
    }
    return elem ? elem.parentNode : null;
  },
  /**
   * Adds the e-mail type menulist to Postbox's emailaddress-input element.
   * This also overrides the addRow method to add the type menulist to
   * future emailaddress-input elements (and calls the original addRow)
   * @param aElem The emailaddress-input element.
   * @returns {boolean} True if the application is Postbox and the menulist was
   *                    added.
   */
  addPostboxEmailType: function CardDialogOverlay_addPBEmailType(aElem) {
    if (!aElem || aElem.tagName !== "emailaddress-input") {
      return false;
    }
    /*
    var emailTypes = com.gContactSync.gdata.contacts.EMAIL_TYPES;
    this.addMenuItems(aElem, emailTypes, "", "other");
    // save the original addRow method
    aElem.origAddRow = aElem.addRow;
    // override addRow to call the original then add the e-mail types
    aElem.addRow = function gContactSync_addRow() {
      // call the original
      this.origAddRow.apply(this, arguments);
      // add the e-mail type menulist
      com.gContactSync.CardDialogOverlay.addPostboxEmailType(this.nextSibling);
      // resize the window
      window.sizeToContent();
    }
    */
    return true;
  },
  /**
   * Sets the attributes added by this extension as the value in the textbox or
   * drop down menu in aDoc whose ID is identical to the attribute's name.
   * Calls the original CheckAndSetCardValues function when finished.
   * @param aCard  {nsIAbCard} The card to set the values for.
   * @param aDoc   {Document Object} The document.
   * @param aCheck Unused, but passed to the original method.
   */
  CheckAndSetCardValues: function CardDialogOverlay_CheckAndSetCardValues(aCard, aDoc, aCheck) {
    // make sure the required data is present (abCardOverlay.js)
    if (!CheckCardRequiredDataPresence(aDoc)) {
      return false;
    }
    var contact = new com.gContactSync.TBContact(aCard);
    var existingTypes = {
      "WorkPhoneType":      {},
      "HomePhoneType":      {},
      "FaxNumberType":      {},
      "CellularNumberType": {},
      "PagerNumberType":    {}
    };
    // iterate through all the added attributes and types and set the card's value
    // for each one of them
    for (var attr in com.gContactSync.gAttributes) {
      try {
        // if the element exists, set the card's value as its value
        var elem = aDoc.getElementById(attr);
        if (elem) {
          // I do not know why this is necessary, but it seems to be the only
          // way to get the value correct in TB 2...
          if (attr === "HomeFaxNumberType" || attr === "OtherNumberType") {
            elem.value = elem.getAttribute("value");
          }
          com.gContactSync.LOGGER.VERBOSE_LOG("Attribute: '" + attr + "' - Value: '" + elem.value + "'");
          contact.setValue(attr, elem.value);
        }
      }
      catch (e) {
        com.gContactSync.alertError("Error in com.gContactSync.CheckAndSetCardValues: " + attr + "\n" + e);
      }
    }

    // get the anniversary information from the dialog
    var anniversaryElem = aDoc.getElementById("Anniversary");
    var anniversaryMonth = anniversaryElem.monthField.value;
    var anniversaryDay = anniversaryElem.dateField.value;
    var anniversaryYear = anniversaryElem.yearField.value;

    com.gContactSync.LOGGER.VERBOSE_LOG("Anniversary: " + anniversaryYear + "-" + anniversaryMonth + "-" + anniversaryDay);

    // set the anniversary day, month, and year properties
    contact.setValue("AnniversaryDay", anniversaryDay);
    contact.setValue("AnniversaryMonth", anniversaryMonth);
    contact.setValue("AnniversaryYear", anniversaryYear);

    if (!contact.mContact.getProperty && gEditCard.abURI) {
      if (contact.mContact.editCardToDatabase) { // Thunderbird 2
        contact.mContact.editCardToDatabase(gEditCard.abURI);
      } else if (GetDirectoryFromURI) { // Postbox doesn't have editCardToDatabase
        var dir = GetDirectoryFromURI(gEditCard.abURI);
        if (dir) {
          dir.modifyCard(contact.mContact);
        }
      }
    }

    // ensure that every contact edited through this dialog has at least a dummy
    // e-mail address if necessary
    var primEmailElem = aDoc.getElementById("PrimaryEmail");
    if (!primEmailElem.value && gEditCard.abURI) {
      // if it is a new contact it isn't already in any lists
      // Check if it is in any mailing lists.  If so, force a dummy address
      // When fetching lists, do not get the contacts (if it is found there is
      // no need to get the contacts in every list)
      try {
        var tbAB = com.gContactSync.GAbManager.getAbByURI(gEditCard.abURI);
        var dummyEmailNeeded = tbAB.isMailList;
        if (!dummyEmailNeeded) {
          var lists = tbAB ? new com.gContactSync.GAddressBook(tbAB).getAllLists(true) : [];
          for (var i in lists) {
            // if the list does have the contact then make sure it gets a dummy
            // e-mail address regardless of the preference
            // do not check the PrimaryEmail address in hasContact since it is now
            // empty
            if (lists[i].hasContact(contact)) {
              dummyEmailNeeded = true;
              break;
            }
          }
        }
        if (dummyEmailNeeded) {
          primEmailElem.value = com.gContactSync.makeDummyEmail(contact.mContact, true);
          com.gContactSync.alert(com.gContactSync.StringBundle.getStr("dummyEmailAdded") + "\n" + primEmailElem.value);
        }
      } catch (e) {alert("Error checking if the contact needs a dummy e-mail address\n" + e);}
    }
    try {
      // call the original and return its return value
      return com.gContactSync.originalCheckAndSetCardValues.apply(this, arguments);
    } catch (ex) {alert("CheckAndSetCardValues threw an exception:\n" + ex);}
  },
  /**
   * A method that gets all of the attributes added by this extension and sets
   * the value of the textbox or drop down menu in aDoc whose ID is identical to
   * the attribute's name.
   * @param aCard {nsIAbCard} The card to get the values from.
   * @param aDoc  {Document Object} The document.
   */
  GetCardValues: function CardDialogOverlay_GetCardValues(aCard, aDoc) {
    // iterate through all the added type elements and get the card's value for
    // each one of them to set as the value for the element
    for (var attr in com.gContactSync.gAttributes) {
      try {
        var elem = aDoc.getElementById(attr);
        // if the element exists, set its value as the card's value
        if (elem) {
          var value;
          if (aCard.getProperty) // post Bug 413260
            value = aCard.getProperty(attr, null);
          else // pre Bug 413260
            value = aCard.getStringAttribute(attr);
          // set the element's value if attr isn't a type OR it is a type and
          // the card's value for the attribute isn't null or blank
          if (attr.indexOf("Type") == -1 || (value && value != "")) {
            elem.value = value;
            // If it is a menulist and the label is still blank (ie custom label)
            // then add it as a new menuitem
            if (elem.tagName === "menulist" && !elem.label) {
              var item = document.createElement("menuitem");
              item.setAttribute("value", value);
              item.setAttribute("label", value);
              elem.menupopup.appendChild(item);
              elem.value = value;
            }
          }
        }
      } catch (e) { com.gContactSync.alertError("Error in com.gContactSync.GetCardValues: " + attr + "\n" + e); }
    }

    // Anniversary
    var anniversaryElem = document.getElementById("Anniversary");
    var year, month, day;
    if (aCard.getProperty) { // post Bug 413260
      year  = aCard.getProperty("AnniversaryYear", null);
      month = aCard.getProperty("AnniversaryMonth", null);
      day   = aCard.getProperty("AnniversaryDay", null);
    } else { // pre Bug 413260
      year  = aCard.getStringAttribute("AnniversaryYear");
      month = aCard.getStringAttribute("AnniversaryMonth");
      day   = aCard.getStringAttribute("AnniversaryDay");
    }

    // Default the year to 2000 (a leap year)
    if (year && year < 10000 && year > 0) {
      anniversaryElem.year = year;
      anniversaryElem.yearField.value = year;
    } else {
      anniversaryElem.year = 2000;
      anniversaryElem.yearField.value = null;
    }
    if (month > 0 && month < 13) {
      anniversaryElem.month = month - 1;
    } else {
      anniversaryElem.monthField.value = null;
    }
    if (day > 0 && day < 32) {
      anniversaryElem.date = day;
    } else {
      anniversaryElem.dateField.value = null;
    }

    // In TB 10 the way photos are saved changed and now requires two copies of
    // each photo.  One persistent copy is required as TB will copy it to the
    // Photos directory and delete the previous copy when the contact is edited.
    // gContactSync only saves one copy so TB deletes the original on the first
    // edit of the contact then TB fails to copy from the original in future
    // edits of the contact.
    // As a workaround check if the photo at PhotoURI still exists.
    // If it doesn't exist then update it to point to the photo at PhotoName.
    var photoURI = aCard.getProperty("PhotoURI", "");
    var photoType = aCard.getProperty("PhotoType", "");
    if (photoURI && photoType === "file") {
      var ios = Components.classes["@mozilla.org/network/io-service;1"]
                              .getService(Components.interfaces.nsIIOService);
      var uriFile = ios.newURI(photoURI, null, null)
                       .QueryInterface(Components.interfaces.nsIFileURL)
                       .file;
      if (!uriFile.exists()) {
        var photoName = aCard.getProperty("PhotoName", "");
        com.gContactSync.LOGGER.VERBOSE_LOG("Photo workaround for URI: " +
                                            photoURI + "...Name: " + photoName);
        var photoNameFile = Components.classes["@mozilla.org/file/directory_service;1"]
                                      .getService(Components.interfaces.nsIProperties)
                                      .get("ProfD", Components.interfaces.nsIFile);
        photoNameFile.append("Photos");
        photoNameFile.append(photoName);
        if (photoNameFile.exists()) {
          var newPhotoURI = ios.newFileURI(photoNameFile).spec;
          com.gContactSync.LOGGER.VERBOSE_LOG("New URI: " + newPhotoURI);
          aCard.setProperty("PhotoURI", newPhotoURI);
          loadPhoto(aCard);
          setCardEditorPhoto(photoType, aCard);
        }
      }
    }
  
    if (com.gContactSync.isDummyEmail(aDoc.getElementById("PrimaryEmail").value))
      aDoc.getElementById("PrimaryEmail").value = null;
  },
  /**
   * Sets up a type menu list element with a menuitem for each string in the
   * array.
   * @param aBox   {XUL Box} The box element to which this menu list is added.
   * @param aArray {array}  The array of values to set for the menuitems.  There
   *                        must be a string in the string bundle with the same
   *                        name as the value.
   * @param aID    {string} The ID for this menu list, which should be the name
   *                        of the attribute with Type added to the end, such as
   *                        WorkNumberType
   * @param aValue {string} The default value to set for this list.
   * @param aWidth {int}    The maximum width, if any.
   *
   * @returns {XULElement}  The menulist element.
   */
  addMenuItems: function CardDialogOverlay_addMenuItems(aBox, aArray, aID, aValue, aWidth) {
    if (!aBox) {
      return false;
    }
    var menuList = document.createElement("menulist");
    menuList.setAttribute("id", aID);
    var menuPopup = document.createElement("menupopup");
    // put the default value first in the menupopup, if possible
    var index = aArray.indexOf(aValue);
    var elem;
    // Make sure the default value is in aArray
    if (index == -1) {
      aArray.push(aValue);
      index = aArray.length - 1;
    }
    if (index > -1 && index < aArray.length) {
      elem = document.createElement("menuitem");
      elem.setAttribute("value", aValue);
      elem.setAttribute("label", com.gContactSync.StringBundle.getStr(aValue ? aValue : "blank"));
      aArray[index] = null;
      menuPopup.appendChild(elem);
    }
    // then add the other values
    for (var i = 0; i < aArray.length; i++) {
      if (!aArray[i]) { // if this element is null it was the default value
        aArray[i] = aValue; // so restore its value and skip adding it again
        continue;
      }
      elem = document.createElement("menuitem");
      elem.setAttribute("value", aArray[i]);
      elem.setAttribute("label", com.gContactSync.StringBundle.getStr(aArray[i]));
      menuPopup.appendChild(elem);
    }
    menuList.setAttribute("sizetopopup", "always");
    if (aWidth) {
      menuList.setAttribute("width", aWidth);
      menuList.style.width = aWidth;
      menuList.style.maxWidth = aWidth;
    }
    // add the popup to the menu list
    menuList.appendChild(menuPopup);
    // disable the menu list if this card is read-only
    menuList.setAttribute("disabled", com.gContactSync.CardDialogOverlay.mDisabled);
    // add the menu list to the box
    aBox.appendChild(menuList);
    return menuList;
  },
  /**
   * Adds an hbox containing a label and textbox for a phone number.
   * @param aID    {string} The ID for the textbox.
   * @param aLabel {string} The text for the textbox's label.
   */
  setupNumBox: function CardDialogOverlay_setupNumBox(aID, aLabel) {
    var box = document.createElement("hbox");
    box.setAttribute("align", "center");
    var spacer = document.createElement("spacer");
    spacer.setAttribute("flex", 1);
    box.appendChild(spacer);
    var label = document.createElement("label");
    label.setAttribute("control", aID);
    label.setAttribute("value", aLabel);
    box.appendChild(label);
    var textbox = document.createElement("textbox");
    textbox.setAttribute("id", aID);
    textbox.setAttribute("class", "PhoneEditWidth");
    if (com.gContactSync.CardDialogOverlay.mDisabled)
      textbox.setAttribute("readonly", true);
    else if (textbox.hasAttribute("readonly"))
      textbox.removeAttribute("readonly");
    textbox.setAttribute("width", "150px");
    box.appendChild(textbox);
    return box;
  }
};