var Chat = Class.create({

  chatwindowPrefix: "#chatwindow",

  periodicalExecuter:           { },
  checkForChatmessagesInterval: 10,
  authenticityToken:            "",
  running:                      true,
  
  setAuthenticityToken: function(value) {
    this.authenticityToken = value;
  },

  getAuthenticityToken: function() {
    return this.authenticityToken;
  },
  
  isRunning: function() {
    return this.running;
  },

  showWindow: function(id, chatsession_id, chatmessages_url, top, left, width, height) {
    var elementId = this.chatwindowPrefix + "_" + id;

    // create dialog
    j$(elementId).dialog({
      position: [ top, left ],
      width: width,
      height: height,
      minWidth: 200,
      minHeight: 300,
      
      dragStop: function(event, ui) {
        new Ajax.Request(
          "/chatsessions/" + chatsession_id + "/chatwindow" +
            "?authenticity_token=" + chat.getAuthenticityToken() +
            "&window[left]=" + ui.position.left +
            "&window[top]=" + ui.position.top,
          { method: 'put' }
        );
      },
      
      // calculate input field wisth
      resize: function(event, ui) {
        j$('#chatwindows_window_' + id + '_input').css('width', ui.size.width - 130)
      },
      
      resizeStop: function(event, ui) {
        new Ajax.Request(
          "/chatsessions/" + chatsession_id + "/chatwindow" +
            "?authenticity_token=" + chat.getAuthenticityToken() +
            "&window[width]=" + ui.size.width +
            "&window[height]=" + ui.size.height,
          { method: 'put' }
        );
      },
      
      close: function(event, ui) {
        new Ajax.Request(
          "/chatsessions/" + chatsession_id + "/chatwindow" +
            "?authenticity_token=" + chat.getAuthenticityToken() +
            "&window[visible]=false",
          { method: 'put' }
        );
      }
    });

    // set input field wisth
    j$('#chatwindows_window_' + id + '_input').css('width', width - 130)
    
    if (!this.periodicalExecuter) this.periodicalExecuter = new Hash();
    
    // create PeriodicalExecuter for polling of chatmessages
    this.periodicalExecuter[id] = new PeriodicalExecuter(function(executer) {
      if ( chat.isRunning() ) {
        new Ajax.Request(chatmessages_url, {
          asynchronous: true,
          evalScripts:  true,
          method:       'GET',
          parameters:   'authenticity_token=' + encodeURIComponent( chat.getAuthenticityToken() )
        });
      } else {
        executer.stop();
      }
    }, this.checkForChatmessagesInterval)
  },
  
  hideWindow: function(id) {
    var elementId = this.chatwindowPrefix + "_" + id;

    // stop the periodical executer
    this.periodicalExecuter[id].stop();
    
    // close the dialog
    j$(elementId).dialog("close");
  },
  
  stopAllExecuters: function() {
    this.running = false;
  }

});

var chat = new Chat();

