"use strict";

/*----  Functions  ----*/

jQuery.fn.dsvy_is_bound = function(type) {
	if( this.data('events') !== undefined ){
		if (this.data('events')[type] === undefined || this.data('events')[type].length === 0) {
			return false;
		}
		return (-1 !== $.inArray(fn, this.data('events')[type]));
	} else {
		return false;
	}
};

var dsvy_sticky_header = function() {
	if( jQuery('.dsvy-header-sticky-yes').length > 0 ){
		var header_html = jQuery('#masthead .dsvy-main-header-area').html();
		jQuery('.dsvy-sticky-header').append(header_html);
		jQuery('.dsvy-sticky-header #menu-toggle').attr('id', 'menu-toggle2');
		jQuery('#menu-toggle2').on('click', function() {
			jQuery("#menu-toggle").trigger("click");
		});

		jQuery('.dsvy-sticky-header .main-navigation ul, .dsvy-sticky-header .main-navigation ul li, .dsvy-sticky-header .main-navigation ul li a').removeAttr('id');

		jQuery('.dsvy-sticky-header h1').each(function(){
			var thisele = jQuery(this);
			var thisele_class = jQuery(this).attr('class');
			thisele.replaceWith('<span class="' + thisele_class + '">' + jQuery(thisele).html() +'</span>');
		});

		// For infostak header
		if( jQuery('.dsvy-main-header-area').hasClass('dsvy-infostack-header') ){  // check if infostack header
			// for header style 3
			jQuery(".dsvy-sticky-header .dsvy-header-menu-area").insertAfter(".dsvy-sticky-header .site-branding");
			jQuery('.dsvy-sticky-header .dsvy-header-info, .dsvy-sticky-header .dsvy-mobile-search, .dsvy-sticky-header .nav-menu-toggle').remove();

			// for header style 4
			jQuery(".dsvy-sticky-header .dsvy-header-left, .dsvy-sticky-header .dsvy-header-right").remove();
		}

	}
}

var dsvy_sticky_header_class = function() {
	// Add sticky class
	if( jQuery('#wpadminbar').length>0 ){
		jQuery('#masthead').addClass('dsvy-adminbar-exists');
	}

	var offset_px = 300;
	if( jQuery('.dsvy-main-header-area').length>0 ){
		offset_px = jQuery('.dsvy-main-header-area').height() + offset_px;
	}

	jQuery(window).scroll(function() {
		if (jQuery(window).scrollTop() > offset_px) {
			jQuery('#masthead').addClass('dsvy-fixed-header');
			jQuery('.dsvy-sticky-header .mega-menu.max-mega-menu.mega-menu-horizontal').attr("id","mega-menu-designervily-top");
		} else {
			jQuery('#masthead').removeClass('dsvy-fixed-header');
		}
	});

}


var dsvy_toggleSidebar = function() {
	jQuery('#menu-toggle').on('click', function(){
		jQuery("body:not(.mega-menu-designervily-top) .dsvy-navbar > div, body:not(.mega-menu-designervily-top)").toggleClass("active");
	})
	if( jQuery('.dsvy-navbar > div > .closepanel').length==0 ){
		jQuery('.dsvy-navbar > div').append('<span class="closepanel"><i class="dsvy-base-icon-cancel"></i></span>');
		jQuery('.dsvy-navbar > div > .closepanel, .mega-menu-designervily-top .nav-menu-toggle').on('click', function(){	    		
			jQuery(".dsvy-navbar > div, body, .mega-menu-wrap").toggleClass("active");
		});
		// Cart icon
		if( jQuery('.dsvy-main-header-area .dsvy-right-box > .dsvy-cart-wrapper, .dsvy-main-header-area .dsvy-right-box .dsvy-search-cart-box > .dsvy-cart-wrapper').length>0 ){
			if( jQuery('.dsvy-navbar > div > .dsvy-responsive-icons').length==0 ){
				jQuery('.dsvy-navbar > div').append("<div class='dsvy-responsive-icons'></div>");
			}
			jQuery('.dsvy-navbar > div > .dsvy-responsive-icons').append('<div class="dsvy-cart-wrapper"></div>');
			jQuery('.dsvy-navbar > div > .dsvy-responsive-icons .dsvy-cart-wrapper').append( jQuery('.dsvy-main-header-area .dsvy-right-box > .dsvy-cart-wrapper, .dsvy-main-header-area .dsvy-right-box .dsvy-search-cart-box > .dsvy-cart-wrapper').html() );
		}
		// Search icon
		if( jQuery('.dsvy-main-header-area .dsvy-right-box > .dsvy-header-search-btn, .dsvy-main-header-area .dsvy-right-box .dsvy-search-cart-box > .dsvy-header-search-btn').length>0 ){
			if( jQuery('.dsvy-navbar > div > .dsvy-responsive-icons').length==0 ){
				jQuery('.dsvy-navbar > div').append("<div class='dsvy-responsive-icons'></div>");
			}
			jQuery('.dsvy-navbar > div > .dsvy-responsive-icons').append('<div class="dsvy-header-search-btn"></div>');
			jQuery('.dsvy-navbar > div > .dsvy-responsive-icons .dsvy-header-search-btn').append( jQuery('.dsvy-main-header-area .dsvy-right-box > .dsvy-header-search-btn, .dsvy-main-header-area .dsvy-right-box .dsvy-search-cart-box > .dsvy-header-search-btn').html() );
		}
		return false;
	}
}

