ListingsSectionVisualSearch = function(){
	this.ITEMS_PER_PAGE = 5;
	
	this.Page = 1;
	this.Pages = 0;
	
	this.$form = $j("#ls_visualsearch form");
	this.$container = $j("#ls_visualsearch .container");
	this.$results = this.$container.find(".results ul");	
}

ListingsSectionVisualSearch.prototype.Search = function(){
	objVisualSearch = this;
	this.$container.find(".noresults").fadeOut();
	this.$results.fadeTo("normal", 0.2);
	$j.post(location.pathname, this.$form.serialize(), function(sResponse){
		try{
			objVisualSearch.$results.empty();
			eval("var aListings = " + sResponse);
			
			if(aListings.length != 0){
				for(i=0; i<aListings.length; i++){
					listing = aListings[i];
					if(listing.thumbnail == "") continue;
					objVisualSearch.$results.append($j("<li><a href=\"" + listing.url + "\"><img src=\"" + listing.thumbnail + "\" alt=\"\" /><span>" + listing.name + "</span></a></li>"));
				}
				
				objVisualSearch.Listings = aListings;
				objVisualSearch.Pages = Math.ceil(objVisualSearch.Listings.length / objVisualSearch.ITEMS_PER_PAGE);
				
				objVisualSearch.ItemWidth = objVisualSearch.$results.find("li").outerWidth(true);
				$j("#ls_visualsearch .container .results ul").width(objVisualSearch.ItemWidth * objVisualSearch.Listings.length);
				
				objVisualSearch.SetPage(1);
				
				objVisualSearch.$results.stop().fadeTo("normal", 1);
			}
			else{
				this.Page = 1;
				this.Pages = 0;
				objVisualSearch.$results.fadeTo("normal", 0);
				objVisualSearch.$container.stop().find(".noresults").fadeIn();
			}
		}
		catch(e){}
	});
}

ListingsSectionVisualSearch.prototype.ChangePage = function(iStep){
	iPage = this.Page + iStep;
	if(iPage < 1) iPage = 1;
	if(iPage > this.Pages) iPage = this.Pages;
	if(iPage != this.Page){
		this.SetPage(iPage);
	}
}

ListingsSectionVisualSearch.prototype.SetPage = function(iPage){
	if(iPage < 1 || iPage > this.Pages) return;
	this.Page = iPage;
	this.$results.animate({left: -((this.ItemWidth * this.ITEMS_PER_PAGE) * (this.Page - 1))});
}

$j(function(){
	VisualSearch = new ListingsSectionVisualSearch();
	
	VisualSearch.$form.find("select").change(function(){
		VisualSearch.Search();
	});
	
	VisualSearch.$form.find("input[type=checkbox]").click(function(){
		VisualSearch.Search();
	});
	
	VisualSearch.$container.find(".previous a").click(function(){
		VisualSearch.ChangePage(-1);
		return false;
	});
	
	VisualSearch.$container.find(".next a").click(function(){
		VisualSearch.ChangePage(1);
		return false;
	});
	
	VisualSearch.Search();
});
