$(document).ready(function() {
    var type;
	var id;
	var params = $.getUrlParams();

	var curr = $("#currCount").html();
	var total = $("#totalCount").html();
	var quoteCount = $(".seqItem").length;
	
	if (total == 1) {
		$("#anotherItem").hide();
		$("#anotherBlock").html('&nbsp;');
		$("#backItem").hide();
		if (type = 'quote') {
			$("#seqCount").hide();
		}
	} else if (curr == 1 && quoteCount < total) {
		$("#backItem").hide();
	}

	$('#anotherItem').click(function() {
		curr++;
		if (curr > total) {
			curr = 1;
			var another = $(".seqItem").first();
		} else {
			var another = $(".seqItem:visible").next();
		}

	// get more quotes if we've hit the edge
		if (curr >= quoteCount && total > quoteCount) {
			$.ajax({
				async: false,				
				url: "/quotebook-feed?type=" + params['type'] + "&id=" + params['id'] + "&offset=" + curr,
				success: function(quotes){
					$("#seqBlock").append(quotes);
				},
				complete: function(){
					quoteCount = $(".seqItem").length;
				}
			});
		}

	// display new item	
		$(".seqItem:visible").hide();
		another.fadeIn();
	   	setCurrCount(curr);
	});

	$('#backItem').click(function() {
		curr--;
		if (curr <= 0) { 
			curr = total;
			var back = $(".seqItem").last();
		} else {
			var back = $(".seqItem:visible").prev();
		}

	// display new item	
		$(".seqItem:visible").hide();
		back.fadeIn();
	   	setCurrCount(curr);
	});
	
	$('#backBlock').hover(
		function() {
			$('#backBlock').addClass('hoverBlock');
			$('#backBlock').find('img').attr('src', '/img/arrow-left-over.png');
		}, 
		function() {
			$('#backBlock').removeClass('hoverBlock');
			$('#backBlock').find('img').attr('src', '/img/arrow-left.png');
		}
	);
	
	$('#anotherBlock').hover(
		function() {
			$('#anotherBlock').addClass('hoverBlock');
			$('#anotherBlock').find('img').attr('src', '/img/arrow-right-over.png');
		}, 
		function() {
			$('#anotherBlock').removeClass('hoverBlock');
			$('#anotherBlock').find('img').attr('src', '/img/arrow-right.png');
		}
	);

	function setCurrCount(curr) 
	{
		$("#currCount").html(curr);
		if (curr != 1 || quoteCount == total) {
			$("#backItem").show();
		} else if (curr == 1 && quoteCount < total) {
			$("#backItem").hide();
		}
	}

// dropdown onchange
	$("#source").change(function() {
    	window.location = '/soup-shack/quotebook/source/' + $(this).val() + '/';
    	return false;
	});

	$("#place").change(function() {
    	window.location = '/soup-shack/quotebook/place/' + $(this).val() + '/';
    	return false;
	});	
});

$.extend({
	getUrlParams: function(){
		var vars = [], hash;
		vars.push('type');		
		vars.push('id');		
		var pieces = window.location.href.replace('http://slammo.com/soup-shack/quotebook/', '').split('/');
		if (pieces.length == 3) {
			vars['type'] = pieces[0];
			vars['id'] = pieces[1];
		} else if (pieces.length == 2) {
			vars['type'] = 'quote';
			vars['id'] = pieces[0];
		} else {
			vars['type'] = 'all';
			vars['id'] = 0;
		}
		return vars;
	}
});