/* ====================================== */
/* Cart page qty update
/* ====================================== */
var dsvy_wc_cart_page_qty_update = function() {
	if (typeof jQuery.fn.observe == "function") {
		jQuery('.wp-block-woocommerce-cart').observe('childlist subtree characterData', function(record) {
			setTimeout(function() {
				dsvy_wc_update_header_cart_total();
			}, 500 );
		});
		jQuery('.wc-block-components-totals-wrapper').observe('childlist subtree characterData', function(record) {
			setTimeout(function() {
				dsvy_wc_update_header_cart_total();
			}, 500 );
		});
		jQuery('.wc-block-components-quantity-selector__button--plus, .wc-block-components-quantity-selector__button--minus, .wc-block-cart-item__remove-link').on('click, mousedown', function () {
			setTimeout(function() {
				dsvy_wc_update_header_cart_total();
			}, 500 );
		});
		jQuery(".product-quantity .quantity input.input-text.qty, .wc-block-components-quantity-selector__input").on("input", function() {
			setTimeout(function() {
				dsvy_wc_update_header_cart_total();
			}, 500 );
		});
	}
}
var dsvy_wc_update_header_cart_total = function() {
	var total_qty		= 0;
	var total_amount	= '';
	var curent_qty		= 0;
	if( jQuery('table.wc-block-cart-items.wp-block-woocommerce-cart-line-items-block > tbody > tr').length > 0 ){
		jQuery('table.wc-block-cart-items.wp-block-woocommerce-cart-line-items-block > tbody > tr').each(function(){
			curent_qty = parseInt(jQuery(this).find('input.wc-block-components-quantity-selector__input').val());
			total_qty = total_qty + curent_qty;
		});
		total_amount = jQuery('.wc-block-components-totals-footer-item-tax-value').html(); // Amount
	}
	jQuery('.dsvy-cart-count').html(total_qty);
	jQuery('.dsvy-cart-wrapper .woocommerce-Price-amount').html(total_amount);
}

var dsvy_preloader = function() {
	jQuery(".dsvy-preloader").fadeOut('600');
}

var dsvy_sorting = function() {
	jQuery('.dsvy-sortable-yes:not(.dsvy-ajax-sortable-yes)').each(function(){
		var boxes	= jQuery('.dsvy-element-posts-wrapper', this );
		var links	= jQuery('.dsvy-sortable-list a', this );			
		boxes.isotope({
			animationEngine : 'best-available',
			layoutMode: 'masonry',
			masonry: {
				horizontalOrder: true
			}
		});
		links.on('click', function(e){
			var selector = jQuery(this).data('sortby');
			if( selector != '*' ){
				var selector = '.' + selector;
			}
			boxes.isotope({
				filter			: selector,
				itemSelector	: '.dsvy-ele',
				layoutMode		: 'fitRows',
				masonry: {
					horizontalOrder: true
				}
			});
			links.removeClass('dsvy-selected');
			jQuery(this).addClass('dsvy-selected');
			e.preventDefault();
		});
	});
}

