var sidebarFilters = {
	options: {
		monthNamesShort: [ 'Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec' ],
		currencySymbol: '£'
	},
	
	requestIndex: 0,
	resultPopup: null,
	resultPopupTimeout: null,
	
	init: function() {
		var self = this;
		
		if($('body').hasClass('site-us-publishing') || $('body').hasClass('site-us-distribution')) {
			this.options.currencySymbol = '$';
		}
		
		if(!$('#filters').size()) {
			return;
		}
		
		this.resultPopup = $('<div />').attr('id', 'filter-result-popup');
		this.resultPopup.append($('<div />').addClass('indicator'));
		this.resultPopup.append($('<div />').addClass('message'));
		$('body').append(this.resultPopup);
		this.resultPopup.hide();

		this.resultPopup.hover(
			function() {
				window.clearTimeout(self.resultPopupTimeout);
				self.resultPopup.stop(true, true).show();
			},
			function() {
				window.clearTimeout(self.resultPopupTimeout);
				self.resultPopupTimeout = window.setTimeout(
					function() {
						self.resultPopup.stop(true, true).fadeOut('fast');
					},
					2000
					);
			}
			);

		$(window).bind(
			'scroll.sidebarfilterresults',
			function() {
				var filterContainer = $('#filters');
				var popupX = filterContainer.offset().left + filterContainer.outerWidth();
				
				var popupMinY = filterContainer.offset().top + 45;
				var popupMaxY = (filterContainer.offset().top + filterContainer.outerHeight()) - self.resultPopup.outerHeight();
				
				var scrollTop = ($(document.documentElement).scrollTop() || $(document.documentElement.ownerDocument.body).scrollTop());
				var scrollTopSpacing = 50;
			
				var popupY = Math.max(popupMinY, Math.min((scrollTop + scrollTopSpacing), popupMaxY));

				self.resultPopup.css( {
					left: popupX + 'px',
					top: popupY + 'px'
				});
			}
			);
		
		$(window).trigger('scroll.sidebarfilterresults');

		// Text			
		var textInput = $('#filter-search-text');
		
		if(textInput.size()) {
			textInput.data('last_value', textInput.val());
			
			window.setInterval(
				function() {
					if(textInput.val() != textInput.data('last_value')) {
						textInput.data('last_value', textInput.val());
						self.search();
					}
				},
				500
			);
		}
		
		/*
		$('#filter-search-text').data()
			.click( function(event) {
				self.search();
			})
			.change( function(event) {
				self.search();
			})
			.keyup( function(event) {
				self.search();
			});
		*/
	
		$('#filter-publisher input:checkbox').each( function() {
			if($(this).is(':checked')) {
				$(this).closest('label').addClass('selected');
			}
		});
	
		$('#filter-publisher label').click( function(event) {
			var checkbox = $('input[type="checkbox"]', this);
			
			if(checkbox.is(':checked')) {
				checkbox.removeAttr('checked');
				$(this).removeClass('selected');
			} else {
				checkbox.attr('checked', 'checked');
				$(this).addClass('selected');
			}
			
			self.search();
			return false;
		});

		// Price slider
		$('#filter-price-slider').slider( {
			range: true,
			min: 0,
			max: 110,
			step: 10,

			create: function(event, ui) {
				$('#filter-price label').hide();
				$('#filter-price input').hide();

				var limits = [ $(this).slider('option', 'min'), $(this).slider('option', 'max') ];
				var values = [ valueMin, valueMax ];

				var valueMin = parseInt($('#filter-price-min').val());
				values[0] = !isNaN(valueMin) ? Math.max(limits[0], Math.min(limits[1], valueMin)) : limits[0];
				
				var valueMax = parseInt($('#filter-price-max').val());
				values[1] = !isNaN(valueMax) ? Math.max(limits[0], Math.min(limits[1], valueMax)) : limits[1];

				$(this).slider('option', 'values', values);
				
				self.updatePriceDisplay(limits, values);
			},

			slide: function(event, ui) {
				var limits = [ $(this).slider('option', 'min'), $(this).slider('option', 'max') ];
				var values = [ ui.values[0], ui.values[1] ];
				
				$('#filter-price-min').val(((values[0] > limits[0]) && (values[0] < limits[1])) ? values[0] : '');
				$('#filter-price-max').val(((values[1] > limits[0]) && (values[1] < limits[1])) ? values[1] : '');

				self.updatePriceDisplay(limits, values);
			},

			stop: function(event, ui) {
				self.search();
			}
		});
		
		// Publish date
		$('#filter-publishdate').show();
	
		// Publish date slider
		$('#filter-publishdate-slider').slider( {
			range: true,
			min: -5,
			max: 12,
			step: 1,

			create: function(event, ui) {
				$('#filter-publishdate label').hide();
				$('#filter-publishdate input').hide();

				var limits = [ $(this).slider('option', 'min'), $(this).slider('option', 'max') ];
				var values = [ valueMin, valueMax ];

				var valueMin = parseInt($('#filter-publishdate-from').val());
				values[0] = !isNaN(valueMin) ? Math.max(limits[0], Math.min(limits[1], valueMin)) : limits[0];
				
				var valueMax = parseInt($('#filter-publishdate-to').val());
				values[1] = !isNaN(valueMax) ? Math.max(limits[0], Math.min(limits[1], valueMax)) : limits[1];

				$(this).slider('option', 'values', values);
				
				self.updatePublicationDateDisplay(limits, values);
			},

			slide: function(event, ui) {
				var limits = [ $(this).slider('option', 'min'), $(this).slider('option', 'max') ];
				var values = [ ui.values[0], ui.values[1] ];
				
				$('#filter-publishdate-from').val(((values[0] > limits[0]) && (values[0] < limits[1])) ? values[0] : '');
				$('#filter-publishdate-to').val(((values[1] > limits[0]) && (values[1] < limits[1])) ? values[1] : '');
	
				self.updatePublicationDateDisplay(limits, values);
			},
			
			stop: function(event, ui) {
				self.search();
			}
		});
	
		$('#filter-category li').each( function() {
			if($('ul', this).size()) {
				$('> label', this).append($('<div />').addClass('control'));
			}
		});
										
		$('#filter-category .control').click( function(event) {
			var control = $(this);
			
			if(control.hasClass('open')) {
				control.closest('li').find('> ul').slideUp();
				control.removeClass('open');
			} else {
				control.closest('li').find('> ul').slideDown();
				control.addClass('open');
			}
			
			return false;
		});
	
		$('#filter-category ul').hide();
		$('#filter-category ul:first').show();
	
		$('#filter-category input:checkbox').each( function() {
			if($(this).is(':checked')) {
				$(this).closest('label').addClass('selected');
			}
		});
	
		$('#filter-category label').click( function(event) {
			var checkbox = $('input[type="checkbox"]', this);
			
			if(checkbox.is(':checked')) {
				checkbox.removeAttr('checked');
				$(this).removeClass('selected');
			} else {
				checkbox.attr('checked', 'checked');
				$(this).addClass('selected');
			}
			
			self.search();
		
			return false;
		});

		$('#filter-internal input:checkbox').click( function(event) {
			self.search();
		});
	},
	
	updatePriceDisplay: function(limits, values) {
		var text = 'Everything';
		
		if((values[0] < limits[1]) && (values[1] > limits[0]) && ((values[0] > limits[0]) || (values[1] < limits[1]))) {
			if(values[0] == values[1]) {
				text = this.options.currencySymbol + values[0];
			} else if(values[1] >= limits[1]) {
				text = this.options.currencySymbol + values[0] + ' and over';
			} else if(values[0] == limits[0]) {
				text = 'Up to ' + this.options.currencySymbol + values[1];
			} else {
				text = this.options.currencySymbol + values[0] + ' - ' + this.options.currencySymbol + values[1];
			}
		}
		
		$('#filter-price-display').text(text);
	},
	
	updatePublicationDateDisplay: function(limits, values) {
		var currentDateTime = new Date();
	
		// From date
		var fromMonth = currentDateTime.getMonth() + 1;
		var fromYear = currentDateTime.getFullYear();
		
		if(values[0] < 0) {
			fromYear += values[0];
		} else {
			fromMonth += values[0];
			
			if(fromMonth > 12) {
				fromYear += Math.floor(fromMonth / 12);
				fromMonth = fromMonth % 12;
			}
		}
	
		// To date
		var toMonth = currentDateTime.getMonth() + 1;
		var toYear = currentDateTime.getFullYear();
	
		if(values[1] < 0) {
			toYear += values[1];
		} else {
			toMonth += values[1];
			
			if(toMonth > 12) {
				toYear += Math.floor(toMonth / 12);
				toMonth = toMonth % 12;
			}
		}
		
		var text = 'Everything';
		
		if((values[0] < limits[1]) && (values[1] > limits[0]) && ((values[0] > limits[0]) || (values[1] < limits[1]))) {
			if(values[0] == values[1]) {
				text = 'During ' + (this.options.monthNamesShort[fromMonth - 1] + ' ' + fromYear);
			} else if(values[1] >= limits[1]) {
				text = (this.options.monthNamesShort[fromMonth - 1] + ' ' + fromYear) + ' and after';
			} else if(values[0] == limits[0]) {
				text = 'Up to ' + (this.options.monthNamesShort[toMonth - 1] + ' ' + toYear);
			} else {
				text = (this.options.monthNamesShort[fromMonth - 1] + ' ' + fromYear) + ' - ' + (this.options.monthNamesShort[toMonth - 1] + ' ' + toYear);
			}
		}
		
		$('#filter-publishdate-display').text(text);
	},

	search: function() {
		var self = this;

		if(this.xhr) {
			this.xhr.abort();
		}
		
		var data = $('#filters :input').serializeArray();
		data.push( { name: 'offset', value: 0 } );
		data.push( { name: 'limit', value: 0 } );
		
		this.resultPopup.addClass('loading');
		$('.message', this.resultPopup).text('Searching...');
		this.resultPopup.fadeIn('fast');
		
		this.xhr = $.ajax({
			url: interfaceBaseURI + 'store/product_search',
			data: data,
			dataType: 'json',
			_requestIndex: ++this.requestIndex,

			success: function(data, status, jqXHR) {
				if(this._requestIndex === self.requestIndex) {
					self.resultPopup.removeClass('loading');

					if(data.count > 0) {
						var message = 'Found ' + data.count + ' books.<br />Click here to view them.';

						if(data.count == 1) {
							message = 'Found 1 book.<br />Click here to view it.';
						}

						var link = $('<a />');
						link.html(message);
						link.click( function() {
							$('#filters form').submit();
						});
						
						$('.message', self.resultPopup).empty().append(link);
					} else {
						$('.message', self.resultPopup).text('No products were found');
					}
					
					window.clearTimeout(self.resultPopupTimeout);
					self.resultPopupTimeout = window.setTimeout(
						function() {
							self.resultPopup.stop(true, true).fadeOut('fast');
						},
						10000
						);
				}
			},

			error: function(jqXHR, status) {
				if(status == 'abort') {
					return;
				}
				
				if(this._requestIndex === self.requestIndex) {
					window.clearTimeout(self.resultPopupTimeout);
					self.resultPopup.stop(true, true).fadeOut('fast');
				}
			}
		});
	}
};
	

