/*
  Creates a pop-outed browser window when the user clicks on the specified element.
  After the new window is closed, a callback may be fired in the main window.

  Example:

  var target = '/facebook_sharing/connect',
    opts   = { popoutOpts: 'width=1024,height=460' };
  $('.facebook_connect').popoutWindow(target, 'facebookPopout', opts);

*/

(function ($) {

  /*
    Mandatory arguments:

      target:     The url to open
      popoutName:  The name of the popout
              This should be unused key in the main window's object namespace

    Optional arguments:

      opts.selector:     The jQuery selector to be passed into the 'on' call
      opts.close_callback:   The callback to be fired when the popout window is closed
      opts.popoutOpts:    Options to be sent to window.open
                   This is a comma separated list of features
      opts.success_callback: The callback to be fired when the popout window is marked
                   success
      opts.error_callback:   The callback to be fired when the popout window is marked
                   error
  */

  $.fn.popoutWindow = function (target, popoutName, opts) {

    opts = opts || {};

    if (!opts.beforeFilter) {
      opts.beforeFilter = function () {
        return true;
      };
    }

    if (!opts.closeCallback) {
      opts.closeCallback = function () {
        window.location.reload();
      };
    }

    if (!opts.successCallback) {
      opts.successCallback = function () {
        window.location.reload();
      };
    }

    if (!opts.errorCallback) {
      opts.errorCallback = function () { };
    }

    return this.each(function () {

      $(this).on('click', opts.selector, function (e) {
        var $this = $(this);

        e.preventDefault();

        if (!opts.beforeFilter() || $this.data('popout_debounce')) {
          return;
        }

        if ($this.data('popout_interval')) {
          clearInterval($this.data('popout_interval'));
        }

        var actualTarget;
        if (_.isFunction(target)) {
          actualTarget = target();
        } else {
          actualTarget = target;
        }
        window[popoutName] = window.open(actualTarget, popoutName, opts.popoutOpts);

        $this.data('popout_debounce', true);
        setTimeout(function () {
          $this.data('popout_debounce', false);
        }, 2000);

        $this.data('popout_interval', setInterval(function () {
          if (window[popoutName] && window[popoutName].closed) {
            clearInterval($this.data('popout_interval'));
            opts.closeCallback();
          }
          if (window[popoutName] && window[popoutName].success) {
            clearInterval($this.data('popout_interval'));
            opts.successCallback();
          }
          if (window[popoutName] && window[popoutName].error) {
            clearInterval($this.data('popout_interval'));
            opts.errorCallback();
          }
        }, 500));
      });

    });

  };

})(jQuery);