var dsvy_ajax_sorting = function() {

	jQuery('.designervily-element.dsvy-sortable-yes.dsvy-ajax-sortable-yes .dsvy-sortable-list-ul a').on('click', function(){

		var thisEle = jQuery( this );
		var main_ele = jQuery( this ).closest('.designervily-element');

		// add loader class
		jQuery('.dsvy-element-posts-wrapper', main_ele).addClass('dsvy-ajax-loading');

		// Active class
		var ul_ele = jQuery( this ).closest('.dsvy-sortable-list-ul');
		jQuery('a', ul_ele).removeClass('dsvy-selected');
		jQuery(this).addClass('dsvy-selected');
		
		var cpt				= main_ele.data('cpt');
		var style			= main_ele.data('style');
		var show			= main_ele.data('show');
		var columns			= thisEle.data('columns');
		var from_category	= thisEle.data('category');
		var orderby			= '';
		var order			= '';
		var selected_category = '';

		var infinitre_scroll_data = jQuery( '.dsvy-infinite-scroll-data', main_ele ).html();
		if( infinitre_scroll_data!='' ){
			var url_attributes = '';
			jQuery.each( jQuery.parseJSON(infinitre_scroll_data), function(key, value){
				if( key == 'cpt' ){
					cpt = value;
				} else if( key == 'style' ){
					style = value;
				} else if( key == 'show' ){
					show = value;
				} else if( key == 'columns' ){
					columns = value;
				} else if( key == 'orderby' ){
					orderby = value;
				} else if( key == 'order' ){
					order = value;
				} else if( key == 'from_category' ){
					selected_category = value;
				}
			});
		}

		// click on ALL button
		if( from_category == '*' &&  selected_category != ''){
            from_category = selected_category.join(',');
		}

		if( from_category == '*' ){
			from_category = '';
			if( selected_category != ''){
            	from_category = selected_category.join(',');
			}
		}

		jQuery.ajax({
			type	: "post",
			url		: dsvy_js_variables.ajaxurl,
			data 	: {
				action			: "dsvy_ajax_sortable_category",
				cpt				: cpt,
				style			: style,
				show			: show,
				columns			: columns,
				from_category	: from_category,
				orderby			: orderby,
				order			: order,

				nonce			: dsvy_js_variables.ajaxnonce_sortcat
			},
			success	: function(response){
				jQuery('.dsvy-element-posts-wrapper', main_ele).removeClass('dsvy-ajax-loading');
				jQuery('.dsvy-element-posts-wrapper', main_ele).html(response);
			}
		});
		
		

		return false;
	});

}


var dsvy_back_to_top = function() {
	// scroll-to-top
	var btn = jQuery('.scroll-to-top');
	jQuery(window).scroll(function() {
	if (jQuery(window).scrollTop() > 300) {
		btn.addClass('show');
	} else {
		btn.removeClass('show');
	}
	});
	btn.on('click', function(e) {
	e.preventDefault();
	jQuery('html, body').animate({scrollTop:0}, '300');
	});
}

var dsvy_navbar = function() {
	if( !jQuery('ul#dsvy-top-menu > li > a[href="#"]').dsvy_is_bound('click') ) {
		jQuery('ul#dsvy-top-menu > li > a[href="#"]').click(function(){ return false; });
	}
	jQuery('.dsvy-navbar > div > ul li:has(ul)').append("<span class='sub-menu-toggle'><i class='dsvy-base-icon-down-open-big'></i></span>");
	jQuery('.dsvy-navbar li').hover(function() {	
		if(jQuery(this).children("ul").length == 1) {
			var parent		= jQuery(this);
			var child_menu	= jQuery(this).children("ul");
			if( jQuery(parent).offset().left + jQuery(parent).width() + jQuery(child_menu).width() > jQuery(window).width() ){
				jQuery(child_menu).addClass('dsvy-nav-left');
			} else {
				jQuery(child_menu).removeClass('dsvy-nav-left');
			}
		}
	});
	jQuery('.sub-menu-toggle').on( 'click', function() {
		if(jQuery(this).siblings('.sub-menu, .children').hasClass('show')){
			jQuery(this).siblings('.sub-menu, .children').removeClass('show');
			jQuery( 'i', jQuery(this) ).removeClass('dsvy-base-icon-up-open-big').addClass('dsvy-base-icon-down-open-big');
		} else {
			jQuery(this).siblings('.sub-menu, .children').addClass('show');
			jQuery( 'i', jQuery(this) ).removeClass('dsvy-base-icon-down-open-big').addClass('dsvy-base-icon-up-open-big');
		}
		return false;
	});
		jQuery('.dsvy-navbar ul.menu > li > a').on( 'click', function() {
			if( jQuery(this).attr('href')=='#' && jQuery(this).siblings('ul.sub-menu, ul.children').length>0 ){
				jQuery(this).siblings('.sub-menu-toggle').trigger('click');
				return false;
			}
		});
}

var dsvy_lightbox = function() {
	var i_type = 'image';
	jQuery('a.dsvy-lightbox, a.dsvy-lightbox-video, .dsvy-lightbox-video a, .dsvy-lightbox a').each(function(){
		if( jQuery(this).hasClass('dsvy-lightbox-video') || jQuery(this).closest('.elementor-element').hasClass('dsvy-lightbox-video') ){
			i_type = 'iframe';
		} else {
			i_type = 'image';
		}
		if( jQuery(this).closest('.dsvy-ele-portfolio').length == 0 ){
			jQuery(this).magnificPopup({type:i_type});
		}
	});
}

var dsvy_video_popup = function() {
	jQuery('.dsvy-popup').on('click', function(event) {
		event.preventDefault();
		var href  = jQuery(this).attr('href');
		var title = jQuery(this).attr('title');
		window.open( href , title, "width=600,height=500");
	});
}

