module ApplicationHelper

  FLASH_NOTICE_KEYS = [:error, :notice, :warning]
  
  def colorize_in_use_locale(locale)
    @site_in_use_locales.include?(locale)? 'green' : 'red'
  end
  
  def flash_messages
    return unless messages = flash.keys.select{|k| FLASH_NOTICE_KEYS.include?(k)}
    formatted_messages = messages.map do |type|      
      content_tag :div, :class => type.to_s do
        message_for_item(flash[type], flash["#{type}_item".to_sym])
      end
    end
    raw(formatted_messages.join)
  end
  
  def link_back
     link_to t('back'), get_go_back, :class => 'nav'
  end
  
  # Clean the link back
  # Remove the locale but keep all the other params
  def get_go_back
    begin
      if request.url.include?('locale=')
        session[:last_page]
      else
        target = request.referer.split('?')
        vars = target[1].split('&') rescue []
        vars.delete_if {|var| var.include? 'locale=' }
        session[:last_page] = if vars.size > 0
         target[0].to_s + '?' + vars.join('&')
        else
          target[0].to_s
        end
      end
    rescue
      eval(params[:controller].split('/').join('_') << '_url')
    end
  end

  def message_for_item(message, item = nil)
    if item.is_a?(Array)
      message % link_to(*item)
    else
      message % item
    end
  end
  
  def add_attribute(partial, f, attribute)
    new_object = f.object.send(attribute).build
    fields = f.fields_for(attribute, new_object, :child_index => "new_#{attribute}") do |f|
      render :partial => partial, :object => new_object, :locals => {:f => f}
    end
  end

end
