SG =
  $sections: $(".styleguide-example")
  scope: ""
  $scopedSections: @.$sections
  classes: []

  setScope: ->
    amplify.store "section-scope", SG.scope

    SG.$scopedSections = SG.$sections

    SG.filter.call($("#query-filter")[0])

  queryMatches: ($el, findBy) ->
    $pattern = $el.children(".styleguide-element")
    !!($pattern.find("[id*='#{findBy}']").length || $pattern.find("[class*='#{findBy}']").length || $pattern.find(findBy).length)

  filter: (data) ->
    findBy = @.value or "*"
    amplify.store "query-filter", findBy

    SG.$sections.hide()

    unless SG.$scopedSections == undefined
      SG.$scopedSections.each ->
        $this = $(@)
        $this.toggle SG.queryMatches($this, findBy)

  setQueryFilter: ->
    value = amplify.store("query-filter")

    if value == "*"
      value = ""

    $("#query-filter").val(value)

  checkVisibility: (check) ->
    $check = $(check)

    if $check.css('display') == 'block'
      $('html, body').animate
        scrollTop: $check.offset().top
      , 500

  showCode: (e) ->
    $section = $(@).closest(".styleguide-example")
    $codeSection = $section.children(".styleguide-code");
    e.preventDefault()

    $codeSection.toggle()
    SG.checkVisibility($codeSection)

  gatherClasses: ->
    classes = {}
    SG.$sections.each ->
      $(@).find("*").each ->
        $.each @.className.split(/\s+/), ->
          classes[@] = @

    for item of classes
      SG.classes.push(item)

  showHidden: ->
    SG.$sections.find(".styleguide-element").children().each ->
      $this = $(this)
      $this.css("display", "inherit") if $this.css("display") == "none"
      $this.css("position", "relative") if $this.css("position") == "absolute"

  toggleTOC: ->
    $(".styleguide-toc").toggleClass "toc-open"

  init: ->
    $("#query-filter").on "keyup change", SG.filter
    $(".showCode-button").on "click", SG.showCode
    $(".styleguide-toc-activator, .styleguide-toc-activator a").on "click", SG.toggleTOC

    SG.setQueryFilter()
    amplify.store("section-scope")
    SG.setScope()

    SG.showHidden()

    window.hljs.initHighlightingOnLoad()

    # Autocomplete class names
    SG.gatherClasses()
    $( "#query-filter" ).autocomplete
      source: SG.classes


SG.init()
