(function($) {
	'use strict';
	var Focus = window.Focus = window.Focus || {};

	Focus.PrintController = {
		visible     : false,
		post_string : '',
		customPrint : null,

		showOptions : function() {
			var $options = $('.focus-print-options');
			var $button  = $('.print-options-button');
			var rect     = $button.get(0).getBoundingClientRect();
			var padding  = 10;

			$options.removeClass('hidden');
			var width = $options.outerWidth();

			$options
				.css({
					left   : (rect.left - width + padding) + 'px',
					bottom : (window.innerHeight - rect.top + padding) + 'px',
				});

			Focus.prepareAnimations($options);
			$options.addClass('animate');
		},

		hideOptions : function() {
			var $options = $('.focus-print-options');

			$options
				.addClass('hidden')
				.removeClass('animate');
		},

		print : function(parameters) {
			if(typeof this.customPrint === 'function') {
				return this.customPrint(parameters);
			}

			return this._print(parameters);
		},

		_print : function(parameters) {
			if(parameters && typeof parameters === 'object') {
				for(var key in parameters) {
					this.post_string[key] = parameters[key];
				}
			}

			var print_small = false;

			this.post_string["pdf_id"]        = 'search';
			this.post_string["_FOCUS_PRINT"]  = 1;
			this.post_string["_FOCUS_PDF"]    = 1;
			this.post_string["ajax"]          = 1;
			this.post_string['print_options'] = true;
			this.post_string['default_print'] = 1; // use htmldoc for printing pdf unless overridden

			if (this.post_string['print_small']) {
				print_small = true;
			}

			$.ajax({
				url: 'Modules.php',
				type: 'POST',
				data: this.post_string,
			})
			.done(function() {
				var url     = 'Modules.php?_FOCUS_PDF=1&_FOCUS_PRINT=1&pdf_id=search&time=' + Date.now();
				if (print_small) {
					url = url + '&print_small=1';
				}
				var $print  = $('.focus-print');
				var $iframe = $('.focus-print-iframe');
				var isAtLeastIE11 = !!(navigator.userAgent.match(/Trident/) && !navigator.userAgent.match(/MSIE/));

				// Mobile Safari is unable to process pdfs inside iframes properly.
				// Multi page pdfs are not scrollable.
				// To work around this, mobile safari will not use an iframe, and will load the pdf directly.
				var ua            = window.navigator.userAgent;
				var ios           = !!ua.match(/iPad/i) || !!ua.match(/iPhone/i);
				var webkit        = !!ua.match(/WebKit/i);
				var is_ios_safari = ios && webkit;

				if (!isAtLeastIE11 && !is_ios_safari) {
					var $modal  = Focus.modal($print);
					$modal
						.addClass('focus-iframe-modal')
						.trigger('focusModalLoading')
						.on('focusModalClose', function() {
							$iframe.prop('src', 'about:blank');
						});

					$iframe
						.prop('src', url)
						.on('load', function() {
							$modal.trigger('focusModalLoaded');
						});
				}
				else {
					window.location=url;
				}
			});
		}
	};
}(jQuery));
