jQuery(function($){
	
	// do not run for monthly layout
	if ( $( '.tournament-listing.monthly' ).length > 0 ) {
		return;
	}
	
	
	if ( $( '.starts_with_list li' ).length > 0 ) {
		
		$( '.starts_with_list li a' ).on( 'click', function ( e ) {
			
			e.preventDefault();
			
			var clicked_letter = $( this ).data( 'letter' );
			
			console.log( clicked_letter );
			
			$( '#starts_with_select' ).val( clicked_letter ).change();
			$( '#filter_submit' ).trigger( 'click' );
			
			return false;
			
		});
	}

	var button = $('.post-listing .load-more');
	
	var page = 2;
	var loading = false;
	var scrollHandling = {
	    allow: true,
	    reallow: function() {
	        scrollHandling.allow = true;
	    },
	    delay: 500 //(milliseconds) adjust to the highest acceptable value
	};

	var elementTop = $('.inner_wrapper .post_wrapper').offset().top;
	$(window).scroll(function(){
		
		if( ! loading && scrollHandling.allow ) {
			scrollHandling.allow = false;
			setTimeout(scrollHandling.reallow, scrollHandling.delay);
			// var offset = $(button).offset().top - $(window).scrollTop();
			// var offset = 0;

			//var offset = $(window).scrollTop();
			
			var elementBottom = elementTop + $('.inner_wrapper .post_wrapper').outerHeight();

			var viewportTop = $(window).scrollTop();
			var viewportBottom = viewportTop + ( 4 * $(window).height() );
						
			if ( viewportBottom >= elementBottom ) {
				$('.post-listing').after( beloadmore.loader );
				loading = true;
				var data = {
					action: 'be_ajax_load_more',
					nonce: beloadmore.nonce,
					page: page,
					query: beloadmore.query,
					gparma: beloadmore.gparma
				};
				if ( $( 'body.post-type-archive-tournaments' ).length > 0 ) {
					data.lastmonth = $( '.dtable.post-listing .drow:last-child' ).data( 'month' );
					data.lastyear = $( '.dtable.post-listing .drow:last-child' ).data( 'year' );
				}
								
				$.post(beloadmore.url, data, function(res) {
					res = res.trim();

					if(res && res != 0) {
						$('.dynamic_loader').remove();
						$('.post-listing').append( res );
						page = page + 1;
						loading = false;
					} else {
						loading = true;
						$('.dynamic_loader').remove();
					}
				}).fail(function(xhr, textStatus, e) {
					// console.log(xhr.responseText);
				});

			}
		}
	});
});