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

	def new
		@block_content = BlockContent.new(:nbr_columns => 2)

		respond_to do |format|
			format.html {
				if request.xhr?
					render :layout => false
				end
			}
			format.js { render :template => "portlet/shared/new" }
		end
	end

	def create
		@block_content = BlockContent.new(params[:block_content])

		respond_to do |format|
			if @block_content.save
				@block_content.nbr_columns.times do 
					@block = Block.new(:block_name => "")
					@block.blockable = @block_content
					@block.save
				end
				
				@portlet = Portlet.create(:position => params[:position], :block_id => params[:block_id], :content => @block_content)
				
				
				if @portlet.block and @portlet.block.blockable
					@portlet.block.blockable.updated_at = Time.now
					@portlet.block.blockable.save
					
				end
				
				
				
				format.html { redirect_to([:admin, @portlet.block.blockable], :notice => 'Elément ajouté avec succès.') }
				format.js { render :template => "portlet/shared/create" }
			else
				format.html { render :action => "new" }
				format.js { render :template => "portlet/shared/new" }
			end
		end
	end

	def edit
		@block_content = BlockContent.find(params[:id])
		@portlet = Portlet.find(params[:portlet_id])
		respond_to do |format|
			format.html {
				if request.xhr?
					render :template => "portlet/shared/edit", :layout => false
				end
			}
			format.js { render :template => "portlet/shared/edit" }
		end
	end
	
	



	def show


	end

	def update
		@block_content = BlockContent.find(params[:id])
		@portlet = Portlet.find(params[:portlet_id])
		
		respond_to do |format|
	        if @block_content.update_attributes(params[:block_content])
				if @portlet.block and @portlet.block.blockable
					@portlet.block.blockable.updated_at = Time.now
					@portlet.block.blockable.save
				
				end
		
	        	format.html { redirect_to([:admin, @portlet.block.blockable], :notice => 'Titre mis à jour.') }
				format.js { render :template => "portlet/shared/update" }
	        else
	        	format.html { render :action => "portlet/shared/edit" } 
				format.js { render :template => "portlet/shared/edit" }
	        end

		end
	end

	def destroy
		@portlet = Portlet.find(params[:portlet_id])
		@block_content = BlockContent.find(params[:id])
		@block_content.destroy
		
		if @portlet.block and @portlet.block.blockable
			@portlet.block.blockable.updated_at = Time.now
			@portlet.block.blockable.save
		
		end
		
		respond_to do |format|
			format.html {}
			format.js { render :template => "portlet/shared/destroy" }
		end
	end

 
end
