function createAjaxURL(formElemement) {
    return formElemement.attr('action') + "/true";
}

function buildUpFormParams(formElement) {
    var mapOfParams = {};
    $("input", formElement).each(function(counter, element) {
        var e = $(element);
        mapOfParams[e.attr('name')] = e.attr('value');
    });
    return mapOfParams;
}

function formIsValid(formElement) {
    var valid = true;
    $(":text").each(function() {
        var jqField = $(this);
        if ($.trim(jqField.val()).length === 0) {
            $(jqField).parent().addClass('emptyValue');
            valid = false;
			if ($(this).attr('id') == 'band_name') {
	            alert('Please enter the name of a band or artist you\'d like to get tickets for.');								
			} else {
	            alert('Please enter your email address to receive updates.');				
			}
        }
        if (jqField.attr("name") == "email") {
            var emailReg = /^([\w-\.]+@([\w-]+\.)+[\w-]{2,4})?$/;
            if (!emailReg.test(jqField.val())) {
                $(jqField).parent().addClass('emptyValue');
                valid = false;
                alert("Oops, looks like you've entered an invalid email address. Please double check and try again.");
            }
        }
    });
    return valid;
}

function attachAjaxToForm() {
    // on refresh of page reenable buttons
    $('form #submit').removeAttr('disabled');

    // focus input field
    $(":text").live('focus', function() {
        $(this).parent().addClass('focus');
    });
    $(":text").live('blur', function() {
        $(this).parent().removeClass('focus');
    });

    $(":text").live('click', function() {
        $(this).removeClass('emptyValue');
    });

    $("#submit", $("form")).live('click', function() {
        if (!formIsValid($("form"))) {
            return false;
        }
        $(this).attr('disabled', 'disabled');
        var url = createAjaxURL($("form"));
        $.post(url, buildUpFormParams($("form")),
            function(data) {
                $("#container #content", document).replaceWith(data);
            }).complete(function(data) {
                $(this).removeAttr('disabled');
            });
        return false;
    });
}

$(document).ready(function() {
    attachAjaxToForm();
});
