var BASE_HREF = BASE_HREF || '../';

Cufon.replace('.subintro-box .tbnr .text-box p', { fontWeight: 400 });
Cufon.replace('h2.underline, #main-menu li a, .superfooter-signpost ul li h3, .call-us, a.facebook-love strong, .side-box h2, .content-box h1, .content-box h2, .search-solution-box h2', { fontWeight: 600 });
Cufon.replace('.project-player .desc-box .controls-box .page-active, .subintro-box .tbnr .text-box h2, .subintro-box .tbnr .text-box h1', { fontWeight: 700 });
Cufon.replace('.filter-box h3', { fontWeight: 600 });

if(!$.browser.msie)
{
	Cufon.replace('.featured-projects-box ul li .text-box h3 a', { fontWeight: 600 });
	Cufon.replace('.price-title-box', { fontWeight: 600 });
	Cufon.replace('.filter-box label .in', { fontWeight: 400, hover: true, hoverables: { 'span': true } });
}

var galleryData = galleryData || [];
	
$(document).ready(function()
{
	$.fn.kfBox && $('.lightbox').kfBox();

	$('table tr:nth-child(even)').addClass('even');

	$('a.external').click(function(){return !window.open($(this).attr("href"))});

	$('#q').inputDefaultText({ text: 'Hledaný výraz'});
	$('#solutionType').inputDefaultText({ text: 'Zadejte název řešení (např. firemní web)'});
	
	if($('#usercontactform').size())
	{
		$('input[name=usercontactform\\[name\\]]').inputDefaultText({ text: 'Vaše jméno a příjmení'});
		$('input[name=usercontactform\\[email\\]]').inputDefaultText({ text: 'E-mail'});
		$('input[name=usercontactform\\[phone\\]]').inputDefaultText({ text: 'Telefon'});
		$('textarea[name=usercontactform\\[text\\]]').inputDefaultText({ text: 'Váš dotaz / poptávka'});
	}
	
	// $('#solutionType').sSelect();
	
	/* Scrollovátko aktualit na titulce */
	var $prevnext2 = $('<div class="prevnext"><a href="#" class="btn-prev">předchozí</a> <a href="#" class="btn-next">další</a></div>');
    $('.news-home .hscroll-box').before($prevnext2);
    var newsHomeScroller = new kff.widgets.SherwoodScroller('.news-home .hscroll-box', { 
		scrollWidth: 482, 
		carouselWidth: 952, 
		prev: '.news-home .btn-prev', 
		next: '.news-home .btn-next', 
		name: $('.submenu-hscroll-box').attr('id') || null 
	});
	newsHomeScroller.activate();
	
	/* Autocompleter na titulce */
	if($.fn.autocomplete && $('#solutionType').size()) $('#solutionType').autocomplete(
	{ 
		//serviceUrl: BASE_HREF+'ajaxactags/',
		minChars:1, 
		maxHeight:400,
		width: 628,
		zIndex: 9999,
		deferRequestBy: 0, //miliseconds
		noCache: false,
		autoSubmit: true,
		lookup: catalogueLookup
	}); 

	/* SherwoodGallery init */	
	var sherwoodGallery = new KSherwoodGallery({
		data: galleryData,
		slideshowSpeed: 1000,
		domHooks: {
			title: $('.project-player h2'),
			image: $('.project-player .img-box'),
			description: $('.project-player .desc'),
			author: $('.project-player .photo-author'),				
			next: $('.project-player .btn-next'),
			prev: $('.project-player .btn-prev'),
			pageActive: $('.project-player .page-active'),
			pageTotal: $('.project-player .page-count'),
			slideshowButton: $('.project-player .btn-play'),
			slideshowFastButton: $('.project-player .slideshow-fast-button'),
			startSlideshowButton: $('.project-player .btn-start-slideshow')
		}
	});

	$('.project-player .prevnext2 .btn-prev').bind('mouseenter',function(){
		$(this).stop().animate({ backgroundPosition: '(0px 0)', opacity: 1 }, 800, 'easeOutQuint');
	}).bind('mouseleave',function(){
		$(this).stop().animate({ backgroundPosition: '(20px 0)', opacity: 0.2 }, 800, 'easeOutQuint');
	});
	
	$('.project-player .prevnext2 .btn-next').bind('mouseenter',function(){
		$(this).stop().animate({ backgroundPosition: '(20px 0)', opacity: 1 }, 800, 'easeOutQuint');
	}).bind('mouseleave',function(){
		$(this).stop().animate({ backgroundPosition: '(0px 0)', opacity: 0.2 }, 800, 'easeOutQuint');
	});
	
	/* Project filter form init: */
	if($('.filter-box form').size()) var projectsForm = new FormController('.filter-box form').init();
	
	
	$(document).delegate('.featured-projects-box>ul>li', 'mouseenter', function(){
		$(this).find('.overlay').css({ display: 'block', opacity: 0 }).stop().fadeTo(200, 1);
		var $a = $(this).find('h3>a').addClass('hover');
		if(!$.browser.msie) Cufon.replace($a.get(0), { fontWeight: 600 });	
	});
	$(document).delegate('.featured-projects-box>ul>li', 'mouseleave', function(){
		$(this).find('.overlay').stop().fadeTo(400, 0);
		var $a = $(this).find('h3>a').removeClass('hover');
		if(!$.browser.msie) Cufon.replace($a.get(0), { fontWeight: 600 });
	});
	
	$(document).delegate('.featured-projects-box>ul>li', 'click', function(){
		window.location = $(this).find('a').attr('href');
	});	
	
	
	var attachedFilesController = new AttachedFilesController({ 
		element: '.attached-files-box',
		text1: 'Připojit soubory…',
		text2: 'Připojit další soubory…' });
	attachedFilesController.init();

});

