class Admin::PagesController < ApplicationController

  layout "site_editor"
  
  before_filter :authenticate_user!
  before_filter :find_parent_item
  before_filter :is_admin?
  before_filter :set_current_item
  
  def show
    @item = Page.find(params[:id])
    respond_to do |format|
      format.html { 
        render 'admin/items/index' 
      }
      format.js  {}
    end
  end

  def new
    @item = Page.new
    @item.parent = Item.find(params[:parent_id]) rescue nil
    @apps = ModuleApp.all
    @designs = Design.all.entries
    @design = Design.first
  end

  def edit
    @item = Page.find(params[:id])
    @apps = ModuleApp.all
    @designs = Design.all.entries
    @design = @item.design ? @item.design : @designs.first
    @app_frontend_urls = @item.module_app.app_pages if @item.module_app
    if @item.module_app
      case @item.module_app.key
        when 'announcement'
          @categories =  BulletinCategory.all
        when 'news'
          @categories =  NewsBulletinCategory.all
        when 'web_resource'
          @categories =  WebLinkCategory.all
      end
    else
      @categories = nil
    end
  end

  def create
    @item = Page.new(params[:page])
	
	if @item.module_app.key == 'page_content'
	  @item.page_contexts.build(:create_user_id => current_user.id, :update_user_id => current_user.id )
	end
	
    if @item.save
      flash.now[:notice] = t('admin.create_success_page')
      respond_to do |format|
        format.html { 
          redirect_to admin_page_url(@item) 
        }
        format.js {}
      end
    else
      flash.now[:error] = t('admin.create_error_page')
      @apps = ModuleApp.all
      @designs = Design.all.entries
      @design = Design.first
      render :action => "new"
    end
  end

  def update
    @item = Page.find(params[:id])

	  if @item.module_app && @item.module_app.key == 'page_content' && @item.page_contexts.blank?
	    @item.page_contexts.build(:create_user_id => current_user.id, :update_user_id => current_user.id )
	  end
	
    if @item.update_attributes(params[:page])
      flash[:notice] = t('admin.update_success_page')
      respond_to do |format|
        format.html {
          redirect_to admin_page_url(@item) 
        }
        format.js {}
      end
    else
      render :action => "edit"
    end
  end

  def destroy
    @item = Page.find(params[:id])
    @item.destroy
    respond_to do |format|
      format.html { 
        redirect_to admin_items_url( :parent_id => @item.parent_id )
      }
      format.js  {}
    end
  end
  
  def delete
    respond_to do |format|
      format.html {}
      format.js  { destroy }
    end
  end
  
  def reload_themes
    @design = Design.find(params[:id])
    @themes = @design.themes
    respond_to do |format|
      format.js  {}
    end
  end
  
end
