class AppliedProjectController < ApplicationController

  #申请加入项目
  def applied_join_project
    @user_id = params[:user_id]
    @project = Project.find_by_id(params[:project_id])
    if params[:project_join]
      if @project
        user = User.find @user_id
        if user.member_of?(@project)
          @status = 3
        else
          @applieds = AppliedProject.where("user_id = ? and project_id = ?", params[:user_id],params[:project_id])
          if  @applieds.count == 0
            appliedproject = AppliedProject.create(:user_id => params[:user_id], :project_id => params[:project_id])
            Mailer.run.applied_project(appliedproject)
            @status = 2
          else
            @status = 1
          end
        end
      else
        @status = 0
      end
      respond_to do |format|
        format.js
      end
      return
    end

    @applieds = AppliedProject.where("user_id = ? and project_id = ?", params[:user_id],params[:project_id])
    if  @applieds.count == 0
      appliedproject = AppliedProject.create(:user_id => params[:user_id], :project_id => params[:project_id])
      Mailer.run.applied_project(appliedproject)
    end

    #redirect_to project_path(params[:project_id])
    #redirect_to_referer_or {render :text => ( 'applied success.'), :layout => true}
    respond_to do |format|
      format.html { redirect_to_referer_or {render :text => (watching ? 'Watcher added.' : 'Watcher removed.'), :layout => true}}
      format.js { render :partial => 'set_applied'}
    end
  end

  #取消申请
  def unapplied_join_project
    @project = Project.find(params[:project_id])
    #@applied = AppliedProject.find(params[:id])
    #@applied.destroy

    AppliedProject.deleteappiled(params[:user_id], params[:project_id])

    respond_to do |format|
      format.html { redirect_to_referer_or {render :text => (watching ? 'Watcher added.' : 'Watcher removed.'), :layout => true}}
      format.js { render :partial => 'set_applied' }
    end
  end

end