$(window).load(function()
{
	// $('#solutionBudget').stylishSelect();
	var fakeSelect = new KFakeSelect($('#solutionBudget'));
	fakeSelect.activate();
	//$('#solutionBudget').kfFakeSelect();
	
	/* Home page motive slider */
	var motiveController = new KMotiveController();
	motiveController.init();
	
})

$.fn.inputDefaultText = function(options)
{
	options = $.extend({
		text: 'Hledany vyraz'
	}, options);
	
	return this.each(function()
	{
		var $this = $(this);
		if($this.val() == options.text || $this.val() == '') $this.val(options.text);
		$this
			.bind('focus', function(){ if($(this).val() == options.text) $(this).val(''); })
			.bind('blur', function(){ if($(this).val() == '') $(this).val(options.text); });
		
		$this.closest('form').bind('submit', function(){
			if($this.val() == options.text) $this.val('');
		});
	});
};




var AttachedFilesController = function(options)
{
	this.options = $.extend({ 
		element: null,
		text1: 'Připojit soubory…',
		text2: 'Připojit další soubory…'
	}, options);
};

AttachedFilesController.prototype.init = function()
{
	this.$element = $(this.options.element);
	this.$attachFiles = $('<a href="#" class="attach-files"></a>');
	this.$fileRow = $('<span class="file-row"><input type="file" name="contactform[uploads][]" /> <span class="ico-remove-file">Odstranit</span></span>');
	this.$attachFiles.html(this.options.text1);	
	this.$element.append(this.$attachFiles);
	
	
	this.$attachFiles.bind('click', $.proxy(this.appendFile, this));
	this.$element.delegate('.ico-remove-file', 'click', $.proxy(this.removeFile, this));
};

AttachedFilesController.prototype.appendFile = function()
{
	this.$element.append(this.$fileRow.clone());
	this.$element.append(this.$attachFiles);
	this.$attachFiles.html(this.options.text2);
	return false;
}

AttachedFilesController.prototype.removeFile = function(event)
{
	$(event.currentTarget).closest('.file-row').remove();
	if(this.$element.find('.file-row').size() == 0) 	this.$attachFiles.html(this.options.text1);
	return false;
}


/**
 * Motive controller
 */ 
var KMotiveController = function()
{
}

