// JavaScript Document


var RESULTCOLS = 4;

var SPEED_MOVE =1000;
var SPEED_FADE =1000;
var SPEED_RESIZE = 500;
var INITIALISED  = false;

var RESULT_WIDTH = 175;
var RESULT_HEIGHT = 162;
var ROW_MARGIN = 12;
var COL_MARGIN = 12;

function SearchResults(objects) {

	
	$("#refinableProductsContainer #noProducts").fadeOut(1);
	//$(".productsContainer #noProducts").css("display", "block");
	this.results = [];
	
	for (var i=0; i<objects.size(); i++) {
		this.results.push(new SearchResult($(objects.get(i)), i));	
	}
	
	this.initFilterOptions();
	
	this.filter = {};
	

	
	var me = this;
	$(window).load(function() { me.updateFilter() });
	
	// bind the events
	$("#resultsFilter select").bind("change", function() {me.updateFilter()});
	
}


SearchResults.prototype.initFilterOptions = function () {
	// =========================
	// lamp cap
	// =========================
	var lampCaps = [];
	var numBulbOptions = [];
	var lampShapes = [];
	var brands = [];
	
	for (var i=0; i<this.results.length; i++) {
		
		if	( ($.inArray(this.results[i].data.lampCap, lampCaps) == -1)  &&  (this.results[i].data.lampCap) ) {
				lampCaps.push(this.results[i].data.lampCap);
		}
		
		if ( ($.inArray(this.results[i].data.lamps, numBulbOptions) == -1)  &&  (this.results[i].data.lamps) ) {	
			numBulbOptions.push(this.results[i].data.lamps);
		}
		
		if ( ($.inArray(this.results[i].data.lampShape, lampShapes) == -1)  &&  (this.results[i].data.lampShape) ) {	
			lampShapes.push(this.results[i].data.lampShape);
		}
		
		if ( ($.inArray(this.results[i].data.brand, brands) == -1)  &&  (this.results[i].data.brand) ) {
			brands.push(this.results[i].data.brand);
		}
		
	}
	
	if (brands.length > 1) {
		$("#brand").append('<option value="">Any</option>')
		brands.sort();
		for (var i=0; i<brands.length; i++) {
			$("#brand").append('<option value="' + brands[i] + '">' + brands[i]  + '</option>')
		}
		$(".brandOptions").show();
		
	} else {
		$(".brandOptions").hide();
	}
	
	if (lampShapes.length > 1) {
		$("#lampShape").append('<option value="">Any</option>')
		for (var i=0; i<lampShapes.length; i++) {
			$("#lampShape").append('<option value="' + lampShapes[i] + '">' + lampShapes[i]  + '</option>')
		}
		$(".lampShapeOptions").show();
	} else {
		$(".lampShapeOptions").hide();
	}
	
	
	if (lampCaps.length > 1) {
		$("#lampCap").append('<option value="">Any</option>')
		for (var i=0; i<lampCaps.length; i++) {
			$("#lampCap").append('<option value="' + lampCaps[i] + '">' + lampCaps[i]  + '</option>')
		}
		$(".lampCapOptions").show();
	} else {
		$(".lampCapOptions").hide();
	}
	
	
	numBulbOptions.sort();
	if (numBulbOptions.length > 1) {
		$("#maxLamps").append('<option value="0">Any</option>')
		$("#minLamps").append('<option value="0">Any</option>')
		for (var i=0; i<numBulbOptions.length; i++) {
			$("#maxLamps").append('<option value="' + numBulbOptions[i] + '">' + numBulbOptions[i]  + '</option>');
			$("#minLamps").append('<option value="' + numBulbOptions[i] + '">' + numBulbOptions[i]  + '</option>');
		}
		$(".numberOfBulbsOptions").show();
	} else {
		$(".numberOfBulbsOptions").hide();
	}
}



SearchResults.prototype.updateFilter = function () {
	this.filter.maxPrice = $("#maxPrice option:selected").val();
	this.filter.minPrice = $("#minPrice option:selected").val();
	this.filter.maxLamps = $("#maxLamps option:selected").val();
	this.filter.minLamps = $("#minLamps option:selected").val();
	this.filter.lampCap = $("#lampCap option:selected").val() || "";
	this.filter.lampShape = $("#lampShape option:selected").val() || "";
	this.filter.brand = $("#brand option:selected").val() || "";
	// sort this.results here
	
	
	// set the indexes of each result
	var index=0;
	for (var i=0; i<this.results.length; i++) {
		this.results[i].setVisible(this.filter);

		if (this.results[i].visible) {
			this.results[i].index = index;
			this.results[i].setLocation();
			
			index++;
		}
		//this.results[i].move();
	}

	this.setContainerHeight();
	
	this.showNoResultsMsg();
}

SearchResults.prototype.showNoResultsMsg = function() {
	if (this.visibleCount() > 0) {
		$("#refinableProductsContainer #noProducts").fadeOut(SPEED_FADE);
	} else {
		$("#refinableProductsContainer #noProducts").fadeIn(SPEED_FADE);
	}
}


