$(document).on('submit', '#profile-cover-change-form', function(e){
  var coverFileName = $($(this).find('.js-add-photo').find('input[type="file"]')[1]).val();
  if (coverFileName == '') {
   $(this).find('.profile_error_container').show();
   $(this).find('.profile_error_container').text(t('Загрузите изображение'));
   return false;
  }
  $(this).find('.profile_error_container').hide();
  return true;
});
$(document).on('click','.profile-tab_block a',function(e){
  e.preventDefault();
  scrollToAnchor($(this).attr('href'));
  $('.profile-tab_block .active').removeClass('active');
  $(this).addClass('active');
});

$(document).on('click','.profile-tab_block_js a',function(e){
  e.preventDefault();
  $('.profile-tab_block_js .active').removeClass('active');
  $(this).addClass('active');
  $('.user_tab').addClass('m-visible');
  $($(this).attr('href') + '_tab').removeClass('m-visible');
});

//if (window.matchMedia("(max-width:767px)").matches || isMobile()) {

ReviewsModule.init({
	id: profile_user_id,
	onPage: 10,
	onPageStart: 5,
	entity: 'user',
	baseUrl: ORIGIN_URL
});

var slideMobileModule = new SlideModule();
var slideDesktopModule = new SlideModule();
    $(window).load(function(){
        setTimeout(function(){
        slideMobileModule.init({
            sliderName: '.prd_slider_mobile #slider_mobile',
            settings: {
                lazyLoad: 'ondemand',
                slidesToShow: 1,
                slidesToScroll: 1,
                dots: true,
                arrows: false,
                infinite: true,
                sliderCount:true,
                adaptiveHeight: true
            }},200);
        });
        slideDesktopModule.init({
            sliderName: '.prd_slider_desktop #slider_desktop',
            settings: {
                lazyLoad: 'ondemand',
                slidesToShow: 1,
                slidesToScroll: 1,
                dots: false,
                arrows: true,
                infinite: true,
                speed: 100,
                fade: true,
                cssEase: 'linear'
            }
        });
});

