$(function() {
	// default page
	var selectedList = 'companies';
	//pagination related
	var perPage = 20; // how many per page
	var currPage = 1; // starting page
	
	function init() {
		$('.types a').bind('click', function() { 
			selectedList = $(this).attr("id").substr(5); 
			currPage = 1;
			swap(); 
			paginate(); 
		});
		swap();
		paginate();
	}
	
	function swap(){
		// swap the links
		$('.types a').each(function() { 
				$(this).removeClass(); 
				if($(this).attr('id') == "link-"+selectedList) {
					$(this).addClass('selected');
				}
			});
		
		
		// swap the lists
		$('.list ul').hide();
		$('#'+selectedList).show();
	}
	
	function pageDown() {
		currPage--;
		paginate();
	}
	
	function pageUp() {
		currPage++;
		paginate();
	}
	
	function paginate () {
		//window.console.log(currPage);
		var total = $('#'+selectedList+' li').length;
		if(total > 0 ) {
			var numPages = Math.ceil(total/perPage);
		    var start = (currPage - 1) * perPage;
			var end = currPage * perPage;
			if(end > total) end = total;
			
		    var i = 0; 
		    $('#'+selectedList+' li').each( function() {
		        if(i >= start && i < end) {
		            $(this).show();
		        }else{
		            $(this).hide();
		        }
		        i++;
		    });
			
			// adjust the UI
			var startVal = start+1;
			$('.counter').html(startVal+'-'+end+' of <span class="total">'+total+'</span>');
			if(currPage <= 1 ){ // first page, or invalid input
				$('#prevpage').attr("src", "/img/btn_clients-prev-inactive.gif");
				$('#prevpage').unbind("click");
				$('#prevpage').unbind("mouseover");
				$('#prevpage').unbind("mouseout");
			}else{
				$('#prevpage').attr("src", "/img/btn_clients-prev.gif");
				$('#prevpage').bind("click", pageDown); 
				$('#prevpage').bind("mouseover", function() {$(this).attr("src", "/img/btn_clients-prev-hover.gif");});
				$('#prevpage').bind("mouseout", function() {$(this).attr("src", "/img/btn_clients-prev.gif");});
			}
			
			if(currPage == numPages){ // last page
				$('#nextpage').attr("src", "/img/btn_clients-next-inactive.gif");
				$("#nextpage").unbind("click");
				$("#nextpage").unbind("mouseover");				
				$("#nextpage").unbind("mouseout");				
			}else{
				$('#nextpage').attr("src", "/img/btn_clients-next.gif");
				$('#nextpage').bind("click", pageUp); 
				$("#nextpage").bind("mouseover", function() { $(this).attr("src", "/img/btn_clients-next-hover.gif"); });
				$("#nextpage").bind("mouseout", function() { $(this).attr("src", "/img/btn_clients-next.gif"); });
			}
		}

	}
	
	init();
});
