# -*- encoding : utf-8 -*-
class Admin::SlidesController < ApplicationController
  
  	before_filter :authenticate_admin!
	load_and_authorize_resource
	
	layout "admin"

	navigation :home_pages


	def new

		@slide = Slide.new(:slider_id => params[:slider_id])
		
		@slide.cible = CibleArticle.new()
		
	end

	def create
	
		@slides = Slide.order(:position)
		
		
		
		
		params[:resource => "slide"]

		params_content = params[:slide].delete(:cible_attributes)
		content_type = params[:slide][:cible_type]

		cible_id = params[:slide][:cible_id].to_i if params[:slide][:cible_id].to_i != 0

	

		if !cible_id
			content = content_type.constantize.new(params_content)
		else
			content = content_type.constantize.find(cible_id) 

			content.attributes = params_content
		end


		@slide = Slide.new(params[:slide])
		@slide.cible = content



		
		
		
		
		
		
		
		if @slide.save
			flash[:notice] = "La slide à bien été créé."
			
			respond_to do |format|
				format.js
			end
			
		else
			
			respond_to do |format|
				format.js { render :action => :new}
			end
					
		end
		
	end

	def update
		
		@slide = Slide.find(params[:id])
		@slides = Slide.order(:position)
		
		
		
		params[:resource => "slide"]

		params_content = params[:slide].delete(:cible_attributes)
		content_type = params[:slide][:cible_type]

		cible_id = params[:slide][:cible_id].to_i if params[:slide][:cible_id].to_i != 0

		puts cible_id.to_i

		if !cible_id
			content = content_type.constantize.new(params_content)
		else
			content = content_type.constantize.find(cible_id) 

			content.attributes = params_content
		end



		@slide.cible = content
		
		
		
		
		
		if @slide.update_attributes(params[:slide])
			flash[:notice] = "Le slide à bien été modifiée."

			respond_to do |format|
				format.js
			end

		else
			respond_to do |format|
				format.js { render :action => :edit}
			end		
		end
		
	end

	def edit
		@slide = Slide.find(params[:id])
	end

	def show
		@slide = Slide.find(params[:id])
	end

	def destroy
		@slide = Slide.find(params[:id])
		@slide.destroy


		flash[:notice] = "Le slide à bien été supprimée."
	end
	
	
	def reorder
		i = 0
		params[:slide].each do |slide_id|
			i += 1
			slide = Slide.find(slide_id)
			slide.position = i
			slide.save
		end
		render :inline => "ok"
	end

end