SearchResults.prototype.moveAll = function () {
	for (var i=0; i<this.results.length; i++) {
		this.results[i].move();
	}
}

SearchResults.prototype.setContainerHeight = function() {
	var currentHeight = parseInt($("#refinableProductsContainer").outerHeight());
	var newHeight = this.rowCount() * (RESULT_HEIGHT + ROW_MARGIN);
	
	var increase = newHeight - currentHeight;

	var me = this;
	
	if (increase > 0) {	// we're getting bigger, rezize the box then move the products
		if (INITIALISED) {
			$("#refinableProductsContainer").animate(
				{"height": "+=" + increase + "px"},
				SPEED_RESIZE,
				"swing",
				function () {
					for (var i=0; i<me.results.length; i++) {
						me.results[i].move();
					}
				}
			);
		} else {
				$("#refinableProductsContainer").css("height", newHeight + "px");
				me.moveAll();
				INITIALISED = true;	// next time we can animate rather than jumping...
	
		}
		
	} else {	// we're getting smaller	do the product then resize the box
	
		me.moveAll()
		
		window.setTimeout('$("#refinableProductsContainer").animate({"height": "+=' + increase + 'px"}, ' + SPEED_RESIZE + ', "swing")', SPEED_MOVE);
		
	}

}

SearchResults.prototype.rowCount = function() {
	return Math.ceil(this.visibleCount()/RESULTCOLS);
}

SearchResults.prototype.visibleCount = function() {
	var count=0;
	for (var i=0; i<this.results.length; i++) {
		if (this.results[i].visible) {
			count++;
		}
	}
	return (count);
}


function SearchResult(object, index) {
	// pass in a jquery object
	this.WIDTH = RESULT_WIDTH + COL_MARGIN;
	this.HEIGHT = RESULT_HEIGHT + ROW_MARGIN;
	this.obj = object;
	this.index = index;
	this.visible = true;
	
	
	this.data = JSON.parse(object.find(".sortingData").val())
	
	this.setLocation();
	
	this.obj.css("left", (this.left * this.WIDTH) + "px");
	this.obj.css("top", (this.top * this.HEIGHT) + "px");
	this.obj.css("position", "absolute");
}


SearchResult.prototype.setVisible = function(filter) {
	this.visible = true;
	
	// Price
	if ($.toNum(this.data.price) > $.toNum(filter.maxPrice)) {
		this.visible=false;
	}
	
	if ($.toNum(this.data.price) < $.toNum(filter.minPrice)) {
		this.visible=false;
	}
	
	// number of bulbs
	if (($.toNum(filter.maxLamps) > 0) && ($.toNum(this.data.lamps) > $.toNum(filter.maxLamps))) {
		this.visible=false;
	}
	if (($.toNum(filter.minLamps) > 0) && ($.toNum(this.data.lamps) < $.toNum(filter.minLamps))) {
		this.visible=false;
	}
	
	// lamp cap
	if ((filter.lampCap != "") && (this.data.lampCap != filter.lampCap)) {
		this.visible=false;
	}
	
	// lamp shape
	if ((filter.lampShape != "") && (this.data.lampShape != filter.lampShape)) {
		this.visible=false;
	}
	
	// brand
	if ((filter.brand != "") && (this.data.brand != filter.brand)) {
		this.visible=false;
	}
	
}



SearchResult.prototype.setLocation = function() {
	this.left = (this.index % RESULTCOLS);
	this.top = Math.floor(this.index / RESULTCOLS);
	//console.log(this.index + " :  " + this.left + " : " + this.WIDTH);
}


SearchResult.prototype.move = function() {
	
	// first move the object to the right place if it's already invisible
	if ((this.obj.css('display') == 'none')) {
		this.obj.css(
			{
				display: 'block',
				opacity: 0,
				left: this.left * this.WIDTH + "px",
				top: this.top * this.HEIGHT + "px"
			}
		);
	}
	
	var FADED_OPACITY = 0;
	
	// fade in / out and move to new positions
	var me = this;
	this.obj.stop();	// stop previous animations if they haven't finished yet...
	this.obj.animate(
			{
				left: this.left * this.WIDTH + "px",
				top: this.top * this.HEIGHT + "px",
				opacity: (this.visible ? 1 : FADED_OPACITY)
			},
			{
				easing: "swing",
				duration: SPEED_MOVE,
				complete: function() {
						if ($(this).css("opacity") == FADED_OPACITY) {
							$(this).css({
									"display" : 'none',
									"left" : '0px',
									'top' : '0px'
										});	
						}
				}
			}
			
	);

}

SearchResult.prototype.removeInvisible = function () {

	if ($(this).css("opacity") == 0.5) {
		$(this).css({
					"display" : "none",
					"left" : '0px'
					});	
	}
}


