var FormController = function(element, options)
{
	var that = this;
	this.options = $.extend({	}, options);
	this.$element = $(element);

	var priceMin = Math.floor(Number($('#filter-priceMin').val())/10)*10;
	var priceMax = Math.floor(Number($('#filter-priceMax').val())/10 + 1)*10;
	var bearingMin = Number($('#filter-bearingMin').val());
	var bearingMax = Number($('#filter-bearingMax').val());

	this.updating = false;
	this.initializing = false;
	this.historyCount = 0;

	this.priceRangeSelect = new kff.widgets.AhornRangeSlider('.price-range-box', {
		steps: (priceMax - priceMin)/10,
		min: priceMin,
		max: priceMax,
		position: {a: Math.floor(Number($('#filter-priceFrom').val())/10)*10, b: Math.floor(Number($('#filter-priceTo').val())/10 + 1)*10},
		change: function(p)
		{
			$('#filter-priceFrom').val(p.a);
			$('#filter-priceTo').val(p.b);
			$('#filter-page').val(1);
			if(!that.initializing) that.addHistorySnap();
		}
	});
	
	if(bearingMax != bearingMin)
	{
		this.bearingRangeSelect = new kff.widgets.AhornSlider('.bearing-range-box', {
			steps: (bearingMax - bearingMin),
			min: bearingMin,
			max: bearingMax,
			position: $('#filter-bearing').val(),
			change: function(p)
			{
				$('#filter-bearing').val(p);
				$('#filter-page').val(1);
				if(!that.initializing) that.addHistorySnap();
			}
		});
	}
	else $('#h3-bearing').remove();
};

FormController.prototype.init = function()
{
	var that = this;
	this.active= true;
	this.initializing = true;

	$(window).bind( 'hashchange', function(e) {
		var hash = location.hash;
		that.setState(hash);
	});

	this.priceRangeSelect.init();
	$('#filter-priceFrom, #filter-priceTo').hide();

	if(this.bearingRangeSelect) this.bearingRangeSelect.init();
	$('#filter-bearing').hide();

	this.$element.find('input[type=checkbox], input[type=radio]').bind('click', function(){
		$('#filter-page').val(1);
		that.addHistorySnap();
	});
	this.$element.find('select').bind('change', function(){
		that.addHistorySnap();
	});
	this.$element.find('#filter-sortingDirA').bind('click', function(event){
		$('#filter-sortingDirD').removeClass('btn-active');
		$(this).addClass('btn-active');
		$('#filter-sortDir').val('a');
		that.addHistorySnap();
		event.preventDefault();
		return false;
	});
	this.$element.find('#filter-sortingDirD').bind('click', function(event){
		$('#filter-sortingDirA').removeClass('btn-active');
		$(this).addClass('btn-active');
		$('#filter-sortDir').val('b');
		that.addHistorySnap();
		event.preventDefault();
		return false;
	});

	this.$element.bind('submit', function(){
		return false;
	});

	$('.product-list-wrap').delegate('.paging a', 'click', function()
	{
		var page = $(this).attr('href');
		page = page.replace(/^.*\?page=/, '');
		$('#filter-page').val(page);
		that.addHistorySnap();
		return false;
	});
	this.initializing = false;

	if(this.historyCount == 0)
	{
		this.initialState = this.$element.serialize();
		$(window).trigger('hashchange');
	}
	//this.addHistorySnap();
}

FormController.prototype.unserialize = function(serialized)
{
	var unserialized = new Array();
	var p;
	$.each(serialized.split("&"), function(){
	    p = this.split("=");
	    unserialized[p[0]] = p[1];
	});
	return unserialized;
}

FormController.prototype.addHistorySnap = function()
{
	if(!this.updating)
	{
		var serialized = this.$element.serialize();

		var href = location.href + '';

		if(href.indexOf('?') != -1)
		{
			href = href.replace(/(\#.*)$/, '');
			href = href + '#' + serialized;
			location.href= href;
		}
		else location.hash = serialized;
	}
}

FormController.prototype.setState = function(stateHash)
{
	stateHash = stateHash.replace('#', '').replace(/%5B/g, '[').replace(/%5D/g, ']');

	var firstLoad = this.historyCount == 0 && stateHash == '';

	this.updating = true;

	if(stateHash == '')
	{
		stateHash = this.initialState;
	}

	var formData = this.unserialize(stateHash);

	this.$element.find('input[type=text], input[type=checkbox], input[type=radio], select, #filter-sortDir').each(function(i)
	{
		if(this.type == 'checkbox')
		{
			if(formData[this.name]) $(this).attr('checked', true);
			else $(this).attr('checked', false);
		}
		if(this.type == 'radio')
		{
			if(formData[this.name] && formData[this.name] == $(this).val()) $(this).attr('checked', true);
			else $(this).attr('checked', false);
		}

		if(this.type == 'text' || this.type == 'hidden')
		{
			if(formData[this.name]) $(this).val(formData[this.name]);
		}
		if($(this).is('select'))
		{
			if(formData[this.name]) $(this).val(formData[this.name]);

		}
	});
	this.priceRangeSelect.setPosition(Number($('#filter-priceFrom').val()), Number($('#filter-priceTo').val()));

	if(this.bearingRangeSelect) this.bearingRangeSelect.setPosition(Number($('#filter-bearing').val()));

	this.$element.find('#filter-sortingDirA, #filter-sortingDirD').removeClass('btn-active');
	if(this.$element.find('#filter-sortDir').val() == 'a') this.$element.find('#filter-sortingDirA').addClass('btn-active');
	else this.$element.find('#filter-sortingDirD').addClass('btn-active');

	if(!firstLoad)
	{
		$('.product-list-wrap').css('opacity', 0.5);
		$('.product-loader').removeClass('product-loader-out');
		var ajaxUrl = window.location + '';
		if($('#filter').hasClass('favourites')){
			ajaxUrl = ajaxUrl.replace(/#.*$/, '') + '&ajax=favprods';
		} else {
			ajaxUrl = ajaxUrl.replace(/#.*$/, '') + '?ajax=prods';
		}

		$.ajax({
			url: ajaxUrl,
			//url: 'ajax-products.html',
			data: stateHash,
			success: function(html)
			{
				$('.product-list-wrap').html(html).stop().fadeTo(400, 1, function(){ this.style.filter = null; });
	        	$('.product-loader').addClass('product-loader-out');
	        	$('.product-list>ul').kfEqualizeColumns({ column: '>li' });
	        }
		});
	}
	this.updating = false;
	this.historyCount++;
}


