$(document).ready(function(){
    enableFancyLabels();
    hijaxForm();
});

function enableFancyLabels() {
    var fields = $('input[type="text"], textarea');
    fields.each(function(){
        $(this).val('');
    });
    fields.blur(function(){
        if ($.trim($(this).val()) == '') {
            $(this).val($(this).prev('label').text());
            $(this).css('color', '#929191');
            $(this).focus(function(){
                $(this).val('');
                $(this).css('color', '#333');
            });
        } else {
            $(this).unbind('focus');
        }
    });
    fields.each(function(){
        $(this).blur();
    });
}

function hijaxForm() {

    $('form').submit(function(){
        var doSubmit = true;

        // Validate presence of form info
        var requiredText = ' is required';
        $('input[name=first_name], input[name=last_name], input[name=email], input[name=phone], textarea[name=message]').each(function(){
            var labelText = $(this).prev('label').text();
            if ($(this).val() == labelText || $(this).val() == labelText + requiredText) {
                $(this).val(labelText + requiredText);
                $(this).css('color', '#a22');
                doSubmit = false;
                
            }
        });
        // Validate email address
        var email = $('input[name=email]');
        var validEmail = /^[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,4}$/;
        if (email.val() != email.prev('label').text() + requiredText && !email.val().match(validEmail)) {
            email.val('Email Address must be valid.');
            email.css('color', '#a22');
            email.focus(function(){
                $(this).val('');
                $(this).css('color', '#111');
            });
            doSubmit = false;
        }

        // There were problems, don't send
        if (!doSubmit) {
        //alert("dont send");
            return false;
        // Everything is fine, send it
        } else {
        //alert("send");
            // Reset fields that weren't actually filled in
            $('input[type="text"], textarea').each(function(){
                if ($(this).val() == $(this).prev('label').text()) {
                    $(this).val(' ');
                }
            });
            // Ajax submit with callback
            $.post('https://www.salesforce.com/servlet/servlet.WebToLead?encoding=UTF-8', $('form').serialize(), onSend);
            return false;
        }
    });
}


function onSend() {
    var form = $('#form');
    form.css('opacity', 0.999);

    // Keep width and height the same, even after modifying contents
    form.width(form.width());
    form.height(form.height());

    // Replace form with confirmation message
    form.children().fadeOut('normal', function(){
        form.html('<div style="display:none">Thank you for your message. You will receive an email shortly from us. </div>');
        form.children().fadeIn('normal');
    });
}
