﻿function getQueryString(url, key, default_) {
    if (default_ == null) default_ = "";
    key = key.replace(/[\[]/, "\\\[").replace(/[\]]/, "\\\]");
    var regex = new RegExp("[\\?&]" + key + "=([^&#]*)");
    var qs = regex.exec(url);
    if (qs == null)
        return default_;
    else
        return qs[1];
}

$(".formSubmit").click(function () {

    if (typeof preventSubmission == "function") {
        if (preventSubmission($(this).parent())) {
            return;
        }
    }

    $(this).parent().find(".divField:visible").each(function () {

        var fieldValue = $(".field", this).val();

        if ($("input:radio.field", this).length > 0) fieldValue = $("input:radio.field:checked", this).val();

        if ($(".fieldCustom", this).length > 0) {
            fieldValue = ""

            $(".fieldCustom", this).each(function () {
                fieldValue += $(this).val();
            });

            $(".field", this).val(fieldValue);
        }

        if ($("input[name=required]", this).val() != "" && (fieldValue == "" || fieldValue == null)) {
            $(".error", this).html($("input[name=required]", this).val());
            $(".field", this).css("background", "#ff9988");

            //ga to track non-completed required fields
            if (typeof recordGAEvent == "function") {
                _gaq.push(['_trackEvent', 'Form Error', $(this).parent().find("[name=FormName]").val() + " - " + $(this).find(".caption").html(), $("input[name=required]", this).val()]);
            }

        }
        else {
            $(".error", this).html("");
            $(".field", this).css("background", "");
        }

        var fieldRegex = $("input[name=regex]", this).val();
        if ($("input[name=regexCustom]", this).val() != null && $("input[name=regexCustom]", this).val() != "") {
            fieldRegex = $("input[name=regexCustom]", this).val();
        }

        if (fieldRegex != "" && fieldValue != "") {
            //alert(fieldRegex);
            var regex = new RegExp(fieldRegex);
            if (!regex.test(fieldValue)) {
                $(".error", this).html("Invalid");
                $(".field", this).css("background", "#ff9988");

                //ga to track incorrectly completed fields
                if (typeof recordGAEvent == "function") {
                    _gaq.push(['_trackEvent', 'Form Error', $(this).parent().find("[name=FormName]").val() + " - " + $(this).find(".caption").html(), "Invalid"]);
                }
            }
            else {
                $(".error", this).html("");
                $(".field", this).css("background", "");
            }
        }
    });


    var errors = $(this).parent().find(".error:visible").filter(function () {
        return $.trim(this.innerHTML) != "";
    });


    //if ($(this).parent().find(".error[innerHTML!='']:visible").length == 0) {
    if (errors.length == 0) {
        $(this).parent().find(".formButton").hide();
        $(this).parent().find(".imgProcess").show();

        //ga to track valid form
        if (typeof recordGAEvent == "function") {
            _gaq.push(['_trackEvent', 'Valid Form Submission', $(this).parent().find("[name=FormName]").val()]);
        }

        $(this).parent().find(".divField:visible").each(function () {
            var fieldValue = $.trim($(".field", this).val());
            if (fieldValue == "") {
                //ga to track incompleted non-required fields
                if (typeof recordGAEvent == "function") {
                    _gaq.push(['_trackEvent', 'Uncompleted Non-Required Form Field', $(this).parent().find("[name=FormName]").val(), $(this).find(".caption").html()]);
                }
            }
        });


        if ($(this).parent().find(".inputPostalZipCode").length == 1) {
            var postalCode = $.trim($(this).parent().find(".inputPostalZipCode").val()).toUpperCase();
            if (postalCode != "") {
                //replace value with uppercase
                $(this).parent().find(".inputPostalZipCode").val(postalCode);
                //ga to track postal code
                if (typeof recordGAEvent == "function") {
                    _gaq.push(['_trackEvent', 'ZIP Code Form Field', $(this).parent().find("[name=FormName]").val(), postalCode]);
                }
            }
        }

        //alert('valid');
        if ($(this).parent().find("input[name='postUrl']").val() != "") {

            $(this).parent().find("input[name='valkey']").val("55555");
            var nextUrl = $(this).parent().find("input[name='nextUrl']").val();

            var _tmp_ = getQueryString(window.location.href, "__TMP__");
            if (_tmp_ != "") {
                if (nextUrl.indexOf("?") >= 0) nextUrl += "&__TMP__=" + _tmp_;
                else nextUrl += "?__TMP__=" + _tmp_;
            }

            $.ajax({
                //context: this,
                type: "post",
                url: $(this).parent().find("input[name='postUrl']").val(),
                data: $(this).parent().serialize(),
                success: function (response) {
                    //alert(response);
                    if (response != "") {
                        if (nextUrl.indexOf("?") >= 0) nextUrl += "&" + response;
                        else nextUrl += "?" + response;
                    }
                    document.location = nextUrl;
                },
                error: function () {
                    $(this).parent().find(".formButton").show();
                    $(this).parent().find(".imgProcess").hide();
                    alert("Please try again later");
                }
            });
        }
        else {
            document.location = $(this).parent().find("input[name='nextUrl']").val();
        }
    }
    else {
        //ga to track invalid form
        if (typeof recordGAEvent == "function") {
            _gaq.push(['_trackEvent', 'Invalid Form Submission', $(this).parent().find("[name=FormName]").val()]);
        }


        /*
        var errors = $(this).parent().find(".error:visible").filter(function () {
        return $.trim(this.innerHTML) != "";
        });
        alert(errors.length);
        */
        //alert($(this).parent().find(".error[innerHTML!='']:visible").length);
    }
});
