

jQuery(document).ready(function($){
	init_rgh();	
});

function init_rgh(){
	jQuery('.rh_grid').RHGallery({});
	jQuery('.rh_grid_manual').each(function(i,el){
		new CBPGridGallery( el, {} );	
	});
}

;;
(function( $ ){
	var methods = {
		init : function( options ) {
			var _default = $.extend( {
				test:'',
				max_retries:3,
				scrolloffset:'',
				autoload: true,
				slide_more: 3
			}, (options||{}));
						
			return this.each(function(){
				options = $.extend(_default, ($(this).data('options')||{}) );				
				gallery = new RHGallery( this, options );
				$(this).data('RHGallery', gallery);
			});
		}
	};
	
function RHGallery( element, options ){

	var t = this;
	t.loaded = false;
	t.options = options;
	t.options.autoload = parseInt( t.options.autoload );
	t.handle_scroll = handle_scroll;
	t.load = load;
	t.next_url = options.source;
	t.have_posts = false;
	t.scroll_lockdown = false;
	t.first_time = true;
	
	t.gridgallery = null;
	t.animonscroll = null;

	t.loading = loading;
	t.load_retries = 0;
	
	t.init_grid = init_grid;
	
	init();
	
	function init(){
		listeners();
		if( t.options.prerender ){
			init_grid( element );
		}
		load();
	}
	
	function listeners(){
		if( t.options.autoload ){
			window.addEventListener( 'scroll', function() {
				t.handle_scroll();
			}, false );			
		}
	}
	
	function load(){			
		if( ''==t.next_url ) return;

		t.loading(true);
		
		if( 'function' == typeof t.next_url ){
			t.next_url( t );
		}else{
			jQuery.ajax({
	       		url: t.next_url,
	       		data: {
					'numberposts': options.numberposts||9
				},
				dataType: 'html',
	       		success: function(data){  		
					t.have_posts = ( $(data).find('.griditem').length > 0 );
					_callback = options.render||render;
					_callback( element, data );		
	       		},
				error: function(){	
					if( t.options.max_retries > t.load_retries++ ){
						t.load();
					}
				}     
	    	});//jQuery.ajax			
		}
	}
	
	function loading(loading){	
		if(loading){
			$(element).addClass('rhg-loading');
		}else{
			$(element).removeClass('rhg-loading');
		}
	}

	function render(el,data){
		if( data ){
			var next_posts = $(data).find('#nextposts');
			var next_url = next_posts.data('nextposts');
			t.next_url = next_url;
			
			$(el).data('next_url', next_url);	
			if( $(data).find('.griditem').length > 0 ){
				$(data).find('.griditem').each(function(i,item){
					if( t.options.direct_link ){
						var url = $(item).data('url') || '';
						$(el).find('section.grid-wrap ul.rhg_grid').append( 
							$('<li></li>')
								.attr('data-url', url)
								.attr('data-target', (t.options.link_target||'_self') )
								.append(item)
						);	
					}else{
						$(el).find('section.grid-wrap ul.rhg_grid').append( 
							$('<li></li>').append(item)
						);					
					}
				});
				
				$(data).find('.slideshow-item').each(function(i,item){
					$(el).find('section.slideshow ul.rhg_slideshow_items')
						.append(
							$('<li></li>').append(item)
						)
					;
				});
				
				if( t.options.classes && t.options.classes.length ){
					$(el).addClass( t.options.classes.join(' ') );
				}
				
				if( t.options.link_target && ''!=t.options.link_target ){
					$(el).find('.grid-gallery-link').attr('target', t.options.link_target );
				}
				
				$(el).find('section.grid-wrap .griditem-img').each(function(i,fig){
					if( $(this).find('img').length==0 ){
						$(this).parents('li').addClass('rhg-no-image');
					}			
				});	
									
				init_grid( el );
			
		
			}		
		}

		
		loading(false);
		t.scroll_lockdown = false;	
	}
	
	function init_grid( el ){
		if( t.first_time ){		
			if( ! $(el).attr('id') ){
				$(el).attr('id', 'grid-' + new Date().valueOf() );
			}

			var settings = {
				'openSlideshow':handle_slideshow_more,
				'navigate':handle_slideshow_more
			};
		
			if( parseInt(t.options.sameheight) ){
				settings.makeSameHeight = true;
			}
		
			if( t.options && t.options.enableslideshow && t.options.enableslideshow=='0' ){
				settings.enableslideshow = false;
			}

			t.gridgallery = new CBPGridGallery( el, settings );		

			$(t.gridgallery.slideshow_container).find('.rhg_slideshow').swipe( {
				swipe:function(event, direction, distance, duration, fingerCount, fingerData) {
					switch (direction){
						case 'left':					
							t.gridgallery._navigate('next');	
							break;
						case 'right':
							t.gridgallery._navigate('prev');
							break;
					} 
				},
         		threshold:10//default 75px
     		});			
			
		}else{		
			t.gridgallery._addItems();	
		}

		t.first_time = false;
	}
	
	function handle_slideshow_more( o, w ){
		var slide_more = parseInt( t.options.slide_more ) + w;	
		if( !t.scroll_lockdown && ((o.itemsCount-o.current) <= slide_more) ){
			//trigger more.
			t.scroll_lockdown = true;
			t.load();
			$(element).trigger('slideshow_more');	
		}
	}
	
	function handle_scroll(){
		if( false===t.have_posts ) return;
		var _view = $(element);
		if( _view.is(':visible') && !t.scroll_lockdown){
			// Get the positon of the more_items div if all your items are ind objects and they push down the more_item will it alwase be in a different pos
			var items_div = _view;
			var items_div_offset = items_div.offset();
			// extra calibration for mobil phones
			if (window.mobile){
				paddingForMobile = 1000;
			}else{
				paddingForMobile = 0;
			}

			if( ($(window).scrollTop() + $(window).height()) == $(document).height() ){
				//scroll hit the bottom
				t.scroll_lockdown = true;
				t.load();	
				$(element).trigger('more_events_scroll');				
			}else{
				//bottom of list passed a certain offset
				var _offset =  ( t.options.scrolloffset && ''!=t.options.scrolloffset ) ? t.options.scrolloffset : ( -1 * parseInt($(window).height()) );
				var _offset = _offset -paddingForMobile ; 
				document_bottom = $(document).scrollTop()+$(window).height();
				bottom_position = items_div_offset.top + items_div.outerHeight();				
				if ( document_bottom > (bottom_position + _offset) ){
					t.scroll_lockdown = true;
					t.load();
					$(element).trigger('more_events_scroll');			
				}
			}						
		}		
	}		
}//end of RHGallery
		
	$.fn.RHGallery = function( method ) {			
	    if ( methods[method] ) {
			return methods[method].apply( this, Array.prototype.slice.call( arguments, 1 ));
	    } else if ( typeof method === 'object' || ! method ) {
			return methods.init.apply( this, arguments );
	    } else {
			$.error( 'Method ' +  method + ' does not exist on jQuery.RHGallery' );
	    }    
	};
})( jQuery );

/*
function _console(_msg){
	if( jQuery('#debug_console').length==0 ){
		jQuery('BODY').append('<div id="debug_console" class="debug-console"></div>');
	}
	jQuery('#debug_console').prepend('<div>'+_msg+'</div>');
}
*/