// ==========================================================================
//
// FullScreen
// Adds fullscreen functionality
//
// ==========================================================================
;(function (document, $) {
	'use strict';

	var FullScreen = function( instance ) {

		this.instance = instance;

		this.init();

	};

	$.extend( FullScreen.prototype, {

		$button : null,

		init : function() {
			var self = this;

			if ( !self.isAvailable() ) {
				return;
			}

			self.$button = $('<button data-fancybox-fullscreen class="fancybox-button fancybox-button--fullscreen" title="Full screen (F)"></button>')
				.appendTo( self.instance.$refs.buttons );

			self.instance.$refs.container.on('click.fb-fullscreen', '[data-fancybox-fullscreen]', function(e) {

				e.stopPropagation();
				e.preventDefault();

				self.toggle();

			});

			$(document).on('onUpdate.fb', function(e, instance) {
				self.$button.toggle( !!instance.current.opts.fullScreen );

				self.$button.toggleClass('fancybox-button-shrink', self.isActivated() );

			});

			$(document).on('afterClose.fb', function() {
				self.exit();
			});

		},

		isAvailable : function() {
			var element = this.instance.$refs.container.get(0);

			return !!(element.requestFullscreen || element.msRequestFullscreen || element.mozRequestFullScreen || element.webkitRequestFullscreen);

		},

		isActivated : function() {
			return !(!document.fullscreenElement && !document.mozFullScreenElement && !document.webkitFullscreenElement && !document.msFullscreenElement);

		},

		launch : function() {
			var element = this.instance.$refs.container.get(0);

			if ( !element || this.instance.isClosing ) {
				return;
			}

			if (element.requestFullscreen) {
				element.requestFullscreen();

			} else if (element.msRequestFullscreen) {
				element.msRequestFullscreen();

			} else if (element.mozRequestFullScreen) {
				element.mozRequestFullScreen();

			} else if (element.webkitRequestFullscreen) {
				element.webkitRequestFullscreen(element.ALLOW_KEYBOARD_INPUT);
			}

		},

		exit : function() {

			if (document.exitFullscreen) {
				document.exitFullscreen();

			} else if (document.msExitFullscreen) {
				document.msExitFullscreen();

			} else if (document.mozCancelFullScreen) {
				document.mozCancelFullScreen();

			} else if (document.webkitExitFullscreen) {
				document.webkitExitFullscreen();
			}

		},

		toggle : function() {

			if ( this.isActivated() ) {
				this.exit();

			} else if ( this.isAvailable() ) {
				this.launch();
			}

		}
	});

	$(document).on('onInit.fb', function(e, instance) {

		if ( !!instance.opts.fullScreen && !instance.FullScreen) {
			instance.FullScreen = new FullScreen( instance );
		}

	});

}(document, window.jQuery));
