$(document).ready(function(){
	
	$("a[href*=#]").click(function() {
		var target = $(this).attr("href");	
		if (target == "#") {
			return false;
		} else {
			var targetOffset = $(target).offset().top;
		
			// scrollTo plugin - corrige bug no opera e habilita histórico no browser
			$("html,body").scrollTo($(target), 600);
			
			return false;
		}
		
	});
	
	// Evento Submit
	$('#contact_form').submit(function(e){
		
		// If a previous submit is in progress:
		//if($('#submit_btn').hasClass('active')) return false;
		
		// Adding the active class to the button. Will show the preloader gif:
		//$('#submit_btn').addClass('active');
		
		// Removing the current error tooltips
		$('#alert').hide();
									   
		var nome = $('#nome').val();
		var email = $('#email').val();
		var msg = $('#msg').val();				
		var validEmail = validateEmail(email);
		var error_list = "";
		
		if (nome == "" || nome.length <= 3) {
            error_list += "<li>Informe seu nome!</li>";
        };	
		
		if (!validEmail) {
            error_list += "<li>Informe um e-mail válido!</li>";
        };
		
		if (msg == "" || !msg.length) {
            error_list += "<li>Digite sua mensagem!</li>";
        };
		
		// verifica se há erros
		if(error_list.length){			
			openAlertBox(error_list);			
		} else {								
			$.post(
			   $('#contact_form').attr('action'), $('#contact_form').serialize()+'&fromAjax=1', function(response){			
					if(!response.status) {						
						openAlertBox(response.errors);
					} else {	
						$('#contact_form')[0].reset();
						openAlertBox(response.success);
					}
					//$('#submit_btn').removeClass('active');
				},'json');			
			
		};
		//$('#submit_btn').removeClass('active');
		// Cancela comportamento padrão ( =return false)
		e.preventDefault();
	});
});

// validar e-mail
function validateEmail(mail){
    var reg = /^[\w-\.\']{1,}\@([\da-zA-Z-]{1,}\.){1,}[\da-zA-Z-]{2,}$/;
    return (reg.test(mail));
};

function openAlertBox(msg){
	$("#alert ul").empty().append(msg);
	$('#alert').slideDown();
	setTimeout(closeAlertBox, 7000);
};

function closeAlertBox(){
	$('#alert').slideUp('normal', function(){$("#alert ul").empty();}); 
};
