(function($){

	$('.hitmag-block').on('click', '.hmajax-btn', function() {

		var clickedBtn = $(this),
			direction = clickedBtn.data('hmnextprev'),
			currentBlock = clickedBtn.closest('.hitmag-block'),
			dataContainer = clickedBtn.closest('.hmp-pagination-data'),
			blockuid = dataContainer.data('blockuid'),
			cat = dataContainer.data('hmcat'),
			postsPerPage = dataContainer.data('hmppp'),
			currentPage = parseInt(dataContainer.data('currentpage'));
			

		var blockId = '#'+blockuid;
		var loader = $(currentBlock).prev('.hmw-spinner');

		$(clickedBtn).attr("disabled", true);
		$(currentBlock).css('opacity', '0.2');
		$(loader).css('display', 'inline-block');

		if ( direction == "next" ) {
			paged = currentPage+1;
		} else if( direction == "prev" ) {
			if( currentPage == 1 ) {
				$(currentBlock).css('opacity', '1');
				$(loader).css('display', 'none');
			} else {
				paged = currentPage-1;
			}
		}

		if( postsPerPage > 10 ) {
			postsPerPage = 10;
		}

		$.ajax({
			type: 'POST',
			url: hitmag_ajax_object.ajaxurl,
			data: {
				action: 'hitmag_pro_get_wp_query',
				blockuid: blockuid,
				hmwCurrentPage: currentPage,
				hmwPostsPerPage: postsPerPage,
				hmwCategory: cat, 
				hmwPaged: paged
			},
			success: function(data, textStatus, XMLHttpRequest) {
				//console.log(data);
				$(currentBlock).html('');
				$(currentBlock).append(data);
				$(currentBlock).css('opacity', '1');
				$(loader).css('display', 'none');
				$(clickedBtn).attr("disabled", false);
			},
			error: function(MLHttpRequest, textStatus, errorThrown) {
				alert(errorThrown);
			}
		});

	});

})(jQuery);