var contactForm =
{
    submit: function(event)
    {
        jQuery('.contactform form.smashform input[type="submit"]').attr('disabled', 'disabled');
        jQuery('.contactform form.smashform .container span.error').html('');

        var data = jQuery('.contactform form.smashform').serialize();

        if(data.length>0)
        {
            data = data+"&action=validateSmashContactFormHandler";
        } else {
            data = "action=validateSmashContactFormHandler";
        }

        jQuery.post(ajaxurl, data, function(response)
        {
            if(jQuery.fn.jquery == '1.2.6')
            {
                response = JSON.parse(response);
            }

            jQuery.each(response.fields, function(index, value)
            {
                jQuery('.contactform form.smashform .container.'+index+' span.error').html('<p>'+value+'</p>');
            });
            jQuery('.contactform form.smashform input[type="submit"]').removeAttr("disabled");

            if(response.fields && response.fields.length == 0)
            {
                window.location = '/contact-form-thank-you/';
            } else {
                jQuery('body').stop().scrollTo( jQuery("span.error p:nth-child(1)"), 100 );
            }
        });

        return false;
    },

    restrict: function(event)
    {
        var l = jQuery('.contactform #msg').val().length;
        var max = 420;

        jQuery('.contactform #formlimitcounter').html(max-l<1?"0":max-l);

        if( l >= max-max*0.1)
        {
            jQuery(".contactform #formlimitcountermsg").stop().fadeTo(150, 0.25, function()
            {
                jQuery(".contactform #formlimitcountermsg").fadeTo(150, 1);
            });
        }

        if( l >= max)
        {
            jQuery('.contactform #msg').val(jQuery('.contactform #msg').val().substr(0,max));
        }
    }
}

jQuery(document).ready(function()
{
    if(jQuery('.contactform #msg').val() !== undefined)
    {
        contactForm.restrict();
        jQuery('.contactform #msg').keyup(contactForm.restrict);
    }
});