( function( $ ) {
	'use strict';

	/**
	 * Main theme object.
	 */
	var EvolveThemes_Crowley = function() {

		var self = this;

		/**
		 * Load fonts.
		 */
		this.load_fonts = function() {
			if ( typeof window.FontsLoadr === 'undefined' ) {
				return;
			}

			if ( typeof window.crowley.fonts === 'undefined' ) {
				return;
			}

			if ( typeof window.Preloadr !== 'undefined' ) {
				window.document.documentElement.addEventListener( 'evolvethemes-fonts-active', function() {
					window.Preloadr.complete( 'fonts' );
				} );

				window.document.documentElement.addEventListener( 'evolvethemes-fonts-inactive', function() {
					window.Preloadr.complete( 'fonts' );
				} );
			}

			window.FontsLoadr.init( window.crowley.fonts );
		};

		/**
		 * Correctly size embeds.
		 */
		this.size_embeds = function() {
			$( '.crowley-mc-content' ).fitVids();
		};

		/**
		 * Load images.
		 */
		this.load_images = function( figure ) {
			if ( typeof window.ImgLoadr === 'undefined' || typeof window.Inviewr === 'undefined' ) {
				return;
			}

			var selector = ".evolvethemes-image";
			var images = document.querySelectorAll( selector );

			window.ImgLoadr.size();
			window.Inviewr.register( selector, {} );

			images.forEach( function( figure ) {
				figure.addEventListener( 'evolvethemes-inview', function() {
					window.ImgLoadr.loadSingle( $( 'img', figure ).get( 0 ) );
				} );
			} );

			window.Inviewr.refresh();
		};

		/**
		 * Initialize the preloader.
		 */
		this.init_preloader = function() {
			if ( typeof window.Preloadr === 'undefined' ) {
				return;
			}

			if ( typeof window.crowley.preloader === 'undefined' ) {
				return;
			}

			window.Preloadr.init( window.crowley.preloader );
		};

		/**
		 * Event binding.
		 */
		this.bind = function() {
			/* Initialize the preloader. */
			self.init_preloader();

			/* Load fonts. */
			self.load_fonts();

			/* Load images. */
			self.load_images();

			// var images = document.querySelectorAll( ".evolvethemes-image" );

			// images.forEach( function( figure ) {
			// 	figure.addEventListener( 'evolvethemes-inview', function() {
			// 		self.load_images( figure );
			// 	} )
			// } );

			// window.evolvethemes.inviewr.register( ".evolvethemes-image", {
			// 	inViewCallback: function( figure ) {
			// 		window.evolvethemes.load_images( $( "img", figure ) );
			// 	}
			// } );

			// self.load_images();

			/* Size embeds. */
			self.size_embeds();
		};

		/**
		 * Initialization.
		 */
		this.init = function() {
			self.bind();
		};

		this.init();

	};

	( window.crowley.controller = new EvolveThemes_Crowley() );

} )( jQuery );