var dsvy_testimonial = function() {
	jQuery('.dsvy-testimonial-active').each(function(){
		var ele_parent = jQuery(this).closest('.dsvy-element-posts-wrapper');
		jQuery('.designervily-ele.designervily-ele-testimonial', ele_parent ).on('mouseover', function() {
			jQuery('.designervily-ele.designervily-ele-testimonial', ele_parent ).removeClass('dsvy-testimonial-active');
			jQuery(this).addClass('dsvy-testimonial-active');
		});
	});
}

var dsvy_search_btn = function(){
	jQuery(function() {
		jQuery('.dsvy-header-search-btn').on("click", function(event) {
			event.preventDefault();
			jQuery(".dsvy-header-search-form-wrapper").addClass("open");
			jQuery('.dsvy-header-search-form-wrapper input[type="search"]').focus();
		});
		jQuery(".dsvy-search-close").on("click keyup", function(event) {
			jQuery(".dsvy-header-search-form-wrapper").removeClass("open");
		});
	});
}

var dsvy_gallery = function(){
	jQuery("div.dsvy-gallery").each(function(){
		jQuery( this ).lightSlider({ item: 1, auto: true, loop: true, controls: false, speed: 1500, pause: 5500 }); 
	});
}

var dsvy_center_logo_header_class = function() {
	if( jQuery('#masthead.dsvy-header-style-5 ul#dsvy-top-menu').length > 0 ){
		var has_class = jQuery('#masthead.dsvy-header-style-5 ul#dsvy-top-menu > li').hasClass('dsvy-logo-append');
		if( has_class==false ){
			var total_li = jQuery('#masthead.dsvy-header-style-5 ul#dsvy-top-menu > li').length;
			var li = Math.floor( total_li / 2 );
			jQuery('#masthead.dsvy-header-style-5 ul#dsvy-top-menu > li:nth-child('+li+')').addClass('dsvy-logo-append');
		}
	}
}

var dsvy_selectwrap = function(){
	jQuery("select:not(#rating)").each(function(){
		jQuery( this ).wrap( "<div class='dsvy-select'></div>" );
	});
}

/* ====================================== */
/* Circle Progress bar
/* ====================================== */
var dsvy_circle_progressbar = function() {

	jQuery('.dsvy-circle-outer').each(function(){

		var this_circle = jQuery(this);

		// Circle settings
		var emptyFill_val = "rgba(0, 0, 0, 0)";
		var thickness_val = 10;
		var fill_val      = this_circle.data('fill');
		var size_val      = 110;

		if( typeof this_circle.data('emptyfill') !== 'undefined' && this_circle.data('emptyfill')!='' ){
			emptyFill_val = this_circle.data('emptyfill');
		}
		if( typeof this_circle.data('thickness') !== 'undefined' && this_circle.data('thickness')!='' ){
			thickness_val = this_circle.data('thickness');
		}
		if( typeof this_circle.data('size') !== 'undefined' && this_circle.data('size')!='' ){
			size_val = this_circle.data('size');
		}
		if( typeof this_circle.data('filltype') !== 'undefined' && this_circle.data('filltype')=='gradient' ){
			fill_val = {gradient: [ this_circle.data('gradient1') , this_circle.data('gradient2') ], gradientAngle: Math.PI / 4 };
		}

		if( typeof jQuery.fn.circleProgress == "function" ){
			var digit   = this_circle.data('digit');
			var before  = this_circle.data('before');
			var after   = this_circle.data('after');
			var digit       = Number( digit );
			var short_digit = ( digit/100 ); 

			jQuery('.dsvy-circle', this_circle ).circleProgress({
				value		: 0,
				size		: size_val,
				startAngle	: -Math.PI / 4 * 2,
				thickness	: thickness_val,
				emptyFill	: emptyFill_val,
				fill		: fill_val
			}).on('circle-animation-progress', function(event, progress, stepValue) { // Rotate number when animating
				this_circle.find('.dsvy-circle-number').html( before + Math.round( stepValue*100 ) + after );
			});
		}

		this_circle.waypoint(function(direction) {
			if( !this_circle.hasClass('completed') ){
				// Re draw when view
				if( typeof jQuery.fn.circleProgress == "function" ){
					jQuery('.dsvy-circle', this_circle ).circleProgress( { value: short_digit } );
				};
				this_circle.addClass('completed');
			}
		}, { offset:'85%' });

	});
}

