var previousScroll = 0, // previous scroll position
    menuOffset = 110, // height of menu (once scroll passed it, menu is hidden)
    detachPoint = $(window).height(), // point of detach (after scroll passed it, menu is fixed)
    hideShowOffset = 20; // scrolling value after which triggers hide/show menu

function onInputFocus() {
  $(this).parent().addClass('filled');
}

function onInputBlur(ev) {
  if( ev.target.value.trim() === '' ) {
    $(this).parent().removeClass('filled');
  }
}

var headroom = function() {
  window.requestAnimationFrame(function() {

    // variables
    var currentScroll = $(window).scrollTop(),
    // gets current scroll position
    scrollDifference = Math.abs(currentScroll - previousScroll); // calculates how fast user is scrolling

    // if scrolled past menu
    if (currentScroll > menuOffset) {
      // if scrolled past detach point add class to fix menu
      if (currentScroll > detachPoint) {
        if (!$('#header').hasClass('detached')) {
          $('#header').addClass('detached');
        }
      }

      // if scrolling faster than hideShowOffset hide/show menu
      if (scrollDifference >= hideShowOffset) {
        if (currentScroll > previousScroll) {
          // scrolling down; hide menu
          if (!$('#header').hasClass('invisible')) { $('#header').addClass('invisible'); }
        } else {
          // scrolling up; show menu
          if ($('#header').hasClass('invisible')) { $('#header').removeClass('invisible'); }
        }
      }
    } else {
      // only remove “detached” class if user is at the top of document (menu jump fix)
      if (currentScroll <= 0) {
        $('#header').removeClass('detached invisible');
        if($('body').hasClass('invert-top')) {
          // $('#header').removeClass('day').addClass('night');
        }
      }
    }

    // replace previous scroll position with new one
    previousScroll = currentScroll;

  }.bind(this));
};

$(window).on('scroll', function () {
  headroom();
});

$(document).ready(function(){

  $('body').on('click', '.tot_dropdown > a', function(e) {
    e.preventDefault();
    $(this).parent().toggleClass('open');
  });

  $('input[name="s"]').autocomplete({
    appendTo: '.search-wrapper',
    serviceUrl: '/wp-admin/admin-ajax.php?action=get_listing_names',
    minChars: 2,
    maxHeight: 'auto',
    preserveInput: true,
    onSearchStart: function() {
      $(this).removeClass('error');
      $(this).parent().addClass('loading');
    },
    onSearchComplete: function(query, suggestions) {
      $(this).parent().removeClass('loading');
      if(!suggestions.length) {
        $(this).addClass('error');
      }
    },
    formatResult: function(suggestion, currentValue) {
      var pattern = '('+currentValue.replace(/[|\\{}()[\]^$+*?.]/g, "\\$&")+')';
      var excerpt = suggestion.excerpt
        .replace(new RegExp(pattern, 'gi'), '<span>$1<\/span>')
        .replace(/&/g, '&amp;')
        .replace(/</g, '&lt;')
        .replace(/>/g, '&gt;')
        .replace(/"/g, '&quot;')
        .replace(/&lt;(\/?span)&gt;/g, '<$1>');

      return '<h4>'+suggestion.value+'</h4><p>'+excerpt+'</p>';
    },
    beforeRender: function(container, suggestions, search) {
      container.wrapInner('<div class="results-scroll"></div>');
      container.append('<div class="see-all"><a href="/search/'+search.replace(/ /g, '+')+'">See All Results <img src="/assets/img/arrow-right.svg" alt="Arrow"></a></div>');
    },
    onSelect: function(suggestion) {
      window.location.href = suggestion.link;
    }
  });

  $('.form-control').each( function() {
    if( $(this).val().trim() !== '' ) {
      $(this).parent().addClass('filled');
    }

    // events:
    $(this).on( 'focus', onInputFocus );
    $(this).on( 'blur', onInputBlur );
  });


  $(".article-feedback a").click(function(){

    var feedback = $(this);

    // Retrieve post ID from data attribute
    var post_id = feedback.data('post-id');
    var vote_nonce = feedback.data('post-nonce');
    var vote_type = feedback.data('vote-type');

    // Ajax call
    $.ajax({
      type: 'post',
      url: '/wp-admin/admin-ajax.php',
      data: 'action=post-feedback&nonce='+vote_nonce+'&post_'+vote_type+'=&post_id='+post_id,
      success: function(count){
        // If vote successful
        if (count !== 'already') {
          feedback.addClass('active');
          $('.vote-count').velocity({opacity: 0}, 200, function() {
            $('.vote-count').html('Thanks for the feedback!');
            $('.vote-count').velocity({opacity: 1}, 200);
          });
        } else {

          $('.article-feedback .gotcha').addClass('show');
          setTimeout(function() {
            $('.article-feedback .gotcha').removeClass('show');
          }, 2000);

        }
      }
    });

    return false;
  });

  $('.video-wrapper').fitVids();

  $('.new-ticket-form').on('submit', function(e) {
    e.preventDefault();
  }).validate({
    errorPlacement: function errorPlacement() {},
    highlight: function highlight(element, errorClass) {
      $(element).parent().addClass(errorClass);
    },
    unhighlight: function unhighlight(element, errorClass) {
      $(element).parent().removeClass(errorClass);
    },
    rules: {
      ticket_name: {
        required: true
      },
      ticket_email: {
        required: true,
        email: true
      },
      ticket_subject: {
        required: true
      },
      ticket_details: {
        required: true
      }
    },
    submitHandler: function(form) {
      var $formBtn = $('.submit-button .btn', form),
          btnOrigText = $formBtn.text(),
          btnActiveText = $formBtn.data('loading');

      $formBtn.addClass('loading').text(btnActiveText);

      var data = $(form).serialize();
      var processURL = $(form).attr('action');

      $.post({
        url: processURL,
        data: data,
        error: function() {},
        success: function(res) {
          if (res.success) {
            $('.ticket-success-msg span.name').text(res.name);
            $('.ticket-success-msg span.email').text(res.email);
            $('.new-ticket-form').addClass('success');
          } else {
            $formBtn.removeClass('loading').text('Error! Try again');
            setTimeout(function() {
              $formBtn.text(btnOrigText);
            }, 3000);
          }
        }
      });
      return false;

    }
  });

});