var SurveyPopup = Class.create({

  // Create a new SurveyPopup that will go to the given URL
  initialize: function(url, ask, options) {
    this.url = url;

    this.ask = $(ask);

    if(!options) options = {}
    default_options = {
      width: 300  // Default size of popup in pixels
    };
    this.options = $H(default_options).merge(options);

    // Configure popup (hide it and center it)
    this.ask.hide(); // Just in case
    this.ask.setStyle({
      width: this.options.get('width')+'px',
      position: 'absolute',
      top: '3em', left: '50%',
      marginLeft: -1*this.options.get('width')/2+'px'
    });

    // Bind event listeners to buttons
    this.ask.down('.deny').observe('click', this.deny.bind(this));
    this.ask.down('.close').observe('click', this.close.bind(this));
    this.ask.down('.launch').observe('click', this.launch.bind(this));
  },

  /* Open up div to ask for survey participation. Will check if the
   * user has previous denyed the popup and ignore if they have.
   * 
   * USAGE: (new SurveyPopup('url', 'popup')).open()
   */
  open: function() {
    if(this.denyed()) return;
    this.ask.show();
  },

  // Close div and never ask again
  deny: function() {
    this.setDeny();
    this.close();
  },

  // Just close the div. Will ask again later
  close: function() {
    this.ask.hide()
  },

  // Actually launch the survey, the person should not be asked again
  launch: function() {
    this.setDeny();
    location.href = this.url;
  },

  // Has the user previously denyed the popup?
  denyed: function() {
    return document.cookie.include(this.denyKey()+'=deny')
  },

  // Set the cookie to actually deny the popup in the future
  setDeny: function() {
    var future = 'Sat, 5 Nov 2020 00:00:00 UTC';
    document.cookie = this.denyKey()+'=deny; expires='+future+'; path=/'
  },

  // The key used to store the deny by
  denyKey: function() {
    return "popup_"+this.url.replace(/\W+/g, '_');
  }

});