/* ====================================== */
/* Carousel
/* ====================================== */
var dsvy_carousel = function() {

	jQuery(".designervily-element-viewtype-carousel").each(function() {

		var carouselElement = jQuery( this );

		jQuery('.dsvy-ele' , carouselElement).removeClass( function (index, className) {
			return (className.match (/(^|\s)col-md-\S+/g) || []).join(' ');
		}).removeClass( function (index, className) {
			return (className.match (/(^|\s)col-lg-\S+/g) || []).join(' ');
		}).removeClass( function (index, className) {
			return (className.match (/(^|\s)wpem-col\S+/g) || []).join(' ');
		}).removeClass( function (index, className) {
			return (className.match (/(^|\s)wpem-event-box-col\S+/g) || []).join(' ');
		}).removeClass( 'wpem-col' );

		var columns = jQuery( this ).data('columns');
		var loop = jQuery( this ).data('loop');

		if( columns == '1' ){
			var responsive_items = [ /* 1199 : */ '1', /* 991 : */ '1', /* 767 : */ '1', /* 575 : */ '1', /* 0 : */ '1' ];
		} else if( columns == '2' ){
			var responsive_items = [ /* 1199 : */ '2', /* 991 : */ '2', /* 767 : */ '2', /* 575 : */ '2', /* 0 : */ '1' ];
		} else if( columns == '3' ){
			var responsive_items = [ /* 1199 : */ '3', /* 991 : */ '2', /* 767 : */ '2', /* 575 : */ '2', /* 0 : */ '1' ];
		} else if( columns == '4' ){
			var responsive_items = [ /* 1199 : */ '4', /* 991 : */ '4', /* 767 : */ '3', /* 575 : */ '2', /* 0 : */ '1' ];
		} else if( columns == '5' ){
			var responsive_items = [ /* 1199 : */ '5', /* 991 : */ '4', /* 767 : */ '3', /* 575 : */ '2', /* 0 : */ '1' ];
		} else if( columns == '6' ){
			var responsive_items = [ /* 1199 : */ '6', /* 991 : */ '4', /* 767 : */ '3', /* 575 : */ '2', /* 0 : */ '1' ];
		} else {
			var responsive_items = [ /* 1199 : */ '3', /* 991 : */ '3', /* 767 : */ '3', /* 575 : */ '2', /* 0 : */ '1' ];
		}

		var margin_val = 30;
		if( jQuery(carouselElement).data('margin')!='' ){
			margin_val = jQuery(carouselElement).data('margin');
		}

		var posts_wrapper_class = '.dsvy-element-posts-wrapper';

		var val_nav = jQuery(carouselElement).data('nav');
		if( val_nav=='above' ){
			val_nav = false;
		}

		var car_options = {
			loop			: jQuery(carouselElement).data('loop'),
			autoplay		: jQuery(carouselElement).data('autoplay'),
			center			: jQuery(carouselElement).data('center'),
			nav				: val_nav,
			dots			: jQuery(carouselElement).data('dots'),
			autoplaySpeed	: jQuery(carouselElement).data('autoplayspeed'),
			autoplayTimeout	: jQuery(carouselElement).data('autoplayspeed') + 5000,
			navSpeed		: jQuery(carouselElement).data('autoplayspeed'),
			dotsSpeed		: jQuery(carouselElement).data('autoplayspeed'),
			dragEndSpeed	: jQuery(carouselElement).data('autoplayspeed'),
			margin			: 30,
			items			: columns,
			responsiveClass	: true,
			responsive		: {
				1199 : {
					items	: responsive_items[0],
				},
				991	 : {
					items	: responsive_items[1],
				},
				767	 : {
					items	: responsive_items[2],
				},
				575	 : {
					items	: responsive_items[3],
				},
				0	 : {
					items	: responsive_items[4],
				}
			}
		};

		// gap - margin
		if( typeof margin_val == "string" && margin_val!='' ){
			margin_val = margin_val.replace( 'px', '');
			margin_val = parseInt(margin_val);
			car_options['margin'] = margin_val;
		}

		// apply carousel effect with options
		var dsvy_owl = jQuery( posts_wrapper_class, carouselElement).removeClass('row multi-columns-row').addClass('owl-carousel').owlCarousel( car_options ).removeClass('wpem-row');

		jQuery('.dsvy-carousel-prev', carouselElement).click(function(event) {
			event.preventDefault();
			dsvy_owl.trigger('prev.owl.carousel', [jQuery(carouselElement).data('autoplayspeed')]);

		});
		jQuery('.dsvy-carousel-next', carouselElement).click(function(event) {
			event.preventDefault();
			dsvy_owl.trigger('next.owl.carousel', [jQuery(carouselElement).data('autoplayspeed')]);
		});

	});
};

/* ====================================== */
/* Menu item count
/* ====================================== */
var dsvy_menu_count = function() {
	if( jQuery('ul#dsvy-top-menu > li').length>0 || jQuery('div#dsvy-top-menu > ul > li').length>0 ){
		if( jQuery('ul#dsvy-top-menu > li').length>0 ){
			var total_li = jQuery( 'ul#dsvy-top-menu > li' ).length;
		}
		if( jQuery('div#dsvy-top-menu > ul > li').length>0 ){
			var total_li = jQuery( 'div#dsvy-top-menu > ul > li' ).length;
		}
		if( total_li > 6 ){
			jQuery('#site-navigation').addClass('dsvy-bigger-menu');
		}
	}
}

