$(document).ready(function () {
    var formValidate = function (form) {
        if (form.attemptedSubmit == undefined) {
            return false;
        }

        var errChild = false;
        var errLocation = false;
        var errorBox = $(form).find(".ct-booking-error");
        errorBox.empty();

        $(form).find(".ct-booking-travelers-children-ages:visible .ct-booking-travelers-children-age:visible select:visible").each(function (i) {
            if (this.selectedIndex == 0) {
                $(this).addClass("error");
                errChild = true;
            } else {
                $(this).removeClass("error");
            }
        });

        var func = function (i) {
            var l = this.value.length;
            if (l < 3 || l > 25) {
                $(this).addClass("error");
                errLocation = true;
            } else {
                $(this).removeClass("error");
            }
        }
        $(form).find(".ct-travel-from-location:visible input").each(func);
        $(form).find(".ct-travel-to-location:visible input").each(func);

        if (!errChild && !errLocation) {
            errorBox.hide();
            return true;
        }
        if (errLocation) {
            errorBox.append("<p>Please enter a city or airport code of 3 to 25 characters.</p>");
        }
        if (errChild) {
            errorBox.append("<p>Please enter the age of each child.</p>");
        }
        errorBox.show();

        return false;
    }

    $(".ct-booking-travelers-children select").change(function () {
        var i = this.selectedIndex;
        if (i == 0) {
            $("#"+this.id+"-ages").hide();
        } else {
            $("#"+this.id+"-ages").show();
            for (var j = 1; j <= i; ++j) {
                $("#"+this.id+"-"+j).show();
            }
            for (; j < this.options.length; ++j) {
                $("#"+this.id+"-"+j).hide();
            }
        }
        formValidate($(this).parents("form.ct-booking-form")[0]);
    });

    $(".ct-booking-travelers-children select").change();

    $(".ct-travel-from-location input").add(".ct-travel-to-location input").add(".ct-booking-travelers-children-age select").change(function () {
        formValidate($(this).parents("form.ct-booking-form")[0]);
    });

    $("form.ct-booking-form").submit(function () {
        this.attemptedSubmit = true;
        return formValidate(this);
    });

    $(".ct-booking-error").click(function () {
        $(this).hide();
    });
});