class Www::DirectoriesController < WwwController
  before_filter :prepare_breadcrumb, only: [:organization]
  before_filter :init_filters, :load_states
  before_filter :redirected
  layout 'directory'

  def index
  end

  def organizations
    page = params[:page].to_i
    page = 1 if page < 1
    params[:q][:department_cont] = State.find(params[:state]).name.mb_chars.upcase.to_s if params[:state] rescue nil
    params[:q][:city_cont] = params[:city] if params[:city]
    @q = Organization.order("name ASC").search(params[:q])
    @q = params[:organization_themes].blank? ? Organization.order(:name).search(params[:q]) : Organization.joins(:organization_branches => :organization_branch_areas).where(:organization_branch_areas => {:themes => params[:organization_themes]}).uniq.search(params[:q])
    @organizations = @q.result.paginate(page: params[:page])
  end

  def organization
    @organization = Organization.find(params[:id])
  end

  def get_cities
    #@state = State.where(params[:name].mb_chars.capitalize.to_s).first
    @state = State.find(params[:id])
    @cities = {}

    @state.cities.each do |c|
      @cities[c.id] = c.name.mb_chars.upcase.to_s
    end

    respond_to do |format|
      format.json { render json: @cities, callback: params[:callback] }
    end
  end

  private

  def redirected
    redirect_to www_root_path and return
  end

  def init_filters
    @organization_themes = OrganizationBranchArea.group(:themes).map(&:themes).delete_if(&:blank?)
  end

  def load_states
    @states = State.order(:name)
  end

  def prepare_breadcrumb
  end

end