/* ====================================== */
/* Animate on scroll : Number rotator
/* ====================================== */
var dsvy_number_rotate = function() {
	jQuery(".dsvy-number-rotate").each(function() {
		var self      = jQuery(this);
		var delay     = (self.data("appear-animation-delay") ? self.data("appear-animation-delay") : 0);
		var animation = self.data("appear-animation");

		self.html('0');
		self.waypoint(function(direction) {
			if( !self.hasClass('completed') ){
				var from     = self.data('from');
				var to       = self.data('to');
				var interval = self.data('interval');
				self.numinate({
					format: '%counter%',
					from: from,
					to: to,
					runningInterval: 2000,
					stepUnit: interval,
					onComplete: function(elem) {
						self.addClass('completed');
					}
				});
			}
		}, { offset:'85%' });
	});
};

/* ====================================== */
/* Image size correction
/* ====================================== */
var dsvy_img_size_correction = function() {
	setTimeout(function(){
		jQuery("img").each(function() {
			var thisimg = jQuery( this );
			var p_width = jQuery( this ).parent().width();
			var width   = jQuery( this ).attr('width');
			var height  = jQuery( this ).attr('height');
			if( (typeof width !== typeof undefined && width !== false) && (typeof height !== typeof undefined && height !== false) ){
				var ratio  = height/width;
				jQuery( this ).data('dsvy-ratio', ratio);
				var real_width = jQuery( this ).width();
				var new_height = Math.round(real_width * ratio);
			}
		});
	}, 100);
};

/* ====================================== */
/* Tabs
/* ====================================== */
var dsvy_tabs_element = function() {
	var tab_number = '';
	jQuery('.dsvy-tab-link').on('click', function(){
		if( !jQuery(this).hasClass('dsvy-tab-li-active') ){
			var parent = jQuery(this).closest('ul.dsvy-tabs-heading');
			jQuery( 'li', parent).each(function(){
				jQuery(this).removeClass('dsvy-tab-li-active')
			});
			jQuery(this).addClass('dsvy-tab-li-active');
			tab_number = jQuery( this ).data('dsvy-tab');
			jQuery(this).parent().parent().find('.dsvy-tab-content').removeClass('dsvy-tab-active');
			jQuery(this).parent().parent().find('.dsvy-tab-content-'+tab_number).addClass('dsvy-tab-active');
		}
	});
	var this_title = '';
	jQuery('.dsvy-tab-content-title').on('click', function(){
		this_title = jQuery(this);
		tab_number = jQuery( this ).data('dsvy-tab');
		jQuery( this ).closest('.dsvy-tabs').find('li.dsvy-tab-link[data-dsvy-tab="'+tab_number+'"]',  ).trigger('click');
		var animateTo = jQuery(this_title).offset().top - 10;
		if (jQuery('#wpadminbar').length > 0) {
			animateTo = animateTo - jQuery('#wpadminbar').height();
		}
		jQuery('html, body').animate({
			scrollTop: animateTo
		}, 500);
	});
};

