"use strict";

jQuery(function($) {
	/*-----------------------------------------------------------------------------------*/
	/*	00. HELPER FUNCTIONS
	/*-----------------------------------------------------------------------------------*/

	$.fn.hasAttr = function(name) {  
	   return this.attr(name) !== undefined;
	};

	function spacingTitle() {
		if( $('.site').width() > 763 ) {
			$('.spacing-title').each(function(index, el) {
				$(el).css('padding-top', $(el).parents('.panel-grid-cell').siblings(':first').find('.title').outerHeight(true) + 'px');
			});
		} else {
			$('.spacing-title').css('padding-top', '0px');
		}
	}

	spacingTitle();

	$( window ).resize(function() {
		spacingTitle();
	});

	function unLoadSite(time) {
		$('body').removeClass('site-loaded');
		$('.preloader').fadeIn(time);
	}

	function loadSite(time) {
		if( time == "" ) {
			time = 800;
		}
		
		$('body').addClass('site-loaded');
		$('.preloader').fadeOut(time);
	}

	function changeLogo(logo, logoURL, logoLightURL) {
		if( $('body').hasClass('nav-sticky-style-2') ||
			$('body').hasClass('nav-open') ||
			$('body').hasClass('background--dark') &&
			! $('body').hasClass('nav-scroll-active') &&
			!$('body').hasClass('nav-side') ) {
			if( $('body').hasClass('nav-default-style-2') && $('body').hasClass('nav-open') ) {
				logo.attr('src', logoURL);
			} else {
				logo.attr('src', logoLightURL);
			}
		} else {
			logo.attr('src', logoURL);
		}
	}

	/* Fix masonry image */

	var masonryFix = $('.blog-masonry .blog-post-image');

	if( masonryFix.length ) {
		masonryFix.imagesLoaded( function() {
			masonryFix.each(function(index) {
				var el = masonryFix.eq(index);
				var width = -el.find('img').width() + el.width();
				if( width < 0 ) {
					el.find('img').css('left', width/2);
				}
			});
		});
	}

	$('.map').each(function(index, el) {
		/*var el = $(el).eq(index);
		map(el.attr('id'), el.attr('location'), el.attr('zoom'));
		console.log($(el).eq(index).attr('data-location'));*/
	});

	/*-----------------------------------------------------------------------------------*/
	/*	01. PARALLAX
	/*-----------------------------------------------------------------------------------*/

	$('.parallax').each(function(index, el) {
		$(el).imagesLoaded( function() { $(el).parallax("50%", 0.6); });
	});

	/*-----------------------------------------------------------------------------------*/
	/*	02. HEADER NAVIGATION
	/*-----------------------------------------------------------------------------------*/

	// Open/Close navigation

	var logo = "";
	var logoURL = "";
	var logoLightURL = "";

	if( $('.site-logo').attr('data-light') ) {
		logo = $('.site-logo').find('img');
		logoURL = $('.site-logo').find('img').attr('src');
		logoLightURL = $('.site-logo').attr('data-light');

		changeLogo(logo, logoURL, logoLightURL);
	}

	if( ! $('.nav-scroll-disabled').length && ( $('.page-cover').length || $('.portfolio-header-cover').length || $('.rev_slider').length ) ) {
		$('body').addClass('nav-scroll');
		$('body').removeClass('page-spacing page-spacing-off');
	}

	if( $('.portfolio-post-header').length ) {
		$('body').removeClass('page-spacing page-spacing-off');
	}

	if( $('.portfolio-header-cover').length ) {
		$('body').addClass('background--dark');
	}

	$('.nav-toggle').on('click', function() {
		$('body').toggleClass('nav-open');

		if( $('.site-logo').attr('data-light') ) {
			changeLogo(logo, logoURL, logoLightURL);
		}
	});

	// Close navigation on clicking on a menu link

	$('.nav-menu a').on('click', function() {
		if ( $('.nav-toggle').is(":visible") ) {
			$('.nav-toggle').click();
		}
	});

	// Scrolling menu change

	function stickyScroll() {
		if ($(window).scrollTop() >= 80) {
			$('body').addClass('nav-scroll-active');
		} else {
			$('body').removeClass('nav-scroll-active');
		}

		if( $('.site-logo').attr('data-light') ) {
			changeLogo(logo, logoURL, logoLightURL);
		}
	}

	stickyScroll();

	if( $('.nav-sticky').length ) {
		$(window).scroll(function() {
			stickyScroll();
		});
	}

	// Add scroll animation on anchor links

	$('a[href*=#]:not([href=#]):not([data-toggle])').click(function() {
	  if (location.pathname.replace(/^\//,'') === this.pathname.replace(/^\//,'') 
	      || location.hostname === this.hostname) {

	  	var href = $.attr(this, 'href');
	  	var fullURL = href.split('#');

	  	if( fullURL[0] != '' ) {
	  		if( $(this).parent().hasClass('current-menu-item') ) {
	  			href = fullURL[1];
	  		} else {
	  			return true;
	  		}
	  	}

	    var target = $(this.hash);
	    var mobile = 0;

	    if( $(window).width() < 992 ) {
	    	mobile = -75;
	    }

	    var targetOffset = 0;

	    if (target.length) {
	    	targetOffset = target.offset().top;
	    }

		$('html,body').animate({
			scrollTop: targetOffset + mobile
		}, 1000, function () {
			window.location.hash = href;
		});

		if( $('.site-logo').attr('data-light') ) {
			changeLogo(logo, logoURL, logoLightURL);
		}

	    return false;
	  }
	});

	/*-----------------------------------------------------------------------------------*/
	/*	03. PORTFOLIO
	/*-----------------------------------------------------------------------------------*/

	if( $('.portfolio').length ) {
		var layoutMode = 'masonry';
		var currentCategory = '*';

		if( $('.portfolio-4-columns').length ) {
			layoutMode = 'fitRows';
		}
		var $portfolio = $('.portfolio').imagesLoaded( function() {
			$portfolio.isotope({
				itemSelector: '.portfolio-item',
				layoutMode: layoutMode
			}).isotope('layout');
		});
		var all = $portfolio.attr('data-all');

		$('.filter').on( 'click', 'button', function() {
			var filterValue = $(this).attr('data-filter');
			currentCategory = filterValue;
			$portfolio.isotope({ filter: filterValue });

			$('.filter .selected').removeClass('selected');
			$(this).addClass('selected');

			moreButtonStatus(filterValue);
		});

		var portfolioPosts = {
			perPage   : $portfolio.attr('data-per-page'),
			categories: $portfolio.attr('data-categories'),
			type      : $portfolio.attr('data-type'),
			order     : $portfolio.attr('data-order'),
			orderby   : $portfolio.attr('data-orderby'),
		};

		/* Load More Portfolio Posts */

		$('.portfolio-more > button').on('click', function() {
			$('.portfolio-more > button').attr('disabled', true);

			var categories = portfolioPosts.categories;
			var exclude = '';
			var excludeEl = '.portfolio-item';

			if( currentCategory != '*' ) {
				categories = currentCategory;
				excludeEl += currentCategory;
			}

			$(excludeEl).each(function() {
				if( exclude !== '' ) {
					exclude += ',';
				} 
			    exclude += $(this).attr("data-id");
			});

			$.ajax({
				url: ajaxpagination.ajaxurl,
				type: 'post',
				data: {
					action: 'portfolio_more',
					per_page: portfolioPosts.perPage,
					type: portfolioPosts.type,
					categories: categories,
					order: portfolioPosts.order,
					orderby: portfolioPosts.orderby,
					exclude: exclude
				},
				success: function( result ) {
					var posts = result.split('</article>');
					var els = $(posts[0] + '</article>');

					for(var i=1; i<posts.length; i++) {
						els = els.add($(posts[i] + '</article>'));
					}

					$portfolio.isotope( 'insert', els );

					$portfolio.imagesLoaded( function() {
						$portfolio.isotope('layout');
					});

					moreButtonStatus($('.filter .selected').attr('data-filter'));

					$('.portfolio-more > button').blur();

					$('.portfolio-ajax a').on('click', function(e) {
						portfolioAJAXitem(e, $(this));

						e.preventDefault(); 
						return false;
					});
				}
			});
		}); 
	}

	function moreButtonStatus(filterValue) {
		if( filterValue != '*' ) {
			var category = filterValue.substring(1);

			if( $portfolio.find('.' + category).length < $portfolio.attr('data-' + category) ) {
				$('.portfolio-more > button').attr('disabled', false);
				return false;
			}
		} else {
			if( $portfolio.find('.portfolio-item').length < $portfolio.attr('data-all') ) {
				$('.portfolio-more > button').attr('disabled', false);
				return false;
			}
		}

		$('.portfolio-more > button').attr('disabled', true);
		return true;
	}

	function portfolioAJAXitem(e, org) {
		if( !org.hasClass('porftolio-post-close') ) {
			unLoadSite(100);
		}
		
		$.ajax({
			url: ajaxpagination.ajaxurl,
			type: 'post',
			data: {
				action: 'portfolio_single',
				id: org.parent().attr('data-id'),
			},
		  	success: function(html) {				  	
			    $('body').append('<div class="portfolio-content">' + html + '</div>');

				$('.porftolio-post-close').on('click', function() {
					$('body').removeClass('portfolio-ajax-active');
				});

				$('.porftolio-post-prev, .portfolio-nav .prev').on('click', function() {
					org.parent().prev().find('a').click();
				});

				$('.porftolio-post-next, .portfolio-nav .next').on('click', function() {
					org.parent().next().find('a').click();
				});

			    $('portfolio-content').imagesLoaded(function() {
					$('body').addClass('portfolio-ajax-active');
					
					loadSite(500);
			    });

			    // This will handle stretching the cells.
			    $('.portfolio-content .siteorigin-panels-stretch.panel-row-style').each(function(){
			        var $$ = $(this);

			        var onResize = function(){

			            $$.css({
			                'margin-left' : 0,
			                'margin-right' : 0,
			                'padding-left' : 0,
			                'padding-right' : 0
			            });

			            var leftSpace = $$.offset().left;
			            var rightSpace = $(window).outerWidth() - $$.offset().left - $$.parent().outerWidth();

			            $$.css({
			                'margin-left' : -leftSpace,
			                'margin-right' : -rightSpace,
			                'padding-left' : $$.data('stretch-type') === 'full' ? leftSpace : 0,
			                'padding-right' : $$.data('stretch-type') === 'full' ? rightSpace : 0
			            });

			            var cells = $$.find('> .panel-grid-cell');

			            if( $$.data('stretch-type') === 'full-stretched' && cells.length === 1 ) {
			                cells.css({
			                    'padding-left' : 0,
			                    'padding-right' : 0
			                });
			            }
			        };

			        $(window).resize( onResize );
			        onResize();

			        $$.css({
			            'border-left' : 0,
			            'border-right' : 0
			        });
			    });
			}
		});
	}

	if( $('.portfolio-ajax').length ) {
		$('.portfolio-ajax a').on('click', function(e) {
			portfolioAJAXitem(e, $(this));

			e.preventDefault(); 
			return false;
		});
	}

	/*-----------------------------------------------------------------------------------*/
	/*	04. VIDEOS (for background video, either from YouTube or using the video element)
	/*-----------------------------------------------------------------------------------*/

	$(".player").mb_YTPlayer();

	$('.statement.video').each(function() {
		if( $(this).attr('data-background-video-external') ) {
			$(this).append('<video src="' + $(this).attr('data-background-video-external') + '" autoplay loop muted></video>');
		} else if ( $(this).attr('data-background-video') ) {
			$(this).append('<video src="' + $(this).attr('data-background-video') + '" autoplay loop muted></video>');
		}
	});

	$(".video video").prop("volume", 0);

	/*-----------------------------------------------------------------------------------*/
	/*	05. SLICK CAROUSEL (testimonials, projects)
	/*-----------------------------------------------------------------------------------*/

/*	if( $('.projects').length || $('.testimonials').length ) {
		$('.testimonials').slick({
			dots: true,
			fade: true,
			arrows: false,
			autoplay: true,
			autoplaySpeed: 5000
		});
		$('.projects').slick();
	}*/

	/*-----------------------------------------------------------------------------------*/
	/*	06. INSTAGRAM
	/*-----------------------------------------------------------------------------------*/

	$('.instagram').on('didLoadInstagram', function(event, response) {
		var instagram = {};
		var $url = 'https://api.instagram.com/v1/users/' + response.data[0].id.split('_')[1] + '/?access_token=2346574156.71ed503.20f8b92a2d31453a97db5384e33ce3f9';

		$.ajax({
			method : "GET",
			url : $url,
			dataType : "jsonp",
			jsonp : "callback",
			success : function(dataSuccess) {
				instagram.authorPhoto = dataSuccess.data.profile_picture;
				instagram.followers = dataSuccess.data.counts.followed_by;
				instagram.photos = dataSuccess.data.counts.media;
				instagram.username = dataSuccess.data.username;
				instagram.full_name = dataSuccess.data.full_name;

				var data = response.data;
				var tagNames = [];
				var tagNums = [];
				var tags = [];
				instagram.target = event.currentTarget.id;
				instagram.likes = 0;

				for(var i=0; i<data.length; i++) {
					instagram.likes += data[i].likes.count;

					/* Get tag names and how many are there */
					for(var j=0; j<data[i].tags.length; j++) {
						if(tagNames.indexOf(data[i].tags[j]) === -1) {
							tagNames.push(data[i].tags[j]);
							tagNums.push(1);
						} else {
							tagNums[tagNames.indexOf(data[i].tags[j])]++;
						}
					}
				};

				/* Sort tags array */
				for (var i = 0; i < tagNames.length; i++) { tags.push({ 'name': tagNames[i], 'value': tagNums[i] }); }
				tags.sort(function(a, b) { return b.value - a.value; });

				/* Add instagram photos */

				for(var i=0; i<12; i++) {
					if( data[i] ) {
						$("#" + instagram.target + ' .instagram-images').append('<li style="background-image: url(' + data[i].images.low_resolution.url + ')"></li>');
					} else {
						break;
					}
				}

				/* Add Instagram User Information */
				$("#" + instagram.target + ' .instagram-author-photo').append('<img src="' + instagram.authorPhoto + '" alt="' + instagram.full_name + '" />');
				for(var i=0; i<4; i++) {
					if( tags[i] ) {
						$("#" + instagram.target + ' .instagram-tags').append('<a href="http://www.enjoygram.com/tag/' + tags[i].name + '" target="_blank">#' + tags[i].name + '</a> ');
					}
				}
				$("#" + instagram.target + ' .instagram-author-tag').append('<a href="http://instagram.com/' + instagram.username + '" target="_blank">#' + instagram.username + '</a>');
				$("#" + instagram.target + ' .num-photos span').html(instagram.photos);
				$("#" + instagram.target + ' .num-followers span').html(instagram.followers);
				$("#" + instagram.target + ' .num-likes span').html(instagram.likes);
				$("#" + instagram.target + ' .instagram-follow').attr('href', 'http://instagram.com/' + instagram.username);
			}
		});
	});

	/*-----------------------------------------------------------------------------------*/
	/*	07. BLOG MASONRY
	/*-----------------------------------------------------------------------------------*/

	var $blogMasonry;

	if( $('.blog-masonry').length ) {
		$('.site').addClass('style-2');

		$blogMasonry = $('.blog-masonry').imagesLoaded( function() {
			$blogMasonry.isotope({
				itemSelector: '.blog-masonry > div',
				layoutMode: 'masonry'
			});
		});
	}

	/* Load More Blog Posts */

	if( $('.blog-wrapper').length ) {
		var blogParent = $('.blog-wrapper');
		var blogPosts = {
			perPage   : blogParent.attr('data-per-page'),
			categories: blogParent.attr('data-categories'),
			type      : blogParent.attr('data-type'),
			page      : 2,
			maxPage   : blogParent.attr('data-max-page')
		};

		$('.blog-load-more').on('click', function() {
			$.ajax({
				url: ajaxpagination.ajaxurl,
				type: 'post',
				data: {
					action: 'blog_more',
					per_page: blogPosts.perPage,
					page: blogPosts.page,
					categories: blogPosts.categories,
					type: blogPosts.type
				},
				success: function( result ) {
					blogParent.append(result);
					var numPosts = result.match(/blog-posts/g).length;
					blogPosts.page += 1;

					if( $('.blog-masonry').length ) {
						for(var i=numPosts; i>0; i--) {
							$blogMasonry.isotope('appended', blogParent.children().eq(-i));
						}
					}

					$blogMasonry.imagesLoaded( function() {
						$blogMasonry.isotope('layout');
					});

					$('.blog-load-more').blur();

					if( blogPosts.page > blogPosts.maxPage ) {
						$('.blog-load-more').attr('disabled', true);
					}
				}
			});
		}); 
	}

	/*-----------------------------------------------------------------------------------*/
	/*	08. Preloader
	/*-----------------------------------------------------------------------------------*/

	$('.site').imagesLoaded( function() {
		loadSite();
	});

	setTimeout(loadSite, 10000);

	/*-----------------------------------------------------------------------------------*/
	/*	09. FORMS
	/*-----------------------------------------------------------------------------------*/

	var formElement = $('form[data-form="contact-form"]');

	if( formElement.length ) {
		formElement.validate({
			 submitHandler: function(form) {
			 	$('#contact-form-message').remove();
			 	
		        try {
					$.ajax({
						type: 'POST',
						url: 'http://zmthemes.com/dropout-html/php/mail.php',
						data: {
							form : formElement.serialize(),
						}
					}).success(function(msg) {
						formElement.append('<label id="contact-form-message" class="success">' + msg + '</label>');
					});
		        } catch(e) { console.log(e); }

				return false;
			 }
		});
	}

	$('form[data-form="submit"] input').keypress(function (e) {		
		if (e.which == 13) {
			$(this).parent().submit();
			e.preventDefault(); 
			return false;
		}
	});

	if( $('.animate').length ) {
		$('.animate').waypoint(function() {
			var el = $(this);
			el.addClass('animated');

			if( el.hasClass('counter') ) {
				el.find('span').each(function () {
				    $(this).prop('Counter',0).animate({
				        Counter: $(this).attr('data-val')
				    }, {
				        duration: 3000,
				        easing: 'swing',
				        step: function (now) {
				            $(this).text(Math.ceil(now));
				        }
				    });
				});
			}
		}, { offset: 'bottom-in-view', triggerOnce: true });
	}

	/*-----------------------------------------------------------------------------------*/
	/*	10. Fullscreen Section
	/*-----------------------------------------------------------------------------------*/

	if( $('.section-fs').length ) {
		if( !$('.nav-side').length ) {
			$('body').addClass('nav-sticky-style-2');
		}
		$('body').addClass('section-scroll');

		if( $('.site-logo').attr('data-light') && !$('.nav-side').length ) {
			$('.site-logo img').attr('src', $('.site-logo').attr('data-light'));
		}

		$('.nav-menu').attr('data-nav', 'sections');

		if ( $('.section-fs').eq(0).hasClass('background-dark') ) {
			$('body').addClass('background--dark');
		}

		var secAnchors = [];
		var secTooltips = [];

		$('.section-fs').each(function() {
			secAnchors.push($(this).attr('data-anchor'));
			secTooltips.push( ($(this).attr('data-tooltip')) ? $(this).attr('data-tooltip') : '' );
		});

		$('.section-fs-container').fullpage({
	        //Navigation
	        menu: $('.section-fs-container').hasAttr('data-nav'),
	        navigation: $('.section-fs-container').hasAttr('data-nav'),
	        showActiveTooltip: true,
	        anchors: secAnchors,
	        navigationTooltips: secTooltips,

	        responsiveWidth: 992,
	        responsiveHeight: 400,
	        
	        //Scrolling
	        scrollBar: $('.section-fs-container').hasAttr('data-scroll'),

	        //Custom selectors
	        sectionSelector: '.section-fs',
	    });
	}

	/*-----------------------------------------------------------------------------------*/
	/*	11. IE9 Placeholders
	/*-----------------------------------------------------------------------------------*/

	$.support.placeholder = ('placeholder' in document.createElement('input'))
	if (!$.support.placeholder) {
		$("[placeholder]").focus(function () {
			if ($(this).val() == $(this).attr("placeholder")) $(this).val("");
		}).blur(function () {
			if ($(this).val() == "") $(this).val($(this).attr("placeholder"));
		}).blur();

		$("[placeholder]").parents("form").submit(function () {
			$(this).find('[placeholder]').each(function() {
				if ($(this).val() == $(this).attr("placeholder")) {
					$(this).val("");
				}
			});
		});
	}

	/*-----------------------------------------------------------------------------------*/
	/*	12. GALLERY
	/*-----------------------------------------------------------------------------------*/

	if( $('.gallery').length ) {
		$('.gallery').each(function(index) {
			var id = $('.gallery').eq(index).attr('id');

			$('#' + id + ' .gallery-item a').featherlightGallery({
			    previousIcon:  '<svg><use xlink:href="#shape-arrow-thin-left"></use></svg>',
			    nextIcon:      '<svg><use xlink:href="#shape-arrow-thin-right"></use></svg>',
			    galleryFadeIn: 400,
			    closeIcon:     '×',
			    openSpeed:     400
			});
		});
	}

	if( $('.portfolio-lightbox').length ) {
		$('.portfolio-lightbox a').featherlightGallery({
		    previousIcon:  '<svg><use xlink:href="#shape-arrow-thin-left"></use></svg>',
		    nextIcon:      '<svg><use xlink:href="#shape-arrow-thin-right"></use></svg>',
		    galleryFadeIn: 400,
		    closeIcon:     '×',
		    openSpeed:     400,
		    afterContent: function() {
		    	$('.featherlight-content').removeClass('fl-video');
		    	$('.featherlight-content .video-wrapper > *').unwrap();

		    	if( $('.featherlight-content iframe').length ) {
			    	$('.featherlight-content').addClass('fl-video');
			    	$('.featherlight-content iframe').wrap('<div class="video-wrapper"></div>');
			    	$('.featherlight-content iframe').attr('src', $('.featherlight-content iframe').attr('data-src'));
			    }
		    }
		});
	}
});

/*-----------------------------------------------------------------------------------*/
/*	13. GOOGLE MAPS
/*-----------------------------------------------------------------------------------*/

function map(element, location, zoom, marker, scrollwheel, draggable) {
	if( scrollwheel === 'on' ) {
		scrollwheel = true;
	} else {
		scrollwheel = false;
	}

	if( draggable === 'on' ) {
		draggable = true;
	} else {
		draggable = false;
	}

	jQuery(element).gmap3({
		map: {
			options: {
				zoom: zoom,
				scrollwheel: scrollwheel,
				draggable: draggable,
			}
		},
		getlatlng:{
			address: location,
			callback: function(results) {
			if ( !results ) { return; }
			jQuery(this).gmap3('get').setCenter(new google.maps.LatLng(results[0].geometry.location.lat(), results[0].geometry.location.lng()));
			jQuery(this).gmap3({
				marker: {
					latLng:results[0].geometry.location,
					options: {
						icon: marker
					}
				}
			});
			}
		}
	});
}