KMotiveController.prototype.init = function()
{
	this.$menuItems = $('.motive-menu a');
	this.$motives = $('.motives .motive');
	this.currentMotiveIndex = 0;
	this.timer = null;
	
	var that = this;
	
	// Preloading prvního motivu:
	var url = this.$motives.eq(0).attr('data-img');
	var $img = $('<img />');
	$img.bind('load', function(){
		that.motivesLoaded = 1;
		that.$motives.eq(0).prepend(this);
		that.switchMotive(0);
		
		// Preloading ostatních motivů
		that.$motives.each(function(i)
		{
			if(i != 0)
			{
				var url = that.$motives.eq(i).attr('data-img');
				var $img = $('<img />');
				$img.bind('load', function(){
					that.$motives.eq(i).prepend(this);
					that.onMotiveLoad();
				});
				$img.attr('src', url);
			}
		});
	});
	$img.attr('src', url);	
};

KMotiveController.prototype.onMotiveLoad = function()
{
	this.motivesLoaded++;
	if(this.motivesLoaded == this.$motives.size())
	{
		this.bindHandlers();
		this.autoslide(1);
	}
}

KMotiveController.prototype.bindHandlers = function()
{
	this.$menuItems.bind('click', $.proxy(function(event)
	{
		this.switchMotive(this.$menuItems.index(event.currentTarget));
		this.autoslide(1);	
		return false;
	}, this));
	
	$('#motive-box .btn-prev').bind('click', $.proxy(function(event)
	{
		this.switchMotive((this.currentMotiveIndex - 1 + this.$motives.size()) % this.$motives.size());
		this.autoslide(1);
		return false;
	}, this))
	.bind('mouseenter',$.proxy(function(event)
	{
		$(event.currentTarget).stop().animate({ backgroundPosition: '(0px 0)', opacity: 1 }, 800, 'easeOutQuint');
	}, this))
	.bind('mouseleave', $.proxy(function(event)
	{
		$(event.currentTarget).stop().animate({ backgroundPosition: '(20px 0)', opacity: 0.2 }, 800, 'easeOutQuint');
	}, this));
	
	$('#motive-box .btn-next').bind('click', $.proxy(function(event){
		this.switchMotive((this.currentMotiveIndex + 1)  % this.$motives.size());
		this.autoslide(1);
		return false;
	}, this))
	.bind('mouseenter', $.proxy(function(event)
	{
		$(event.currentTarget).stop().animate({ backgroundPosition: '(20px 0)', opacity: 1 }, 800, 'easeOutQuint');
	}, this))
	.bind('mouseleave', $.proxy(function(event){
		$(event.currentTarget).stop().animate({ backgroundPosition: '(0px 0)', opacity: 0.2 }, 800, 'easeOutQuint');
	}, this));
}

KMotiveController.prototype.switchMotive = function(i)
{
	var $oldMotive = this.$motives.eq(this.currentMotiveIndex);
	var $currentMotive = this.$motives.eq(i);
	this.$menuItems.removeClass('active').eq(i).addClass('active');
	
	$currentMotive.css({ opacity: 0, left: 0 }).stop().delay(300).animate({ opacity: 1 }, 500, 'easeOutQuint');
	if(i != this.currentMotiveIndex) $oldMotive.stop().animate({ opacity: 0 }, 500, 'easeOutQuint', function(){
		$(this).css({ left: -9999 });
	});
	this.currentMotiveIndex = i;	
	return false;	
};

KMotiveController.prototype.autoslide = function(slide)
{
	if(slide != 1) this.switchMotive((this.currentMotiveIndex + 1)  % this.$motives.size());
	if(this.timer) clearTimeout(this.timer);
	this.timer = setTimeout($.proxy(function(){ this.autoslide(0); }, this), 9000);
};


/**
 * Standard dialog box
 */
kff.widgets.SherwoodScroller = function(element, options)
{
	kff.widgets.Scroller.call(this, element, options);
};

kff.extend(kff.widgets.SherwoodScroller, kff.widgets.Scroller);