var dsvy_infinite_scroll = function() {
	if( jQuery('.dsvy-infinite-scroll-yes').length>0 ){
		jQuery('.dsvy-infinite-scroll-yes').each(function(){

			var main_ele	= jQuery(this);
			var style		= jQuery(this).data('style');
			var cpt			= jQuery(this).data('cpt');
			var columns		= jQuery(this).data('columns');
			var show		= jQuery(this).data('show');
			var totalpagination	= jQuery(this).data('totalpagination');

			var infinitre_scroll_data = jQuery( '.dsvy-infinite-scroll-data', main_ele ).html();
			if( infinitre_scroll_data!='' ){
				var url_attributes = '';
				jQuery.each( jQuery.parseJSON(infinitre_scroll_data), function(key, value){
					url_attributes = url_attributes + '&'+key+'='+value;
				});
			}

			if( jQuery(this).hasClass('dsvy-infinite-scroll-button-yes') ){
				var x = 2;

				// init Masonry
				let $grid = jQuery('.dsvy-element-posts-wrapper', main_ele).masonry({
					itemSelector	: 'none', // select none at first
					columnWidth		: '.dsvy-ele',
					gutter			: 0,
					percentPosition	: true,
					stagger			: 30,
					// nicer reveal transition
					visibleStyle	: { transform: 'translateY(0)', opacity: 1 },
					hiddenStyle		: { transform: 'translateY(100px)', opacity: 0 },
				});

				// get Masonry instance
				let msnry = $grid.data('masonry');

				// initial items reveal
				$grid.imagesLoaded( function() {
					$grid.removeClass('are-images-unloaded');
					$grid.masonry( 'option', { itemSelector: '.dsvy-ele' });
					let $items = $grid.find('.dsvy-ele');
					$grid.masonry( 'appended', $items );
				});

				// init Infinte Scroll
				$grid.infiniteScroll({
					// options
					path			: dsvy_js_variables.ajaxurl + '?action=dsvy_infinite_scroll&page_no={{#}}&nonce='+ dsvy_js_variables.ajaxnonce + url_attributes,
					checkLastPage	: false,
					button			: '.dsvy-ajax-load-more-btn > a',
					scrollThreshold	: false,
					status			: '.dsvy-infinite-loader',  // disable loading on scroll
					append			: '.dsvy-ele',
					history			: false,
					visibleStyle	: { transform: 'translateY(0)', opacity: 1 },
					outlayer		: msnry,
				});
				$grid.on( 'append.infiniteScroll', function( event, body, path, items, response ) {
					jQuery(items).each(function(){
						jQuery(this).addClass('dsvy-infinite-scroll-animation');
					});

					if( x >= totalpagination ){
						jQuery('.dsvy-ajax-load-more-btn > a', main_ele).hide();
						jQuery('.dsvy-infinite-loader', main_ele).addClass('dsvy-infinite-loader-hide');
						jQuery('.dsvy-infinite-scroll-last', main_ele).show();
					}
					x++;
				});

			} else {

				// infinite scroll without button

				// hide load more button
				var x = 2;
				if( x >= totalpagination ){ jQuery('.dsvy-ajax-load-more-btn > a', main_ele).hide(); } // hide button on page load if lower post found

				//-------------------------------------//
				// init Masonry

				let $grid = jQuery('.dsvy-element-posts-wrapper', main_ele).masonry({
					itemSelector: 'none', // select none at first
					columnWidth: '.dsvy-ele',
					gutter: 0,
					percentPosition: true,
					stagger: 30,
					// nicer reveal transition
					visibleStyle: { transform: 'translateY(0)', opacity: 1 },
					hiddenStyle: { transform: 'translateY(100px)', opacity: 0 },
				});

				// get Masonry instance
				let msnry = $grid.data('masonry');

				// initial items reveal
				$grid.imagesLoaded( function() {
					$grid.removeClass('are-images-unloaded');
					$grid.masonry( 'option', { itemSelector: '.dsvy-ele' });
					let $items = $grid.find('.dsvy-ele');
					$grid.masonry( 'appended', $items );
				});

				//-------------------------------------//
				// init Infinte Scroll

				$grid.infiniteScroll({
					path		: dsvy_js_variables.ajaxurl + '?action=dsvy_infinite_scroll&page_no={{#}}&nonce='+ dsvy_js_variables.ajaxnonce + url_attributes,
					append		: '.dsvy-ele',
					outlayer	: msnry,
					status		: '.dsvy-infinite-loader',
					history			: false,
					scrollThreshold: -200,
				});

				$grid.on( 'append.infiniteScroll', function( event, body, path, items, response ) {
					if( x >= totalpagination ){
						jQuery('.dsvy-infinite-loader', main_ele).addClass('dsvy-infinite-loader-hide');
						jQuery('.dsvy-infinite-scroll-last', main_ele).show();
					}
					x++;
				});

			}

		});

	}
}

var dsvy_progressbar = function() {
	jQuery('.dsvy-progressbar').each(function(){
		var $progressbar_ele = jQuery(this);
		jQuery(this).waypoint(function(direction) {
			var $progressbar = jQuery( '.elementor-progress-bar', $progressbar_ele );
			if( !$progressbar.hasClass('completed') ){
				$progressbar.css('width', $progressbar.data('max') + '%').addClass('completed');
			}
		}, { offset:'99%' });
	});
}

var dsvy_search_results = function() {
	if( jQuery('.dsvy-search-results-main-wrapper').length > 0 && jQuery('.dsvy-search-result-tab-links').length > 0 ){
		jQuery('.dsvy-search-results-main-wrapper').skeletabs({keyboard:false});
	}
}

/* ====================================== */
/* Comment form validator
/* ====================================== */
var dsvy_validate = function() {
	jQuery("#commentform").submit( function( event ){
		var error = false;
		jQuery('.dsvy-form-error').hide();
		if( jQuery("#author").length > 0 && ! jQuery("#author").val() ){  // empty author
			jQuery('.comment-form-author .dsvy-form-error').show();
			error = true;
		}
		if( jQuery("#comment").length > 0 && ! jQuery("#comment").val() ){  // empty comment
			jQuery('.comment-form-comment .dsvy-form-error').show();
			error = true;
		}
		if( jQuery("#email").length > 0 ) {
			if( ! jQuery("#email").val() ){ // empty email
				jQuery('.comment-form-email .dsvy-form-error.dsvy-empty-email').show();
				error = true;
			} else {
				var valid_email = (/^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/.test( jQuery("#email").val() ));
				if( valid_email != true ){
					jQuery('.comment-form-email .dsvy-form-error.dsvy-invalid-email').show();
					error = true;
				}
			}
		}
		if( error == true ){
			event.preventDefault();
			return false;
		} else {
			return true;
		}
	});
}

