var isMobile = {
    Android: function() {
        return navigator.userAgent.match(/Android/i);
    },
    BlackBerry: function() {
        return navigator.userAgent.match(/BlackBerry/i);
    },
    iOS: function() {
        return navigator.userAgent.match(/iPhone|iPad|iPod/i);
    },
    Opera: function() {
        return navigator.userAgent.match(/Opera Mini/i);
    },
    Windows: function() {
        return navigator.userAgent.match(/IEMobile/i);
    },
    any: function() {
        return (isMobile.Android() || isMobile.BlackBerry() || isMobile.iOS() || isMobile.Opera() || isMobile.Windows());
    }
};

$(function () {
    $('.btn-blue:eq(0)').click(function () {
        $('.sign-in-popup').toggle();
    });
    $('.name-article').click(function () {
        // $('.text-content:eq(0)').slideToggle('slow');
        $(this).next().slideToggle('fast');
        if ($(this).hasClass('active')) {
            $(this).removeClass('active');
        } else {
            $(this).addClass('active');
        }
    });

    $('.btn-top-menu').click(function () {

        if ( $('.btn-filter-table').hasClass('active'))
        {
            $('.btn-filter-table').click();
        }
        $(this).toggleClass('active');

        $('.mob-devices').toggle();
        var mobDevice = $('.mob-devices').css('display');
        if (mobDevice == 'block') {
            var menuHeight = $('.mob-devices').outerHeight() + 10 + 'px';
            $('.top-ten-sites .wrap, .main-content .wrap').css('marginTop', menuHeight);
            $('.contact-us').css('marginTop', '136px');
        } else {
            $('.top-ten-sites .wrap, .main-content .wrap').css('marginTop', '0');
            $('.contact-us').css('marginTop', '0');
        }
    });

    $('.btn-filter-table').click(function() {

        if ( $('.btn-top-menu').hasClass('active'))
        {
            $('.btn-top-menu').click();
        }

        $(this).toggleClass('active');
        $('.mob-sort-menu').toggle();
        $('.top-ten-sites .wrap').css({
            'marginTop': '150px'
        });
        if ($('.mob-sort-menu').css('display') == 'none') {
            $('.top-ten-sites .wrap').css({
                'marginTop': '0'
            });
        }
    });
    $(window).resize(function () {
        if ($(window).width() >= '860') {
            $('.mob-devices').css('display', 'none');
            $('.top-ten-sites .wrap, .main-content .wrap').css('marginTop', '0');
            $('.contact-us').css('marginTop', '0');
        }
    });
    $('.go-top').click(function () {
        $('html, body').animate({
            scrollTop: 0
        }, 800);
    });

    $('.main-content .mainbar .navigation li').click(function () {
        $('.score-product.score-product_popularity.active').removeClass('active');
        $('#future-' + $(this).attr('data-mode')).addClass('active');
        $('.main-content .mainbar .navigation li').removeClass('active');
        $(this).addClass('active');
    });

    $('.score-product .mob-title').click(function () {
        $(this).closest('article').find('.score-product .inner-content').removeClass('active').siblings().removeClass('hidden');
        $(this).siblings().addClass('active');
        $(this).addClass('hidden');
    });


    stickyTopBar();

    var toggleText = [
        $('.main-content .mainbar .detail-info p:not(".js-not-hide-text")'),
        $('.top-ten-sites .description-block p')
    ];

    $.each(toggleText, function () {
        var that = $(this);
        that.append('<a class="toggle" href="#"><span class="open">more</span><span class="close">hide</span></a>');
        clickReadMore(that);
        that.find('a.toggle').click();
    });

    reviewsReadMore();

    $(window).resize(function () {
        $.each(toggleText, function () {
            var that = $(this);
            destroyDots.call(this, that);
            createDots.call(this, that);
        });
    });

    $(document).on('click', '.js-clickable-chart-row', function (e) {
        if (e.target.tagName != 'A' && !$(e.target).hasClass('js-site-like')) {
            var href = createRedirectId($(this).attr('data-url'));
            window.open(href, '_blank');
            return false;
        }
    });

    circles.init('js-circle-box');
    initSignInForm();
});
function stickyTopBar() {
    var $bar = $('.main-content .sidebar .top-sites'),
        scrollTopToStart = $bar.offset() ? $bar.offset().top : 0,
        minWindowWidth = 1040,
        scrollTopToFinish;

    function calculateLimits() {
        $bar.css({'position': 'relative'});
        scrollTopToStart = $bar.offset() ? $bar.offset().top : 0,
            scrollTopToFinish = $('footer.footer').offset().top - $bar.height();
    }
    $(window).on('load', calculateLimits);
    $(window).on('resize', calculateLimits);
    $(window).scroll(function () {
        if (($(window).scrollTop() > scrollTopToStart)
            && ($(document).width() >= minWindowWidth)
            && ($(window).scrollTop() <= scrollTopToFinish
            && ($('.mainbar article').length > 3 || $('.main-content_detail-article .mainbar article').length))) {
            $bar.css({'position': 'fixed', 'top': '0','width': 'auto'});
        } else {
            $bar.css({'position': 'relative'});
        }
    });
}
function clickReadMore(that) {
    that.on(
        'click',
        'a.toggle',
        function () {
            that.toggleClass('opened');
            if (that.hasClass('opened')) {
                destroyDots.call(this, that);
            } else {
                createDots.call(this, that);
            }
            return false;
        }
    );
}

