
var $j = jQuery.noConflict();
$j(document).ready(function(){

	$j("div.scrollable").scrollable({
		size: 1,
		items: '#thumbs',
		hoverClass: 'hover',
		next:'.nextPage',
		prev:'.prevPage',
		speed: 400,
		keyboard: false,
		clickable: false
	}).navigator();

	// get access to the API
	var api = $j("div.scrollable").data("scrollable");
	var s_total = 1;
	var s_now = 1;
	var end_reached = false;
	var paged = 1; // We already show 2 posts, so AJAX start with 3rd page.

	// do something upon scroll
	api.onSeek(function() {
		s_total = this.getSize() / 3;
		s_now = this.getIndex() + 1;
		if(s_now <= 2 ){
			$j(".left.browse").hide();
		}else{
			$j(".left.browse").show();
		}
	});

	$j(".right.browse").click(function() {
		//console.info("TOtal is " + s_total + " NOw @ " + s_now);
		//if(s_total == (s_now + 2)) {
		if(end_reached) {
			//console.info("No more posts found");
		}
		else {
			//console.info("Load another item now......");
			addDivItem(); replaceDivItem();
		}
	});
	$j(".left.browse").click(function() {
		if(s_now == 3){}
	});

	$j(".scrollable .loading").live("click", function(){
    	//console.info("Working... ");
	    $j(this).remove();
	});

	function addDivItem() {
    	// get handle to scrollable API
		var api = $j("div.scrollable").data("scrollable");
	    // use API to add our new item. after the item is being added seek to the end
		api.addItem($j("#loading div.loading").clone());
		api.end();
	}

	$j('#featured .nextPage').bind("ajaxSend", function() {
		$j(this).hide();
	}).bind("ajaxComplete", function() {
		if(end_reached) { $j(this).hide(); } else { $j(this).show(); }
	});

	$j('#featured .prevPage').bind("click", function() {
		$j('#featured .nextPage').show();
	});

	function replaceDivItem() {
    	// get handle to scrollable API
		var api = $j("div.scrollable").data("scrollable");
		$j.ajax( {
			url: template_url + '/ajax.php',
			type: 'get',
			data: "paged="+paged,
			success: function( r ) {
				$j(".scrollable .loading").trigger('click');
				if($j.trim(r) == '') {
					//alert('No older posts present to show!');
					end_reached = true;
				} else {
					if($j(r).find("h2").length < 3) end_reached = true;
	    				api.addItem(r);
					paged = paged + 1;
				}
				api.end();
			},
			error: function( r ) {
				$j(".scrollable .loading").trigger('click');
				//alert('Oops! Sorry unable to load more posts!');
				api.prev();
			}
		});
	}
});
