$(document).ready(function() {
    /* IE Hacks */
    /**
    * documentMode is an IE-only property
    * http://msdn.microsoft.com/en-us/library/ie/cc196988(v=vs.85).aspx
    */

    var msie = document.documentMode;
    if (msie < 9) { /* code for IE < 9  */
        $('body').addClass('ie8');
    }

    /* Gallery */
    if ( $('.swiper-content .swiper-slide').length > 0 ) {
        /* Swiper Content */

        var doLoop = true;
        
        if ( $('.swiper-content .swiper-slide').length == 1 ) {
            doLoop = false;
            $('.slideshow-controller .btn').addClass('disabled');
        }

        var contentSwiper = $('.swiper-content').swiper({
            loop: doLoop,
            visibilityFullFit: false,
            watchActiveIndex: true,
            keyboardControl: true,
            /* Auto Height */
            calculateHeight: true,
            /* Apply CSS for width and/or height */
            initialized: function() {
                setContentSize();
                sliderButtonPosition();
            },
            onSlideChangeStart: function(){
                updateNavPosition();
                navSwiper.swipeTo( contentSwiper.activeLoopIndex );
                sliderIndexUpdate( contentSwiper.activeLoopIndex );
            },
            onSlideChangeEnd: function(){
                setContentSize();
                sliderButtonPosition();
                /* sliderButtonPosition(); */
            }
        });

        var navSwiper = $('.swiper-nav').swiper({
            slidesPerView: 'auto',
            loop: doLoop,
            visibilityFullFit: false,
            watchActiveIndex: true,
            keyboardControl: true,
            centeredSlides: true,
            /*Auto Height*/
            calculateHeight: true,
            /*Thumbnails Clicks*/
            onSlideClick: function(){
                navSwiper.swipeTo( navSwiper.clickedSlideLoopIndex  );
                contentSwiper.swipeTo( navSwiper.clickedSlideLoopIndex );
            }
        });

        $('.swiper-button-next').click( function() {
            navSwiper.swipeNext();
            contentSwiper.swipeNext();
        });

        $('.swiper-button-prev').click( function() {
            navSwiper.swipePrev();
            contentSwiper.swipePrev();
        });

        $('.btn-next').click(function(){
            $('.swiper-button-next').click();
        });

        $('.btn-prev').click(function(){
            $('.swiper-button-prev').click();
        });

        setContentSize();
        sliderButtonPosition();
        $(window).resize(function(){
            setContentSize();
            sliderButtonPosition();
        });
    }

    function setContentSize() {
        var captionHeight = $('.swiper-content .swiper-slide-active .caption').height();

        var newHeight = $('.swiper-content .swiper-slide-active img').height() + captionHeight + 21;
        $('.swiper-content, .swiper-content .swiper-wrapper, .swiper-content .swiper-slide-active').css({
            height: newHeight
        });
    }

    function updateNavPosition(){
        $('.swiper-nav .active-nav').removeClass('active-nav');
        var activeNav = $('.swiper-nav .swiper-slide').eq(contentSwiper.activeIndex).addClass('active-nav');
        if (!activeNav.hasClass('swiper-slide-visible')) {
            if (activeNav.index()>navSwiper.activeIndex) {
                var thumbsPerNav = Math.floor(navSwiper.width/activeNav.width())-1;
                navSwiper.swipeTo(activeNav.index()-thumbsPerNav);
            }
            else {
                navSwiper.swipeTo(activeNav.index());
            }
        }
    }

    function sliderIndexUpdate( index ) {
        $('.slideshow-controller .index span').text( index + 1);
    }

    function sliderButtonPosition() {
        if ( $(window).width() > 500 ) {
            var caption =  $('.swiper-content .swiper-slide-active .caption');
            if ( caption.length > 0 && caption.text().length > 0 ) {
                var captionHeight = $('.swiper-content').find('.swiper-slide-active .caption').height();
                var btnHeight = $('.slideshow-controller').height();
                var diff = captionHeight - btnHeight;

                if ( captionHeight > 0 ) {
                    var margin = ( captionHeight + 10 ) * -1 + 'px';
                    var height = captionHeight + 45 + 'px';
                    $('.slideshow-controller').css({ 'margin-top' : margin, 'height' : height }, 300);

                }
                else {
                    $('.slideshow-controller').removeAttr('style');
                }
            }
            else {
                $('.slideshow-controller').removeAttr('style');
            }
        }
        else {
            $('.slideshow-controller').removeAttr('style');
        }
    }

    if ( $('.widget .region-list').length > 0 ) {
        regionSublist();
    }

    /* set selected menu */
    var oMenu = {
      articles: 'news|features|lifestyle|opinion|interviews|tech|articles',
      photos: 'photos',
      videos: 'videos',
      races: 'calendar|races|rd_aids',
      coaching: 'coaching|coaches',
      gravel: 'gravel',
      podcast: 'podcast',
      training: 'training',
      bikefit: 'bike_fit|fit_calculator',
      products: 'products',
      local: 'local-listings|runshops|triclubs|retailers|fitters'
    };
    var uri = window.location.href.replace(/(.*).com\//, '');
    var prefix = uri.substring(0, uri.search(/\//)).toLowerCase();

    if (prefix == '') { prefix = uri.replace(/.html/, ''); }
    if (prefix != '') {
      var selected;
      for (var i in oMenu) {
        if (oMenu[i].search(prefix) != -1) {
          selected = i;
          break;
        }
      }
      if (selected) $('#menu a[rel=' + selected + ']').parent().addClass('selected');
    }

    /* trigger subcategory */
    $('select[name=subcat]').change(function() {
        window.location = $(this).val();
    })
})

function regionSublist() {
    $('.widget .list-item').click(function(){
        $('.widget .list-item span').text('+');
        if ( $(this).find('.sublist').css('display') !== 'none' ) {
            $('.widget .sublist').hide();
        }
        else {
            $('.widget .sublist').hide();
            $(this).find('.sublist').show();          
            $(this).find('span').text('-');
        }
    })
}

function copyFromTemplate() {
    $('.copytpl').each( function(){
        var template = $(this).attr('data-tpl');
        $( '.' + template + ':eq(0)' ).clone().insertAfter( $(this) );
        $(this).remove();
    });
}