var PortfolioTooltip = (function (document) {

    var __initTooltip = function ($portfolioBlock) {
        var img = new Image(),
            src = $portfolioBlock.data('src');

        var $tooltip = $('<div class="review__portfolio-tooltip portfolio-tooltip">');
        var $container = $('<div class="portfolio-tooltip__container">');
        var $portfilioImgBlock = $('<div class="portfolio-tooltip__img-block">');
        var $portfolioTitle = $('<div class="portfolio-tooltip__title">').text($portfolioBlock.data('title'));
        var $portfolioReviewBlock = $('<div class="portfolio-tooltip__review-block fs13">');

        $tooltip.append($container);

        $container.append($portfolioTitle);

        $container.append($portfilioImgBlock);
        $portfilioImgBlock.html('<span class="preloader__ico preloader__ico_small portfolio-tooltip__preloader">');

        if ($portfolioBlock.data('review')) {
            var userName = '<span class="semibold">' + $portfolioBlock.data('username') + ': </span>';
            $portfolioReviewBlock.html(userName + '"' + unescape($portfolioBlock.data('review')) + '"');
            $container.append($portfolioReviewBlock);
        }

        img.onload = function () {
            var $img = $('<img class="portfolio-tooltip__image">').attr('src', src);
            $portfilioImgBlock.addClass('portfolio-tooltip__img-block_loaded');
            $portfilioImgBlock.html($img);
        };

        img.src = src;

        $portfolioBlock.data('portfolioTooltip', $tooltip);
        $portfolioBlock.prepend($tooltip);
    };

    /**
     * Получить дозволенные границы для тултипа по высоте
     *
     * @returns {{top: number, bottom: number, avail: number}}
     * @private
     */
    var __getBorders = function(){
        var top = ($(window).scrollTop() ^ 0) + 84 + 50;
        var bottom = Utils.getWindowOffset() - 10;

        return {
            top: top,
            bottom: bottom,
            avail: bottom - top
        }
    };

    /**
     * Получить размер тултипа
     *
     * @param $tooltip
     * @returns {{imgBlockHeight: number, height: number, width: number}}
     * @private
     */
    var __getTooltipSize = function ($tooltip) {
        var height = $tooltip.height();
        var paddings = $tooltip.outerHeight() - height;
        var reviewHeight = $tooltip.find('.portfolio-tooltip__review-block').outerHeight(true);
        var titleHeight = $tooltip.find('.portfolio-tooltip__title').outerHeight(true);
        var maxHeight = __getBorders().avail - paddings - reviewHeight;
        var imgHeight = height - reviewHeight - titleHeight - 2;

        var width = $tooltip.width();

        if (imgHeight > maxHeight) {
            width = (width * maxHeight / imgHeight);
            height = maxHeight + paddings + reviewHeight + titleHeight;
        }else{
            maxHeight = imgHeight;
        }

        return {
            imgBlockHeight: maxHeight - 10,
            height: height ^ 0,
            width: width ^ 0
        };
    };

    var __showTooltip = function () {
        if (!$(this).data('portfolioTooltip')) {
            __initTooltip($(this));
        }
        $(this).addClass('review-portfolio_hover');
        var $tooltip = $(this).data('portfolioTooltip');
        $tooltip.removeClass('hidden');

        $tooltip.css('top', '0');

        var tooltipSize = __getTooltipSize($tooltip);

        $tooltip.find('.portfolio-tooltip__img-block').height(tooltipSize.imgBlockHeight);
        $tooltip.find('.portfolio-tooltip__image').width(tooltipSize.width - 12).height('auto');

        var tooltipTop = ((tooltipSize.height - $(this).height()) / 2);

        var minOffset = __getBorders().top;

        var tooltipMaxTop = $(this).offset().top - Math.max(minOffset, $(this).offset().top - tooltipTop);

        tooltipTop = Math.max(tooltipMaxTop, 0);

        var maxOffset = Math.min(Utils.getWindowOffset() - 20, $(this).offset().top + tooltipSize.height);
        var tooltipMinTop = tooltipSize.height - (maxOffset - $(this).offset().top);

        tooltipTop = Math.max(tooltipMinTop, tooltipTop);

        tooltipTop = Math.min(tooltipTop, tooltipSize.height - 30);

        $tooltip.width(tooltipSize.width).height(tooltipSize.height);
        $tooltip.css({
            'top': '-' + tooltipTop + 'px',
            'left': '-' + (tooltipSize.width + 10) + 'px'
        });
    };

    var __setTooltipArrow = function(){
        if(Utils.getWindowOffset() - ($(this).offset().top + 95) < 0){
            $(this).addClass('review-portfolio_half');
        }else{
            $(this).removeClass('review-portfolio_half');
        }
    };

    var __hideTooltip = function () {
        $(this).removeClass('review-portfolio_hover');
        if (typeof $(this).data('portfolioTooltip') != 'undefined') {
            $(this).data('portfolioTooltip').addClass('hidden');
        }
    };

    var __showPopup = function () {
        var youtubeId = $(this).data('youtubeId');
        var review = '';
        if ($(this).data('review')) {
            var userName = '<span class="semibold">' + $(this).data('username') + ': </span>';
            review =
                '<hr class="gray mt20 balance-popup__line">' +
                '<div>' +
                userName + '"' + unescape($(this).data('review')) + '"' +
                '</div>';
        }

        var html = '';
        if (youtubeId) {
            html = '' +
                '<div class="js-popup__inner-content" style="width:650px">' +
                '<h2 class="popup__title" style="font-size: 22px;line-height: 30px;">' + $(this).data('title') + '</h2>' +
                '<hr class="gray mt20 balance-popup__line">' +
                '<div class="clear" style="margin-bottom:32px;"></div>' +
                '<div style="display:inline-block;width:100%;">' +
                '<iframe width="650" height="480" src="https://www.youtube.com/embed/' + youtubeId + '" frameborder="0" allowfullscreen></iframe>' +
                '</div>' +
                review +
                '</div>';
        } else {
            html = '' +
                '<div class="js-popup__inner-content" style="width:650px">' +
                '<h2 class="popup__title" style="font-size: 22px;line-height: 30px;">' + $(this).data('title') + '</h2>' +
                '<hr class="gray mt20 balance-popup__line">' +
                '<div class="clear" style="margin-bottom:32px;"></div>' +
                '<div style="display:inline-block;width:100%;">' +
                '<img src="' + $(this).data('src') + '">' +
                '</div>' +
                review +
                '</div>';
        }

        show_popup(html, null, true);
    };

    var __setEvents = function () {
        if (window.matchMedia("(max-width:767px)").matches || isMobile()) {
            $(document).on('click', '.js-review-portfolio', __showPopup);
        } else {
            $(document).on('mouseenter', '.js-review-portfolio', function(){
                var that = this;

                if(Utils.getWindowOffset() - ($(this).offset().top + 30) < 0){
                    return false;
                }

                clearTimeout($(that).data('timer_hide')^0);

                var timer = setTimeout(function(){
                    __showTooltip.apply(that);
                    __setTooltipArrow.apply(that);
                }, 100);
                $(that).data('timer_show', timer);
            });

            $(document).on('mouseleave', '.js-review-portfolio', function(){
                var that = this;

                clearTimeout($(that).data('timer_show')^0);

                var timer = setTimeout(function(){
                    __hideTooltip.apply(that);
                }, 100);
                $(that).data('timer_hide', timer);
            });

            $(document).on('click', '.js-review-portfolio_video', __showPopup);
        }
    };

    return {
        init: function () {
            __setEvents();
        }
    }
})(document);

$(function () {
    PortfolioTooltip.init();
});

jQuery(function() {
	var certificatesCount = jQuery('#certificates_portfolio').find('[data-certificates-id]').length;

	$('#certificates_portfolio').on('click', '[data-certificates-id]', function() {
		var $el = $(this);

		if (!$el.length) {
			return false;
		}

    if($(this).find('.certificate_edit a:hover').length > 0) {
      return true;
    } else {
  		var certificatesId = $el.data('certificatesId');

  		if (certificatesId) {
  			certificatesCard.getCertificates(certificatesId);
  		}
    }
	});

	var portfolioCount = jQuery('#portfolio_portfolio').find('[data-portfolio-id]').length;

	$('#portfolio_portfolio').on('click', '[data-portfolio-id]', function() {
		var $el = $(this);

		if (!$el.length) {
			return false;
		}

    if($(this).find('.portfolio_edit a:hover').length > 0) {
      return true;
    } else {
  		var portfolioId = $el.data('portfolioId');

  		if (portfolioId) {
  			portfolioCard.getPortfolio(portfolioId);
  		}
    }
	});
});