(function($) {
  "use strict";

  // Page Loaded...
  $(document).ready(function() {
    $('.selectpicker').selectpicker();

    /* ========== Accordion ========== */
    $('.panel-heading a').on('click', function() {
      $('.panel-heading').removeClass('active');
      $(this).parents('.panel-heading').addClass('active');
      $('.panel-heading .icon .fa-minus-square-o').removeClass('fa-minus-square-o').addClass('fa-plus-square');
      $(this).find('i').removeClass('fa-plus-square').addClass('fa-minus-square-o');
    });

    /* ========== Responsive Navigation ========== */
    $('.main-nav').children().clone().appendTo('.responsive-nav');
    $('.responsive-menu-open').on('click', function(event) {
      event.preventDefault();
      $('body').addClass('no-scroll');
      $('.responsive-menu').addClass('open');
      return false;
    });
    $('.responsive-menu-close').on('click', function(event) {
      event.preventDefault();
      $('body').removeClass('no-scroll');
      $('.responsive-menu').removeClass('open');
      return false;
    });

    /* ========== Range Sliders ========== */
    $('#price-slider').noUiSlider({
      connect : true,
      behaviour : 'tap',
      margin : 5000,
      start : [20000, 100000],
      step : 2000,
      range : {
        'min' : 0,
        'max' : 150000
      }
    });
    $('#price-slider').Link('lower').to($('#price-min'), null, wNumb({
      decimals : 0
    }));
    $('#price-slider').Link('upper').to($('#price-max'), null, wNumb({
      decimals : 0
    }));
    $('#distance-slider').noUiSlider({
      connect : true,
      behaviour : 'tap',
      margin : 20000,
      start : [100000, 400000],
      step : 10000,
      range : {
        'min' : 0,
        'max' : 500000
      }
    });
    $('#distance-slider').Link('lower').to($('#distance-min'), null, wNumb({
      decimals : 0
    }));
    $('#distance-slider').Link('upper').to($('#distance-max'), null, wNumb({
      decimals : 0
    }));

    /* ========== Featured Cars ========== */
    $('#featured-cars').owlCarousel({
      loop : true,
      nav : true,
      dots : false,
      autoplay : true,
      navText : ['<i class="fa fa-angle-left"></i>', '<i class="fa fa-angle-right"></i>'],
      responsive : {
        0 : {
          items : 1
        },
        768 : {
          items : 3
        },
        1200 : {
          items : 5
        }
      }
    });
    $('#featured-cars-three').owlCarousel({
      loop : true,
      nav : true,
      dots : false,
      autoplay : true,
      navText : ['<i class="fa fa-angle-left"></i>', '<i class="fa fa-angle-right"></i>'],
      responsive : {
        0 : {
          items : 1
        },
        768 : {
          items : 2
        },
        1200 : {
          items : 3
        }
      }
    });

    /* ========== Team ========== */
    $('#team-slider').owlCarousel({
      loop : true,
      nav : false,
      dots : true,
      autoplay : true,
      responsive : {
        0 : {
          items : 1
        },
        768 : {
          items : 2
        },
        1200 : {
          items : 2
        }
      }
    });

    /* ========== Car Mobile Search ========== */

    var navigationSearchBar = function(selector) {
      var el = $(selector);
      if (!el.length) {
        return false;
      }
      if (!el.data('parent')) {
        el.data('parent', el.parent());
      }
      if (window.innerWidth <= 768) {
        el.appendTo('.navigation');
        $('.responsive-menu-search').off('click').on('click', function(event) {
          event.preventDefault();
          el.toggleClass('open');
        });
      } else {
        $('.responsive-menu-search').off('click');
        el.data('parent').append($(selector).removeClass('open'));
      }
    };
    $(window).on('resize', function(e) {
      navigationSearchBar('.search-box');
    }).trigger('resize');

    /* ========== Car Details Slider ========== */
    $('#car-details-slider').owlCarousel({
      items : 1,
      loop : $(this).find('.owl-carousel .item').size() > 1,
      nav : false,
      dots : true,
      autoplay : true
    });

    /* ========== Welcome Slider ========== */
    $('.welcome').flexslider({
      selector : '.slides > .slide',
      smoothHeight : true,
      controlNav : false,
    });
  });

  $(document).ready(function() {
    if ($(window).width() < 768) {
      scrollToError('.form-error', 250);
    } else {
      scrollToError('.form-error', 300);
    }

    function scrollToError(selector, topOffset) {
      if ($('.form-error').length > 0) {
        $('html, body').animate({
          scrollTop : ($(selector).first().offset().top - topOffset)
        }, 500);
      }
    }
  })

  /* ========== File Inputs ========== */
  $(document).on('change', '.file-input :file', function() {
    var input = $(this), numFiles = input.get(0).files ? input.get(0).files.length : 1, label = input.data('empty');
    input.trigger('fileselect', [numFiles, label]);
    return false;
  });
  $('.file-input :file').on('fileselect', function(event, numFiles, label) {
    var input = $(this), log = numFiles ? input.data('selected').replace('%X', numFiles) : label;
    input.parent().next('.file-input-selection').html(log);
    return false;
  });

  /* ========== Validate Email ========== */
  function validateEmail($validate_email) {
    var emailReg = /^([\w-\.]+@([\w-]+\.)+[\w-]{2,4})?$/;
    if (!emailReg.test($validate_email)) {
      return false;
    } else {
      return true;
    }
    return false;
  }

  var selectCars = {'0': 'Válassz kivitelt', 'cabrio': 'cabrio', 'coupe': 'coupe', 'other': 'egyéb',
      'mpv':'egyterű', 'hatchback': 'ferdehátú', 'hotrod':'hot rod', 'minibus':'minibusz', 'stationwagon':'kombi',
      'notchback':'lépcsőshátú', 'pickup':'pickup', 'sedan':'sedan', 'sport':'sport', 'crosscountry':'terepjáró'
  };

  var selectLcvs = {'0': 'Válassz kivitelt', 'closed':'zárt', 'boxed':'dobozos', 'doublecabin':'duplakabinos',
      'cooled':'hűtős', 'flatbed':'platós', 'curtainsider':'ponyvás', 'glazed':'üvegezett'
  };

  if ($('#car-category').val() != '0'){
    var selectCarDesignOptions = ($('#car-category').val() === 'car') ? selectCars : selectLcvs;
    getSelectOptions('#design', selectCarDesignOptions);
  }

  $('#car-category').change(function(){
    var selectCarDesignOptions = ($(this).val() === 'car') ? selectCars : selectLcvs;
    getSelectOptions('#design', selectCarDesignOptions);
  });

  function getSelectOptions(selector, optionsObj){
    $(selector).html('');
    $.each(optionsObj, function(key, value) {
      $(selector)
          .append($("<option></option>")
                     .attr("value",key)
                     .text(value));
    });
  }

  if (typeof(Storage) !== "undefined") {
    var sSelectedCarDesign = sessionStorage.getItem("car_design");
    if (sSelectedCarDesign !== "null"){
      $("#design").val(sSelectedCarDesign);
    }
  }

  $('#design').change(function(){
    if (typeof(Storage) !== "undefined") {
      sessionStorage.setItem("car_design", $(this).val());
    }
  });


})(jQuery);