$(document).ready( function() {
	sidebarFilters.init();

	$('#sidebar .panel-content-tree').each( function() {
		$('li', this).each( function() {
			var ul = $('ul', this);
			
			if(ul.size()) {
				var control = $('<div />').addClass('control');
				control.appendTo($('> a', this));

				control.click( function(event) {
					var control = $(this);
					
					if(control.hasClass('open')) {
						control.closest('li').find('> ul').slideUp();
						control.removeClass('open');
					} else {
						control.closest('li').find('> ul').slideDown();
						control.addClass('open');
					}
					
					return false;
				});

				ul.hide();
			}
		});
			
		$('.selected', this).each( function() {
			var control = $('.control', this);
	
			if(control.size()) {
				control.closest('li').find('> ul').show();
				control.addClass('open');
			}
		});
	});

	$('#sidebar #productlayout-selector a').click( function(event) {
		var thisElement = $(this);
		var currentElement = thisElement.siblings('.current');

		if(thisElement.is('.current')) {
			return false;
		}
				
		if(!currentElement.size()) {
			return false;
		}
				
		var newLayout = String(thisElement.attr('class')).match(/selector-(grid|simple|detail)/)[1];
		var oldLayout = String(currentElement.attr('class')).match(/selector-(grid|simple|detail)/)[1];

		thisElement.addClass('current');
		currentElement.removeClass('current');
		
		$('.productlayout').removeClass('productlayout-' + oldLayout).addClass('productlayout-' + newLayout);
				
		$.ajax( {
			type: 'POST',
			url: interfaceBaseURI + 'user/set_preference',
			dataType: 'json',
			data: {
				name: 'productlayout',
				value: newLayout
			}
		});
		
		return false;
	});
});
