/*
Site : http://themeforest.net/user/kotofey
Author : Constantine
Version: 2.1
*/

(function ($) {

	"use strict";

	var kk_sc_check = true;

	// Adjust Position

	$.fn.kkAdjustImagePositioning = function (callback) {
		$(this).each(function () {
			var this_ = $(this),
			wdt = this_.width(),
			hgt = this_.height();

			this_.find('img, video').css({
				width : '',
				height : ''
			}).each(function () {
				var elem = $(this),
				r_w = hgt / wdt,
				i_w = elem.width(),
				i_h = elem.height(),
				r_i = i_h / i_w,
				new_w,
				new_h,
				new_left,
				new_top;

				if (elem.hasClass('kktfwp-adjust-me')) {
					if (r_w > r_i) {
						new_h = wdt * r_i;
						new_w = wdt;
					} else {
						new_h = hgt;
						new_w = hgt / r_i;
					}
				} else {
					if (r_w > r_i) {
						new_h = hgt;
						new_w = hgt / r_i;
					} else {
						new_h = wdt * r_i;
						new_w = wdt;
					}
				}

				elem.css({
					width : new_w,
					height : new_h,
					left : (wdt - new_w) / 2,
					top : (hgt - new_h) / 2
				});

				if (typeof callback === 'function') {
					callback();
				}
			});
		});
	};

	// Animated Page Change

	if ( kk_js_data.kk_page_anim  == '1' ) {

		var kkPageChange = function() {

			$('.kk-bg').transition({
				left : '100%'
			}, 600, 'cubic-bezier(0.72, 0.03, 0.29, 1.01)', function () {});

			$('.kk-preloader').removeClass('kk-loader-play').addClass('kk-loader-stop');

			var siteUrl = document.location.origin;

			$(document).on( "click", "a[href^='" + siteUrl + "']:not([href*='/wp-admin/']):not([href*='/wp-content/']):not([href*='/wp-login.php']):not([href$='/feed/']):not([href*='/#']):not([href*='/?']):not([target='_blank'])", function (e) {
				
				if (this.parentNode.classList.contains('mtree-node') && this.parentNode.classList.contains('mtree-open')) {
					return;
				}
				
				e.preventDefault();
				var linkLocation = this.href;

				$('.kk-preloader').removeClass('kk-loader-stop').addClass('kk-loader-play');

				$('.kk-bg').css({
					left : 0,
					right : '100%'
				}).transition({
					right : 0
				}, 400, 'cubic-bezier(0.72, 0.03, 0.29, 1.01)', function () {
					window.location = linkLocation;
				});
			});
		};

		kkPageChange();

		$(window).on("pageshow", function (event) {
			if (event.originalEvent.persisted) {
				kkPageChange();
			}
		});

	}

	// Parallax height

	if (typeof kk_title_height !== "undefined") {
		var parallaxHeight = function (el) {
			var height = $(window).height();

			el.css({
				'height' : height + 'px'
			});
		}

		var kk_p_wrapper = $('#kk-parallax-wrapper');

		parallaxHeight(kk_p_wrapper);

		$(window).on( 'resize', function () {
			parallaxHeight(kk_p_wrapper);
		});
	}

	// Parallax ScrollTo

	if ((kk_js_data.kk_menu_type == 'kk-menu-default' || kk_js_data.kk_menu_type == 'kk-menu-default-hidden') && kk_js_data.kk_content_type == 'kk-full') {
		kk_scrollTo($('#kk-parallax-wrapper a[href*="#"]:not([href="#"])'), 40);
	}
	
	// Parallax Video	
	
	$(function () {
		var video = document.getElementById( 'kk-html5-video' );

		if ( video && $('html').hasClass( 'video' )  ) {
			
			var item = document.getElementById( 'kk-parallax-video' ),
				pauseOnScroll = kk_js_data.scrollMonitor,
				elementWatcher = scrollMonitor.create( item );
			
			var pauseVideo = function () {	
				elementWatcher.enterViewport(function() {
					paused();
				});
				elementWatcher.exitViewport(function() {
					paused();
				});				
			}
			
			var paused = function () {
				if ( !video.paused && !elementWatcher.isInViewport ) {
					//pause video
					video.pause();
				} else {
					//play video
					video.play();
				}
			}
						
			var checkLoad = function () {		
				if ( video.readyState == 4 ) {
					$('.kk-parallax-bg').css('opacity', '0');
					$(video).css('opacity', '1');
					if ( pauseOnScroll == 1 ) pauseVideo();
				} else {
					setTimeout(checkLoad, 100);
				}
			}
			checkLoad();	
		} else if ( video && !$('html').hasClass( 'video' )  ) {
			video.remove();
		}
	});
	
	
	// Parallax fadein

	if (typeof kk_title_parallax !== "undefined") {
		$('#kk-img-check').on('load', function () {
			$('#kk-parallax-bg').removeClass('kk-hidden');

			if (typeof kk_title_height !== "undefined") {
				$('#kk-down').removeClass('is-loading').addClass('is-loaded');
			}

		}).each(function () {
			if (this.complete)
				$(this).trigger('load');
		});
	};
	

	//### MENUS ###//

	// Sub-menus

	var kk_submenu = function (el, el2) {
		$(el).on({ 
			mouseenter: function(){
				$(this).find('.sub-menu:first').stop(true, true).transition({
					visibility : 'visible',
					marginLeft : 0 + 'px',
					opacity : 1
				}, 300);
			}, 
			mouseleave: function(){			
				$(this).find('.sub-menu:first').stop(true, true).transition({
					marginLeft : 30 + 'px',
					opacity : 0,
					visibility : 'hidden'
				}, 300);
			}
		});
	};

	// Default menu

	kk_submenu('.kk_menu_default_hidden .main-nav > ul > li, .kk_menu_default .main-nav > ul > li, .kk_menu_default .main-nav .sub-menu li, .kk_menu_default_hidden .main-nav .sub-menu li');

	// Left boxed menu
	kk_submenu('.kk_menu_left_boxed .main-nav > ul > li, .kk_menu_left_boxed .main-nav .sub-menu li');

	// Creative, Fullscreen & Default(hidden) menus

	$('.kk-menu-trigger').on( 'click', function () {

		$('body').toggleClass('kk-menu-open kk-overflow-hidden');

		if ($('.kk_menu_fullscreen').length) {

			$('.menu-wrapper ul.dl-menu').children('li').each(function (i, el) {

				setTimeout(function () {
					$(el).toggleClass('menu-item-in');
				}, 200 + (i * 50));

			});
		}
	});

	if ( $('.dl-menu').length ) {
		$('.main-nav').dlmenu();
	}

	// Change menu style

	var kk_sticky_header = function (el, p) {

		var header = $('.' + el);

		$(window).on('scroll', function () {

			var scroll = $(window).scrollTop();

			if (scroll >= 180) {

				if (kk_sc_check == true) {
					header.removeClass(el).addClass(el + '-fixed');
					$('.content').css({
						paddingTop : header.height() + p + 'px'
					})
					setTimeout(function () {
						$(header).addClass('anim-me');
					}, 100);
				}

				kk_sc_check = false;

			} else {

				if (kk_sc_check == false) {
					header.removeClass(el + '-fixed anim-me').addClass(el);
					$('.content').css({
						paddingTop : p + 'px'
					})
				}

				kk_sc_check = true;
			}
		});
	};

	var kk_sticky_parallax = function (el) {

		var scroll = $(window).scrollTop(),
		height = 80;

		if ($('#kk-parallax-wrapper').length) {
			height = $('#kk-parallax-wrapper').height() - 50;
		};

		if (scroll >= height) {

			if (kk_sc_check == true) {
				$(el).addClass('kk-top-animate');
				$('body').addClass('kk-parallax-animate');
			}

			kk_sc_check = false;

		} else {

			if (kk_sc_check == false) {
				$(el).removeClass('kk-top-animate');
				$('body').removeClass('kk-parallax-animate');
			}

			kk_sc_check = true;
		}
	};

	if (kk_js_data.kk_menu_type == 'kk-menu-fullscreen' & typeof kk_title_parallax !== "undefined") {
		$(window).on('scroll', function () {
			kk_sticky_parallax('.fullscreen-top');
		}).trigger('scroll');

		$(window).on('resize', function () {
			kk_sticky_parallax('.fullscreen-top');
		});

	} else if (kk_js_data.kk_menu_type == 'kk-menu-fullscreen' & typeof kk_title_parallax == "undefined") {
		kk_sticky_header('fullscreen-top', 40);
	};

	if ($('.grid-gal').length) {
		$('body').addClass('kk-grid-active');
	}

	if ($('.type-fullscreen-gallery').length) {
		$('body').addClass('kk-template-fullscreen');
	}

	if (kk_js_data.kk_menu_type == 'kk-menu-slide-right' || kk_js_data.kk_menu_type == 'kk-menu-classic' ) {

		var mainMenu = $('.creative-top-wrapper').length ? $('.creative-top-wrapper') : $('#menu-wrapper'),
		elHeight = mainMenu.innerHeight(),
		elPos = $('#kk-parallax-wrapper'),
		heightCheck = true,
		height = 80;

		$('.logo img').on('load', function () {
			elHeight = mainMenu.innerHeight();
		}).each(function () {
			if (this.complete)
				$(this).trigger('load');
		});

		kk_scrollTo($('#kk-parallax-wrapper a[href*="#"]:not([href="#"])'), elHeight);

		if ($('.is-inner').length) {
			$('.is-inner').css({
				'padding-top' : elHeight + 'px'
			});
		}

		var funcScroll = function (i) {

			var scroll = $(window).scrollTop();

			if (elPos.length & heightCheck == true) {
				height = elPos.height() - 100;
				heightCheck = false;
			}

			if (scroll >= 100) {

				if (kk_sc_check == true) {
					$('.creative-top-wrapper-bg, .kk_menu_classic .menu-wrapper').css({
						'height' : i + 'px'
					}).addClass('kk-top-animate');
					$('body').addClass('kk-parallax-animate');
				}

				kk_sc_check = false;

			} else {
				if (kk_sc_check == false) {
					$('.creative-top-wrapper-bg, .kk_menu_classic .menu-wrapper').css({
						'height' : i + 'px'
					}).removeClass('kk-top-animate');
					$('body').removeClass('kk-parallax-animate');
				}

				kk_sc_check = true;
			}
		}

		$(window).on( 'scroll', function () {
			funcScroll(elHeight);
		}).trigger('scroll');

		$(window).on( 'resize', function () {
			elHeight = $('.creative-top-wrapper').innerHeight();
			$('.creative-top-wrapper-bg').css({
				'height' : elHeight + 'px'
			})
			funcScroll(elHeight);
		});
	}

	if ($('.kk-active-button').length) {
		$('body').addClass('kk-fs-g');
	}

	// Fullscreen searchform

	$('.search-trigger, .kk-search-close').on( 'click', function () {
		$('body').toggleClass('kk-search-open kk-overflow-hidden');
	});

	// Gallery info

	if ($('.kk-info-trigger').length) {
		$('.kk-info-trigger, .kk-info-close').on( 'click', function () {
			$('body').toggleClass('kk-info-open kk-overflow-hidden');
		});
	}

	// Fullscreen Gallery Thumbnails

	if ($('.kk-thumbs-trigger').length) {
		$('body').on( 'click', '.kk-thumbs-trigger', function (e) {
			$(e.delegateTarget).toggleClass('kk-thumbs-on');
			$(this).toggleClass('activeThumb');
		});
	}

	// Gallery & Portfolio Filter

	if ($().mixItUp) {
		$('.isotope-container').mixItUp({
			selectors : {
				target : '.isotope-item'
			},
			animation : {
				duration : 600,
				effects : 'fade scale'
			},
			callbacks : {
				onMixLoad : function (state) {
				}
			}
		});
	}

	$('#filter ul li').on( 'click', function () {
		var $new_text = $(this).text();
		$('#filter-trigger').find('span').text($new_text);
		
		if (Modernizr.touchevents) { 
			$('#filter ul').slideUp(250);
		}

		return false;
	});	
	
	if ( ! Modernizr.touchevents) { 
		$('#filter-trigger').on( 'click', function(e) {
				e.preventDefault();
		});
		$('#filter').on({ 
			mouseenter: function(){
				$(this).find('ul').stop(true, true).slideDown(250);
			}, 
			mouseleave: function(){			
				$(this).find('ul').stop(true, true).slideUp(250);
			}
		});
	} else {
		$('#filter-trigger').on( 'click', function(e) {
			e.preventDefault();
			$(this).parent().find('ul').stop(true, true).slideDown(250);			
		});		
	}

	//Masonry

	if ($().masonry) {
		if ($('.gallery-wrapper').length) {

			var container = $('.isotope-container');
			container.imagesLoaded( function () {
				container.masonry({
					itemSelector : '.masonry',
					isAnimated : false,
					transitionDuration: 0,
					columnWidth : '.masonry',
					percentPosition : true,
					gutter : '.gutter-size'
				});
			});
		}

		if ($('.gallery-full-masonry').length) {
			var $grid = $('.masonry-container').masonry({
					itemSelector : '.masonry-box',
					percentPosition : true,
					isAnimated : false,
					transitionDuration: 0,
					columnWidth : '.masonry-box'
				});
			
			$grid.masonry();
		}
	}

	// Effect FadeIn

	function kk_fade_in(targetClass, startTime, nextTime) {

		if ($(targetClass).length > 0) {

			var time = startTime;

			$(targetClass).each(function () {
				var article = $(this);
				setTimeout(function () {
					article.css({
						'visibility' : 'visible'
					}).addClass('kk_fadeIn');
				}, time);
				time = time + nextTime;
			});
		}
	}

	// Mobile menu

	$('ul.kktfwp-mtree').mtree({
		collapsed: true, // Start with collapsed menu (only level 1 items visible)
		close_same_level: true, // Close elements on same level when opening new node.
		duration: 600, // Animation duration should be tweaked according to easing.
		listAnim: true, // Animate separate list items on open/close element (velocity.js only).
		easing: 'easeOutQuart', // Velocity.js only, defaults to 'swing' with jquery animation.
	});
	
	$('body').on( 'click touch', '.kktfwp-mobile-burger', function () {
		$('body').toggleClass('menu-is-opened');
	});

	// Tipsy

	$('.social a, .flickr_badge_image a img').tipsy({
		gravity : 's',
		fade : true
	});

	// Blog & Portfolio slider

	if ($().royalSlider) {
		$('div.royalSlider[id^="kk_post_slider"]').royalSlider({
			// options go here
			slidesSpacing : 0,
			imageScaleMode : 'none',
			autoScaleSlider : false,
			autoHeight : true,
			imageAlignCenter : false,
			numImagesToPreload : 1,
			usePreloader : true,
			fadeinLoadedSlide : false,
			controlNavigation : 'none',
			arrowsNav : true,
			arrowsNavAutoHide : false,
			arrowsNavHideOnTouch : true,
			globalCaption : true,
			autoPlay: {
				enabled: ( typeof kk_postSlider !== "undefined" && kk_postSlider.state == 'yes' ) ? true : false,
				pauseOnHover: true,
				stopAtAction: true,
				delay: ( typeof kk_postSlider !== "undefined" && kk_postSlider.delay >= 1 ) ? kk_postSlider.delay : 3000,
			}
		});
	}

	// Background video

	if (typeof kk_js_video !== 'undefined') {		
		var muted = true;
		
		if ( kk_js_video.muted === '0' ) {
			muted = false;
		}

		if (typeof kk_js_video.helper == 'undefined') {
			
			// Local video
			
			fallbackVideoImage(kk_js_video);

			var kkHTML5Video = '<div class="kk-preloader kk-loader-play kk-video-preloader"></div><video class="kk-html5-bg" playsinline loop ' + ( ( muted ) ? 'muted' : '') + '><source src="' + kk_js_video.video_source + '" type="video/mp4" >Your browser does not support the video tag.</video>';
			
			var bgPlayer = $('.video-bg #player');

			bgPlayer.append(kkHTML5Video);

			var video = document.querySelector('.kk-html5-bg');
			var promise = video.play();
			
			if (promise !== undefined) {
			  promise.then(_ => {				  
			  }).catch(error => {
				video.muted = true;
				video.play();
			  });
			}
			
			video.addEventListener('playing', function() {
				var this_ = $(this);
				bgPlayer.kkAdjustImagePositioning(function () {
					this_.css({
						opacity : 1
					});					
				});
			});
			
			$('.kk-video-preloader').remove();
			
			$(window).on('resize', function () {
				$('.video-bg').kkAdjustImagePositioning(function () {});
			});

		} else {
			
			// Youtube video
			$('.video-bg > #player').remove();
			fallbackVideoImage(kk_js_video);
			
			$('.video-bg').kkBgVideo({
				videoId : kk_js_video.video_source,
				mute : muted,
				repeat : true
			});
		}
	}
	
	// Fallback video image
	
	function fallbackVideoImage(videoData) {
		if (!videoData.fallback_img) {
			return;
		}
		
		var html = 'style = "background-image: url(' + videoData.fallback_img + '); background-attachment: fixed; background-size: cover; background-origin: border-box; background-clip: border-box; background-position: 50% 50%; background-repeat: no-repeat;"';

		$('body > .video-bg').prepend('<div class="kk-fallback-img" ' + html + '></div>');
	}

	// Slides

	function kk_slides() {

		var slides = '';

		if (typeof kk_js_gallery !== "undefined") {
			var name = kk_js_gallery;
		} else if (typeof kk_js_fs_slideshow !== "undefined") {
			var name = kk_js_fs_slideshow;
		}

		if (typeof kk_js_fs_slideshow !== "undefined") {
			if (typeof kk_js_fs_slideshow.ifDefault !== "undefined") {
				$.each(name.slides, function () {
					slides += '<a class="rsImg" href="' + this.image + '" title="' + this.title + '" /></a>'
				})
			} else {
				$.each(name.slides, function () {
					slides += '<a class="rsImg" href="' + this.full_url + '" title="' + this.title + '" /></a>'
				})
			}
		} else {
			$.each(name.slides, function () {
				
				if ( this.caption !== '' ) {
					var _thisCaption = '<figure class="rsCaption">'+ this.caption +'</figure>';
					slides += '<div class="rsContent" ><a class="rsImg" href="' + this.full_url + '" ><img src="' + this.url + '" class="rsTmb" /></a>'+ _thisCaption + '</div>';
				} else {
					slides += '<div class="rsContent" ><a class="rsImg" href="' + this.full_url + '" ><img src="' + this.url + '" class="rsTmb" /></a></div>';
				}
			})
		}

		return slides;
	};

	function kk_slides_kb() {

		var slides = [];

		if (typeof kk_js_fsk_slideshow.ifDefault !== "undefined") {
			$.each(kk_js_fsk_slideshow.slides, function () {
				slides.push(this.image);
			})
		} else {
			$.each(kk_js_fsk_slideshow.slides, function () {
				slides.push(this.full_url);
			})
		}

		return slides
	};

	// Fullsceen gallery

	if (typeof kk_js_gallery !== "undefined") {

		var kkImagesToPreload = 1,
		kkfaidSlide = 1,
		kkVisibleNearBy = 0,
		kkeaseInOut = 'easeInOutSine',
		kkeaseOut = 'easeOutSine';

		if (kk_js_gallery.visibleNearBy === '1' & kk_js_gallery.galleryScale === 'fit') {
			kkImagesToPreload = 2;
			kkfaidSlide = 0;
			kkVisibleNearBy = 1;
			kkeaseInOut = 'easeInOutCubic';
			kkeaseOut = 'easeInOutCubic';
		};

		if (kk_js_gallery.visibleNearBy === '1' || kk_js_gallery.galleryScale === 'fit') {
			$(' body ').addClass('kk-darkbg');
		}

		var gal_slider = $('.royalSlider_fullscreen').royalSlider({
				// options go here
				slidesSpacing : 0,
				imageScaleMode : kk_js_gallery.galleryScale,
				numImagesToPreload : kkImagesToPreload,
				easeInOut : kkeaseInOut,
				easeOut : kkeaseOut,
				globalCaption:true,
				addActiveClass : true,
				fadeinLoadedSlide : kkfaidSlide,
				usePreloader : true,
				imageScalePadding : 10,
				controlNavigation : 'thumbnails',
				arrowsNav : false,
				thumbs : {
					fitInViewport : false
				},
				visibleNearby : {
					enabled : kkVisibleNearBy,
					centerArea : 0.6,
					navigateByCenterClick : true
				},
				loop : parseInt(kk_js_gallery.galleryLoop, 10),
				transitionSpeed : parseInt(kk_js_gallery.transitionSpeed, 10),
				transitionType : kk_js_gallery.transitionType,
				autoPlay : {
					// autoplay options go gere
					enabled : parseInt(kk_js_gallery.autoplay.enabled, 10),
					pauseOnHover : false,
					delay : parseInt(kk_js_gallery.autoplay.delay, 10)
				},
				slides : kk_slides()
			});

		if (kk_js_gallery.visibleNearBy === '1' & kk_js_gallery.galleryScale === 'fit') {
			$.rsCSS3Easing.easeInOutCubic = 'cubic-bezier(0.645, 0.045, 0.355, 1)';
		};
		var slideCountEl = $('<div class="rsSlideCount"></div>').appendTo(gal_slider);
		var sliderInstance = gal_slider.data('royalSlider');

		var kkCount = function updCount() {
			slideCountEl.html('<span class="rsSlideCur">' + (sliderInstance.currSlideId + 1) + '</span><span class="rsSlideSep">/</span>' + '<span class="rsSlideAll">' + sliderInstance.numSlides + '</span><span class="rsCountInfo">'+ kk_js_gallery.galText +'</span>');
		}

		sliderInstance.ev.on('rsAfterSlideChange', kkCount);
		kkCount();

		if (kk_js_gallery.menuStyle == 'kk-menu-slide-right' || kk_js_gallery.menuStyle == 'kk-menu-fullscreen') {

			sliderInstance.slides[0].holder.on('rsAfterContentSet', function () {
				// fires when every time when slide content is loaded and added to DOM
				kk_BgCheck('.logo a, .some-buttons');
			});

			sliderInstance.ev.on('rsAfterSlideChange', function (event) {
				// triggers after slide change
				kk_BgCheck('.logo a, .some-buttons');

			});
		}

		$('.kk-info-trigger, .kk-info-close, .search-trigger, .kk-search-close, .kk_menu_fullscreen .kk-menu-trigger, .kk_menu_slide_right .kk-menu-trigger').on( 'click', function () {
			sliderInstance.toggleAutoPlay();
		});

		if ( $('.no-touchevents').length && $('.rsSlideCount').length) {

			var $mouseX = 200,
			$mouseY = 200;
			var $xp = 0,
			$yp = 0;
			var $elOffset = 0;

			$(document).mousemove(function (e) {
				$elOffset = $('.royalSlider_fullscreen').offset();
				$mouseX = e.pageX + 12 - $elOffset.left;
				$mouseY = e.pageY + 17 - $elOffset.top;
			});

			var $loop = setInterval(function () {
					// change 12 to alter damping higher is slower
					$xp += (($mouseX - $xp) / 40);
					$yp += (($mouseY - $yp) / 40);
					$('.rsSlideCount').css({
						translate : [$xp, $yp]
					});
				}, 0);
		}
	};

	// Fullsceen Background slideshow - Royal Slider

	if (typeof kk_js_fs_slideshow !== "undefined") {

		var fs_slider = $(".royalSlider_fullscreen").royalSlider({
				// options go here
				slidesSpacing : 0,
				imageScaleMode : 'fill',
				numImagesToPreload : 1,
				usePreloader : true,
				controlNavigation : 'none',
				arrowsNav : false,
				fadeinLoadedSlide : true,
				loop : true,
				randomizeSlides : !!+kk_js_fs_slideshow.randomizeSlides,
				transitionSpeed : parseInt(kk_js_fs_slideshow.transitionSpeed, 10),
				transitionType : kk_js_fs_slideshow.transitionType,
				autoPlay : {
					// autoplay options go gere
					enabled : true,
					pauseOnHover : false,
					stopAtAction : false,
					delay : parseInt(kk_js_fs_slideshow.autoplay.delay, 10)
				},
				slides : kk_slides()
			});

		if (kk_js_fs_slideshow.menuStyle == 'kk-menu-slide-right' || kk_js_fs_slideshow.menuStyle == 'kk-menu-fullscreen') {
			var sliderInstance = fs_slider.data('royalSlider');

			if ($('.page-template-template-homepage-slider .logo a, .page-template-template-homepage-slider .kk-menu-trigger').length) {
				sliderInstance.slides[0].holder.on('rsAfterContentSet', function () {
					// fires when every time when slide content is loaded and added to DOM
					kk_BgCheck('.page-template-template-homepage-slider .logo a, .page-template-template-homepage-slider .some-buttons');

				});

				sliderInstance.ev.on('rsAfterSlideChange', function (event) {
					// triggers after slide change
					kk_BgCheck('.page-template-template-homepage-slider .logo a, .page-template-template-homepage-slider .some-buttons');

				});
			}
		}
	};
	
	// Touch support for lighbox
	if ($().magnificPopup) {
		(function() {
		  var magnificPopup = $.magnificPopup.instance;

		  $( '.kk-lightbox' ).on( 'click', function(e) {
			setTimeout(function() {
				$(".mfp-wrap").swipe( {
					swipeLeft:function(event, direction, distance, duration, fingerCount) {
					magnificPopup.next();
					},
					swipeRight:function(event, direction, distance, duration, fingerCount) {
					  magnificPopup.prev();
					},					
					swipeUp:function(event, direction, distance, duration, fingerCount) {
					  magnificPopup.close();
					},					
					swipeDown:function(event, direction, distance, duration, fingerCount) {
					  magnificPopup.close();
					},
				});
			}, 500);
		  });

		}).call(this);
	}
	
	// 404 error
	
	if ( $('body.error404').length & typeof kk_js_data.errorImg !== "undefined" ) {
		$( '<img/>' ).attr( 'src', kk_js_data.errorImg ).on('load', function() {
			$(this).remove();
			$('body.error404 .bg404').css({
				backgroundImage: 'url('+kk_js_data.errorImg+')',
				opacity : 1
			});
		});
	}
	
	// Password
	
	if ( $('body.password-protected').length & typeof kk_js_passImg !== "undefined" ) {
		$( '<img/>' ).attr( 'src', kk_js_passImg.img_url ).on('load', function() {
			$(this).remove();
			$('body.password-protected .bg404').css({
				backgroundImage: 'url('+kk_js_passImg.img_url+')',
				opacity : 1
			});
		});
	}
	
	// Photo proofing
	
	if ( $('.kk-photo-proofing').length ) {
		$('span.proof-btn').on( 'click', function(e) {
			e.preventDefault();
			var _this = $(this);

			if (_this.data('requestSend')) {
				return;
			}
			_this.data('requestSend', true);

			var image_id = _this.data('photo-id');

			$.ajax({
				url: kk_js_data.ajax_url,
				type: 'post',
				beforeSend: function () {
					_this.addClass('in-process');
				},
				data: {
					action: 'kktfwp_proofing',
					image_id: image_id,
					_wpnonce: kk_js_data.proofing_nonce,
				},
				success: function (response) {
					if ( response.data == 'unchecked' ) {
						_this.data('requestSend', false).removeClass('in-process').parent('.photo-details').removeClass('photo-approved');
					} else {
						_this.data('requestSend', false).removeClass('in-process').parent('.photo-details').addClass('photo-approved');
					}
				},
				error: function (response) {
					_this.data('requestSend', true).removeClass('in-process').parent('.photo-details').addClass('photo-approved');
				}
			});
		});
	}
	
	
	// Background check

	function kk_BgCheck(el) {
		BackgroundCheck.init({
			targets : el,
			images : '.rsImg',
			threshold : 80
		});
		BackgroundCheck.refresh();
	};
	
	
	// ScrollTo

	function kk_scrollTo(el, i) {
		var target,
		scroll;

		$(el).on('click', function (e) {			
			e.preventDefault();
			
			if (location.pathname.replace(/^\//, '') == this.pathname.replace(/^\//, '') && location.hostname == this.hostname) {
				target = $(this.hash);
				target = target.length ? target : $("[id=" + this.hash.slice(1) + "]");

				if (target.length) {
					var avail = $(document).height() - $(window).height();
					scroll = target.offset().top;

					if (scroll > avail) {
						scroll = avail;
					}

					$("body, html").animate({
						scrollTop : scroll - i - i / 2.8
					}, 600);

					return false;
				}
			}
		});
	};

	// Fullsceen Background slideshow - KenB

	if (typeof kk_js_fsk_slideshow !== "undefined") {

		var kenres = (function () {

			$('#kenburns').kenburns({
				//Functionality

				images : kk_slides_kb(),
				frames_per_second : parseInt(kk_js_fsk_slideshow.fps, 10),
				display_time : parseInt(kk_js_fsk_slideshow.delay, 10),
				fade_time : parseInt(kk_js_fsk_slideshow.transitionSpeed, 10),
				zoom : parseFloat(kk_js_fsk_slideshow.zoom),
				background_color : '#ffffff',
				post_render_callback : function ($canvas, context) {
					// Called after the effect is rendered
					// Draw anything you like on to of the canvas

					context.save();
					context.fillStyle = '#000';
					context.font = 'bold 20px sans-serif';

					var width = $(window).width();
					var height = $(window).height();

					var text = "";
					var metric = context.measureText(text);

					context.fillStyle = '#fff';

					context.shadowOffsetX = 3;
					context.shadowOffsetY = 3;
					context.shadowBlur = 4;
					context.shadowColor = 'rgba(0, 0, 0, 0.8)';

					//context.fillText(text, width - metric.width - 8, height - 8);

					context.restore();
				}
			});
		});

		$('body').append('<canvas id="kenburns"><p>Your browser doesn"t support canvas!</p></canvas>');
		$('#kenburns').attr('width', $(window).width() + 'px');
		$('#kenburns').attr('height', $(window).height() + 'px');
		kenres();
		
		$(window).on( 'resize', function () {			
			if ( $(window).width() <= 767 ) return;

			$('#kenburns').remove();
			$('body').append('<canvas id="kenburns"><p>Your browser doesn"t support canvas!</p></canvas>');

			$('#kenburns').attr('width', $(window).width());
			$('#kenburns').attr('height', $(window).height());
			kenres();
		});
	}	

	// Flickr new window

	$('.flickr_badge_image a').each(function () {
		$(this).attr('target', '_blank');
	});
	
	
	// Lightbox

	kk_lightbox();


	// No Right Click
	
	function showLockMessage() {
		$( '.lock-wrapper' ).fadeIn( 'normal' , function() {
			$( 'body' ).addClass( 'lock-message-displayed' );
		});
		$( '.lock-wrapper' ).on( 'click' , function() {
			$( 'body' ).removeClass( 'lock-message-displayed' );
			$( this ).fadeOut( 'normal');
		});
	}

	if ( kk_js_data.kk_right_click.kk_click_check ) {
		$( window ).on( 'contextmenu', function (e) {
			e.preventDefault();			
			showLockMessage()
			return false;
		});
	}

	// Homepage body extra class

	if ($('.kk-is-homecaption').length) {
		$('body').addClass('kk-is-active-homecaption');
	}
	
	
	// Init lazyload
	window.lazySizesConfig = window.lazySizesConfig || {};
	lazySizesConfig.lazyClass = 'responsively-lazy-img';
	lazySizesConfig.loadedClass = 'responsively-loaded';
	lazySizesConfig.expand = 900;
	lazySizesConfig.loadMode = 2;	

	$(document).on('lazybeforeunveil', function(e){
		//use width of parent node instead of the image width itself
		e.detail.width = $(e.target).parent().innerWidth() || e.detail.width;
	}).on('lazyloaded', function(e){
		$(e.target).parent().toggleClass( 'img-loading img-loaded')
		.closest('div')
		.addClass('kk_fadeIn effect-zoom')
		.one( 'animationend webkitAnimationEnd', function() { 
				$(this).removeClass( 'kk_fadeIn' );
			} 
		);	
	});
})(jQuery);

if (!window.requestAnimationFrame) {
	window.requestAnimationFrame = (function () {		
		return window.webkitRequestAnimationFrame ||
		window.mozRequestAnimationFrame ||
		window.oRequestAnimationFrame ||
		window.msRequestAnimationFrame ||
		function (/* function FrameRequestCallback */ callback, /* DOMElement Element */ element) {
			window.setTimeout(callback, 1000 / 60);
		};
	})();
}


// Lightbox

function kk_lightbox() {
	var groups = {},
		$ = jQuery;	

	$('.kk-lightbox').each(function (i, el) {
		if ( $(el).is('a') ) {		
			var id = parseInt($(this).attr('data-group'), 10);

			if (!groups[id]) {
				groups[id] = [];
			}

			groups[id].push(this);
		} else if ( $(el).has('a')	) {		
			
			var id = i;	
			
			$(this).find('a').each( function(i, el) {
				if (!groups[id]) {
					groups[id] = [];
				}
				groups[id].push(this);
			})
		}
	});

	$('.prettyphoto').each(function (e) {		
		var id = $(this).attr('data-rel');

		if (!groups[id]) {
			groups[id] = [];
		}

		groups[id].push(this);
	});

	$.each(groups, function () {		
		$(this).magnificPopup({
			type : 'image',
			preloader : true,
			closeOnContentClick : true,
			closeBtnInside : false,
			//overflowY: 'scroll',
			mainClass : 'mfp-fade',
			removalDelay : 500,
			fixedContentPos : true,
			image : {
				titleSrc : 'data-title',
			},
			gallery : {
				enabled : true,
				tCounter : '%curr% / %total%',
				arrowMarkup : '<button title="%title%" type="button" class="mfp-custom-arrow kk-icon-%dir%-open-big"></button>', // markup of an arrow button
			},
			callbacks : {
				change : function () {
					if (this.isOpen) {			
						if ( this.direction ) {
							this.wrap.removeClass('mfp-open-bd').addClass('mfp-open');					
						} else {							
							this.wrap.removeClass('mfp-open').addClass('mfp-open-bd');								
						}
					}
				},
				beforeOpen : function () {
					$('.mfp-bg').addClass('mfp-kk-open');
				},
				beforeClose : function () {
					// Callback available since v0.9.0
					$('.mfp-bg').removeClass('mfp-kk-open').addClass('mfp-kk-close');
				},
			},
		});
	});	
};

function vc_prettyPhoto() {
	kk_lightbox();
};