module ParserCommon
 include ActionView::Helpers::TagHelper

  def menu_level(page, current_page, current, menu, edit = false)
    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.reverse : page.visible_children
      children.each do |child|
        res << menu_li(child, current_page, current, menu, i, edit)
        i += 1 if i
      end
      if menu.values['home'] && current == 1
        res << menu_li(page, current_page, current, menu, i, edit)
      end
      res << "</ul>"
    end
    res
  end
  
  def menu_li(page, current_page, current, menu, i, edit)
    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='#{edit ? root + admin_page_path(page.id) : (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, edit)
    end unless (page.root? rescue nil)
    res << "</li>"
  end

  # ad_banners
  def parse_ad_banners(body = nil, page = nil, edit=nil)
    body.css('ad_banner').each do |banner|
      res = ''
      ad_banner = AdBanner.find(banner["id"]) rescue nil
      if ad_banner
        res << "<script type='text/javascript'>
                  jQuery(function( $ ){     
                    $.preload( '#slideshow-#{ad_banner.title.dehumanize} img', {
                      onFinish:finish,
                      threshold: 2 //'2' is the default, how many at a time, to load.
                    });
                    function finish(){
                      $('#slideshow-#{ad_banner.title.dehumanize}').cycle({
                        delay: -1000,
                        fx: '#{ad_banner.ad_fx.nil? ? 'fade': ad_banner.ad_fx}',
                        timeoutFn: getTimeout,
                        pager: '.banner_nav-#{ad_banner.title.dehumanize}',
                        pagerAnchorBuilder: function(idx, slide) {
                          return \"<li><a href='#'></a></li>\";
                        }
                      });
                    };
                  });
                </script>"
        res << "<div style='position:relative'>"
        res << "<ul id='banner_nav' class='clear banner_nav-#{ad_banner.title.dehumanize}'></ul>"
        res << "<div id='slideshow-#{ad_banner.title.dehumanize}' class='slideshow'>"
        printable_ad_images = []
        ad_banner.ad_images.each do |ad_image|
          if ad_image.display?
            ad_image.weight.times do
              printable_ad_images << ad_image
            end
          end
        end
        printable_ad_images.shuffle!
        hide = printable_ad_images.size > 1
        printable_ad_images.each  do |ad_image|  #TODO Need Reflact
          res << "<img src='#{ad_image.file}' "
          res << "alt='#{ad_image.title || ' '}' "
          res << "time_to_next='#{ad_banner.transition_msec}' "
          res << "link_open='#{ad_image.link_open}' "
          # res << "link_url='#{(ad_image.direct_to_after_click?? ad_image.out_link : ad_banner.context) || ' '}' "
          res << "link_url='#{(ad_image.out_link)}' "
          res << "style='#{'display:none;' if hide} #{'cursor:pointer;' if !ad_image.out_link.blank?}'"
          res << "/>"          
        end
        res << "</div>"        
        res << "</div>"
      end
      fragment = Nokogiri::HTML::DocumentFragment.new(body, res)
      banner.swap(fragment)
    end
  end

  # page_images
  def parse_images(body, page, edit=nil)
    body.css('.page_image').each do |page_image|
      # image = page.custom_images.detect{|image| image.name.eql?(tag.attr['name']) }
      # image = page.design.custom_images.detect{|image| image.name.eql?(tag.attr['name']) } unless image
      image = page.design.images.detect{|image| image.name.eql?(File.basename(page_image['src'])) } unless image
      if image
        res = "<img src=#{image.file.url} "
        page_image.attributes.each do |l|
          res << "#{l[0]}='#{l[1]}' "
        end
        res << '>'
      end
      fragment = Nokogiri::HTML::DocumentFragment.new(body, res)
      page_image.swap(fragment)
    end
  end

  # page_menu
  def parse_menu(body, page, edit=nil)
    page_menu = body.css('.page_menu').first
    if page_menu
      home = get_homepage
      menu = page.design.layout.menu
      fragment = Nokogiri::HTML::DocumentFragment.new(body, menu_level(home, page, 1, menu, edit))
      page_menu.swap(fragment)
    else
      ''
    end
  end

  # sub_menus
  def parse_sub_menus(body = nil, page = nil, edit=nil)
    body.css('sub_menu').each do |sub_menu|
      menu_page = Page.find(sub_menu['id']) rescue nil
      res = ''
      if menu_page && menu_page.visible_children.size > 0
        res << "<div class='category_list'>"
        res << "<h3 class='h3'>#{menu_page.title}</h3>"
        res << "<ul class='list'>"
        menu_page.visible_children.each do |child|
          res << "<li class='#{page.id.eql?(child.id) ? 'active' : nil}'>"
          root = "/"
          res << "<a href='#{edit ? root + admin_page_path(child.id) : (child.class.to_s.eql?('Page') ? root + child.path : child.url)}'>#{child.title}</a>"
          res << "</li>"
        end
        res << "</ul>"
        res << "</h3>"
        res << "</div>"
      end
      fragment = Nokogiri::HTML::DocumentFragment.new(body, res)
      sub_menu.swap(fragment)
    end
  end

  # page_footer
  def parse_footer(body, page)
    page_footer = body.css('.page_footer').first
    if page_footer
      res = "<div id='#{page_footer['id']}', class='#{page_footer['class']}'>"
      res << @site.footer rescue nil
      res << "</div>"
      fragment = Nokogiri::HTML::DocumentFragment.new(body ,res)
      page_footer.swap(fragment) rescue nil
    else
      ''
    end
  end

  # page_sub_menu
  def parse_sub_menu(body, page)
    page_sub_menu = body.css('.page_sub_menu').first
    if page_sub_menu
      res = "<div id='#{page_sub_menu['id']}', class='#{page_sub_menu['class']}'>"
      res << @site.sub_menu rescue nil
      res << "</div>"
      fragment = Nokogiri::HTML::DocumentFragment.new(body ,res)
      page_sub_menu.swap(fragment) rescue nil
    else
      ''
    end
  end

  # sitemap
  def parse_sitemaps(body = nil, page = nil, edit=nil)
    sitemap = body.css('sitemap').first
    if sitemap
      url = admin_site_sitemap_frontend_path(@site)
      options = "?inner=true"
      fragment = Nokogiri::HTML::DocumentFragment.new(body, "<div class='dymanic_load' path='#{url + options}'></div>")
      sitemap.swap(fragment)
    else
      ''
    end
  end

  # page_contents
  def parse_contents(body, page, edit=nil)
    public_r_tags = []
    body.css('.page_content').each do |content|
      ret = ''
      category = params[:category_id].blank? ? page[:category] : params[:category_id]
      tag = params[:tag_id].blank? ? page[:tag] : params[:tag_id]
      if (content["main"] == "true" && !page.module_app.nil?)
        ret << "<div id='appfrontend' class='dymanic_load' path='/panel/#{page.module_app.key}/front_end/#{page.app_frontend_url}"
        ret << "/#{params[:id]}" if params[:id] && !params[:id].eql?(page.id.to_s)
        ret << "/#{params[:controller_action]}" if params[:controller_action] && params[:id]
        ret << "?inner=true&page_id=#{page.id}&category_id=#{category}&tag_id=#{tag}&preview=#{params[:preview]}&page_main=#{params[:page_main]}&search_query=#{params[:search_query]}&name=#{params[:name]}"
        ret << "'></div>"
      else
        part = page.page_parts.detect{ |p| p.name.to_s == content['name'].to_s } rescue nil
        part_title = part.title rescue nil
        if edit
          ret << "<div id='#{content['name']}' part_id='#{part.id}' class='editable' style='border:solid 1px; margin:5px; padding:5px;'>" if part
          ret << "<div class='edit_link' style='display:none'>"
          ret << " <a href='#{edit_admin_page_part_path(part.id)}' class='nav'>#{t(:edit)}</a>" if part
          ret << '</div>'
        end
        case part.kind
        when 'text'
          ret << part.content rescue ''
        when 'module_widget'
          url = "/panel/#{part.module_app.key}/widget/#{part.widget_path}?inner=true"
          options = "&category_id=#{!part[:category].blank? ? part[:category].blank? : category}&tag_id=#{!part[:tag].blank? ? part[:tag] : tag}&page=#{params[:page]}&search_query=#{params[:search_query]}&part_title=#{Rack::Utils.escape(part_title).gsub("+", "%20") rescue nil}&part_id=#{part.id}"
          ret << "<div class='dymanic_load widget' path='#{url + options}'></div>"
        when 'public_r_tag'
          ret << "<r:#{part.public_r_tag} id='#{part.public_r_tag_object_id}'/>"
          public_r_tags << part.public_r_tag
        else
            ''
        end if part
      end
      scope = "<#{content.name}"
      content.attributes.each_pair do |key, value|
        scope << " #{key}='#{value}'"
      end
      scope << ">#{ret}</#{content.name}>"
      fragment = Nokogiri::HTML::DocumentFragment.new(body, scope)
      content.swap(fragment)
    end
    public_r_tags.uniq
  end

  # page_counter
  def parse_counter(body = nil, page = nil, edit=nil)
    body.css('.page_counter').each do |counter|
      res = ''
      case counter['option']
      when 'all'
        res << display_visitors.to_s
      when 'today'
        res << display_visitors_today.to_s
      when 'this_week'
        res << display_visitors_this_week.to_s
      when 'this_month'
        res << display_visitors_this_month.to_s
      when 'this_year'
        res << display_visitors_this_year.to_s
      end
      fragment = Nokogiri::HTML::DocumentFragment.new(body, res)
      counter.swap(fragment)
    end
  end

end