function reviewsReadMore(setOpen) {
    var reviewsText = $('.top-ten-sites_reviews .table-row .information p');
    $.each(reviewsText, function () {
        var that = $(this);
        if (that.height() <= parseInt(that.css('line-height'))*2) return;
        that.append('<a class="toggle" href="#"><span class="open">more</span><span class="close">hide</span></a>');
        clickReadMore(that);
        that.find('a.toggle').click();
    });
}

function initRatePopup() {
    $('.popup.popup-add-rating .close, .popup-overlay').click(function () {
        hideRatePopup(true);
    });
    $('.popup.popup-thanks .close, .popup-overlay').click(function () {
        $('.popup-overlay, .popup.popup-thanks').hide();
        //$('html, body').animate({
        //     scrollTop: bottomPos - document.documentElement.clientHeight
        //}, 'slow');
    });
}
function showRatePopup() {
    $('.popup-overlay, .popup-add-rating').show();
    bottomPos = $(window).scrollTop() + $(window).height();
    //$('html, body').animate({
    //     scrollTop: 0
    //}, 'slow');
}
function showThanksPopup() {
    $('.popup.popup-thanks, .popup-overlay').show();
}
function hideRatePopup(scrol) {
    $('.popup-overlay, .popup-add-rating').hide();
    //if (scrol) {
    //    $('html, body').animate({
    //         scrollTop: bottomPos - document.documentElement.clientHeight
    //    }, 'slow');
    //}
}

function rateCurrentX2(id, rating) {
    $('.raterater-input[data-id="' + id + '"]').data('rating', rating * 2)
}

function createDots(el) {
    $(el).dotdotdot({
        after: 'a.toggle',
        height: function () {
            var lineHeight = parseInt($(el).css('line-height'));
            if (!isMobile.any())
            {
                lineHeight*=2;
            }
            return lineHeight;
        }
    });
}

function destroyDots(el) {
    $(el).trigger('destroy');
}

function initSignInForm() {
    var form;
    $('form.signin-form').submit(function (event) {
        event.preventDefault();

    });
    $('.signin-form .btn-sign').click(function (event) {
        event.preventDefault();
        sendSignInForm(event);
    });
    $('body').keyup(function (event) {
        if (event.keyCode == 13 && (form = $(event.target).parents('#dating_sites_rating_form'))) {
            event.target.blur();
            form.submit();
        }
        if (event.keyCode == 13 && $(event.target).hasClass('signin')) {
            event.preventDefault();
            event.target.blur();
            sendSignInForm(event);
        }
    });
}

function sendSignInForm(event) {
    var form = $(event.target).parents(".signin-form");
    form.find('input.error').removeClass('error');
    var regEmail = new RegExp("^[a-z0-9._%+-]+@[a-z0-9.-]+\.[a-z]{2,3}$", 'i');

    if (regEmail.test(form.find('input').val())) {
        $.ajax({
            type: 'POST',
            url: '/SitesCatalog/index/signin',
            data: form.serialize(),
            success: function (rsp) {
                rsp = JSON.parse(rsp);
                if (rsp && rsp.status === 'success') {
                    $('.sign-in-popup').hide();
                    window.location.reload()
                }
            },
            dataType: 'html'
        });

        $('.js-success-login-data-layer').trigger('mousedown');
    } else {
        form.find('input').addClass('error');
        var $msg = 'E-mail field cannot be blank.';
        if (form.find('input').val()) {
            $msg = 'Enter a valid E-mail.';
        }
        form.find('.alert-message').css({display: 'block'}).html($msg);
    }
}
$(function () {
    FastClick.attach(document.body);
});

