$(document).ready(function(){
    var timerId;
    
    $('#contact-us form').submit(function(){
        context = $('#contact-us');
        vName = $('input[name="name"]', context).val();
        vEmail = $('input[name="email"]', context).val();
        vMessage = $('textarea[name="message"]', context).val();
        validRegExp = /^([\w-]+(?:\.[\w-]+)*)@((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$/i
        
        errors = []

        if (vName.length < 3)
            errors.push('your name');
        if (vEmail.length < 3)
            errors.push('your email');
        else if (vEmail.search(validRegExp) == -1)
            errors.push('a valid email address');
        if (vMessage.length < 10)
            errors.push('your message');
                    
        if (errors.length) {
            if (errors.length > 1) {
                lastError = errors.pop();
                errorList = errors.join(', ') + ' and ' + lastError;
            } else
                errorList = errors.join(', ');
        
            showMsg('Please enter ' + errorList, 'error');
        } else {
            $('.submit', context).addClass('loading').attr('disabled', 'disabled');
            
            
            $.ajax({
                type:'get',
                url:'sendMessage.php?rnd=' + Math.random() + '&' + $('form', context).serialize(),
                dataType:'json',
                success:function(data){
                    $('.submit', context).removeClass('loading').attr('disabled', '');
                    showMsg(data.msg, data.status);
                },
                error:function (xhr, ajaxOptions, thrownError){
                    $('.submit', context).removeClass('loading').attr('disabled', '');
                    showMsg('An error occurred, please try again later.', 'error');
                }
            });

        }
        return false;
        
        function showMsg(msg, status, secs) {
            if (typeof(secs) == 'undefined') secs=5;
            if (typeof(status) == 'undefined') status='';
        
            $('.msg_contact', context).fadeOut('slow');
            $('.msg_contact', context).remove();
            clearTimeout(timerId);
            
            $('.column2', context).append('<p class="msg_contact ' + status + ' hide">' + msg + '</p>');
            $('.msg_contact', context).fadeIn('slow');
            timerId = setTimeout(function(){$('.msg_contact', context).fadeOut('slow')}, (secs*1000))
        }
    });

    
});
