$(function() {
	$('.nav a').each(function(){
		$(this).click(function(){
			showSection($(this));				
		});
	});
});
activeSection = false;
showSection($('.nav a')[0]);

function showSection(elem){
	var tA = $('.sections .section');
	var t = $('#'+$(elem).attr('href').substr(1));
	
	$('.nav .active').removeClass('active');
	$(elem).addClass('active');
	
	if(activeSection){
		$(activeSection).fadeOut("fast",function(){$(t).fadeIn("fast")});
	}else{
		tA.each(function(){
			if($(this).attr('id') == t.attr('id')){
				$(this).show();
			}else{
				$(this).hide();
			}
		});
	}
			
	activeSection = t;
	
	f = new module_form($('#contact-form,#company-form'));
	
}

function module_form(elem)
{
	this.elem = elem;
	var obj = this;
	$(this.elem).find('input[type="submit"]').bind('click', function(e){
		obj.submit();
		e.stopImmediatePropagation();
		return false;
	});
};

module_form.prototype.submit = function()
{
	var f = $(this.elem).find('form.validate');
	var v = f.validate({
		errorElement: 'span',
		errorPlacement: function(error, element) {
			error.appendTo( element.siblings('label') );
		}
	});
	var scope = this;
	if(f.valid()){
		$.ajax({
			type:'POST',
			url:f.attr('action'),
			data:f.serialize(),
			success:function(data){
				scope.handle(data);
			},
			dataType:'json'
			});
		var obj = $(f).find('input[type="submit"]');
		obj.attr('value','Sending');
		obj.attr('disabled','disabled');
	}
};

module_form.prototype.handle = function(data)
{
	var f = $(this.elem).find('form.validate');
	if(data.result == "success"){
		$(f).slideUp();
		$(this.elem).find('div.response').append(data.message);
	}
};