var circles = {
    box: [],
    currentBar: null,
    containerClass: 'rating-js',
    container: null,
    bur: {},

    init: function (boxClass) {
        this.box = $('.' + boxClass);
        if (this.box.length) {
            this.box.each(function (index, element) {
                this.container = $($(element).find('.' + this.containerClass)[0]);
                this.bar = this.getBar(this.container.attr('id'), this.container.data('score'));
                this.bar.text.style.fontSize = this.container.data('textSize') + 'px';
                this.bar.animate(this.container.data('score').toString().replace(/\,/, ".") / 10);
            }.bind(this));
        }
    },
    getBar: function (containerId, value) {
        return new ProgressBar.Circle('#' + containerId, {
            color: '#586062',
            strokeWidth: 4,
            trailWidth: 4,
            easing: 'easeInOut',
            duration: 1400,
            text: {
                autoStyleContainer: false
            },
            from: {color: '#29c2e1', width: 4},
            to: {color: '#29c2e1', width: 4},
            clientHeight: 30,
            // Set default step function for all animate calls
            step: function (state, circle) {
                circle.path.setAttribute('stroke', 'rgb(41,194,225)');
                circle.setText(value);
            }
        });
    }
};

function mobileSortHandler(cls, sortType) {
    $('.'+cls+'[data-sort="'+sortType+'"]').click();
    $('.btn-filter-table').click();
}

var h_hght = 81;
var h_mrg = 0;
$(function(){
    $(window).scroll(function(){
        var top = $(this).scrollTop();
        var elem = $('.banner-fixed');
        if (top+h_mrg < h_hght) {
            $(".clubBanner").removeClass("banner-fixed");
        } else {
            $(".clubBanner").addClass("banner-fixed");
        }
    });
});
$(function(){
    var bannerSport = $('#Banner-sport-single');
    if (bannerSport.length != 0) {
        bannerSport.slick({
            vertical: true,
            slidesToShow: 1,
            dots: false,
            autoplay: true,
            autoplaySpeed: 5000,
            adaptiveHeight: true,
            prevArrow: $('.Banner-carousel-top .customNavigation .prev'),
            nextArrow: $('.Banner-carousel-top .customNavigation .next'),
            focusOnSelect: false
        });
    }

    function uppdateTimer() {
        var seconds = new Date().getTime() / 1000,
            startDt = $('#Banner-sport-single .slick-active .timestamp').val(),
            timer   = $('#sport-banner-timer'),
            tdDiff  = startDt - seconds;

        if ($(timer).length) {
            if (tdDiff <= 86400 && tdDiff > 0) {
                var  newTimer = $(timer).empty().clone();
                $(newTimer).insertAfter( "#sport-banner-timer" );
                $(timer).remove();
                $(newTimer).attr('data-seconds-left', startDt - seconds);
                $(newTimer).startTimer();
            } else {
                $(timer).empty();
            }
        }
    }

    $('#Banner-sport-single').on('afterChange',function() {
        uppdateTimer();
    });

    uppdateTimer();

    var visitBtn = $('.visit-btn');
    if (visitBtn.length) {
        visitBtn.on('click', function (e) {
            this.href = createRedirectId(this.href);
        });
    }
});

function getUniqueId() {
    return Math.round(Math.random()*100000);
}
function createRedirectId(href) {
    return href.replace(new RegExp('&cId=([A-z0-9]+)(-[0-9]+)?','g'), '&cId=$1-' + getUniqueId());
}

/* Changes start*/
$(function() {
    $('.select-list').click(function(e) {
        $(this).toggleClass('checked');
    });
    $(document).mouseup(function (e){ // событие клика по веб-документу
        var div = $(".dropdown-menu"); // тут указываем ID элемента
        if (!div.is(e.target) // если клик был не по нашему блоку
            && div.has(e.target).length === 0) { // и не по его дочерним элементам
           $('.select-list').removeClass('checked'); // скрываем его
        }
    });
});
/* Changes end*/
$(document).ready(function() {
    $(function(){
        var slider = $('.carousel.slider');
        if (slider.length) {
            slider.slick({
                vertical: true,
                slidesToShow: 1,
                dots: false,
                adaptiveHeight: true,
                prevArrow: $('.widget-articles .customNavigation .prev'),
                nextArrow: $('.widget-articles .customNavigation .next'),
                focusOnSelect: false,
                responsive: [
                    {
                        breakpoint: 860,
                        settings: {
                            infinite: true,
                            vertical: false,
                            dots: true
                        }
                    }
                ]
            });
        }
    });
});


$(function() {
    $('.has-submenu').click(function() {
        $(this).find('.submenu').toggle();
        if ($(this).find('.fa').hasClass('fa-caret-down')) {
            $(this).find('.fa').removeClass('fa-caret-down').addClass('fa-caret-up');
        } else {
            $(this).find('.fa').removeClass('fa-caret-up').addClass('fa-caret-down');
            $('.top-ten-sites .wrap, .main-content .wrap').css('marginTop', '0');
            $('.contact-us').css('marginTop', '0');
        }
    });

    $('.stars-rating').raterater({
        isStatic: "true",
        starWidth: 12,
        spaceWidth: 1,
        numStars: 5
    });

});
