function scrolling()
{
    $('a[href*=#]').click(function() {
    if (location.pathname.replace(/^\//,'') == this.pathname.replace(/^\//,'') 
        && location.hostname == this.hostname) {
            var $target = $(this.hash);
            $target = $target.length && $target || $('[name=' + this.hash.slice(1) +']');
            if ($target.length) {
                var targetOffset = $target.offset().top;
                $('html,body').animate({scrollTop: targetOffset}, 1000);
                return false;
            }
        }
    });
}

function notificate(text)
{
    $("#notification").text(text);
    $("#notification").show();
    setTimeout(function() {
        $("#notification").hide();
    }, 5000);
}

$(document).ready(function() {
    $(".eq-contact").equalHeights();
    $("#fcontact").submit(function(event) {
        $("#submit-contact").attr("disabled", true);
        var emailReg = /^([\w-\.\+]+@([\w-]+\.)+[\w-]{2,4})?$/;
        var error = null;
        // Check every input is not empty
        $('input,textarea', this).each(function(){
            if ($(this).val().length == 0) {
                // Finish when reach submit button
                if ($(this).attr("name") == "submit")
                    return;
                
                // Append error
                var label = $("label[for='" + $(this).attr("id") + "']").text();
                label = label.slice(0, -1);
                if (! error)
                    error = label;
                else
                    error += ", " + label;
                $(this).addClass("error-form");
            } else {
                $(this).removeClass("error-form");
            }
        });
        if (error != null) {
            error = "Error en campo: " + error;
            notificate(error);
            $("#submit-contact").attr("disabled", false);
            event.preventDefault();
            return false;
        }
        
        $("#notification").text("Enviando email...");
        $("#notification").show();
        var data = $(this).serialize();
        $.ajax({
            async: false,
            type: "POST",
            url: $(this).attr("action"),
            data: data,
            success: function(data) {
                notificate("¡Email enviado!");
            },
            error: function(xhr, text, err) {
                if (xhr.status == 400)
                    notificate(xhr.responseText);
                else if (xhr.status == 403)
                    notificate("No se pudo enviar el email, inténtelo de nuevo");
                $("#submit-contact").attr("disabled", false);
            }
        });
        event.preventDefault();
        return true;
    });
    scrolling();
});


