window.Yikes_Mailchimp_Dashboard_Widget = window.Yikes_Mailchimp_Dashboard_Widget || {};

(function( window, document, $, app, undefined ) {
	'use strict';

	// This is generated by PHP.
	app.l10n = window.yikes_mailchimp_dsahboard_widget || {};

	/**
	 * Cache our jQuery objects for reuse.
	 */
	app.cache = function() {
		app.$ = {};
		app.$.change_list = $( document.getElementById( 'yikes-easy-mc-dashboard-change-list' ) );
		app.$.widget_stats = $( document.getElementById( 'yikes-easy-mc-dashboard-widget-stats' ) );
		app.$.preloader = $( '.yikes-easy-mc-widget-preloader' );
	};

	/**
	 * Get new list data.
	 * @returns {boolean}
	 */
	app.new_list_data = function() {
		/* append preloader to our data */
		app.$.widget_stats.children().not( '.yikes-easy-mc-widget-preloader' ).fadeTo( 'fast', '.5' );
		app.$.widget_stats.append( app.l10n.preloader );

		var selected_list = $( this ).val();

		/* build our data */
		var data = {
			'action' : 'get_new_list_data',
			'list_id': selected_list /* grab the form ID to query the API for field data */
		};

		/* submit our ajax request to grab new list data */
		$.ajax({
			url     : app.l10n.ajax_url,
			type    : 'POST',
			data    : data,
			success : function (response, textStatus, jqXHR) {
				console.log(response);
				app.$.preloader.remove();
				app.$.widget_stats.children().fadeTo('fast', '1');
				app.$.widget_stats.html(response);
			},
			error   : function (jqXHR, textStatus, errorThrown) {
				alert(textStatus + jqXHR.status + jqXHR.responseText + "...");
			},
			complete: function (jqXHR, textStatus) {
				/* console.log( 'field successfully added to the form' ); */
			}

		});

		return false;
	};

	/**
	 * Initialize our code.
	 */
	app.init = function() {
		app.cache();
		app.$.change_list.on( 'change', app.new_list_data );
	};

	$( document ).ready( app.init );

})( window, document, jQuery, Yikes_Mailchimp_Dashboard_Widget );