kff.widgets.SherwoodScroller.prototype.animate = function(position, callback)
{
	var isXAxis = this.options.axis != 'y';
	this.animating = true;
    this.scrollPosition = position;
    this.realScrollPosition = this.scrollPosition * this.scrollWidth;
    if(this.realScrollPosition > this.ulWidth - this.carouselWidth)
    {
		this.realScrollPosition = this.ulWidth - this.carouselWidth;
		this.scrollPosition = Math.floor(this.realScrollPosition / this.scrollWidth);
	}
    else if(this.realScrollPosition < 0)
	{
		this.scrollPosition = this.realScrollPosition = 0;
	}
	
	var animateOption = isXAxis ? { scrollLeft: this.realScrollPosition } : { scrollTop: this.realScrollPosition };
	
	var that = this;
	this.$carousel.stop().animate(animateOption, this.options.speed, "easeOutQuint", function(){
		that.savePosition();
		that.animating = false;
	});
	that.updateButtonsState();
}

/*
 * SherwoodGallery     
 *  
 */
var KSherwoodGallery = function(options)
{
	// this.$element = $elements.eq(0);
	this.options = $.extend({
		data: null,
		prefetchCount: 3,
		hashPrefix: 'kfbox-',
		pageSpan: 3,
		pageLeaders: ' … ',
		historyLoadCallback: null,
		afterShowCallback: null,
		slideshowSpeed: 4000,
		slideshowFastFactor: 2,
		speed: 1600,
		easing: 'easeOutQuart',
		domHooks: {
			title: null,
			image: null,
			description: null,
			rating: null,
			next: null,
			prev: null,
			next2: null,
			prev2: null,
			pageActive: null,
			pageTotal: null,
			slideshowButton: null,
			slideshowFastButton: null,
			slideshow: false,
			startSlideshowButton: null
		}
		
	}, options);
	
	this.langCode = this.options.langCode || $('html').attr('xml:lang') || 'cs';
	this.oldHash = '';
	this.activeIndex = 0;
	this.slideshow = this.options.slideshow;
	this.slideshowInterval = null;
	this.timer = null;
	this.render();
	this.showImage(this.activeIndex);
	
	
};

KSherwoodGallery.prototype.showByHash = function(hash)
{
	if(hash.indexOf(this.options.hashPrefix) !== 0) return false;
	var activeIndex = parseInt(hash.replace(this.options.hashPrefix, '')) - 1;
	this.showImage(activeIndex);
	return true;
};

KSherwoodGallery.prototype.render = function()
{
	var that = this;
	this.options.domHooks.next.bind('click', function(){ that.showNext(); return false; });
	this.options.domHooks.prev.bind('click', function(){ that.showPrev(); return false; });
	
	// Slideshow control:
	if(this.options.slideshowSpeed && this.options.domHooks.slideshowButton)
	{
		var slide = function(){
			if(that.activeIndex + 1 >= that.options.data.length)
			{
				that.showImage(0);
				that.stopSlideshow();
			}
			else that.showNext();
		};
		this.options.domHooks.slideshowButton.bind('click', function()
		{
			that.toggleSlideshow();
			return false;
		});
		
		this.options.domHooks.image.bind('click', function()
		{
			that.toggleSlideshow();
			return false;
		});
		
		this.options.domHooks.startSlideshowButton.bind('click', function()
		{
			that.startSlideshow();
			return false;
		});
		
		if(!$.browser.msie)
		{
			this.options.domHooks.startSlideshowButton.css({ backgroundPosition: '0 0' }).bind('mouseenter', function(){
				$(this).find('.in').stop().fadeTo(300, 1);
			}).bind('mouseleave', function(){
				$(this).find('.in').stop().fadeTo(300, 0);
			});
		}
		
		this.options.domHooks.slideshowFastButton.bind('click', function()
		{
			if($(this).hasClass('slideshow-fast'))
			{
				$(this).html('Zrychlit').removeClass('slideshow-fast');
				that.options.slideshowSpeed *= that.options.slideshowFastFactor;
			}
			else
			{
				$(this).html('Zpomalit').addClass('slideshow-fast');
				that.options.slideshowSpeed = Math.floor(that.options.slideshowSpeed / that.options.slideshowFastFactor);
			}			
			
			if(that.slideshowInterval)
			{
				that.startSlideshow();
			}
			return false;
		});
	}
};

KSherwoodGallery.prototype.slide = function()
{
	if(this.activeIndex + 1 >= this.options.data.length)
	{
		this.showImage(0);
		this.stopSlideshow();
	}
	else this.showNext();
};

