# -*- encoding : utf-8 -*-
class Portlet::PortletsController < ApplicationController
	layout "admin"



	def new
		@portlet = Portlet.new(:block_id => params[:block_id])
		
		
		respond_to do |format|
			format.html {
				if request.xhr?
					render :layout => false
				end
			}
			format.js
		end

	end


	def show
		@portlet = Portlet.find(params[:id])
	end

  

  def edit
    @portlet = Portlet.find(params[:id])
	if request.xhr?
		render :layout => false
	end
  end



  def update
    @portlet = Portlet.find(params[:id])

    flash[:notice] = "Le contenu à été mis à jour avec succès."
    if @portlet.update_attributes(params[:portlet])
      
      if @portlet.block and @portlet.block.blockable
        @portlet.block.blockable.updated_at = Time.now
        @portlet.block.blockable.save
		if @portlet.block.blockable_type == "Page"
			
			to_my_log("[Page_"+@portlet.block.blockable.id.to_s+"] "+"Modification de la page "+@portlet.block.blockable.title.to_s)
		end
      end
      render :action => "update"
  
    else
      render :action => "edit" 
    end
    
      

    
  end

  def destroy
    @portlet = Portlet.find(params[:id])
    @portlet.destroy
    flash[:notice] = "Le contenu à été supprimé avec succès."
    if @portlet.block and @portlet.block.blockable
      @portlet.block.blockable.updated_at = Time.now
      @portlet.block.blockable.save
    end
  end
  
  def ajax_create
    @t = params[:type]
    if @t == "Title"
      @content = TitleContent.new()
    elsif @t == "Text"
      @content = TextContent.new()
    elsif @t == "Image"
      @content = ImageContent.new()
    elsif @t == "Gallery"
      @content = GalleryContent.new()
    elsif @t == "Link"
      @content = LinkContent.new()
    elsif @t == "Break"
      @content = BreakContent.new()
    elsif @t == "Html"
      @content = HtmlContent.new()
    elsif @t == "Download"
      @content = DownloadContent.new()
    elsif @t == "DynamicContent"
      @content = DynamicContent.new()
    end
    @portlet = Portlet.new(:block_id => params[:block_id])
    @content.portlets << @portlet
    @content.save!
    if @portlet.block and @portlet.block.blockable
      @portlet.block.blockable.updated_at = Time.now
      @portlet.block.blockable.save
    end
    flash[:notice] = "Le contenu à été créé avec succès."
  end

  def reorder
    
	params[:blocks].each do |index, block|

		block_id = block["block_id"].to_i
		i = 0
		if block["block_portlet_ids"].kind_of?(Array)
			block["block_portlet_ids"].each do |portlet_id|
				i += 1
				Portlet.find(portlet_id.to_i).update_attributes(:position => i, :block_id => block_id)
			end
		end
		
	end

	render :inline => "ok"
    
  end
end
