$(function() {
    var textMissing = {
        'vorname':'Bitte geben Sie Ihren Namen an.',
        'nachname':'Bitte geben Sie Ihren Nachnamen an.',
        'email':'Bitte geben Sie Ihre E-Mail Adresse an.',
        'mitteilung':'Bitte geben Sie Ihre Mitteilung an.'
    };
    
    var textInvalid = {
        'email':'Bitte geben Sie eine valide E-Mail Adresse an.'
    };
    
    var textMatch = {
        'email':'^([a-zA-Z0-9\\-\\.\\_]+)(\\@)([a-zA-Z0-9\\-\\.]+)(\\.)([a-zA-Z]{2,4})$'
    };

    $(".mailform")
        .find("input[type='text'],textarea").each(function () {
        $(this)
            .focus(function() {
                $(this).addClass('focus');
            })
            .blur(function() {
                $(this).removeClass('focus');
                var parent = $(this).parent();
                
                if ( parent.find('label').text().indexOf('*') != -1 ) {
                    var name = $(this).attr('name');
                    var errorFrame = parent.find('.error');
                    if ( ! $(this).val() ) {
                        if ( errorFrame.text() ) {
                            errorFrame.fadeOut('fast',function () { errorFrame.text(textMissing[name]).fadeIn('fast') });
                        } else {
                            errorFrame.text(textMissing[name]).fadeIn('slow');
                        }
                    } else {
                        if (textMatch[name] && !$(this).val().match(textMatch[name])) {
                            if ( errorFrame.text() ) {
                                errorFrame.fadeOut('fast',function () { errorFrame.text(textInvalid[name]).fadeIn('fast') });
                            } else {
                                errorFrame.text(textInvalid[name]).fadeIn('slow');
                            }
                        } else {
                            errorFrame.fadeOut('slow');
                        }
                    }
                }
            });
        })
        .end()
        .find(".error").each(function() {
            $(this).css('display','none');
            
            if ($(this).html()) {
                $(this).fadeIn('slow');
            }
        })
        .end()
        .parent().submit(function() {
            var error = false;
            $('.mailform',this).find('input[type!="hidden"],textarea').each(function () {
                var name = $(this).attr('name');
                if ($(this).parent().find('label').text().indexOf('*') != -1 && (!$(this).val() || (textMatch[name] && !$(this).val().match(textMatch[name]))) && !error) {
                    $(this).blur().focus();
                    error = !error;
                }
            });
            return !error;
        });
});