KSherwoodGallery.prototype.autoslide = function()
{
	clearTimeout(this.timer);
	if(this.slideshow)
	{
		this.slide();
		var timeout = this.options.data[(this.activeIndex + 1) % this.options.data.length].time ||  this.options.slideshowSpeed;
		if(this.options.domHooks.slideshowFastButton.hasClass('slideshow-fast')) timeout *= this.options.slideshowFastFactor;
		this.timer = setTimeout($.proxy(this.autoslide, this), timeout);
	}
};

KSherwoodGallery.prototype.startSlideshow = function()
{	
	this.slideshow = true;					
	this.options.domHooks.slideshowButton.html('Zastavit slideshow').removeClass('slideshow-stopped').addClass('slideshow-running');
	this.slide();
	this.autoslide();
};

KSherwoodGallery.prototype.stopSlideshow = function()
{
	clearTimeout(this.timer);
	this.options.domHooks.slideshowButton.html('Spustit slideshow').removeClass('slideshow-running').addClass('slideshow-stopped');
	this.slideshowInterval = null;
	this.slideshow = false;
};

KSherwoodGallery.prototype.toggleSlideshow = function()
{
	if(this.slideshow) this.stopSlideshow();
	else this.startSlideshow();
};

KSherwoodGallery.prototype.showNext = function()
{
	this.showImage(this.activeIndex + 1);
};

KSherwoodGallery.prototype.showPrev = function()
{
	this.showImage(this.activeIndex - 1);
};

KSherwoodGallery.prototype.preloadSiblings = function(index)
{
	var prefetchCount = this.options.prefetchCount;
	for(var i = 1; i <= prefetchCount; i++)
	{
		if(this.options.data[index + i])
		{
			$(document.createElement('img')).attr('src', this.options.data[index + i].imageUrlFull );
			$(document.createElement('img')).attr('src', this.options.data[index + i].imageUrlThumb );
		}
		if(this.options.data[index - i])
		{
			$(document.createElement('img')).attr('src', this.options.data[index - i].imageUrlFull );
			$(document.createElement('img')).attr('src', this.options.data[index - i].imageUrlThumb );
		}
	}
};

KSherwoodGallery.prototype.showImage = function(imageIndex)
{
	if(typeof this.options.data[imageIndex] !== 'undefined')
	{
		var that = this;
		var image = $(document.createElement('img'))
			.bind('load', function(e)
				{
					that.transitionTo(imageIndex);
					that.preloadSiblings(imageIndex);
				})
			.attr('src', that.options.data[imageIndex].imageUrlFull);
		if(imageIndex != 0) this.options.domHooks.startSlideshowButton.hide();
		else this.options.domHooks.startSlideshowButton.show();
	}
};

KSherwoodGallery.prototype.transitionTo = function(imageIndex)
{	
	var that = this;
	var parentSize = {x: this.options.domHooks.image.width(), y: this.options.domHooks.image.height() };
	
	var $oldImg = $('img', this.options.domHooks.image);

	

	var image = $(document.createElement('img'))
		.bind('load', function(){
			$(this)
				.css({ 
					position: 'absolute',
					left: (parentSize.x - this.width) / 2, 
					top: (parentSize.y - this.height) / 2, 
					opacity: 0 })
				.appendTo(that.options.domHooks.image);
			$(this).animate({opacity: 1}, that.options.speed, that.options.easing);
			$oldImg.animate({opacity: 0}, that.options.speed, that.options.easing, function(){ $(this).remove(); });	
		})
		.attr('src', that.options.data[imageIndex].imageUrlFull);
	
	setTimeout(function()
	{
		$.each(that.options.domHooks, function(key, value)
		{
			if(key == 'image' || key == 'next' || key == 'prev' || key == "slideshowButton" || key == "slideshowFastButton" || key == "startSlideshowButton") return;
			if(that.options.data[imageIndex][key] == 'undefined') return;
			if(value instanceof jQuery) value.empty().append(that.options.data[imageIndex][key]);
			else if(typeof value == 'function') value(that.options.data[imageIndex][key]);
		});
		
		that.options.domHooks.pageActive.html(imageIndex + 1);
		that.options.domHooks.pageTotal.html(that.options.data.length);
		
		/* Thumbnails next-prev */
		$('img', that.options.domHooks.prev).remove();
		$('img', that.options.domHooks.next).remove();
		if(that.options.data[imageIndex + 1])
		{
			that.options.domHooks.next.append('<img src="'+ that.options.data[imageIndex + 1].imageUrlThumb +'" />').show();
		}
		else that.options.domHooks.next.hide();
		if(that.options.data[imageIndex - 1])
		{				
			that.options.domHooks.prev.append('<img src="'+ that.options.data[imageIndex - 1].imageUrlThumb +'" />').show();
		}
		else that.options.domHooks.prev.hide();	
		
		// Cufon.replace('.project-player .desc-box h2', { fontWeight: 400 });
		Cufon.replace('.project-player .desc-box .controls-box .page-active', { fontWeight: 700 });				
	}, 0);

	this.activeIndex = imageIndex;
};


