(function() {

var year = '';
var authorId = '';

function change() {
	var loadingText = (aeGlobal.loadingText == undefined) ? 'Loading...' : aeGlobal.loadingText + '...';

	var url = aeGlobal.serverUrl + '/?action=ea_monthly_ajax'
			+ '&year=' + year
			+ '&author=' + authorId;

	jQuery.ajax({
		type		:'GET',
		url			:url,
		cache		:false,
		contentType	:'text/html; charset=utf-8',

		beforeSend: function(data){
			document.body.style.cursor = 'wait';
			jQuery('#easy-archives div.ea-filter').html('<div class="ea-loader">' + loadingText + '</div>');
		},

		success: function(data){
			jQuery('#easy-archives').fadeOut(function(){
				jQuery(this).html(data).fadeIn(function(){
					bindActions();
				});
			});
			document.body.style.cursor = 'auto';
		},

		error: function(data){
			jQuery('#easy-archives').html('<p>Oops, failed to load data.</p>');
			document.body.style.cursor = 'auto';
		}
	});
}

function changeYear(select) {
	year = select.value;
	change();
}

function changeAuthor(select) {
	authorId = select.value;
	change();
}

function toggle(button, isEffect) {
	var duration = 0;
	if(isEffect) {
		duration = 400;
	}

	if (button.is('.ea-open-button')) {
		button.parent().next().hide(duration, function() {
			button.removeClass().addClass('ea-closed-button');
		}).removeClass().addClass('ea-closed');
	} else {
		button.parent().next().show(duration, function() {
			button.removeClass().addClass('ea-open-button');
		}).removeClass().addClass('ea-open');
	}
}

function collapseAll() {
	jQuery('#easy-archives a.ea-open-button').each(function() {
		toggle(jQuery(this), false);
	});
}

function expandAll() {
	jQuery('#easy-archives a.ea-closed-button').each(function() {
		toggle(jQuery(this), false);
	});
}

function bindActions() {
	jQuery('#easy-archives a.ea-open-button').click(function(){
		toggle(jQuery(this), true);
	});

	jQuery('#easy-archives a.ea-closed-button').click(function(){
		toggle(jQuery(this), true);
	});

	jQuery('#easy-archives input.ea-expand-all').click(function(){
		expandAll();
	});

	jQuery('#easy-archives input.ea-collapse-all').click(function(){
		collapseAll();
	});

	jQuery('#easy-archives select.ea-year-selector').change(function(){
		changeYear(this);
	});

	jQuery('#easy-archives select.ea-author-selector').change(function(){
		changeAuthor(this);
	});
}

jQuery(document).ready(function(){
	jQuery('#easy-archives select.ea-year-selector').attr('selectedIndex', '0');
	jQuery('#easy-archives select.ea-author-selector').attr('selectedIndex', '0');
	bindActions();
});

})();
