jQuery(function ($) {

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

	var msgWrapper = $('#js-if-api-ajax-response');

	//#! Disconnect from IconFinder API
	var disconnectButton = $('#iconfinder_disconnect_api_btn');
	if (disconnectButton && disconnectButton.length > 0) {
		disconnectButton.on('click', function (e) {
			e.preventDefault();
			e.stopPropagation();
			var ajaxConfig = {
				url: ajaxurl,
				method: 'POST',
				timeout: 5000,
				async: true,
				cache: false,
				dataType: 'JSON',
				data: {
					action: 'disconnect_if_api',
					disconnect_if_api: true
				}
			};
			ajaxConfig.data[iconFinderApiLocale.if_nonce_name] = iconFinderApiLocale.if_nonce;

			$.ajax(ajaxConfig)
				.done(function(response){
					if( ! response){
						msgWrapper.addClass('notice-error').html(response.data).fadeIn('fast');
					}
					else if( response.success === false ){
						msgWrapper.addClass('notice-error').html(response.data).fadeIn('fast');
					}
					else {
						window.location.reload();
					}
				})
				.fail(function(x,s,e){
					msgWrapper.addClass('notice-error').html(e).fadeIn('fast');
				})
				.always(function() {
					window.setTimeout(function(){
						msgWrapper.fadeOut('slow').html('').attr('class', '');
					}, 3000);
				});
		});
	}

	$('.js-refreshData').on('click', function(e){
		e.preventDefault();

		var $t = $(e.currentTarget);
		$t.addClass('btn-is-loading');

		var data = {
			'action': 'refresh_user_data'
		};
		if( typeof iconFinderApiLocale.if_nonce_name !== 'undefined' ){
			data[iconFinderApiLocale.if_nonce_name] = iconFinderApiLocale.if_nonce;
		}

		$.post(ajaxurl, data, function(response) {
			if( response.success ) {
				$('#js-ip-ifAuth-details').html( response.data );
				$t.removeClass('btn-is-loading');
			}
		});
	});
});