/* Fake select */
var KFakeSelect = function(element, options)
{
	this.$element = $(element).eq(0);
	this.options = $.extend({ }, options);
	this.$fakeContainer = null; 
};

KFakeSelect.prototype.activate = function()
{
	var that = this;
	this.$fakeContainer = $('<div class="fake-select-box"><div class="fake-select-text"><div class="in">haf</div></div><div class="fake-select-list"><ul></ul></div></div>');
	this.$element.after(this.$fakeContainer).addClass('out').css({ position: 'absolute', top: 0, left: -9000});
	
	this.$fakeListContainer = this.$fakeContainer.find('.fake-select-list');
	this.$fakeList = this.$fakeContainer.find('ul');
	this.$fakeText = this.$fakeContainer.find('.fake-select-text .in');
	
	this.$element.find('option').each(function(){
		var $li = $('<li />').text($(this).text()).attr('value', $(this).attr('value'));
		that.$fakeList.append($li);
	});
	
	this.bindEvents();
	this.updateState();
}

KFakeSelect.prototype.bindEvents = function()
{
	var that = this;
	
	this.$element.bind('click keyup change', function(){
		that.updateState();
	}).bind('focus',function(){
		that.$fakeText.addClass('fake-select-text-focused');
		that.updateState();
	}).bind('blur',function(){
		that.$fakeText.removeClass('fake-select-text-focused');
		that.updateState();
		
	}).bind('keydown',function(event){
		if(event.keyCode == 13)
		{
			that.$fakeContainer.find('li.selected').triggerHandler('click');
		}
		if(event.keyCode == 9)
		{
			that.$fakeListContainer.removeClass('fake-select-list-open');
		}
	});
	
	$(document).bind('click', function(event){ 
		that.$fakeListContainer.removeClass('fake-select-list-open');
	});
	
	this.$fakeList.find('li').bind('click', function(event){
		var val = $(this).attr('value');
		that.$element.val(val);
		that.updateState();
		event.stopPropagation();
		event.preventDefault();
		return false;
	});
	
	this.$fakeText.bind('click', function(event){
		that.$element.focus();
		that.$fakeListContainer.toggleClass('fake-select-list-open');
		return false;		
	});
	
	this.$fakeContainer.find('li').bind('click', function(){
		var val = $(this).attr('value');
		that.$element.val(val);
		that.updateState();
		that.$fakeListContainer.removeClass('fake-select-list-open');
		that.$element.focus();
	});
}

KFakeSelect.prototype.updateState = function()
{
	var $selected = this.$element.find('option:selected');
	var index = this.$element.find('option').index($selected);
	this.$fakeText.text($selected.text());
	this.$fakeList.find('li').filter('.selected').removeClass('selected').end().eq(index).addClass('selected');
}



kff.widgets.SherwoodPriceSlider = function(element, options)
{
	kff.widgets.Slider.call(this, element, options);
};

kff.extend(kff.widgets.SherwoodPriceSlider, kff.widgets.Slider);

kff.widgets.SherwoodPriceSlider.prototype.render = function()
{
	kff.widgets.Slider.prototype.render.call(this);
}

