# File app/controllers/tasks_controller.rb, line 50
  def update
    redirect_to(:controller => 'backlogs', :action => :index) unless params[:id]
    if params[:task] && params[:task][:description] == ''
      destroy
      return
    end
    @task = Task.find(params[:id])
    unless (@task.period && @task.period.active?) || (params[:task] && params[:task][:period_id] && params[:task][:period_id].to_i > 0 && (period = Period.find_by_id(params[:task][:period_id])) && period.active?)
      @task.errors.add(:period_id, "You may not update a task in an inactive period.  Move the task to an active period first.")
      back_or_redirect_to :controller => 'periods', :action => :show, :id => @task.period, :task => @task.id
      return
    end
    
    # TODO (uwe): This should be moved to the Task model: Task#period=
    if params[:task] && params[:task][:period_id]
      if params[:task][:period_id] != ''
        if params[:task][:period_id].to_i != @task.period_id
          @task.remove_from_list
          params[:task][:position] = Period.find(params[:task][:period_id]).tasks.size
        end
      else
        if @task.period_id != nil
          @task.remove_from_list
          @task.period = nil
          new_pos = @task.backlog.tasks.count(:conditions => 'period_id IS NULL') + 1
          params[:task][:position] = new_pos
        end
      end
    end
    
    if params[:task] && @task.update_attributes(params[:task])
      flash[:notice] = 'Task was successfully updated.'
      if params[:task][:todo] && params[:task][:todo].to_i == 0
        unless @task.finished_at
          next_task = @task.lower_item || @task.higher_item
          @task.finish Task::COMPLETED, true, user
          @task.save!
          back_or_redirect_to :controller => 'periods', :action => :show, :id => @task.period, :task => next_task ? next_task.id : nil
        else
          back_or_redirect_to :controller => 'periods', :action => :show, :id => @task.period, :task => @task.id
        end
      else
        if @task.finished_at
          reopen
        else
          if @task.period
            back_or_redirect_to :controller => 'periods', :action => :show, :id => @task.period, :task => @task.id
          else
            back_or_redirect_to :controller => 'backlogs', :action => :show, :id => @task.backlog, :task => @task.id
          end
        end
      end
    else
      flash[:notice] = 'Task was not saved.'
      populate_layout
      edit
      render :action => 'edit'
    end
  end