var NewDebate = Behavior.create({
  
  initialize:function(){
    this.setupDebateExampleText();
    this.setupDebateTopicObservers();
  },
  
  setupDebateExampleText: function(){
    this.debateTopic = this.element.down('#debate_topic');
    this.debateTopic.value = "Ex: Who is the greatest rapper ever, Biggie or Pac?";
    this.debateTopic.exampleSet = true;
  },

  setupDebateTopicObservers: function() {
    $('debate_topic').observe('focus', function(evt) {
      var textField = evt.element();
      if (textField.exampleSet) { textField.exampleSet = false; textField.value = ''; }
      $('new_debate').removeClassName('inactive').addClassName('active');
    });
    
    $('debate_topic').observe('blur', function(evt) {
      var textField = evt.element();
      if (!textField.exampleSet && textField.value.blank()) {
        this.setupDebateExampleText();
      }
      $('new_debate').removeClassName('active').addClassName('inactive');
    }.bind(this));
  }
  
});

var DebateVote = Behavior.create ({
  initialize: function(){
    this.vote_link = this.element;
    this.debate_response = this.vote_link.up('.debate_response');
    this.actions = this.debate_response.down('.actions');
    this.score = this.debate_response.down('.score');
    this.debate_prompt = $('debate_prompt');
  },
  
  onclick: function(evt){
    evt.stop();
    new Ajax.Request(this.element.href, {
      requestHeaders: { Accept: 'application/json' },
      method: 'POST',
      onFailure: this._handleFailure.bind(this),
      onSuccess: this._handleSuccess.bind(this), 
    });
  },
  
  _handleFailure: function(transport){
    console.log(transport.responseJSON);
  },
  
  _handleSuccess: function(transport){
    var data = transport.responseJSON;
    this.debate_prompt.update(data.debate_prompt.content);
    this.actions.update(data.actions.content);
    this.score.update(data.score.content);
  }
});

var NewDebateResponse = Behavior.create({
  initialize: function(){
    this.form = this.element;
    this.form.insert({bottom: "<img class=\"spinner large center\" style=\"display:none;\">"});
    this.spinner = this.form.down(".spinner");
  },
  
  onsubmit: function(event){
    event.stop();
    this.showSpinner();
    this.form.request({
      requestHeaders: { 'Accept': 'application/json' },
      onSuccess: this._handleSuccess.bind(this),
      onFailure: this._handleFailure.bind(this)
    });
  },

  showSpinner: function(){
    this.spinner.clonePosition(this.form);
    this.form.setOpacity(0.25);
    this.spinner.show();
  },
  
  hideSpinner: function(){
    this.spinner.hide();
    this.form.setOpacity(1);
  },
  
  _handleSuccess: function(transport){
    var data = transport.responseJSON;
    window.location.href = data.redirectTo
  },
  
  _handleFailure: function(transport){
    this.hideSpinner();
    this.form.update(transport.responseJSON.content);
  }
  
});

var DebateResponseManager = Behavior.create ({
  initialize: function() {
    this.debate_prompt = $('debate_prompt');
    this._debateResponse = this.element.up('.debate_response');
    this.rationale = this._debateResponse.down('.rationale');
    this.editor = this._debateResponse.down('.response_editor');
    this.error_explanation = this.editor.down('.errorExplanation');
    this.editor_button = this._debateResponse.down('.edit_response_button');
    this.delete_button = this._debateResponse.down('.delete_response_button');
    this.editor_form = this._debateResponse.down('.edit_debate_response');
    this._registerHandlers();
    },

  _registerHandlers: function() {
    this.editor_button.observe('click', this._toggleEditor.bind(this) );
    this.delete_button.observe('click', this._handleDelete.bind(this) );
    this._debateResponse.down('.edit_debate_response').observe('change', this._handleSubmit.bind(this) );
  },

  _toggleEditor: function(evt) {
    this.rationale.toggle() && this.editor.toggle();
    this.editor_button.update( this.editor.visible() ? 'Cancel' : 'Edit');
    if (evt) { evt.stop(); }
  },

  _handleSubmit: function(evt) {
    $(this.editor_form).request({ 
      evalJSON: 'force', 
      onSuccess: this._handleSubmitSuccess.bind(this),
      onFailure: this._handleSubmitFailure.bind(this) 
    });
    evt.stop();
  },

  _handleSubmitSuccess: function(transport) {
    this.rationale.update(transport.responseJSON.content);
    this.error_explanation.update('');
    this._toggleEditor();
  },

  _handleSubmitFailure: function(transport) {
    this.error_explanation.update(transport.responseJSON.error)
  },

  _handleDelete: function(evt) {
    new Ajax.Request(this.delete_button.readAttribute('data-url'), {
      method: 'delete', 
      evalJSON: 'force',
      parameters: Application.authenticityTokenParameter(),
      onSuccess: this._handleDeleteSuccess.bind(this),
      onFailure: this._handleDeleteFailure.bind(this)
    });
    evt.stop();
  },

  _handleDeleteSuccess: function(transport) { 
    this._debateResponse.remove();
    this.debate_prompt.update(transport.responseJSON.debate_prompt.content);
  },

  _handleDeleteFailure: function(transport) { 
    console.log(transport); 
  }
});

Event.addBehavior({
  'body.debates form#new_debate': NewDebate,
  'body.debates .debate_response .actions a.vote-link': DebateVote,
  'body.debates .debate_response .admin': DebateResponseManager,
  'body.debates #new_debate_response': NewDebateResponse // form#debate_response is not working
});