kff.widgets.SherwoodPriceSlider.prototype.drag = function(position)
{
	if(typeof this.options.drag == 'function') this.options.drag(position);
}

kff.widgets.SherwoodPriceSlider.prototype.change = function(position)
{
	if(typeof this.options.change == 'function') this.options.change(position); 
}

var FormController = function(element, options)
{
	var that = this;
	this.options = $.extend({	}, options);
	this.$element = $(element);
	
	var priceMin = 0;
	var priceMax = 5;
	
	this.updating = false;
	this.initializing = false;
	this.historyCount = 0;

	this.priceSlider = new kff.widgets.SherwoodPriceSlider('.price-slider-box', {
		steps: priceMax - priceMin,
		min: priceMin,
		max: priceMax,
		position: $('#filter-price').val(),
		change: function(p)
		{
			var $activeLi = $('.price-slider-box .price-slider-stops li').removeClass('active').eq(p).addClass('active');
			$('.price-title-box').html($activeLi.attr('title'));
			$('#filter-price').val(p);
			if(!that.initializing) that.addHistorySnap();
			if(!$.browser.msie)	Cufon.replace('.price-title-box', { fontWeight: 600 });
		},
		drag: function(p)
		{
			var $activeLi = $('.price-slider-box .price-slider-stops li').removeClass('active').eq(p).addClass('active');
			$('.price-title-box').html($activeLi.attr('title'));
			if(!$.browser.msie)	Cufon.replace('.price-title-box', { fontWeight: 600 });
		},
		speed: 120
	});
};

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);
	});
	
	/* Range Select */
	var priceMin = 0;
	var priceMax = 6;
	
	this.priceSlider.init();
	$('#filter-price, .filter-box .jshide').hide();
	
	$('.price-slider-box .kff-slider-box').append('<div class="price-slider-stops"><ul><li title="Neomezeně">neomez.</li><li title="0-100 tis. Kč">0–100</li><li title="100-200 tis. Kč">100–200</li><li title="200-500 tis. Kč">200–500</li><li title="500-1000 tis. Kč">500–1M</li><li title="více než milion Kč">1000+</li></ul></div>');


	this.$element.find('input[type=checkbox]').bind('click', function(){
		$(this).closest('ul').find('input[type=checkbox]').not(this).attr('checked', false).end()
		that.updateLabels();		
		that.addHistorySnap();
	});
	this.$element.find('select').bind('change', function(){
		that.addHistorySnap();
	});	
	
	this.$element.bind('submit', function(){
		return false;
	});
	
	this.updateLabels();
	this.initializing = false;
	
	if(this.historyCount == 0)
	{
		this.initialState = this.$element.serialize();
		$(window).trigger('hashchange');
	}
}

FormController.prototype.updateLabels = function()
{
	$('.filter-box .check-list').find('label').each(function(){
		if($('#' + $(this).attr('for')).is(':checked')) $(this).addClass('active');
		else $(this).removeClass('active');
	});
}

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').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.priceSlider.setPosition(parseInt($('#filter-price').val()));
	this.updateLabels();
	if(!$.browser.msie)	Cufon.refresh('.filter-box label .in', { fontWeight: 400, hover: true, hoverables: { 'span': true } });
	if(!$.browser.msie)	Cufon.refresh('.price-title-box', { fontWeight: 600 });

	// Ajaxload:
	if(!firstLoad)
	{
		$('.product-list-wrap').css('opacity', 0.5);
		$('.product-loader').removeClass('product-loader-out');
		$.ajax({
			url: location.protocol + '//' + location.hostname + location.pathname,
			/// url: 'ajax-products.html', 
			data: stateHash + "&ajax=1",
			success: function(html)
			{
				$('.product-list-wrap').html(html).stop().fadeTo(400, 1);
	        	$('.product-loader').addClass('product-loader-out');
	        	Cufon.replace('.product-list-wrap h2.underline', { fontWeight: 600 });
	        	if(!$.browser.msie)	Cufon.replace('.product-list-wrap .featured-projects-box ul li .text-box h3 a', { fontWeight: 600, hover: true });
	        }
		});
	}
	this.updating = false;
	this.historyCount++;
}

