// JavaScript Document

var RESULTCOLS = 4;

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

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

var SHOWING_SEARCH_RESULTS = false;

function SearchResults(objects, $container, showNoProductsCallBack) {

	this.INITIALISED = 0;

	this.name = "no heading";
	
	$("#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));	
	}
	
	
	

	// find out src
	var script = $('script[src*="results.js"]:first');
	
	if ( script.length !== 0 ) {
		// Uncompressed
		params = $.getParams(script.attr("src"));
		
		SHOWING_SEARCH_RESULTS = params.results ? true : false;
		
		//console.log(script);
	}

	
	

	this.$container = $container;
	
	if (this.$container.parents(".sectionContainer").length > 0) {
		this.$container = this.$container.parents(".sectionContainer");
		this.name = this.$container.find(".ui-widget-header").text();
	}
	
	this.filter = {};
	

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

	
	$(this).bind("checkNoProducts", showNoProductsCallBack);
	
}

// this function is no longer an instance menthod  it belongs to the class instead
SearchResults.initFilterOptions = function (results) {
	
	
	// =========================
	// lamp cap
	// =========================
	var lampCaps = [];
	var numBulbOptions = [];
	var lampShapes = [];
	var brands = [];
	var voltages = [];
	var wattages = [];
	var productTypes = [];
	
	var bulbsOnly = true;

	
	
	for (var i=0; i<results.length; i++) {
		
		if	( ($.inArray(results[i].data.lampCap, lampCaps) == -1)  &&  (results[i].data.lampCap) ) {
				lampCaps.push(results[i].data.lampCap);
		}
		
		if ( ($.inArray(results[i].data.lamps, numBulbOptions) == -1)  &&  (results[i].data.lamps) ) {	
			numBulbOptions.push(results[i].data.lamps);
		}
		
		if ( ($.inArray(results[i].data.lampShape, lampShapes) == -1)  &&  (results[i].data.lampShape) ) {	
			lampShapes.push(results[i].data.lampShape);
		}
		
		if ( ($.inArray(results[i].data.brand, brands) == -1)  &&  (results[i].data.brand) ) {
			brands.push(results[i].data.brand);
		}
		
		if ( ($.inArray(results[i].data.volts, voltages) == -1)  &&  (results[i].data.volts) ) {
			voltages.push(results[i].data.volts);
		}
		
		if ( ($.inArray(results[i].data.watts, wattages) == -1)  &&  (results[i].data.watts) ) {
			wattages.push(results[i].data.watts);
		}
		
		if ( ($.inArray(results[i].data.type, productTypes) == -1)  &&  (results[i].data.type) ) {
			productTypes.push(results[i].data.type);
			
			if (results[i].data.type.indexOf('F') > -1) {
				bulbsOnly = false;
			}
		}
		
	}
	
	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++) {
			var selected = "";
			if ((typeof(INITIAL_REFINE_OPTIONS) != "undefined") && (typeof(INITIAL_REFINE_OPTIONS.lampShape) != "undefined")) {
				selected = (lampShapes[i].toLowerCase() == INITIAL_REFINE_OPTIONS.lampShape.toLowerCase() ? "selected" : "");
			}
			$("#lampShape").append('<option value="' + lampShapes[i] + '" ' + selected + '>' + 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();
	}
	
	
	if (!bulbsOnly && !SHOWING_SEARCH_RESULTS)  {
		// this page contains light fittings, not just lamps, so hide the options for voltage and wattage
		$(".voltageOptions, .wattageOptions").hide();
	} else {
		
		if (voltages.length > 1) {
			$("#voltage").append('<option value="">Any</option>')
			voltages = voltages.sort(function(a,b){ return $.toNum(a) - $.toNum(b) });
			for (var i=0; i<voltages.length; i++) {
				$("#voltage").append('<option value="' + voltages[i] + '">' + voltages[i]  + '</option>');
			}
			$(".voltageOptions").show();
		} else {
			$(".voltageOptions").hide();
		}
		
			
		if (wattages.length > 1) {
			$("#wattage").append('<option value="">Any</option>')
			wattages = wattages.sort(function(a,b){ return $.toNum(a) - $.toNum(b) });
			for (var i=0; i<wattages.length; i++) {
				if ((typeof(INITIAL_REFINE_OPTIONS) != "undefined") && (typeof(INITIAL_REFINE_OPTIONS.wattage) != "undefined")) {
					selected = (wattages[i].toLowerCase() == INITIAL_REFINE_OPTIONS.wattage.toLowerCase() ? "selected" : "");
				}
				$("#wattage").append('<option value="' + wattages[i] + '"' + selected + '>' + wattages[i]  + '</option>');
			}
			$(".wattageOptions").show();
		} else {
			$(".wattageOptions").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() || "";
	this.filter.wattage = $("#wattage option:selected").val() || "";
	this.filter.voltage = $("#voltage 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).trigger("checkNoProducts");
	//this.showNoResultsMsg();
}


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

SearchResults.prototype.setContainerHeight = function() {
	
	
	// $container might be a section container, or it might be a products container
	
	var $innerContainer = this.$container;
	var $outerContainer = null;
	if (this.$container.find(".ui-widget-header").length > 0) {
		$outerContainer = $innerContainer;
		$innerContainer = $outerContainer.find(".productsContainer");
	}
	
	var currentHeight = parseInt($innerContainer.outerHeight());
	
	var diff = 0;
	if ($outerContainer) {
		diff = parseInt($outerContainer.outerHeight()) - currentHeight;
	}
	

	var newHeight = (this.rowCount() * (RESULT_HEIGHT + ROW_MARGIN));
	
	var outerHeight = this.rowCount() > 0 ? newHeight + diff : 0;
	
	var me = this;

	//console.log(this.name + " : currentHeight: " + currentHeight + " innerHeight: " + innerHeight + "  newHeight: " + newHeight + "outerHeight: " + outerHeight);
	var increase = newHeight - currentHeight;
	
	//console.log("increase? : " + (increase > 0) );
	//console.log("row count: " + me.rowCount());

	

	if (increase > 0) {	// we're getting bigger, rezize the box then move the products
		if (this.INITIALISED > 0) {	// we increment by 1 when we initialise everuthing, then again when we read in the initial filter
			if ((me.rowCount() >=0) && ($outerContainer)) {
				$outerContainer.show();
			};
			
			$innerContainer.animate(
				{"height": "" + newHeight + "px"},
				SPEED_RESIZE,
				"swing",
				function () {
					me.moveAll();
					
				}
			);
			
		} else {
				$innerContainer.css("height", newHeight + "px");
			//	$outerContainer.css("height", outerHeight + "px");
				me.moveAll();
				this.INITIALISED ++;	// next time we can animate rather than jumping...
	
		}
		
	} else {	// we're getting smaller	do the product then resize the box
	
		
	
		me.moveAll();
		
		window.setTimeout(
			function() {
				if (me.INITIALISED > 0) {	// we increment by 1 when we initialise everuthing, then again when we read in the initial filter
			
					$innerContainer.animate(
											{"height": "" + newHeight + "px"}, 
											SPEED_RESIZE,
											"swing",
											function() {
												if ((me.rowCount() <=0) && ($outerContainer)) {
													$outerContainer.hide();
												};
											}
					);
					
				} else {
				
					$innerContainer.css("height", newHeight + "px");
					me.INITIALISED ++;	// next time we can animate rather than jumping...
					if ((me.rowCount() <=0) && ($outerContainer)) {
						$outerContainer.hide();
					};

				}
				// 	$outerContainer.animate({"height": + outerHeight + "px"},  SPEED_RESIZE, "swing", SPEED_MOVE);
			},
			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;
	}
	
	// voltage
	if ((filter.voltage != "") && (this.data.volts != filter.voltage)) {
		this.visible=false;
	}
	
	// wattage
	if ((filter.wattage != "") && (this.data.watts != filter.wattage)) {
		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'
					});	
	}
}