/* ====================================== */
/* Slider counter number
/* ====================================== */

var dsvy_slider_dot_number = function() {
	var x = 1;
	jQuery('.sr7-bullets .sr7-bullet').each(function(i) {
		//var $this = $(this); 
		//var newClass = "delay" + i++;
		jQuery(this).html('0'+x);
		x++;
	});

}

/*----  Events  ----*/

var dsvy_ajax_pagination = function() {

	if( jQuery('.designervily-element.dsvy-ajax-pagination-yes').length > 0 ){

		jQuery('.designervily-element.dsvy-ajax-pagination-yes').each(function(){
			var main_ele = jQuery(this);

			jQuery('.dsvy-pagination a', main_ele).each(function(i,e){
				var link_href = jQuery(e).attr('href');
				var link_href_array = link_href.split("page");
				var page_number = link_href_array[link_href_array.length - 1];
				page_number = page_number.replace("/", "");
				page_number = page_number.replace("/", "");
				page_number = page_number.replace("d=", "");

				jQuery(e).attr('data-pagenum', page_number );

			})

			jQuery('.dsvy-pagination .page-numbers', main_ele).click(function(e){
				
				e.preventDefault();
				
				var thisEle = jQuery( this );

				if( thisEle.hasClass('current') ){
					return;
				}
		
				// add loader class
				jQuery('.dsvy-element-posts-wrapper', main_ele).addClass('dsvy-ajax-loading');
		
				// Active class
				var div_pagination = jQuery( this ).closest('.dsvy-pagination');
				jQuery('a, .page-numbers', div_pagination).removeClass('current');
				
				jQuery(this).addClass('current');

				var pagination = 1;
				if( jQuery( this ).data('pagenum') != '' ){
					pagination = jQuery( this ).data('pagenum')
				}
				
				var cpt				= main_ele.data('cpt');
				var style			= main_ele.data('style');
				var show			= main_ele.data('show');
				var columns			= main_ele.data('columns');
				var from_category	= main_ele.data('sortby');
				var orderby			= '';
				var order			= '';
				//var pagination			= pagenumber;
		
				var infinitre_scroll_data = jQuery( '.dsvy-infinite-scroll-data', main_ele ).html();
				if( infinitre_scroll_data!='' ){
					var url_attributes = '';
					jQuery.each( jQuery.parseJSON(infinitre_scroll_data), function(key, value){
						if( key == 'cpt' ){
							cpt = value;
						} else if( key == 'style' ){
							style = value;
						} else if( key == 'show' ){
							show = value;
						} else if( key == 'columns' ){
							columns = value;
						} else if( key == 'orderby' ){
							orderby = value;
						} else if( key == 'order' ){
							order = value;
						} else if( key == 'from_category' ){
							from_category = value;
						}
					});
				}

				jQuery.ajax({
					type	: "post",
					url		: dsvy_js_variables.ajaxurl,
					data 	: {
						action			: "dsvy_ajax_pagination",
						cpt				: cpt,
						style			: style,
						show			: show,
						columns			: columns,
						from_category	: from_category,
						orderby			: orderby,
						order			: order,
						pagination		: pagination,
		
						nonce			: dsvy_js_variables.ajaxnonce_ajax_pagination
					},
					success	: function(response){
						jQuery('.dsvy-element-posts-wrapper', main_ele).removeClass('dsvy-ajax-loading');
						jQuery('.dsvy-element-posts-wrapper', main_ele).html(response);
					}
				});
			});
		}); // each
	}
}

// On resize
jQuery(window).resize(function(){
	/* Image size correction */
	dsvy_img_size_correction();

});

// on ready
jQuery(document).ready(function(){
	dsvy_validate();
	dsvy_search_results();
	dsvy_toggleSidebar();
	dsvy_tabs_element();
	dsvy_sorting();
	dsvy_ajax_sorting();
	dsvy_back_to_top();
	dsvy_sticky_header();
	dsvy_navbar();
	dsvy_lightbox();
	dsvy_video_popup();
	dsvy_testimonial();
	dsvy_search_btn();
	dsvy_center_logo_header_class();
	dsvy_selectwrap();
	dsvy_menu_count();
	setTimeout(function(){ dsvy_carousel(); }, 200);
	dsvy_img_size_correction();
	dsvy_number_rotate();
	dsvy_sticky_header_class();
	dsvy_progressbar();
	dsvy_ajax_pagination();
});	

// on load (jQuery 3.0+ compatible)
jQuery(window).on('load', function(){
	dsvy_preloader();
	dsvy_sorting();
	dsvy_gallery();
	dsvy_circle_progressbar();
	dsvy_infinite_scroll();
	setTimeout(function() { dsvy_wc_cart_page_qty_update(); }, 500);
	setTimeout(function(){ dsvy_slider_dot_number(); }, 200);
	
});

