(function ($) {
"use strict";


/* bwmap */
function gg_bwmap_init() {
	if($('#bwmap').length > 0){
		$( '#bwmap' ).each(function(){

			var $this = $(this),
			latitude = $this.attr('data-latitude'),
			longitude = $this.attr('data-longitude'),
			infow = $this.attr('data-infow'),
			infowtitle = $this.attr('data-infowtitle'),
			infowcontent = $this.attr('data-infowcontent'),
			mapzoom = $this.attr('data-zoom');

			var map;
        	var bwmap = new google.maps.LatLng(latitude, longitude);

        	function initialize() {

	            var mapOptions = {
	                zoom: 14,
	                scrollwheel: false,
	                center: bwmap,
	                mapTypeId: google.maps.MapTypeId.ROADMAP,
	          		styles : [{featureType:'all',stylers:[{saturation:-100},{gamma:0.0}]}]
	            };

	            map = new google.maps.Map(document.getElementById('bwmap'),
	                mapOptions);

	            var marker = new google.maps.Marker({
					position: bwmap,
					map: map
				});

	            if (infow =='use_infow') {
					var contentString = '<div id="content">'+
				      '<div id="siteNotice">'+
				      '</div>'+
				      '<h1 id="firstHeading" class="firstHeading">' + infowtitle + '</h1>'+
				      '<div id="bodyContent">'+
				      '<p>' + infowcontent + '</p>'+
				      '</div>'+
				      '</div>';

		            var infowindow = new google.maps.InfoWindow({
					    content: contentString
					});

		            google.maps.event.addListener(marker, 'click', function() {
						infowindow.open(map,marker);
					});
				}

	        }

        google.maps.event.addDomListener(window, 'load', initialize);

		});
	}
}

function gg_isotope_init() {
	if($('.image-grid:not(.owl-carousel)').length > 0){
	    var layout_modes = {
	        fitrows: 'fitRows',
	        masonry: 'masonry'
	    }
	    jQuery('.gg_posts_grid').each(function(){
	        var $container = jQuery(this);
	        var $thumbs = $container.find('.image-grid:not(.owl-carousel)');
	        var layout_mode = $thumbs.attr('data-layout-mode');
	        $thumbs.isotope({
	            // options
	            itemSelector : '.isotope-item',
	            layoutMode : (layout_modes[layout_mode]==undefined ? 'fitRows' : layout_modes[layout_mode])
	        });
	        $container.find('.categories_filter a').data('isotope', $thumbs).click(function(e){
	            e.preventDefault();
	            var $thumbs = jQuery(this).data('isotope');
	            jQuery(this).parent().parent().find('.active').removeClass('active');
	            jQuery(this).parent().addClass('active');
	            $thumbs.isotope({filter: jQuery(this).attr('data-filter')});
	        });
	        jQuery(window).bind('load resize', function() {
	            $thumbs.isotope("layout");
	        });
	    });
	}
}

/* Magnific */
function gg_magnific_init() {
	if($('.image-grid, .team-grid, .owl-carousel.has_magnific, .wpb_image_grid.has_magnific, .wpb_single_image.has_magnific').length > 0){
		$( '.image-grid, .team-grid, .owl-carousel.has_magnific, .wpb_image_grid.has_magnific, .wpb_single_image.has_magnific' ).each(function(){
			$(this).magnificPopup({
				delegate: 'a.lightbox-el',
				type: 'image',
				gallery: {
		            enabled: true
		        },
				callbacks: {
				    elementParse: function(item) {
				      if(item.el.context.className == 'lightbox-el extra-links lightbox-video') {
				         item.type = 'iframe';
				      } else {
				         item.type = 'image';
				      }
				    }
				}
			});
		});
	}
}

/* OwlCarousel */
function gg_owlcarousel_init() {
	if($('.owl-carousel').length > 0){
		$( '.owl-carousel' ).each(function(){

			var $this = $(this),
			slidesPerView = $this.attr('data-slides-per-view'),
			singleItemData = $this.attr('data-single-item') == "true" ? true : false,
			transitionSlide = $this.attr('data-transition-slide'),
			navigationData = $this.attr('data-navigation-owl') == "true" ? true : false,
			paginationData = $this.attr('data-pagination-owl') == "true" ? true : false,
			lazyloadData = $this.attr('data-lazyload') == "true" ? true : false,
			autoplayData = $this.attr('data-autoplay') == "3000" ? 3000 : false,
			rewindData = $this.attr('data-rewind') == "true" ? true : false,
			speedData = $this.attr('data-speed'),
			pagColor = $this.attr('data-pag-color'),
			cID = $this.attr('data-c-id'),
			heightData = $this.attr('data-height') == "true" ? true : false,
			afterInitData = $this.attr('data-afterinit') == "navColor" ? navColor : '';

			$this.owlCarousel({
			    items : slidesPerView,
			    navigation : navigationData,
			    pagination : paginationData,
			    lazyLoad : lazyloadData,
			    navigationText: [
					"<i class='arrow_carrot-left_alt2'></i>",
					"<i class='arrow_carrot-right_alt2'></i>"
					],
			    
			    singleItem : singleItemData,
			    transitionStyle : transitionSlide, //fade, backSlide, goDown, scaleUp
			    autoPlay : autoplayData,
			    rewindNav : rewindData,
			    slideSpeed : speedData,
			    autoHeight : heightData,
			    afterInit: navColor,
			    afterUpdate: navColor

		  	});

			//function for thumbnail navigation
		  	function navColor() {

			  	if ($('.owl-carousel[data-pag-color="' + pagColor + '" ]').length > 0){	
			  		$('.owl-carousel[data-pag-color="' + pagColor + '" ]').find('.owl-controls .owl-page span, .owl-controls .owl-buttons > div').css('background-color',pagColor);
			  	}

		    }

		});

	}
}

/* Portfolio overlay */
function gg_portfolio_init() {
if($('.gg-overlay-page').length > 0){
	$('.gg-overlay-page').each(function() {
		$(this).magnificPopup({
		type: 'ajax',
	   	ajax: {
	    	settings: null,
	    	cursor: 'mfp-ajax-cur',
	    	thisError: '<a href="%url%">The content</a> could not be loaded.'
	   },
	   closeOnContentClick: false,
	   closeOnBgClick: false,
	   showCloseBtn: false,
	   closeBtnInside:false,
	   fixedContentPos: true,
	   overflowY:'scroll',
	   removalDelay: 500,
	   tLoading: '<div class="firstbuffer"></div><div class="secbuffer"></div><div class="thirdbuffer"></div>',	
	   mainClass: 'mfp-fade gg-style',
	   callbacks: {
	    updateStatus: function(data) {

	    console.log('Status changed', data);
	    	if(data.status === 'ready') {
	    		gg_owlcarousel_init();
				//get carousel instance data and store it in variable owl
				$('body').find(".owl-carousel").data('owlCarousel');
	    	}
		 },
	     parseAjax: function(mfpResponse) {
	            mfpResponse.data = $(mfpResponse.data).find('#single-header, #content');
	            console.log('Ajax content loaded:', mfpResponse);
	     },
	     ajaxContentAdded: function() {
	     	$('.navigation.post-navigation').remove();
	     	$('.mfp-content').prepend('<span class="close-project-overlay"><i class="icon_close"></i></span>');
	     	$('.mfp-content').find('.close-project-overlay').on('click',function(e){
	            e.preventDefault();
	            $.magnificPopup.close();

	        });
	        console.log(this.content);
	     },
	     close: function() {
	        // destroy the slider to avoid memory leaks
	        $('body').find(".owl-carousel").data('owlCarousel').destroy();
	        this.wrap.removeClass('mfp-image-loaded');
	      }
	  }
	  
	});
	});
}
}

/* Counter */
function gg_counter_init(){
	if($('.counter').length > 0){
		jQuery('.counter-holder').waypoint(function() {
			$('.counter').each(function() {
				if(!$(this).hasClass('initialized')){
					$(this).addClass('initialized');
					var $this = $(this),
					countToNumber = $this.attr('data-number'),
					refreshInt = $this.attr('data-interval'),
					speedInt = $this.attr('data-speed');

					$(this).countTo({
						from: 0,
						to: countToNumber,
						speed: speedInt,
						refreshInterval: refreshInt
					});
				}
			});
		}, { offset: '85%' });
	}
}

$(document).ready(function () {

	gg_owlcarousel_init();
    gg_magnific_init();
    gg_portfolio_init();
    gg_counter_init();
    gg_isotope_init();
    gg_bwmap_init();

    // Do our DOM lookups beforehand
	var nav_container = $("#main-menu-header");
    var nav = $("nav.navbar-default");
	var top_spacing = 0;
	var waypoint_offset = 0;

	if (nav.hasClass("header-animation-on")){
		waypoint_offset = nav.outerHeight();
	} else {
		waypoint_offset = 0;
	}

	if ($("body").hasClass("admin-bar")){
		top_spacing = 32;
	} else {
		top_spacing = 0;
	}

	nav_container.waypoint({
	 
	  handler: function(direction) {
	 
	    if (direction == 'down') {
	 
	      nav_container.css({ 'height' : nav.outerHeight() });
	      if (nav.hasClass('header-animation-on')){
		      nav.addClass("sticky")
		         .stop()
		         .css("top", -nav.outerHeight())
		         .css({"top" : top_spacing});
	      }   
	 
	    } else {
	 
	      nav_container.css({ 'height' : 'auto' });
	      if (nav.hasClass('header-animation-on')){
		      nav.removeClass("sticky")
		         .stop()
		         .css("top", nav.outerHeight() + waypoint_offset)
		         .css({"top" : ""});
	      }   
	 
	    }
	 
	  },
	 
	  offset: function() {
	    return - (nav.outerHeight() + waypoint_offset);
	  }

	});

	var sections = $('.gg-scroll-section');
	var navigation_links = $('nav a');
	  
	sections.waypoint({
	handler: function(direction) {
	  	var active_section;
		active_section = $(this);
		if (direction === "up") active_section = active_section.prev();
		 
		var active_link = $('nav a[href*="#' + active_section.attr("id") + '"]');
		navigation_links.removeClass("selected");
		active_link.addClass("selected");
	},
	offset: '35%'
	});

	var navigation_links_hash = $('nav a[href*="#"]');
	navigation_links_hash.click( function(event) {

 	$.scrollTo(

		$(this).attr('href').substring($(this).attr('href').indexOf('#')),
		{
	    	duration: 600,
	    	offset: { 'left':0, 'top': - waypoint_offset - top_spacing + 1}
	    }
		);
	});


	//calling jPreLoader

	var $preloader = $( '.home.preloader-on' );
	if($preloader.length > 0){
		$preloader.jpreLoader({
			loaderVPos: '50%',
			autoClose: true,
		}, function() {	//callback function
			$preloader.addClass( 'preloader-off' );
		});
	}


    //scroll to top
    $(window).scroll(function(){
      if ($(this).scrollTop() > 100) {
        $('.scrollup').fadeIn();

        } else {
        $('.scrollup').fadeOut();

      }
    });

    $('.scrollup').click(function(){
      $("html, body").animate({ scrollTop: 0 }, 1000);
        return false;
    });
   
	// here for each comment reply link of wordpress
	$( '.comment-reply-link' ).addClass( 'btn btn-primary btn-xs' );
	
	// here for the submit button of the comment reply form
	$( '.more-link, #submit, input[type="button"], input[type="reset"], input[type="submit"]' ).addClass( 'btn btn-primary' );	
	
	$( 'table#wp-calendar' ).addClass( 'table table-striped');

	$( 'table' ).addClass( 'table');

	$( 'form' ).addClass( 'table');

	$('form').attr('role', 'form');

	var inputs = $('input, textarea')
            .not(':input[type=button], :input[type=submit], :input[type=reset]');

	$(inputs).each(function() {
	    $(this).addClass('form-control');
	});


    var $scroll = 0;
    $(window).scroll(function() {
		"use strict";
		$scroll = $(window).scrollTop();
	});

    
    if($('body:not(.vivido-agent-devices) .parallax-section').length){
			$('body:not(.vivido-agent-devices) .parallax-section').each(function() {
				var $self = $(this);
				var section_height = $self.data('height');
				$self.height(section_height);
				var rate = (section_height / $(document).height()) * 0.7;
				
				var distance = $scroll - $self.offset().top + 104;
				var bpos = - (distance * rate);
				$self.css({'background-position': 'center ' + bpos  + 'px', 'background-attachment': 'fixed' });
				$(window).bind('scroll', function() {
					var distance = $scroll - $self.offset().top + 104;
					var bpos = - (distance * rate);
					$self.css({'background-position': 'center ' + bpos  + 'px', 'background-attachment': 'fixed' });
				});
			});
		return this;
	}

});        

})(jQuery);