jQuery(document).ready(function($) {
    "use strict";

    /* ==============================================
     VIDEOS -->
     =============================================== */

    var videos$ = $('a[id^="video_"]');

    function videoInitHandler()
    {
        var el$ = $(this);

        var text = el$.text();
        var length = text.length - 11;
        var caption = text.substring(0, length);
        var expl = this.id.substring(6, this.id.length);

        $('<iframe />')
            .attr({
                width: '100%',
                height: 500,
                src: '//www.youtube-nocookie.com/embed/'+ expl,
                frameborder: 0,
                allowfullscreen: true,
                'data-st-video': this.id
            })
            .hide()
            .insertAfter(this)
        ;
        el$
            .addClass('st-collapsed')
            //.css('background-image', 'url(/images/st2/icons/arrowup.gif)')
            .text(caption + ' einblenden')
            .attr('href', 'javascript:void(0);')
        ;
    }

    videos$.each(videoInitHandler);

    videos$.click(function() {

        var el$ = $(this);
        var video$ = $('[data-st-video='+ this.id +']');
        var text = el$.text();
        var length = text.length - 11;
        var caption = text.substring(0, length);

        if (el$.hasClass('st-collapsed'))
        {
            video$.slideDown('slow');
            el$.text(caption + ' ausblenden');
            el$.removeClass('st-collapsed');
        }
        else
        {
            video$.slideUp(400);
            el$.text(caption + ' einblenden');
            el$.addClass('st-collapsed');
        }
    });

    /* ==============================================
    KEYWORDS -->
     =============================================== */

    var modal$ = $('#st-default-modal');

    $('a.show-layer').click(function() {

        $.get($(this).attr('href')).then(function(r) {

            modal$.find('.modal-body').html(r);
            modal$.find('a[id^="video_"]').each(videoInitHandler);
            modal$.modal('show');
        });
        return false;
    });

    /* ==============================================
     SIDEBAR BOX SLIDER -->
     =============================================== */

    function createSlider(ctx$, interval)
    {
        if (!interval)
        {
            interval = 0;
        }

        function setSlideInterval()
        {
            if (interval <= 0)
            {
                return;
            }

            if(slideInterval)
            {
                clearInterval(slideInterval);
            }
            slideInterval = setInterval(function() {

                jumpToNextSlide();
            }, interval);
        }

        function jumpToNextSlide()
        {
            setActiveSlide(slideIndex === slideCount - 1 ? 0 : slideIndex + 1);
            setSlideInterval();
        }

        function setActiveSlide(newIndex)
        {
            slide$s[slideIndex].removeClass('active');
            slideIndex = newIndex;
            slide$s[slideIndex].addClass('active');
        }

        var slides$ = $('.slide', ctx$);
        var slideCount = slides$.length;
        if(slideCount > 1)
        {
            var slideInterval;

            var slide$s = [];
            for(var i = 0; i < slideCount; ++i)
            {
                slide$s.push($(slides$.get(i)));
            }

            var slideIndex = 0;
            setSlideInterval();

            $('.item-button-next', ctx$).click(function() {
                jumpToNextSlide();
            });
            $('.item-button-prev', ctx$).click(function() {
                setActiveSlide(slideIndex === 0 ? slideCount - 1 : slideIndex - 1);
                setSlideInterval();
            });
        }
    }
    $('.box-slider').each(function() {
        createSlider($(this));
    });

    /* ==============================================
    HEADER STICKY -->
    =============================================== */

    var navbarCollapse = false;

    $(window).scroll(function() {
        if(!navbarCollapse){
            if ($(this).scrollTop() > 1){  
                $('header').addClass("sticky");
            }
            else{
                $('header').removeClass("sticky");
            }
        }
    });
    

    $('#navbar-collapse').on('shown.bs.collapse', function () {
        navbarCollapse = true;
        $('header').removeClass("sticky");
        $(window).scrollTop(0);

    });

    $('#navbar-collapse').on('hide.bs.collapse', function () {
         navbarCollapse = false;
    });


     /* ==============================================
    nav-tabs -->
    =============================================== */
    var hidWidth;
    var scrollBarWidths = 40;
    var windowW = $(window).width();


    var widthOfList = function(){
      var itemsWidth = 0;
      $('.list-nav-tabs li').each(function(){
        var itemWidth = $(this).outerWidth();
        itemsWidth+=itemWidth;
      });
      return itemsWidth;
    };

    var widthOfHidden = function(){
      return (($('.wrapper-nav-tabs').outerWidth())-widthOfList()-getLeftPosi())-scrollBarWidths;
    };

    var getLeftPosi = function(){
        if($('.list-nav-tabs').length){
            return $('.list-nav-tabs').position().left;
        }else{
            return 0;
        }
    };

    var reAdjust = function(){
      if (($('.wrapper-nav-tabs').outerWidth()) < widthOfList()) {
        $('.scroller-right-nav-tabs').show();
      }
      else {
        $('.scroller-right-nav-tabs').hide();
      }
      
      if (getLeftPosi()<0) {
        $('.scroller-left-nav-tabs').show();
      }
      else {
        $('.item').animate({left:"-="+getLeftPosi()+"px"},'slow');
        $('.scroller-left-nav-tabs').hide();
      }
    }

    if(windowW <= 992){    
        reAdjust();
    }
    $(window).on('resize',function(e){  
         var windowW = $(window).width();
         if(windowW <= 992){    
            reAdjust();
        }else{
            $('.scroller-right-nav-tabs').hide();
            $('.scroller-left-nav-tabs').hide();
        }
    });


    $('.scroller-right-nav-tabs').click(function() {
   
      if(((getLeftPosi()*-1) + $('.wrapper-nav-tabs').outerWidth()) < (widthOfHidden()*-1)){
        $('.scroller-left-nav-tabs').fadeIn('slow');
        $('.list-nav-tabs').animate({left:"+="+($('.wrapper-nav-tabs').outerWidth()*-1)+"px"},'slow',function(){

        });
      }else{
        $('.scroller-left-nav-tabs').fadeIn('slow');
        $('.scroller-right-nav-tabs').fadeOut('slow');
        $('.list-nav-tabs').animate({left:"+="+widthOfHidden()+"px"},'slow',function(){

        });
      }
    
    });

    $('.scroller-left-nav-tabs').click(function() {



    if(((getLeftPosi()) + $('.wrapper-nav-tabs').outerWidth()) < 0){
        $('.scroller-left-nav-tabs').fadeIn('slow');
        $('.list-nav-tabs').animate({left:"-="+($('.wrapper-nav-tabs').outerWidth()*-1)+"px"},'slow',function(){

        });
      }else{
        $('.scroller-right-nav-tabs').fadeIn('slow');
        $('.scroller-left-nav-tabs').fadeOut('slow');
        $('.list-nav-tabs').animate({left:"-="+getLeftPosi()+"px"},'slow',function(){
           $('.list-nav-tabs').css({'left': 0});
        });
      }

       
    });    

    /* ==============================================
    MENU HOVER -->
    =============================================== */
    if($(window).width() > 768){      
        $(".header .navbar-nav .dropdown:not(.openClick)").hover(    
            function() {
                $(".dropdown.openClick").removeClass('open');
                $('.dropdown-menu', this).stop( true, true ).slideDown("fast");
                $('.bootstrap-select.open').removeClass('open');
                $(this).toggleClass('open'); 
            },
            function() {
                $('.dropdown-menu', this).stop( true, true ).slideUp("fast");
                $(this).toggleClass('open');   
            }
        );
    }
       $(".header .dropdown:not(.openClick)").click(   
        function() { 
            if($(window).width() > 768){   
            var _self = $(this);
            setTimeout(
              function() 
              {
                window.location.href = _self.find('a').attr('href');
              }, 500);                 
            }
        }
        );


    $('.selectpicker').selectpicker({
        dropupAuto: false
    });
  


    /* ==============================================
    collapse_open -->
    =============================================== */

    function collapse_open(){
        var windowW = $(window).width();
        if(windowW <= 768){
            $('.collapse-widget').addClass('collapsed');
            $('.collapse-widget').parents('.widget').find('.collapse').removeClass('in');
        }else{
            $('.collapse-widget').removeClass('collapsed');
            $('.collapse-widget').parents('.widget').find('.collapse').addClass('in');
        }

    } 

    var $frist = false;
    $(window).resize(function() {
        if(!$first){
            var $first = true;
            collapse_open();
        }
    });
    collapse_open();

    
    /* ==============================================
    nav-tabs -->
    =============================================== */
    $('.nav-tabs li a').click(function (e) {     
        //get selected href
        var href = $(this).attr('href');    
    
        //set all nav tabs to inactive
        $('.nav-tabs li').removeClass('active');
        
        //get all nav tabs matching the href and set to active
        $('.nav-tabs li a[href="'+href+'"]').closest('li').addClass('active');

        //active tab
        $('.tab-pane').removeClass('active');
        $('.tab-pane'+href).addClass('active');

        if($(this).parents('.nav-tabs-bottom').length){
            $('html, body').animate({
            scrollTop: ($(".content-copy").offset().top + 200)
        }, 500);
        }
    
    })

    /* ==============================================
    tooltip -->
    =============================================== */

    $(function () {
      $('[data-toggle="tooltip"]').tooltip()
    })

    /* ==============================================
    carousel -->
    =============================================== */
    
    $('.carousel').carousel({
        interval: 5000 //changes the speed
    })
    
    /* ==============================================
    ACCORDION -->
    =============================================== */

    function toggleChevron(e) {
        console.log(e.target);
        var $i = $(e.target)
            .parent('.panel-group')
            .find("i.indicator");
        
        $i.toggleClass('icon-minus icon-plus');

        if($i.hasClass('icon-minus')){
            $i.parent('h3').find('span').html('Reiseleistungen ausblenden');
        }
        if($i.hasClass('icon-plus')){
            $i.parent('h3').find('span').html('Reiseleistungen einblenden');
        }   
    }
    $('#accordion').on('hidden.bs.collapse', toggleChevron);
    $('#accordion').on('shown.bs.collapse', toggleChevron);

   
    /* ==============================================
    LIGHTBOX -->
    =============================================== */

    /*
    jQuery('a[data-gal]').each(function() {
        jQuery(this).attr('rel', jQuery(this).data('gal'));
        });     
    jQuery("a[data-gal^='prettyPhoto']").prettyPhoto({animationSpeed:'slow',slideshow:false,overlay_gallery: false,theme:'light_square',social_tools:false,deeplinking:false});
    */
    /* ==============================================
    CAROUSEL -->
    =============================================== */

        $('.owl-fullwidth').owlCarousel({
            loop:true,
            margin:0,
            nav:true,
            dots:false,
            navText: [
                "<i class='fa fa-angle-right'></i>",                
                "<i class='fa fa-angle-left'></i>"],
                responsive:{
                0:{
                    items:1
                },
                600:{
                    items:2
                },
                1000:{
                    items:3
                }
            }
        })

      /* ==============================================
    BOX LINK -->
    =============================================== */

    $('.get-box-link').click(function() {
        var el$ = $(this);
        var url = el$.find('.is-box-link').attr('href');
        if (el$.attr('target') === '_blank')
        {
            window.open(url);
        }
        else
        {
            location.href = url;
        }
        return false;
    });

    /*  function resize_box (){
            $('.owl-fullwidth:not(.noresize)').each(function(){
                var boxes = $(this).find('.hl5');
                var maxHeight = Math.max.apply(
                Math, boxes.map(function() {
                    return $(this).height();
                }).get());
                boxes.height(maxHeight);
            });

            $('a.item-button').each(function(){
                  $(this).removeClass('single_line');
                   $(this).removeClass('dobble_line');
                if($(this).height() <= 36){
                    $(this).addClass('single_line');
                }else{
                   $(this).addClass('dobble_line');
                }
            });
            
            
        }
    resize_box();

    $(window).resize(function() {
       resize_box();
    }); */


    /* ==============================================
    resize_travel_img with height < 190 -->
    =============================================== */


    /*function resize_travel_img (){
            $('.travel-wrapper').find('img').each(function(){
                  if($(this).height() < 190){
                    $(this).addClass('lower-height');
                  }
            });
        }
    resize_travel_img();
    $(window).resize(function() {
       resize_travel_img();
    });*/

    
    /* ==============================================
    DATEPICKER -->
    =============================================== */

        $(".datepicker").each(function(){
            var windowW = $(window).width();
            if(windowW <= 768){
                $(this).attr('readonly', 'true');
            }
        });
        $( ".datepicker" ).datepicker({ 
            dateFormat: 'dd.mm.yy', prevText: '&#x3c;zurück', prevStatus: '',
            prevJumpText: '&#x3c;&#x3c;', prevJumpStatus: '',
            nextText: 'Vor&#x3e;', nextStatus: '',
            nextJumpText: '&#x3e;&#x3e;', nextJumpStatus: '',
            currentText: 'heute', currentStatus: '',
            todayText: 'heute', todayStatus: '',
            clearText: '-', clearStatus: '',
            closeText: 'schließen', closeStatus: '',
            monthNames: ['Januar','Februar','März','April','Mai','Juni',
            'Juli','August','September','Oktober','November','Dezember'],
            monthNamesShort: ['Jan','Feb','Mär','Apr','Mai','Jun',
            'Jul','Aug','Sep','Okt','Nov','Dez'],
            dayNames: ['Sonntag','Montag','Dienstag','Mittwoch','Donnerstag','Freitag','Samstag'],
            dayNamesShort: ['So','Mo','Di','Mi','Do','Fr','Sa'],
            dayNamesMin: ['So','Mo','Di','Mi','Do','Fr','Sa'],
            firstDay: 1,
            beforeShowDay: function(date) {
                var allowedDateStrListStr = $(this).attr('data-allowed-dates');
                if (allowedDateStrListStr)
                {
                    var allowedDatesStrList = allowedDateStrListStr.split(';');
                    for (var i = 0; i < allowedDatesStrList.length; ++i)
                    {
                        var allowedDate = new Date(allowedDatesStrList[i]);
                        if (allowedDate.getDate() === date.getDate() && allowedDate.getMonth() === date.getMonth() &&
                            allowedDate.getYear() === date.getYear())
                        {
                            return [true, '', ''];
                        }
                    }
                    return [false, '', '']
                }
                return [true, '', ''];
            }
        });

        function initAutoEndDate(startTxt$, endTxt$)
        {
            startTxt$.add(endTxt$).change(function() {

                var startDate = startTxt$.datepicker('getDate');
                if (startDate > endTxt$.datepicker('getDate'))
                {
                    endTxt$.datepicker('setDate', new Date(startDate.getFullYear(), startDate.getMonth(),
                        startDate.getDate() + 14));
                }
            });
        }
        var ttSearchForm$ = $('.st-tt-search-form');
        if (ttSearchForm$.length)
        {
            initAutoEndDate(ttSearchForm$.find('[name=termin]'), ttSearchForm$.find('[name=ruecktermin]'));
        }
        var searchForm$ = $('.st-search-form');
        if (searchForm$.length)
        {
            initAutoEndDate(searchForm$.find('[name=b]'), searchForm$.find('[name=e]'));
        }

    });