var currentPage = 1;
var searchString;

$(document).ready(function() {
	$("#pages").show();
	$("#noResult").show();
	
	searchString = $("#oldSearch").val();
	if ($("#nbPages").val()==1) $("#pages").hide();
	$("#previousPage").click(function() { search(currentPage-1); });
	$("#nextPage").click(function() { search(currentPage+1); });
	$(".pageLink").click(function() { search($(this).html()); });
});

function search(page) {
	DwrAssociationSearchService.getTableContent($("#idAssociationCategory").val(),null,searchString, page, $("#locale").val(),$("#resultsToDisplay").val(),$("#descriptionLength").val(), function(model) {
		currentPage = model.currentPage;
		$("#results").empty();
		for (i=0;i<model.lines.length;i+=1) {
			var line = "<li id=\"";
			line += model.lines[i].idName+"\">";
			line += '<div class="logo">';
			line += '<a href="/presentation/';
			line += model.lines[i].contentUrl;			
			line += '"><img src="';
			line += model.lines[i].logoMicro;
			line += '" alt="';
			line += model.lines[i].name;
			line += '"></a>';
			line += '</div>';
			line += '<div class="text">';
			line += '<h3><a href="/presentation/';
			line += model.lines[i].contentUrl;			
			line += '">';
			line += model.lines[i].name;
			line += '</a></h3>';
			line += '<p>';
			line += model.lines[i].description;
			line += '<a href="/presentation/';
			line += model.lines[i].contentUrl;			
			line += '">';
			line += $("#choose").val();
			line += '</a></p>';
			line += '</div>';
			line += '</li>';
			$("#results").append(line);
		}
		$("#pageLinks").empty();
		var lowerEnd;
		var higherEnd;
		if (model.nbPages<10) {
			lowerEnd = 1;
			higherEnd = model.nbPages;
			
			if (model.nbPages==1) {
				$("#pages").hide();
			} else {
				$("#pages").show();
			}
		} else if (currentPage < 6) {
			lowerEnd = 1;
			higherEnd = 9;
		} else if (currentPage+4 > model.nbPages) {
			higherEnd = model.nbPages;
			lowerEnd = model.nbPages-8;
		}
		else {
			higherEnd = currentPage+4;
			lowerEnd = currentPage-4;
		}
		for (j=lowerEnd; j<=higherEnd; j+=1) {
			var span = "<li id=\"pageli";
			span += j;
			span +="\"><a href=\"#\" title=\"";
			span += $("#gotopage").val();
			span += "\" class=\"pageLink\" id=\"page";
			span += j;
			span += "\">";
			span += j;
			span += "</a></li>";
			$("#pageLinks").append(span);
		}
		$(".pageLink").click(function() { 
			search($(this).html());
		});
		$("#pageli"+currentPage).addClass("current");
		if (lowerEnd==currentPage)
			$("#previousPage").addClass("disabled");
		else
			$("#previousPage").removeClass("disabled");
		if (higherEnd==currentPage)
			$("#nextPage").addClass("disabled");
		else
			$("#nextPage").removeClass("disabled");
		$("#pagexony").empty();
		$("#pagexony").append(model.currentPageMessage);
	});
}