#####leave message   fq
class WordsController < ApplicationController
  
  before_filter :find_user, :only => [:new, :create, :destroy, :more, :back]
   
  def create
    if params[:new_form][:user_message].size>0
      unless params[:user_id].nil?
        message = params[:new_form][:user_message]
        @user.add_jour(User.current, message)
        # if a_message.size > 5
          # @message = a_message[-5, 5]
        # else
          # @message = a_message
        # end
        # @message_count = a_message.count
      end
    end
    @jour = @user.journals_for_messages
    @jour.each_with_index {|j,i| j.indice = i+1}
     
    respond_to do |format|
     # format.html { redirect_to_referer_or {render :text => 'Watcher added.', :layout => true}}
      format.js
      #format.api { render_api_ok }
    end  
  end
  
  def destroy
    JournalsForMessage.delete_message(params[:object_id])  
    @jour = @user.journals_for_messages
    @jour.each_with_index {|j,i| j.indice = i+1}
    # if a_message.size > 5
      # @message = a_message[-5, 5]
    # else
      # @message = a_message
    # end
    # @message_count = a_message.count
    
    respond_to do |format|
      format.html { redirect_to :back }
      format.js
      #format.api { render_api_ok }
    end
  end
  
  def new
    @jour = JournalsForMessage.find(params[:journal_id]) if params[:journal_id]
    if @jour
      user = @jour.user
      text = @jour.notes
    else
      user = @user
      text = []
    end
    # Replaces pre blocks with [...]
    text = text.to_s.strip.gsub(%r{<pre>((.|\s)*?)</pre>}m, '[...]')
    @content = "#{ll(Setting.default_language, :text_user_wrote, user)}\n> "
    @content << text.gsub(/(\r?\n|\r\n?)/, "\n> ") + "\n\n"
  rescue ActiveRecord::RecordNotFound
    render_404
  end
  
  def more
    @jour = @user.journals_for_messages
    @jour.each_with_index {|j,i| j.indice = i+1}
    @state = true
    
    respond_to do |format|
      format.html { redirect_to :back }
      format.js
      #format.api { render_api_ok }
    end
  end
  
  def back
    @jour = @user.journals_for_messages
    @jour.each_with_index {|j,i| j.indice = i+1}
    @state = false
    
    respond_to do |format|
      format.html { redirect_to :back }
      format.js
      #format.api { render_api_ok }
    end
  end
  
  private

  def find_user
    if params[:user_id]
      @user = User.find(params[:user_id])
    end
  rescue
    render_404
  end
  
  #######end of message
end