# Registering global objects
window._beathaven = null
window._session = null
window._vkontakte = null
window._vk_music = null
window._ajax = null
window._player = null
window._search = null
window._page = null
window._settings = null

$ ->
  l = document.location
  if l.hostname not in ['beathaven.org', 'dev.beathaven.org']
    l.href = 'http://beathaven.org/'+ l.hash
  
  $.ajaxSetup
    beforeSend: (xhr) ->
      xhr.setRequestHeader('X-CSRF-Token', $('meta[name="csrf-token"]').attr('content'))
  
  window._beathaven = new BeatHaven()
  window._beathaven.init()

class window.BeatHaven
  
  last_height: false
  lang: 'ru'
  
  init: ->
    window._vkontakte = new Vkontakte(2335068)
    window._vkontakte.init()
    window._vk_music = new VkontakteMusic
    
    window._ajax = new Ajax()
    
    window._player = new Player()
    window._player.initJplayer()
    
    window._search = new Search()
    
    window._page = new Page()
    
    window._settings = new Settings()
    
    this.setupAutocomplete()
    
    false
  
  setupAutocomplete: ->
    $('#search').first().bh_autocomplete
      serviceUrl: '/artist/autocomplete' # Страница для обработки запросов автозаполнения
      minChars: 3 # Минимальная длина запроса для срабатывания автозаполнения
      delimiter: /(,|;)\s*/ # Разделитель для нескольких запросов, символ или регулярное выражение
      maxHeight: 400 # Максимальная высота списка подсказок, в пикселях
      width: 415 # Ширина списка
      zIndex: 9999 # z-index списка
      deferRequestBy: 500 # Задержка запроса (мсек)
      containerId: 'autocomplete-container'
      containerItemsId: 'autocomplete-items'
      onSelect: ->
        _search.loadArtistData $('#search').val()
  
  localizeHTML: (obj, lang) ->
    unless obj?
      obj = $('body')
    unless lang?
      lang = _beathaven.lang
    $(obj).find('[data-ls]').each ->
      if _locale[$(this).attr 'data-ls']? and _locale[$(this).attr 'data-ls'][lang]?
        if this.nodeName is 'INPUT'
          $(this).val _locale[$(this).attr 'data-ls'][lang]
        else
          $(this).text _locale[$(this).attr 'data-ls'][lang]
    return obj
  
  ls: (id, lang) ->
    unless lang?
      lang = _beathaven.lang
    if _locale[id]? and _locale[id][lang]?
      _locale[id][lang]
    else
      id

String::htmlsafe = ->
  replaces = [
    ["\\", "\\\\"]
    ["\"", """]
    ["<", "&lt;"]
    [">", "&gt;"]
  ]
  str = this
  for item in replaces
    str = str.replace item[0], item[1]
  str

String::trim = ->
  str = this
  while str.indexOf('  ') != -1
    str = str.replace('  ', ' ')
  if str.charAt(0) == ' '
    str = str.substring 1
  if str.charAt(str.length - 1) == ' '
    str = str.substring(0, str.length - 1)
  str