/* globals shrk: false, ajaxurl: false */
'use strict';

jQuery( document ).ready(function( $ ) {

	var $testkit_row = $('#typekit-testkit-button').closest('tr');
	var $spinner     = $('#typekit-testkit-button').siblings('.spinner');

	$('#typekit_module, #typekit_kit_id').on('change keyup', function () {
		visibility_check();
	});

	visibility_check();

	function visibility_check() {
		if ( $('#typekit_module').val() === '1' && $('#typekit_kit_id').val().trim() !== '' ) {
			$testkit_row.show();
		} else {
			$testkit_row.hide();
		}
	}

	$('#typekit-testkit-button').on('click', function () {
		var data = {};

		$('#typekit-testkit-output').slideUp();
		$spinner.addClass('is-active');

		data.action      = 'reduxtypekit_testkit';
		data.kit_id      = $('#typekit_kit_id').val().trim();
		data._ajax_nonce = shrk.ajax.nonce;

		$.post(ajaxurl, data, function(response) {
			$('#typekit-testkit-output').html(response).slideDown();
			$spinner.removeClass('is-active');
		});

		return false;
	});

    $( '.typekit-backup-font-family .redux-container-typography' ).find( '.redux-typography' ).on(
        'change', function() {
            if ( typeof( redux_typekit ) === 'undefined' || typeof( redux_typekit.fonts ) === 'undefined' ) {
            	return;
            }
			var $container = $(this).closest( '.redux-container-typography' );

			setTimeout( function() {
				var sel_font   = $container.find( 'input.redux-typography-font-family.typekit-backup-font-family' ).val();

				if ( sel_font && typeof(redux_typekit.fonts[sel_font]) !== 'undefined' ) {
					// Typekit font
					$container.find( '.typography-family-backup' ).fadeIn( 'fast' );
				}
			}, 1000);	
        }
    );

});