/*
  Launcher for remote-scripted popup window to select name/email pairs from a Plaxo member's address book.
  Contact: Joseph Smarr (joseph@plaxo.com)

  Dependencies: {{{
  - util.js (everyone needs this)
  - basic.js (for popup)
  }}}
*/

registerNamespaces("Plaxo");

Plaxo.Util.Timer.setTimersEnabled(false);

// {{{ stolen from prototype.js so partners don't need to include it (js: moved under Plaxo namespace to play nice with jQuery)

Plaxo.byId = function(elem) {
  if (typeof elem == 'string') {
    elem = document.getElementById(elem);
  }
  return elem;
};

Plaxo.Class = {
  create: function() {
    return function() {
      this.initialize.apply(this, arguments);
    }
  }
};

// }}}

Plaxo.ABLauncher = Plaxo.Class.create();
Plaxo.ABLauncher.prototype = {

  initialize: function() {
      Plaxo.Debug.trace('initializing');
    // {{{ member vars
    this.name =             "Plaxo.ABLauncher 1.0";
    this.abWin =             null;    // popup window

    this.textArea =          null;    // text area with name/emails we're controlling
    this.currentEmails =     {};      // emails currently in text box
    // }}}
  },

  dialogWidth: 460,
  dialogHeight: 480, // if you change this, also change ab_chooser.css (main_content, ab_contents)
 
  /** Turns a map of options into a query string. */
  toQueryString: function(options) {
    var queryComponents = [];
    for (key in options) {
      if (typeof options[key] == 'function') continue;
      var queryComponent = encodeURIComponent(key) + '=' + encodeURIComponent(options[key]);
      queryComponents.push(queryComponent);
    }
    return queryComponents.join('&');
  },

  showABChooser: function(textArea, plaxoHost, callbackPage, extraOptions) {

    this.textArea = Plaxo.byId(textArea);
    if (!this.textArea) {
      Plaxo.Debug.error("can't find text area -> aborting");
      return;
    }
    this.currentEmails = {};
    this.extractEmails(this.textArea.value);

    if (!this.abWin || this.abWin.closed) {
      // ensure callback is on the same domain as the caller
      if (callbackPage.length > 0 && callbackPage.charAt(0) != '/') {
        callbackPage = '/' + callbackPage; // make sure we have a true absolute path
      }
      var cb = location.protocol + '//' + location.host + callbackPage;
      extraOptions.cb = cb;
      
      // record partner URL and when we opened the widget
      extraOptions.host = location.href;
      extraOptions.ts = new Date().getTime();

      var qs = this.toQueryString(extraOptions);
      if (extraOptions.comcast) {
        var url = 'https://' + plaxoHost + '/scc?action=abchooser&' + qs; //'ts=' + ts + '&cb=' + escape(cb) + '&host=' + escape(location.href);
      } else {
        var url = 'https://' + plaxoHost + '/ab_chooser?' + qs; //'ts=' + ts + '&cb=' + escape(cb) + '&host=' + escape(location.href);
      }
      if (extraOptions.plaxoMembersOnly) {
        url += '&direct=1';
      } else {
        var emails = this.getCurrentEmailList().join(',');
        url += '&t=import&emails=' + escape(emails);
      }
      this.abWin = popup(url, "PlaxoABC", this.dialogWidth, this.dialogHeight, 'resizable=no,scrollbars=no');
    }
    if (this.abWin) {
      this.abWin.focus();
    }
  },

  getCurrentEmailList: function() {
    var emails = [];
    for (email in this.currentEmails) {
      emails.push(email);
    }
    return emails;
  },

  /** Extracts all the e-mail addresses in the given string. */
  extractEmails: function(str) {
    var index = 0;
    while (true) {
      index = str.indexOf('@', index);
      if (index == -1) break;

      // for each @, find the beginning and end and extract the email
      var start = Plaxo.String.findBoundary(str, index - 1, false);
      var end = Plaxo.String.findBoundary(str, index + 1, true);
      var email = str.substring(start, end + 1).toLowerCase();
      this.currentEmails[email] = 1;

      index++;
    }
  },
 
  // {{{ adding checked recipients to textbox

  /** Returns true iff the given email is already in the text area. */
  hasCurrentEmail: function(email) {
    return this.currentEmails[email.toLowerCase()];
  },

  addCheckedRecipients: function(text) {
    // TODO: kill first line
    if (!text) return false;

    if (!this.textArea) {
      Plaxo.Debug.error('no text area to add recipients to');
      return false;
    }

    var curText = this.textArea.value;
    if (curText && !curText.trim().endsWith(',')) curText += ', ';
    curText += text;
    this.setTextAreaValue(curText);
    return true;
  },

  setTextAreaValue: function(str) {
    this.textArea.value = str;
  }

  // }}}

};

// shared instance of ab launcher
Plaxo.abl = null;

/**
 * Opens the Plaxo AB Chooser widget.
 *
 * @param textArea the id of the textarea to fill in name/email pairs, or a ref to the textArea
 * @param callbackPage uri on caller's site for page to complete adding the data (e.g. /site/ifr.html)
 * @param plaxoHost (optional) plaxo domain to host ab chooser (for testing only, default: www.plaxo.com)
 * @param plaxoMembersOnly (optional) only show UI to sign in as an existing plaxo member (default: false)
 * @param extraOptions (optional) map of string->string key/value pairs for extra options:
 *        - selType -> multiple (default) | single (allow one or multiple contacts to be chosen)
 *        - fieldType -> email (default) | address (what contact info to choose (email, mailing address)
 *        - plaxoMembersOnly -> false (default) | true (whether to not show import for non-plaxo members)
 */
function showPlaxoABChooser(textArea, callbackPage, plaxoHost, extraOptions) {
  if (!Plaxo.abl) Plaxo.abl = new Plaxo.ABLauncher();
  if (!plaxoHost) plaxoHost = 'www.plaxo.com';
  if (!extraOptions) extraOptions = {};
  Plaxo.abl.showABChooser(textArea, plaxoHost, callbackPage, extraOptions);
}


