class PagesController < ApplicationController
  
  include ApplicationHelper

  before_filter :get_item, :only => [:index_from_link, :show_from_link]
  
  def index
    @item = Page.find_by_name('home')
    if @item
      render_page
    else
      render :text => 'You need a home page'
    end
  end
  
  def show  
     #begin  
       @item = Item.first(:conditions => {:full_name => params[:page_name]})
       if @item && @item.is_published && (@item.enabled_for.nil? ? true : @item.enabled_for.include?(I18n.locale.to_s))
         case @item._type
           when 'Page'    
             render_page(params)
           when 'Link'
             redirect_to "http://#{@item[:url]}"
         end
       else
         render :file => "#{Rails.root}/public/404.html", :status => :not_found
       end
     #rescue
     #  render :file => "#{Rails.root}/public/404.html", :status => :not_found
     #end
   end
   
   def index_from_link
      if params[:page]
        redirect_to "/#{@item.full_name}?page=#{params[:page]}&category_id=#{params[:category_id]}&tag_id=#{params[:tag_id]}"
      else
        redirect_to "/#{@item.full_name}?category_id=#{params[:category_id]}&tag_id=#{params[:tag_id]}"
      end
   end
   
   def show_from_link
     # debugger
     # a=1
     redirect_to "/#{@item.full_name}?id=#{params[:id]}&preview=#{params[:preview]}"
   end
   
   def load_orbit_bar
     render :partial => 'layouts/orbit_bar', :locals => {:referer => request.referer}
   end
   
   protected
   
   def get_item
      module_app = ModuleApp.first(:conditions => {:key => params[:app_name]})
      # if params[:category_id]
      #   @item = Item.first(:conditions => {:module_app_id => module_app.id, :app_frontend_url => params[:app_action], :category => params[:category_id]})  
      # else 
        @item = Item.first(:conditions => {:module_app_id => module_app.id, :app_frontend_url => params[:app_action]})
      # end
   end
  
end
