class Panel::WebResource::BackEnd::WebLinksController < ApplicationController

  
  layout 'admin'
  
  before_filter :authenticate_user!
  before_filter :is_admin?

  def index
  
	get_categorys(params[:web_link_category_id])
	
	@web_links = WebLink.search(params[:category_id])
	
	get_tags()

    respond_to do |format|
      format.html # index.html.erb
      format.xml  { render :xml => @web_links }
    end
  end

  # GET /web_links/1
  # GET /web_links/1.xml
  def show
    @web_link = WebLink.find(params[:id])
	# get_categorys

    respond_to do |format|
      format.html # show.html.erb
      format.xml  { render :xml => @web_link }
    end
  end

  # GET /web_links/new
  # GET /web_links/new.xml
  def new
    @web_link = WebLink.new
	
	get_tags()
	
	get_categorys

    respond_to do |format|
      format.html # new.html.erb
      format.xml  { render :xml => @web_link }
    end
  end

  # GET /web_links/1/edit
  def edit
    @web_link = WebLink.find(params[:id])
	get_categorys
	get_tags()
  end

  # POST /web_links
  # POST /web_links.xml
  def create
    @web_link = WebLink.new(params[:web_link])
	
    @web_link.create_user_id = current_user.id
    @web_link.update_user_id = current_user.id

    respond_to do |format|
      if @web_link.save
        format.html { redirect_to(panel_web_resource_back_end_web_links_url, :notice => t('web_resource.create_web_resource_success')) }
        format.xml  { render :xml => @web_link, :status => :created, :location => @web_link }
      else
        format.html { render :action => "new" }
        format.xml  { render :xml => @web_link.errors, :status => :unprocessable_entity }
      end
    end
  end

  # PUT /web_links/1
  # PUT /web_links/1.xml
  def update
    @web_link = WebLink.find(params[:id])
	
    @web_link.update_user_id = current_user.id
	
	params[:web_link][:tag_ids] ||=[]

    respond_to do |format|
      if @web_link.update_attributes(params[:web_link])
        format.html { redirect_to(panel_web_resource_back_end_web_links_url, :notice => t('web_resource.update_web_resource_success')) }
		format.js  { render 'toggle_enable' }
        format.xml  { head :ok }
      else
        format.html { render :action => "edit" }
        format.xml  { render :xml => @web_link.errors, :status => :unprocessable_entity }
      end
    end
  end

  # DELETE /web_links/1
  # DELETE /web_links/1.xml
  def destroy
    @web_link = WebLink.find(params[:id])
    @web_link.destroy

    respond_to do |format|
      format.html { redirect_to(panel_web_resource_back_end_web_links_url) }
      # format.xml  { head :ok }
      format.js
    end
  end
  
  protected
  
  def get_categorys(id = nil)
    @web_link_categorys = (id ? WebLinkCategory.find(id).to_a : WebLinkCategory.excludes('disabled' => true))
  end
  
  def get_tags()
  	module_app = ModuleApp.first(:conditions => {:key => 'web_resource'})
  	@tags = Tag.all(:conditions => {:module_app_id => module_app.id})
  end
  
end
