//ajax Pagination

(function($){
	var reload_i18n = {
		loading: 'Laaaa'
	};
	$.fn.cst_list_reload_strings = function( s ) {
		reload_i18n = s
	}
	$.fn.cst_list_reload = function( link ) {
		var list = jQuery( this )
			.animate( { opacity: 0.1 } )
			//.fadeOut( )
		
		var loading = jQuery( '<div class="cst-nav-loading">'+reload_i18n.loading+'..</div>' )
			.insertBefore( list );
		
		var direction = jQuery( link ).parent( ).find( 'a.direction' );
		/*
		if( jQuery( link ).parent().hasClass( 'active' ) && !jQuery( link ).hasClass( 'direction' ) ) {
			direction.toggleClass( 'direction-asc' )
			direction.toggleClass( 'direction-desc' )
		}
		 */
		jQuery( link )
			.parent().parent()
				//.animate( { top: -jQuery( link ).parent().prevAll().size() * jQuery( link ).parent().outerHeight()  } )
				.children()
					.removeClass( 'active' )
					.addClass( 'inactive' )
		
		jQuery( link ).parent().removeClass( 'inactive' ).addClass( 'active' )
		
		if( jQuery( link ).hasClass( 'direction' ) ) {
			direction.toggleClass( 'direction-asc' )
			direction.toggleClass( 'direction-desc' )
		}
		
		jQuery.ajax({
			url: link.href + ( direction.hasClass( 'direction-desc' ) ? '&list_order_direction=desc' : '' ),
			success: function( r ) {
				loading.slideUp();
				
				list.replaceWith(
					jQuery( r )
						.find( 'div.cst-list' )
						.find( 'ul.cst-pagina' ).hide( ).end( )
				);
				jQuery( 'div.cst-list' ).cst_scroll_list( );
			}
		});
	}
	
	$.fn.cst_scroll_list = function( options ) {
		var defaults = {
			bottom_add: 100
		}
		var options = $.extend(defaults, options);
		
		var list = jQuery( this );
		list.find( 'ul.cst-pagina' ).hide( );
		
		var firing = false;
		
		jQuery( window ).scroll( function() {
			if( firing ) return;
			
			var view_h = window.innerHeight ? window.innerHeight : jQuery(window).height();

			if( view_h + jQuery( this ).scrollTop() > jQuery( 'body' ).height( ) - options.bottom_add ) {
				firing = true;
				var next_link = jQuery( '.cst-pagina:last .cst-button-next ', list )
				if( next_link[0] ) {
					var loading = jQuery( '<div class="cst-nav-loading">'+reload_i18n.loading+'..</div>' ).appendTo( list )
									
					jQuery.ajax({
						url: next_link.attr( 'href' )+' ',
						success: function( r ) {
							loading.remove( )
							jQuery( r )
								.find( 'div.cst-list' )
								.find( 'ul.cst-pagina' ).hide( ).end( )
								.appendTo( list )
							firing = false;
						}
					})
				} else {
					jQuery( document ).unbind( 'scroll' );
				}
			}
		} );
	}
})(jQuery);
