(function($) {
	'use strict';

	var config = typeof EPCustomFontsAdmin !== 'undefined' ? EPCustomFontsAdmin : {};
	var EPFontAdminApp = {
		variationCount: 0,

		init: function() {
			this.variationCount = $('.ep-font-variation').length;
			this.bindEvents();
		},

		bindEvents: function() {
			var self = this;
			$(document).on('click', '.ep-upload-font-file', function(e) {
				e.preventDefault();
				self.uploadFontFile($(this));
			});
			$(document).on('click', '.ep-remove-font-file', function(e) {
				e.preventDefault();
				self.removeFontFile($(this));
			});
			$(document).on('click', '.ep-add-variation', function(e) {
				e.preventDefault();
				self.addVariation();
			});
			$(document).on('click', '.ep-remove-variation', function(e) {
				e.preventDefault();
				self.removeVariation($(this));
			});
		},

		uploadFontFile: function(button) {
			var row = button.closest('.ep-font-file-row'),
				idInput = row.find('.ep-font-file-id'),
				urlInput = row.find('.ep-font-file-url'),
				format = button.data('format'),
				allowed = (config.allowedFormats && config.allowedFormats[format])
					? config.allowedFormats[format]
					: { extensions: format, mimeType: 'application/octet-stream' },
				ext = allowed.extensions,
				mimeType = allowed.mimeType,
				frameOptions = {
					title: (config.uploadTitle || 'Select Font File') + ' - ' + format.toUpperCase(),
					button: { text: config.uploadButton || 'Use this file' },
					multiple: false,
					library: { type: mimeType },
					uploader: {
						plupload: {
							filters: {
								mime_types: [{
									title: format.toUpperCase() + ' Font',
									extensions: ext
								}]
							}
						}
					}
				};

			var frame = wp.media(frameOptions);

			frame.on('open', function() {
				frame.state().get('library').props.set({ type: mimeType });
			});

			frame.on('select', function() {
				var attachment = frame.state().get('selection').first().toJSON();
				var filename = attachment.filename || (attachment.url ? attachment.url.split('/').pop() : '') || '';
				var fileExt = filename.split('.').pop().toLowerCase();

				if (fileExt !== ext) {
					var msg = (config.wrongFormat || 'Please select a %s file for this field.').replace('%s', ext.toUpperCase());
					alert(msg);
					return;
				}

				idInput.val(attachment.id);
				urlInput.val(attachment.url);
				if (row.find('.ep-remove-font-file').length === 0) {
					button.after('<button type="button" class="button ep-remove-font-file">Remove</button>');
				}
			});

			frame.open();
		},

		removeFontFile: function(button) {
			var row = button.closest('.ep-font-file-row');
			row.find('.ep-font-file-id').val('');
			row.find('.ep-font-file-url').val('');
			button.remove();
		},

		addVariation: function() {
			var container = $('.ep-font-variations'),
				index = this.variationCount,
				html = this.getVariationTemplate(index);
			container.append(html);
			this.variationCount++;
		},

		removeVariation: function(button) {
			if ($('.ep-font-variation').length > 1) {
				button.closest('.ep-font-variation').remove();
				this.updateVariationHeaders();
			}
		},

		updateVariationHeaders: function() {
			$('.ep-font-variation').each(function(index) {
				$(this).find('h4').text('Font Variation ' + (index + 1));
				$(this).find('.ep-remove-variation').prop('disabled', index === 0);
			});
		},

		getVariationTemplate: function(index) {
			var html = '<div class="ep-font-variation" data-index="' + index + '">';
			html += '<div class="ep-font-variation-header">';
			html += '<h4>Font Variation ' + (index + 1) + '</h4>';
			html += '<button type="button" class="button ep-remove-variation">Remove</button>';
			html += '</div>';
			html += '<table class="form-table">';
			html += '<tr><th scope="row"><label>Font Weight</label></th><td>';
			html += '<select name="ep_font_files[' + index + '][font_weight]" class="regular-text">';
			$.each({ 100: '100 - Thin', 200: '200 - Extra Light', 300: '300 - Light', 400: '400 - Normal', 500: '500 - Medium', 600: '600 - Semi Bold', 700: '700 - Bold', 800: '800 - Extra Bold', 900: '900 - Black' }, function(val, label) {
				html += '<option value="' + val + '"' + (val === '400' ? ' selected' : '') + '>' + label + '</option>';
			});
			html += '</select></td></tr>';
			html += '<tr><th scope="row"><label>Font Style</label></th><td>';
			html += '<select name="ep_font_files[' + index + '][font_style]" class="regular-text">';
			html += '<option value="normal" selected>Normal</option><option value="italic">Italic</option><option value="oblique">Oblique</option>';
			html += '</select></td></tr>';
			$.each({ woff2: 'WOFF2 (Recommended)', woff: 'WOFF', ttf: 'TTF', otf: 'OTF', eot: 'EOT (IE Support)', svg: 'SVG (Legacy)' }, function(format, label) {
				html += '<tr class="ep-font-file-row">';
				html += '<th scope="row"><label>' + label + '</label></th>';
				html += '<td>';
				html += '<input type="hidden" name="ep_font_files[' + index + '][' + format + '][id]" class="ep-font-file-id" value="">';
				html += '<input type="text" name="ep_font_files[' + index + '][' + format + '][url]" class="regular-text ep-font-file-url" value="" readonly> ';
				html += '<button type="button" class="button ep-upload-font-file" data-format="' + format + '" data-index="' + index + '">Upload</button>';
				html += '</td></tr>';
			});
			html += '</table></div>';
			return html;
		}
	};

	$(document).ready(function() {
		if ($('.ep-custom-fonts-wrapper').length) {
			EPFontAdminApp.init();
		}
	});

})(jQuery);
