class FrontController < ApplicationController

  layout false

  def show_breadcrumb
    @ancestors = Page.find(params[:id]).ancestors_and_self
    @ancestors = nil if @ancestors.size == 1
  end

  def show_banner
    @ad_banner = AdBanner.find(params[:id]) rescue nil
  end

  def show_footer
    render :text => @site.footer
  end

  def show_menu
    page = Page.find(params[:id]) rescue nil
    render :text => menu_level(Page.root, page, 1, page.design.layout.menu) if page
  end

  def show_site_sub_menu
    render :text => @site.sub_menu
  end

  def show_sitemap
    @items = get_homepage.children.excludes(sitemap_enabled: false) rescue []
  end

  def show_page_sub_menu
    @menu_page = Page.find(params[:menu_page_id]) rescue nil
    @page_id = params[:page_id]
  end

  def show_inner_ad_image
    @ad_image = AdImage.find(params[:id]) rescue nil
    @ad_images = AdImage.all
  end

  def show_tag_cloud
    module_app = ModuleApp.find(params[:id]) rescue nil
    @tags = module_app.sorted_tags_for_cloud
  end

  private

  def menu_level(page, current_page, current, menu)
    res = ''
    if page.visible_children.size > 0
      res << "<ul class='"
      res << menu.values["class_#{current}"] rescue nil
      res << "'>"
      i = nil
      i = 1 if menu.values["li_incremental_#{current}"]
      children = current == 1 ? page.visible_children : page.visible_children
      children.each do |child|
        res << menu_li(child, current_page, current, menu, i)
        i += 1 if i
      end
      if menu.values['home'] && current == 1
        res << menu_li(page, current_page, current, menu, i)
      end
      res << "</ul>"
    end
    res
  end
  
  def menu_li(page, current_page, current, menu, i)
    res = "<li class='"
    res << menu.values["li_class_#{current}"] rescue nil
    res << "_#{i}" if i
    res << " active" if (current_page.id.eql?(page.id) || current_page.descendant_of?(page))
    res << "'>"
    root = "/"
    res << "<a href='#{(page.class.to_s.eql?('Page') ? root + page.path : page.url)}'><span>#{page.title}</span></a>"
    if page.visible_children.size > 0 && current < menu.levels
      res << "<span class='dot'></span>"
      res << menu_level(page, current_page, current + 1, menu)
    end unless (page.root? rescue nil)
    res << "</li>"
  end

end