var needsScrollUpdate = false
var clicks = []
var popped = false


$(window).bind('orientationchange', orientationChange)

function orientationChange() {
  location.reload()
}

$(document).ready(function () {
  attachEvents()
  search()

  if (/Android|webOS|iPhone|iPad|iPod|BlackBerry/i.test(navigator.userAgent)) {
    $('body').addClass('touch')
    $('.album-wrapper').addClass('touch')
  }

  $('.mobile-nav-handle').click(function (e) {
    e.stopPropagation()
    $('#menu-hauptmenue').toggleClass('open')
  })

  $('body').on('click', function () {
    $('#menu-hauptmenue').removeClass('open')
  })
  var href = document.URL.replace(/\?.+/,'')
  var element = $('a[href="' + href + '"]')
  element.click()

  popped = true
})

var initialUrl = location.href


// open overlay for current url when popping state
$(window).bind('popstate', function (e) {

  if (!popped && e.originalEvent.state && e.originalEvent.state.url === initialUrl) {
    popped = true
    return
  }

  url = document.URL

  if (e.originalEvent.state != null && e.originalEvent.state.url !== undefined) {
    url = e.originalEvent.state.url
  }

  if (url === homeUrl + '/') {
    closeOverlay(true)
  } else {
    var element = $('a[href="' + url + '"]')
    element.click()
  }
})


function attachEvents() {
  // close overlay on click on close button and darkened area
  $('#overlay .close img, #darken').unbind('click').click(closeOverlay)

  // close overlay on ESC
  $(document).unbind('keyup')
  $(document).keyup(function (e) {
    if (e.keyCode === 27) {
      closeOverlay()
    }
  })

  // link handling for nav, albums and more-links
  $('nav li.menu-item-has-children > a').click(() => false)
  $('#menu-hauptmenue > li:not(.menu-item-has-children, .home-menu) > a, .album-wrapper a, .more-link, a.page-numbers,#menu-footer a').unbind('click').click(clickLink)
  $('.genre a').click(function (e) {
    e.preventDefault()

    var genre = $(this).text()
    $('#search').val(genre)
    performSearch()
    closeOverlay()

  })

  // hide nav when album is open
  $('.album-wrapper a').click(function () {
    $('nav').fadeOut()
    $('#overlay-wrapper').addClass('album')
  })

  $('.back').click(function () {
    var lastElement = clicks[clicks.length - 2]

    if (lastElement != null) {
      lastElement.click()
    } else {
      $('a[href$="/news/"]').click()
    }
  })
}

function clickLink(e, href) {
  $('#menu-hauptmenue').removeClass('open');

  var element

  if (e) {
    e.preventDefault()
    element = $(this)
    href = element.attr('href')
  } else {
    element = $('a[href="' + href + '"]')
  }

  $('a').removeClass('active')
  element.addClass('active')

  overlay(href)

  clicks.push(element)

  pushState(href)

  return false
}

function search() {
  $('#search').keyup(performSearch)
  $("#search-clear").on("click", function(event) {
    $("#search").val("");
    performSearch();
  });
}

function performSearch() {
  closeOverlay()

  var value = $('#search').val().toLowerCase()

  if (value === '') {
    $('.album-wrapper').show()
    $('#search-container').removeClass('dirty');
    return
  }
  $('#search-container').addClass('dirty');

  var parts = value.split(' ')

  // content search
  var albumsToShow = []
  $('.album-wrapper').hide()

  $('.album-wrapper').each(function () {
    var album = $(this)

    add = true

    $.each(parts, function (key, part) {
      if (album.attr('data-tags').toLowerCase().indexOf(part) < 0 && album.attr('data-genre').toLowerCase().indexOf(part) < 0 && album.attr('data-name')
                                                                                                                                      .toLowerCase()
                                                                                                                                      .indexOf(part) < 0 && album.attr('data-catalog-number')
                                                                                                                                                                 .toLowerCase()
                                                                                                                                                                 .indexOf(part) < 0 && album.text()
                                                                                                                                                                                            .toLowerCase()
                                                                                                                                                                                            .indexOf(part) < 0) {
        add = false
      }

    })

    if (add) {
      albumsToShow.push(album)
    }

  })


  $.each(albumsToShow, function () {
    $(this).show()
  })
}

function overlay(href) {

  $('#darken').fadeIn(function () {
    $('#overlay-wrapper').fadeIn('slow')
  })

  if ($('#overlay-content').hasClass('active')) {
    $('#overlay-content').slideUp(400, function () {
      loadContent(href)
    })
  } else {
    loadContent(href)
  }

  $('html, body').animate({ scrollTop: 0 }, 600)

  $('#albums').css('position', 'fixed')
}

function closeOverlay(dontPush) {
  $('#overlay-wrapper').fadeOut(function () {
    $('#overlay-content').html('')
    $('#darken').fadeOut()
  })

  $('#overlay-content').removeClass('active')
  $('nav a').removeClass('active')
  $('nav').fadeIn()

  $('#overlay-wrapper').removeClass('album')

  $('#albums').css('position', 'static')

  if (!dontPush || dontPush.target) {
    pushState(homeUrl)
  }
}

function loadContent(href) {
  $('#overlay-content').load(href, { 'request_source': 'evrst_ajax' }, function () {
    $('#overlay-content').slideDown(400)
    attachEvents()
  })
}

function pushState(path) {
  if (typeof (window.history.pushState) == 'function') {
    window.history.pushState({ 'url': path }, path, path)
  }
}
