class RaterController < ApplicationController

  # Depending on the type of request, respond differently.
  # Regular (GET) requests are given a redirection (back)
  # While XHR requests respond by returning the updated rating widget
  #
  # TODO deal with case where Guest rating is not allowed
  #   page << 'new Dialog.LoginRegister({message:"Please Login or Register to rate"});' if guest?
  def create
    @rating = AbstractRating.create_for_user_with_type(current_user, params[:rating_type], params[:subject_id], params[:value])
    
    # Fake the response for Registered Guests. Though there ratings are
    # not saved, we respond as if they were.
    if (@rating && !@rating.new_record?) || current_user.is_a?(RegisteredGuest)
      # rating exists, and was saved (validation passed)     
      
      @element_id = "#{@rating.class.to_s.underscore}_for_#{@rating.subject.id}" # TODO move to helper
      
      respond_to do |type|
        type.html do
          # flash[:javascript] = %q{urchinTracker("/funnel/rating/success?type=%s&amp;id=%d")} % [@rating.subject.class, @rating.subject.id]
          redirect_to :back 
        end
        type.js { render :action => 'update_comment' }
      end # respond_to
        
    else
      # a response for Spec failure and Rating save failure
      logger.debug "Rating failures: #{@rating.errors.full_messages.to_yaml}"
      
      respond_to do |type|
        type.html do
          flash[:alert] = "Not allowed"
          redirect_to :action => "index" 
        end
        type.js do 
          render :update do |page|
            message = @rating.errors.full_messages.join("\\n- ")
            # page <<  %q{urchinTracker("/funnel/rating/failure")}
            page << "alert('Not allowed\\n- #{message}');"
          end
        end
      end
    end
  end
  
end
