﻿/******/ (function() { // webpackBootstrap
/******/ 	"use strict";
/******/ 	var __webpack_modules__ = ({

/***/ 642:
/***/ (function(__unused_webpack_module, exports) {


Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.SecondaryActionsApi = void 0;
var SecondaryActionsApi = /** @class */ (function () {
    function SecondaryActionsApi(serviceFramework) {
        this.serviceFramework = serviceFramework;
    }
    SecondaryActionsApi.prototype.getSettings = function (tabModuleId, formId, productId) {
        var url = this.serviceFramework.getServiceRoot("Dominion/SecondaryActions") + "SecondaryActions/GetSecondaryActions";
        var data = {
            tabModuleId: tabModuleId,
            formId: formId,
            productId: productId,
        };
        return $.ajax({
            type: "POST",
            url: url,
            data: JSON.stringify(data),
            contentType: "application/json",
            beforeSend: this.serviceFramework.setModuleHeaders,
        });
    };
    SecondaryActionsApi.prototype.loadContent = function () {
        var ajaxOption = {
            url: "//" + window.location.hostname + "/DesktopModules/Dominion/Common/Forms/SecondaryActions.aspx",
            cache: false,
            beforeSend: this.serviceFramework.setModuleHeaders,
        };
        return $.ajax(ajaxOption);
    };
    return SecondaryActionsApi;
}());
exports.SecondaryActionsApi = SecondaryActionsApi;


/***/ }),

/***/ 562:
/***/ (function(__unused_webpack_module, exports, __webpack_require__) {


var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", ({ value: true }));
var SessionStorageKey_1 = __importDefault(__webpack_require__(373));
var SessionStorage = /** @class */ (function () {
    function SessionStorage() {
    }
    SessionStorage.prototype.clear = function () {
        window.sessionStorage.clear();
    };
    SessionStorage.prototype.keys = function () {
        var len = window.sessionStorage.length;
        var keys = [];
        for (var i = 0; i < len; ++i) {
            keys.push(window.sessionStorage.key(i));
        }
        return keys;
    };
    SessionStorage.prototype.containsKey = function (key) {
        return this.getKeyString(key) !== undefined;
    };
    SessionStorage.prototype.get = function (key) {
        return window.sessionStorage.getItem(this.getKeyString(key));
    };
    SessionStorage.prototype.set = function (key, value) {
        window.sessionStorage.setItem(this.getKeyString(key), value);
    };
    SessionStorage.prototype.remove = function (key) {
        window.sessionStorage.removeItem(this.getKeyString(key));
    };
    SessionStorage.prototype.getAllKeys = function () {
        return Object.keys(SessionStorageKey_1.default)
            .map(function (k) { return SessionStorageKey_1.default[k]; })
            .filter(function (v) { return typeof v === 'string'; });
    };
    SessionStorage.prototype.getKeyString = function (key) {
        if (typeof key === 'string') {
            return key;
        }
        var keyNames = this.getAllKeys();
        return keyNames[key];
    };
    return SessionStorage;
}());
exports["default"] = SessionStorage;


/***/ }),

/***/ 373:
/***/ (function(__unused_webpack_module, exports) {


Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.SessionStorageKey = void 0;
var SessionStorageKey;
(function (SessionStorageKey) {
    SessionStorageKey[SessionStorageKey["FormPrepopulate"] = 0] = "FormPrepopulate";
})(SessionStorageKey = exports.SessionStorageKey || (exports.SessionStorageKey = {}));
exports["default"] = SessionStorageKey;


/***/ }),

/***/ 729:
/***/ (function(__unused_webpack_module, exports, __webpack_require__) {


var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", ({ value: true }));
var SessionStorage_1 = __importDefault(__webpack_require__(562));
var SessionStorageKey_1 = __importDefault(__webpack_require__(373));
var FormPrePopulate = /** @class */ (function () {
    function FormPrePopulate() {
        this.separator = "|||";
        this.sessionStorage = new SessionStorage_1.default();
    }
    FormPrePopulate.prototype.saveFormData = function (data) {
        var totalMilliseconds = new Date().getTime();
        var id = btoa(totalMilliseconds.toString());
        this.sessionStorage.set(SessionStorageKey_1.default.FormPrepopulate, "" + id + this.separator + JSON.stringify(data));
        return id;
    };
    FormPrePopulate.prototype.getFormData = function (id) {
        var value = this.sessionStorage.get(SessionStorageKey_1.default.FormPrepopulate);
        if (!value) {
            return null;
        }
        if (value.indexOf(this.separator) === -1) {
            return null;
        }
        var splittedText = value.split(this.separator);
        if (splittedText.length === 2) {
            if (splittedText[0] !== id) {
                return null;
            }
            try {
                return JSON.parse(splittedText[1]);
            }
            catch (_a) {
                return null;
            }
        }
        return null;
    };
    return FormPrePopulate;
}());
exports["default"] = FormPrePopulate;


/***/ }),

/***/ 363:
/***/ (function(__unused_webpack_module, exports, __webpack_require__) {


Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.SubmissionCompleteView = void 0;
var ButtonActions_1 = __webpack_require__(134);
var SubmissionCompleteView = /** @class */ (function () {
    function SubmissionCompleteView(clientIdSelector, options) {
        this.isDisplaySecondaryActions = false;
        this.selector = {
            container: clientIdSelector,
        };
        this.options = options;
        this.initElements();
        this.secondaryActionsView = new ButtonActions_1.ButtonActions(this.options.portalId, this.options.moduleId);
        this.isDisplaySecondaryActions = this.secondaryActionsView.isShowSecondaryActionsByFormName(this.options.formName);
    }
    SubmissionCompleteView.prototype.initElements = function () {
        this.$element = {
            container: $(this.selector.container)
        };
    };
    SubmissionCompleteView.prototype.displaySubmissionCompletionModal = function () {
        var _this = this;
        var isDisplayAsDialog = this.isDisplaySecondaryActions;
        if (isDisplayAsDialog) {
            this.$element.container.modal("hide");
            this.addSubmissionCompletionModal();
            this.injectBodyContent().then(function () {
                _this.openSubmissionCompletionModal();
            });
        }
        else {
            // the legacy scenario.
            // display message in div
            // for both open a form from dialog or normal page. 
            this.displayMessage();
        }
    };
    SubmissionCompleteView.prototype.displayMessage = function () {
        // legacy method for display message
        if ($('.formControl').length) {
            var formControl = this.$element.container.find('.formControl');
            var modalContent = formControl.closest(".modal-content");
            var modalFooter = modalContent.find(".modal-footer");
            modalFooter.find('.submit-button').hide();
            this.$element.container.find('.formControl').hide();
        }
        else {
            this.$element.container.find('.section-wrap').hide();
            this.$element.container.find('input[type="button"]').hide();
            this.$element.container.find('.form-title').hide();
        }
        if (!this.$element.container.find('.em-message').length) {
            this.$element.container.append('<p class="em-message"></p>');
        }
        this.$element.container.find('.em-message').html(this.options.displayMessage).show();
        this.$element.container.find('.secure-image').hide();
    };
    SubmissionCompleteView.prototype.injectBodyContent = function () {
        var modalSelector = "#" + this.options.modalId;
        var $dialog = $(modalSelector);
        $dialog.find(".modal-body").html("<div><span>" + this.options.displayMessage + "</span></div>");
        if (!this.isDisplaySecondaryActions) {
            return;
        }
        // binding event when open modal dialog
        var view = this;
        $dialog.off("show.bs.modal").on("show.bs.modal", function () {
            view.secondaryActionsView.init(view.options.tabModuleId, view.options.formName, view.options.productId, ".modal-body", view.options.prevSubmissionId).then(function () {
                // override event when show in dialog
                var testRideButton = view.secondaryActionsView.getScheduleTestRideButton();
                testRideButton.off("click").on("click", function (e) {
                    // display schdule test ride
                    view.secondaryActionsView.onScheduleTestRideButtonClicked(e);
                    // then close submission dialog
                    $dialog.modal("hide");
                });
            });
        });
        return this.secondaryActionsView.loadContent()
            .then(function (htmlContent) {
            $dialog.find(".modal-body").append("<br>");
            $dialog.find(".modal-body").append(htmlContent);
        });
    };
    SubmissionCompleteView.prototype.openSubmissionCompletionModal = function () {
        var modalSelector = '#' + this.options.modalId;
        var $dialog = $(modalSelector);
        $dialog.modal("show");
    };
    SubmissionCompleteView.prototype.addSubmissionCompletionModal = function () {
        if (!this.options.modalId || this.options.modalId === "") {
            this.options.modalId = "SubmissionCompletionModal";
        }
        var modalId = this.options.modalId;
        var modalSelector = "#" + this.options.modalId;
        // clone Title from Form Dialog
        var modalTitle = this.options.formName;
        if (this.$element.container
            && this.$element.container.find(".modal-title").length > 0) {
            modalTitle = this.$element.container.find(".modal-title").html();
        }
        if ($(modalSelector).length > 0) {
            // already exist. just change the modal title.
            var $dialog = $(modalSelector);
            $dialog.find(".modal-title").html(modalTitle);
            return;
        }
        var modalLabelId = this.options.modalId + '_label';
        var modalHtml = '\
        <div class="modal fade" id="' + modalId + '" tabindex="-1" role="dialog" aria-labelledby="' + modalLabelId + '" aria-hidden="true">\
          <div class="modal-dialog">\
            <div class="modal-content">\
              <div class="modal-header">\
                <button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times;</button>\
                <h4 class="modal-title" id="' + modalLabelId + '">' + modalTitle + '</h4>\
              </div>\
              <div class="modal-body"></div>\
              <div class="modal-footer">\
              </div>\
            </div>\
          </div>\
        </div>';
        if ($(modalSelector).length === 0) {
            $("body").append(modalHtml);
        }
    };
    ;
    return SubmissionCompleteView;
}());
exports.SubmissionCompleteView = SubmissionCompleteView;


/***/ }),

/***/ 979:
/***/ (function(__unused_webpack_module, exports, __webpack_require__) {


var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.Dx1ViewForm = exports.Dx1ViewFormView = exports.ViewFormUtil = void 0;
var shiftDigitalAnalyticsManager_1 = __importDefault(__webpack_require__(29));
var FormPrePopulate_1 = __importDefault(__webpack_require__(729));
var polarisDigitasManager_1 = __importDefault(__webpack_require__(542));
var SubmissionCompleteDialog_1 = __webpack_require__(363);
exports.ViewFormUtil = {};
(function (ViewFormUtil) {
    function createMappedKeyWithSuffixIndex(obj, questionMappedKey) {
        for (var i = 1; i < 100; i++) {
            var curKey = questionMappedKey + "_" + i;
            var val = obj[curKey];
            if (!val && val !== 0) {
                return curKey;
            }
        }
        return questionMappedKey + "_100";
    }
    function extractCheckedValuesFromMulitpleCheckboxes($multiChkDiv) {
        var vals = $multiChkDiv
            .find(":checkbox:checked")
            .map(function (idx, elm) {
            return $(elm).val();
        }).get();
        if ($.isArray(vals) && vals.length > 0) {
            return vals.join(",");
        }
        return null;
    }
    function getProductIdJqueryObject(clientId) {
        var $root = $("#" + clientId);
        return $root.find("[data-question-mapped-key-name=\"ProductId\"]");
    }
    function getProductIdManufacturerDropdownJqueryObject(clientId) {
        return getProductIdJqueryObject(clientId).find("select.manufacturer-control");
    }
    function getProductIdCategoryDropdownJqueryObject(clientId) {
        return getProductIdJqueryObject(clientId).find("select.category-control");
    }
    function getProductIdModelDropdownJqueryObject(clientId) {
        return getProductIdJqueryObject(clientId).find("select.model-dropdown-control");
    }
    function hasProductIdValue(clientId) {
        var productId = getProductIdModelDropdownJqueryObject(clientId);
        return !!productId.val();
    }
    function getSelectedProductData(clientId) {
        var $productId = getProductIdModelDropdownJqueryObject(clientId);
        if (!$productId.val()) {
            return null;
        }
        var selectedOptionSelector = "option:selected";
        var $option = $productId.find(selectedOptionSelector);
        var isPolarisOrIndianVendor = $option.data("ispolarisorindianvendor").toString() === "1";
        if (!isPolarisOrIndianVendor) {
            return null;
        }
        var manufacturerName = getProductIdManufacturerDropdownJqueryObject(clientId).val();
        var categoryName = getProductIdCategoryDropdownJqueryObject(clientId).val();
        var productTypeName = $option.data("type").toString();
        return {
            isPolarisOrIndianVendor: isPolarisOrIndianVendor,
            manufacturerName: manufacturerName,
            categoryName: categoryName,
            productTypeName: productTypeName
        };
    }
    function isElementModelControl($elm, questionMappedKey) {
        return $elm.find("div.model-control").get(0) && questionMappedKey === "ProductId";
    }
    function extractProductIdFromModelControl($elm) {
        return $elm.find("select.model-dropdown-control").val();
    }
    function extractValueFromInput($elm, questionMappedKey) {
        var val = null;
        var $input = $elm.find("input:visible");
        var $select = $elm.find("select:visible");
        var $textarea = $elm.find("textarea:visible");
        var $multiChkDiv = $elm.find("div.multi-choice");
        var isCheckEmptyValue = false;
        if (isElementModelControl($elm, questionMappedKey)) {
            val = extractProductIdFromModelControl($elm);
        }
        else if ($multiChkDiv.get(0) && questionMappedKey !== "HasJointApplicant") {
            val = extractCheckedValuesFromMulitpleCheckboxes($multiChkDiv);
        }
        else if ($input.get(0)) {
            if ($input.length > 1 && $input.is(":radio")) {
                val = $elm.find("input[type=radio]:checked").val();
            }
            else if ($input.is(":checkbox")) {
                val = $input.is(":checked");
            }
            else {
                val = $input.val();
                isCheckEmptyValue = true;
            }
        }
        else if ($select.get(0)) {
            val = $select.val();
            isCheckEmptyValue = true;
        }
        else if ($textarea.get(0)) {
            val = $textarea.val();
            isCheckEmptyValue = true;
        }
        if (isCheckEmptyValue && val === "") {
            return null;
        }
        if (val && $.type(val) === "string") {
            val = val.trim();
        }
        if (!val && val !== 0 && ["Comment", "JointApplicantComment"].indexOf(questionMappedKey) > -1) {
            return null;
        }
        return val;
    }
    function setPrintLeadInfoData($elm, val, data, questionMappedKey, isBrpRequestMoreInfo) {
        var printLeadInfo = data["PrintLeadInfo"];
        if (!printLeadInfo) {
            printLeadInfo = {};
            data["PrintLeadInfo"] = printLeadInfo;
        }
        if (["Comment", "JointApplicantComment"].indexOf(questionMappedKey) > -1) {
            var $financeAppPrint = $elm.find("[data-financeapp-isprint]");
            if (!$financeAppPrint.length || $financeAppPrint.attr("data-financeapp-isprint").toLowerCase() !== "true") {
                return;
            }
            var commentLabelText = $elm.find("[data-relationship-name]").attr("data-relationship-name");
            if (questionMappedKey === "JointApplicantComment") {
                commentLabelText = "JointApplicant - " + commentLabelText;
            }
            if (isBrpRequestMoreInfo) {
                if (!printLeadInfo[commentLabelText] &&
                    (commentLabelText.toLowerCase() == "comments" || commentLabelText.toLowerCase() == "comment")) {
                    printLeadInfo[commentLabelText] = val;
                }
            }
            else {
                if (!printLeadInfo[commentLabelText]) {
                    printLeadInfo[commentLabelText] = val;
                }
                else {
                    var nextMappedKey = createMappedKeyWithSuffixIndex(printLeadInfo, commentLabelText);
                    printLeadInfo[nextMappedKey] = val;
                }
            }
        }
    }
    function getFormName(clientId) {
        var $root = $("#" + clientId);
        if (!$root.get(0)) {
            return null;
        }
        return $root.find("[data-form-name]").attr("data-form-name");
    }
    var shouldNotMapKeys = ["AdSourceName", "IncomeLevel"];
    var brpRequestMoreInfoFormId = "b3b6cb33-3150-4c83-afff-0b4a497006fe";
    function buildFormJsonRequestMessage(clientId, opts) {
        var $root = $("#" + clientId);
        if (!$root.get(0)) {
            return null;
        }
        var data = {
            FormName: getFormName(clientId)
        };
        var isBrpRequestMoreInfo = false;
        if (opts && opts.formId == brpRequestMoreInfoFormId) {
            isBrpRequestMoreInfo = true;
        }
        $root.find("[data-question-mapped-key-name]").each(function (idx, elm) {
            var $elm = $(elm);
            var questionMappedKey = $elm.attr("data-question-mapped-key-name");
            if (!questionMappedKey || shouldNotMapKeys.indexOf(questionMappedKey) >= 0) {
                return;
            }
            var nextMappedKey;
            var val = extractValueFromInput($elm, questionMappedKey);
            if (val === null) {
                return;
            }
            if (!data[questionMappedKey] && data[questionMappedKey] !== "" && ["Comment", "JointApplicantComment"].indexOf(questionMappedKey) === -1) {
                data[questionMappedKey] = val;
            }
            else {
                var leadInfo = data["LeadInfo"];
                if (!leadInfo) {
                    leadInfo = {};
                    data["LeadInfo"] = leadInfo;
                }
                if (["Comment", "JointApplicantComment"].indexOf(questionMappedKey) > -1) {
                    var commentLabelText = $elm.find("[data-relationship-name]").attr("data-relationship-name");
                    if (questionMappedKey === "JointApplicantComment") {
                        commentLabelText = "JointApplicant - " + commentLabelText;
                    }
                    var $discalimer = $elm.find("[data-financeapp-isdisclaimer]");
                    var isDisclaimer = false;
                    if ($discalimer.length) {
                        isDisclaimer = $discalimer.attr("data-financeapp-isdisclaimer").toLowerCase() === "true";
                    }
                    if (!isDisclaimer) {
                        if (isBrpRequestMoreInfo) {
                            if (!leadInfo[commentLabelText] &&
                                (commentLabelText.toLowerCase() == "comments" || commentLabelText.toLowerCase() == "comment")) {
                                leadInfo[commentLabelText] = val;
                            }
                        }
                        else {
                            if (!leadInfo[commentLabelText]) {
                                leadInfo[commentLabelText] = val;
                            }
                            else {
                                nextMappedKey = createMappedKeyWithSuffixIndex(leadInfo, commentLabelText);
                                leadInfo[nextMappedKey] = val;
                            }
                        }
                    }
                }
                else if (!leadInfo[questionMappedKey]) {
                    leadInfo[questionMappedKey] = val;
                }
                else {
                    nextMappedKey = createMappedKeyWithSuffixIndex(leadInfo, questionMappedKey);
                    leadInfo[nextMappedKey] = val;
                }
                setPrintLeadInfoData($elm, val, data, questionMappedKey, isBrpRequestMoreInfo);
            }
        });
        return data;
    }
    function clearForm(clientId) {
        var $root = $("#" + clientId);
        $root.find("[data-question-mapped-key-name] input:not([type=checkbox]):not([type=radio]):not([type=hidden])").val("");
        $root.find("[data-question-mapped-key-name] select:visible").each(function (idx, elm) {
            var $select = $(elm);
            $select.val("");
            $select.find("option:first").attr("selected", "");
        });
    }
    ViewFormUtil.clearForm = clearForm;
    ViewFormUtil.getFormName = getFormName;
    ViewFormUtil.buildFormJsonRequestMessage = buildFormJsonRequestMessage;
    ViewFormUtil.hasProductIdValue = hasProductIdValue;
    ViewFormUtil.getSelectedProductData = getSelectedProductData;
})(exports.ViewFormUtil);
var Dx1ViewFormView = /** @class */ (function () {
    function Dx1ViewFormView(clientIdSelector, options) {
        this.selector = {
            container: clientIdSelector,
        };
        this.options = options;
        this.initElements();
    }
    Dx1ViewFormView.prototype.displaySubmissionCompletionModal = function (responseMessage) {
        var message = responseMessage ? responseMessage : this.getFinalMessage();
        if ($('.formControl').length) {
            var formControl = this.$element.container.find('.formControl');
            var modalContent = formControl.closest(".modal-content");
            var modalFooter = modalContent.find(".modal-footer");
            modalFooter.find('.submit-button').hide();
            this.$element.container.find('.formControl').hide();
        }
        else {
            this.$element.container.find('.section-wrap').hide();
            this.$element.container.find('input[type="button"]').hide();
            this.$element.container.find('.form-title').hide();
        }
        if (!this.$element.container.find('.em-message').length) {
            this.$element.container.append('<p class="em-message"></p>');
        }
        this.$element.container.find('.em-message').html(message).show();
        this.$element.container.find('.secure-image').hide();
    };
    Dx1ViewFormView.prototype.initElements = function () {
        this.$element = {
            container: $(this.selector.container)
        };
    };
    Dx1ViewFormView.prototype.getFinalMessage = function () {
        return this.options.finalMessage;
    };
    return Dx1ViewFormView;
}());
exports.Dx1ViewFormView = Dx1ViewFormView;
function Dx1ViewForm(clientId, options) {
    var reCaptchaTimeout = 60000;
    var self = this;
    var container = $('#' + clientId);
    var sf = $.ServicesFramework(options.moduleId);
    self.sf = sf;
    self.clientId = clientId;
    self.options = $.extend({
        submitText: 'Submit',
        submittingText: 'Submitting...',
        submittingClass: 'submitting',
        validationGroup: '',
        moduleId: 0
    }, options);
    var formPrepopulate = new FormPrePopulate_1.default();
    var selectors = {
        preferredContactSection: "[data-question-mapped-key-name='PreferredContact']",
        isCcpaSection: "[data-question-mapped-key-name='IsCcpa']",
        isTcpaSection: "[data-question-mapped-key-name='IsTcpa']",
        cellPhoneSection: "[data-question-mapped-key-name='CellPhone']",
        consentCheckboxSection: ".dx1-consent",
    };
    var validationMessage = {
        ccpaIsRequired: "This field is required.",
        tcpaIsRequired: "This field is required when phone or text are selected as the preferred contact method.",
        emailInvalidFormat: "Email Address should be in name@domain.com format.",
        phoneInvalidFormat: "Phone number should only consist of numbers, ( ), -, +",
        dateInvalidFormat: "Date must be in the format MM/DD/YYYY.",
        birthdateIsInvalid: "Date of Birth is not valid.",
    };
    var guidEmpty = "00000000-0000-0000-0000-000000000000";
    function getSelectedModelData() {
        var $selectedModel = container.find("[id$=SelectedModel]");
        if (!$selectedModel || !$selectedModel.length) {
            return null;
        }
        var selectedModel = $selectedModel.val();
        try {
            return JSON.parse(selectedModel);
        }
        catch (err) {
            return null;
        }
    }
    function setSelectedModelData(category, manufacturer, year, model) {
        var json = {
            category: category,
            manufacturer: manufacturer,
            year: year,
            model: model
        };
        var jsonString = JSON.stringify(json);
        var selectedModelHiddenField = container.find("[id$=SelectedModel]");
        selectedModelHiddenField.val(jsonString);
    }
    function setDropDownValue(control, value) {
        if (!control || !control.length || !value) {
            return;
        }
        control.val(value);
    }
    function callAjaxToGetModelLookUpData(url) {
        return $.ajax({
            type: "GET",
            url: url + "&_=" + new Date().getTime(),
            beforeSend: sf.setModuleHeaders
        });
    }
    function getModelDropdownOptions(item) {
        var optionText = item.ProductName;
        if (item.ProductColor && item.ProductColor.length > 0) {
            optionText += "-" + item.ProductColor;
        }
        var isPolarisOrIndianVendor = item.IsPolarisOrIndianVendor ? "1" : "0";
        var $option = $("<option/>").text(optionText)
            .val(item.ProductGuid)
            .attr({
            "data-ispolarisorindianvendor": isPolarisOrIndianVendor,
            "data-type": item.ProductTypeName,
        });
        return $option.get(0).outerHTML;
    }
    function activateAndFillDropdowWithData(ddl, data, defaultValue) {
        var $ddl = $(ddl);
        if (!$ddl.get(0) || !$.isArray(data)) {
            return;
        }
        $ddl.prop("disabled", false);
        $ddl.empty();
        var optionItems = '<option value="">' + defaultValue + '</option>';
        $.each(data, function (idx, obj) {
            if (defaultValue === "Model") {
                optionItems += getModelDropdownOptions(obj);
            }
            else {
                optionItems += '<option value="' + obj + '">' + obj + '</option>';
            }
        });
        $ddl.html(optionItems);
        if ($ddl.get(0) === self.modelDropDown) {
            if (self.options.productId !== guidEmpty) {
                self.modelDropDown.val(self.options.productId);
            }
        }
    }
    function populateManufacturerDropdown(selectedCategoryCode) {
        var url = sf.getServiceRoot('Dominion/Forms')
            + 'Forms/GetManufacturerByFilter?category='
            + selectedCategoryCode;
        return callAjaxToGetModelLookUpData(url)
            .then(function (response) {
            if (response.IsSuccess) {
                activateAndFillDropdowWithData(self.manufacturerDropDown, response.Manufacturers, "Manufacturer");
            }
        });
    }
    function populateYearDropdown(category, manufacturer) {
        var url = sf.getServiceRoot('Dominion/Forms')
            + 'Forms/GetYearByFilter?'
            + 'category=' + category
            + '&manufacturer=' + manufacturer;
        return callAjaxToGetModelLookUpData(url)
            .then(function (response) {
            if (response.IsSuccess) {
                activateAndFillDropdowWithData(self.yearDropDown, response.Years, "Year");
            }
        });
    }
    function populateModelDropdown(category, manufacturer, year) {
        var url = sf.getServiceRoot('Dominion/Forms')
            + 'Forms/GetModelByFilter?'
            + 'category=' + category
            + '&manufacturer=' + manufacturer
            + '&year=' + year;
        return callAjaxToGetModelLookUpData(url)
            .then(function (response) {
            if (response.IsSuccess) {
                activateAndFillDropdowWithData(self.modelDropDown, response.Models, "Model");
            }
        });
    }
    function initModelControlValue() {
        var deferred = $.Deferred();
        var selectedModelJson = getSelectedModelData();
        if (!selectedModelJson || !selectedModelJson.category) {
            return deferred.reject();
        }
        return $.when(populateManufacturerDropdown(selectedModelJson.category), populateYearDropdown(selectedModelJson.category, selectedModelJson.manufacturer), populateModelDropdown(selectedModelJson.category, selectedModelJson.manufacturer, selectedModelJson.year))
            .then(function () {
            setDropDownValue(self.manufacturerDropDown, selectedModelJson.manufacturer);
            setDropDownValue(self.yearDropDown, selectedModelJson.year);
            setDropDownValue(self.modelDropDown, selectedModelJson.model);
            if (!selectedModelJson.manufacturer) {
                self.yearDropDown.prop("disabled", true);
                self.modelDropDown.prop("disabled", true);
            }
            else if (!selectedModelJson.year) {
                self.modelDropDown.prop("disabled", true);
            }
            return $.Deferred().resolve().promise();
        });
    }
    function initCategoryDropDownEventHandler() {
        self.categoryDropDown.change(function () {
            self.modelDropDown.val("");
            self.modelDropDown.prop('disabled', true);
            self.yearDropDown.val("");
            self.yearDropDown.prop('disabled', true);
            self.manufacturerDropDown.val("");
            var selectedCategory = self.categoryDropDown.val();
            if (selectedCategory === '') {
                setSelectedModelData(null, null, null, null);
                self.manufacturerDropDown.prop('disabled', true);
                return;
            }
            populateManufacturerDropdown(selectedCategory);
        });
    }
    function initManufacturerDropdDownEventHandler() {
        self.manufacturerDropDown.change(function () {
            var selectedCategory = self.categoryDropDown.val();
            var selectedManufacturer = self.manufacturerDropDown.val();
            self.modelDropDown.val("");
            self.modelDropDown.prop('disabled', true);
            self.yearDropDown.val("");
            if (selectedManufacturer === '') {
                setSelectedModelData(selectedCategory, null, null, null);
                self.yearDropDown.prop('disabled', true);
                return;
            }
            var isProductCategoryNoYear = self.categoryDropDown
                .find("option[value='" + selectedCategory + "']")
                .attr("data-is-no-product-year") === "true";
            if (isProductCategoryNoYear) {
                self.yearDropDown.prop('disabled', true);
                setSelectedModelData(selectedCategory, selectedManufacturer, null, null);
                populateModelDropdown(selectedCategory, selectedManufacturer, "0");
            }
            else {
                setSelectedModelData(selectedCategory, selectedManufacturer, null, null);
                populateYearDropdown(selectedCategory, selectedManufacturer);
            }
        });
    }
    function initYearDropDownEventHandler() {
        self.yearDropDown.change(function () {
            var selectedCategory = self.categoryDropDown.val();
            var selectedManufacturer = self.manufacturerDropDown.val();
            var selectedYear = self.yearDropDown.val();
            if (selectedYear === '') {
                setSelectedModelData(selectedCategory, selectedManufacturer, null, null);
                self.modelDropDown.val("");
                self.modelDropDown.prop('disabled', true);
                return;
            }
            setSelectedModelData(selectedCategory, selectedManufacturer, selectedYear, null);
            populateModelDropdown(selectedCategory, selectedManufacturer, selectedYear);
        });
    }
    function initModelDropDownEventHandler() {
        self.modelDropDown.change(function () {
            var model = self.modelDropDown.val();
            if (!model) {
                model = null;
            }
            setSelectedModelData(self.categoryDropDown.val(), self.manufacturerDropDown.val(), self.yearDropDown.val(), model);
        });
    }
    function showModal(title, message) {
        var dialogHtml = '<div class="modal fade in" role="dialog" aria-hidden="true"><div class="modal-dialog modal-m"><div class="modal-content">';
        dialogHtml += '<div class="modal-header"><button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button> <h4 class="modal-title">' + title + '</h4></div>';
        dialogHtml += '<div class="modal-body">' + message + '</div>';
        dialogHtml += '<div class="modal-footer" style="text-align:left;"><button type="button" class="btn btn-primary" data-dismiss="modal">OK</button></div>';
        dialogHtml += '</div></div></div>';
        var $dialog = $(dialogHtml);
        $dialog.modal("show");
        $dialog.on("hidden.bs.modal", function (e) {
            $(e.currentTarget).remove();
        });
    }
    function showRecaptionSessionExpiredModel() {
        showModal("Session expired", "Please verify recaptcha to renew your session.");
    }
    function setReCaptchaTimeout() {
        var wrappers = container.find('.recaptcha-wrapper');
        var $wrapper = $(wrappers[0]);
        $wrapper.closest(".form-group").find(".error-message").hide();
        self.timeoutId = setTimeout(function () {
            grecaptcha.reset(self.widgetId);
            showRecaptionSessionExpiredModel();
        }, reCaptchaTimeout);
    }
    function clearReCaptchaTimeout() {
        if (self.timeoutId !== undefined) {
            clearTimeout(self.timeoutId);
            self.timeoutId = undefined;
        }
    }
    function clearReCaptcha() {
        grecaptcha.reset(self.widgetId);
        clearReCaptchaTimeout();
    }
    self.clearReCaptcha = clearReCaptcha;
    function checkReCaptcha() {
        var recaptchaResponse = grecaptcha.getResponse(container.find(".recaptcha-wrapper").attr("widget-id"));
        var errorMessageCtrl = container.find(".recaptcha-section.form-group").find('.error-message');
        if (recaptchaResponse.length === 0) {
            errorMessageCtrl.show();
            errorMessageCtrl.css('display', 'inline');
            return false;
        }
        errorMessageCtrl.hide();
        return true;
    }
    function resetFormAfterSubmitSuccess() {
        clearReCaptcha();
        setSubmitButtonState(false);
        exports.ViewFormUtil.clearForm(self.clientId);
    }
    function handleErrorSubmitForm(button, isInvalidRecaptcha) {
        if (isInvalidRecaptcha) {
            showRecaptionSessionExpiredModel();
        }
        else {
            alert("Sorry there was an error submitting your form.");
        }
        grecaptcha.reset(self.widgetId);
        setSubmitButtonState(false);
    }
    function hasShiftDigitalAnalyticsCookie() {
        var cookieName = "dx1dnn_sd";
        var value = getCookie(cookieName);
        if (value === "") {
            return false;
        }
        try {
            var obj = JSON.parse(value);
            if (obj.CampaignName || obj.CampaignType) {
                return true;
            }
            return false;
        }
        catch (_a) {
            return false;
        }
    }
    function getShiftDigitalAnalyticsCookie(key) {
        var cookieName = "dx1dnn_sd";
        var coookieValue = getCookie(cookieName);
        var json = JSON.parse(coookieValue);
        var value = json[key];
        return value ? decodeURIComponent(value) : null;
    }
    function getShiftDigitalAnalyticsCampaignName() {
        return getShiftDigitalAnalyticsCookie("CampaignName");
    }
    function getShiftDigitalAnalyticsCampaignType() {
        return getShiftDigitalAnalyticsCookie("CampaignType");
    }
    function getDisclaimerFromConsentCheckbox(consentCheckboxSection) {
        if (consentCheckboxSection) {
            var disclaimer = consentCheckboxSection.find(".dx1-consent-label").html();
            return disclaimer;
        }
        return null;
    }
    function getFormData(opts) {
        var data = exports.ViewFormUtil.buildFormJsonRequestMessage(self.clientId, opts);
        if (opts.productId && opts.productId !== guidEmpty) {
            data.ProductId = opts.productId;
            data.CurrentPrice = opts.currentPrice;
        }
        if (opts.dealershipId && opts.dealershipId !== guidEmpty) {
            data.DealershipId = opts.dealershipId;
        }
        data.SiteId = opts.siteId;
        data.BrandIntegrityTemplateSiteId = opts.brandIntegrityTemplateSiteId;
        data.TabModuleId = opts.tabModuleId;
        data.FormId = opts.formId;
        data.SessionId = window["sd"] ? opts.sessionId : null;
        if (hasShiftDigitalAnalyticsCookie()) {
            data.CampaignName = getShiftDigitalAnalyticsCampaignName();
            data.CampaignType = getShiftDigitalAnalyticsCampaignType();
        }
        var $isCcpaSection = container.find(selectors.isCcpaSection);
        if ($isCcpaSection) {
            data.CcpaDisclaimer = getDisclaimerFromConsentCheckbox($isCcpaSection);
        }
        var $isTcpaSection = container.find(selectors.isTcpaSection);
        if ($isTcpaSection) {
            data.TcpaDisclaimer = getDisclaimerFromConsentCheckbox($isTcpaSection);
        }
        return data;
    }
    function sendGoogleAnalyticForFormSubmission() {
        if (!window.ga || !$.isFunction(ga)) {
            return;
        }
        var trackers = ga.getAll();
        if (!$.isArray(trackers)) {
            return;
        }
        var tracker = trackers[0];
        if (!tracker) {
            return;
        }
        tracker.send('pageview', '/Submission-Confirmation');
    }
    function checkPaidExisting() {
        var dx1SemName = "Dx1Sem";
        var value = getCookie(dx1SemName);
        if (value === "") {
            return false;
        }
        var obj = JSON.parse(value);
        return Boolean.parse(obj.IsDx1Sem);
    }
    function getCookie(cookieName) {
        var name = cookieName + "=";
        var allCookies = document.cookie.split(';');
        var cVal = [];
        for (var i = 0; i < allCookies.length; i++) {
            if (allCookies[i].trim().indexOf(name) === 0) {
                cVal = allCookies[i].trim().split("=");
            }
        }
        return cVal.length <= 0 ? "" : decodeURIComponent(cVal[1]);
    }
    function submitForm() {
        var deferred = $.Deferred();
        var opts = self.options;
        var button = self.submitButton;
        setSubmitButtonState(true);
        var recaptchaResponse = grecaptcha.getResponse(self.widgetId);
        var formData = getFormData(opts);
        var formName = formData.FormName;
        var utm_campaign = "";
        var isSemFromCookie = checkPaidExisting();
        if (isSemFromCookie) {
            var value = getCookie("Dx1Sem");
            if (value !== "") {
                utm_campaign = JSON.parse(value).utm_campaign;
            }
        }
        var requestData = {
            isDx1Sem: isSemFromCookie,
            utm_Campaign: utm_campaign,
            formData: formData,
            relativeUrl: $("#" + self.clientId).find("[data-form-relative-url]").attr("data-form-relative-url"),
            reCaptchaResponse: recaptchaResponse,
            reCaptchaEnabled: true
        };
        var relativeUrl = requestData.relativeUrl;
        var submitUrl = "https://"
            + opts.hostPortalAlias
            + "/desktopmodules/dominion/forms/api/Forms/SubmitForm?formId="
            + opts.formId;
        if (self
            && self.options
            && self.options.isFromFeatured) {
            requestData.isFromFeatured = true;
        }
        if (window.brpAnalyticHelper) {
            // UCS144 - Submit Contact Form (get offer)
            window.brpAnalyticHelper.sendAnalyticsEvent("userAction", {
                "category": "form submit",
                "action": "Get Offer",
                "label": "from smartsite",
                "form_option": window.brpAnalyticHelper.selectItem.ProductName,
                "product_status": window.brpAnalyticHelper.selectItem.Condition
            });
        }
        var requestJson = JSON.stringify(requestData);
        $.support.cors = true;
        $.ajax({
            type: "POST",
            url: submitUrl,
            data: requestJson,
            crossDomain: true,
            dataType: "json",
            error: function (jqXhr, textStatus, errorThrown) {
                console.warn(textStatus, errorThrown, jqXhr);
                handleErrorSubmitForm(button, null);
                deferred.reject();
            },
            success: function (response) {
                if (!response.Success) {
                    handleErrorSubmitForm(button, response.IsInvalidRecaptcha);
                    return;
                }
                var submissionSuccessFunc = function () {
                    sendFormSubmissionEventToBrpAnalytics(formName, opts);
                    var submissionId = saveFormPrepopulateData(formName, formData);
                    if (opts.finalUrl) {
                        var productId = formData.ProductId;
                        sendPolarisDigitasSubmitEvent(response.TransactionId);
                        redirectToSubmissionConfirmationPage(opts.finalUrl, productId, opts.tabModuleId, formName, submissionId);
                    }
                    else if (opts.finalMessage) {
                        sendGoogleAnalyticForFormSubmission();
                        sendPolarisDigitasEvents(response.TransactionId);
                        var options_1 = {
                            portalId: opts.portalId,
                            moduleId: opts.moduleId,
                            tabModuleId: opts.tabModuleId,
                            productId: opts.productId,
                            displayMessage: response.Message ? response.Message : opts.finalMessage,
                            formName: formName,
                            modalId: "",
                            prevSubmissionId: submissionId,
                        };
                        var view = new SubmissionCompleteDialog_1.SubmissionCompleteView("#" + clientId, options_1);
                        view.displaySubmissionCompletionModal();
                        resetFormAfterSubmitSuccess();
                    }
                    deferred.resolve();
                };
                if (shiftDigitalAnalyticsManager_1.default === null || shiftDigitalAnalyticsManager_1.default === void 0 ? void 0 : shiftDigitalAnalyticsManager_1.default.isActivated()) {
                    var shiftDigitalAnalyticsVehicleData = opts.shiftDigitalAnalyticsVehicleData;
                    var isPolarisOrIndianVendor = opts.isPolarisOrIndianVendor;
                    if (shiftDigitalAnalyticsVehicleData == null && relativeUrl.toLowerCase().indexOf('postfinanceapplicationlead') > -1) {
                        isPolarisOrIndianVendor = response.IsPolarisOrIndianVendor;
                        shiftDigitalAnalyticsVehicleData = response.ShiftDigitalAnalyticsVehicleData;
                    }
                    var formEventData = {
                        formName: formName,
                        relativeUrl: relativeUrl,
                        productId: opts.productId,
                        shiftDigitalAnalyticsVehicleData: shiftDigitalAnalyticsVehicleData,
                        leadTransactionId: response.TransactionId,
                        isPolarisOrIndianVendor: isPolarisOrIndianVendor
                    };
                    shiftDigitalAnalyticsManager_1.default.instance().sendFormSubmissionEvent(formEventData).then(function () {
                        submissionSuccessFunc();
                    });
                }
                else {
                    submissionSuccessFunc();
                }
            }
        });
        return deferred.promise();
    }
    function isSentWithSecondaryAction(formName) {
        var formList = [
            "request more information",
            "schedule a test drive",
            "quick request more information"
        ];
        var findFormName = formName.toLowerCase();
        var index = formList.findIndex(function (e) { return e === findFormName; });
        return index > -1;
    }
    function redirectToSubmissionConfirmationPage(url, productId, tabModuleId, formName, submissionId) {
        var redirectUrl = url;
        if (productId
            && redirectUrl.indexOf(window.location.host) > -1) {
            redirectUrl = redirectUrl + "/UnitId/" + productId;
            if (isSentWithSecondaryAction(formName)) {
                if (submissionId) {
                    redirectUrl = redirectUrl + "/PrevSubmissionId/" + submissionId;
                }
                if (tabModuleId) {
                    redirectUrl = redirectUrl + "/tabModuleId/" + tabModuleId;
                }
                if (formName) {
                    redirectUrl = redirectUrl + "/reqFormName/" + formName;
                }
            }
        }
        window.location = redirectUrl;
    }
    function sendPolarisDigitasEvents(leadTransactionId) {
        if (!(polarisDigitasManager_1.default === null || polarisDigitasManager_1.default === void 0 ? void 0 : polarisDigitasManager_1.default.isActivated())) {
            return;
        }
        sendPolarisDigitasThankyouPageEvent();
        sendPolarisDigitasSubmitEvent(leadTransactionId);
    }
    function sendPolarisDigitasThankyouPageEvent() {
        if (!(polarisDigitasManager_1.default === null || polarisDigitasManager_1.default === void 0 ? void 0 : polarisDigitasManager_1.default.isActivated())) {
            return;
        }
        var opts = self.options;
        if (!opts.isPolarisOrv) {
            return;
        }
        polarisDigitasManager_1.default.instance().sendThankyouPageEvent(opts.modelDisplayName);
    }
    function sendPolarisDigitasSubmitEvent(leadTransactionId) {
        if (!(polarisDigitasManager_1.default === null || polarisDigitasManager_1.default === void 0 ? void 0 : polarisDigitasManager_1.default.isActivated())) {
            return;
        }
        var clientId = self.clientId;
        var options = self.options;
        if (!options.isPolarisOrIndianVendor && !exports.ViewFormUtil.hasProductIdValue(clientId)) {
            return;
        }
        var data = getPolarisDigitasSubmitEventData(leadTransactionId, options.formTitle);
        if (data) {
            polarisDigitasManager_1.default.instance().sendFormSubmitEvent(data);
        }
    }
    function getPolarisDigitasSubmitEventData(leadTransactionId, formTitle) {
        var options = self.options;
        if (options.isPolarisOrIndianVendor) {
            return {
                leadTransactionId: leadTransactionId,
                isInventory: options.isInventory,
                manufacturerName: options.manufacturer,
                category: options.category,
                type: options.type,
                formTitle: formTitle
            };
        }
        else {
            var productData = exports.ViewFormUtil.getSelectedProductData(clientId);
            if (!productData) {
                return null;
            }
            return {
                leadTransactionId: leadTransactionId,
                isInventory: options.isInventory,
                manufacturerName: productData.manufacturerName,
                category: productData.categoryName,
                type: productData.productTypeName,
                formTitle: formTitle
            };
        }
    }
    function saveFormPrepopulateData(formName, formData) {
        if (!isSentWithSecondaryAction(formName)) {
            return;
        }
        var data = {
            firstName: formData.FirstName,
            lastName: formData.LastName,
            email: formData.Email,
            phone: formData.Phone,
            zipCode: formData.ZipCode,
        };
        return formPrepopulate.saveFormData(data);
    }
    function getValidationControl(selector) {
        var $container = $(selector);
        var $control = $container.find(".form-control").first();
        // finding Rating
        if (!$control.length && $container.find(".dx1-rating").length > 0) {
            $control = $container.find(".dx1-rating").find(":button");
            // making input more identity.
            if (!$control[0].name) {
                $control[0].name = $container.find(".dx1-rating")[0].id;
            }
        }
        // finding Multi Choice
        var $multiChoice = $container.find(".multi-choice");
        if (!$control.length && $multiChoice.length > 0) {
            $control = $multiChoice.find(":checkbox, :radio");
        }
        if ($container.data("question-mapped-key-name") === "ProductId") {
            $control = $container.find(".form-control.model-dropdown-control").first();
        }
        // finding Consent Checkbox
        if (!$control.length && $container.find(selectors.consentCheckboxSection).length > 0) {
            $control = $container.find(selectors.consentCheckboxSection).find(":checkbox");
        }
        return $control;
    }
    function validate(buttonElement) {
        var $validationRules = container.find("[data-question-validation-rules]");
        if ($validationRules && $validationRules.length) {
            var isValidForm = true;
            var $invalidControl;
            $validationRules.each(function (index, element) {
                var $control = getValidationControl(element);
                if ($control && $control.length && !$control.valid() && isValidForm) {
                    isValidForm = false;
                    $invalidControl = $control;
                }
            });
            if (!isValidForm) {
                $invalidControl.focus();
                return $.Deferred().reject().promise();
            }
        }
        self.button = $(buttonElement);
        if (self.options.reCaptchaType === "invisible") {
            grecaptcha.execute(self.widgetId);
        }
        else {
            if (checkReCaptcha()) {
                clearReCaptchaTimeout();
                return submitForm();
            }
        }
        return $.Deferred().reject().promise();
    }
    function moveSubmitButtonToDialogFooterIfShowOnDialog() {
        var newSubmitButton;
        var modalFooter = container.find(".modal-footer");
        if (modalFooter.get(0)) {
            var originalSubmitButton = container.find(".em-view-form-wrap").find('.submit-button');
            newSubmitButton = originalSubmitButton.clone();
            modalFooter.find("input[type=submit]").remove();
            originalSubmitButton.remove();
            newSubmitButton[0].value = self.options.submitText;
            modalFooter.append(newSubmitButton);
        }
        else {
            newSubmitButton = container.find('.submit-button');
        }
        return newSubmitButton;
    }
    function getFormElement() {
        var $form = container.find("form").first();
        if (!$form || !$form.length) {
            $form = container.closest("form");
        }
        return $form;
    }
    function initSubmitButton() {
        var newSubmitButton = moveSubmitButtonToDialogFooterIfShowOnDialog();
        self.submitButton = newSubmitButton;
        self.submitButton.off("click");
        self.submitButton.click(function () {
            self.submitButton.prop("disabled", true);
            validate(this)
                .fail(function () {
                self.submitButton.removeAttr('disabled');
            });
        });
        self.submitButton.show();
        var $form = getFormElement();
        $form.on('submit', function (e) {
            e.preventDefault();
            return false;
        });
    }
    function setSubmitButtonState(isDisable) {
        // submitting data.
        var options = self.options;
        var $button = self.submitButton;
        if (isDisable) {
            if ($button.prop) {
                $button.prop('disabled', true);
            }
            else {
                $button.attr('disabled', 'disabled');
            }
            $button.val(options.submittingText);
            container.addClass(options.submittingClass);
        }
        else {
            $button.val(options.submitText);
            $button.removeAttr("disabled");
        }
    }
    function getValidationMessage(element) {
        var controlLabel = $(element).find("label.question, span.question").first().text().replace("*", "");
        if (controlLabel === "") {
            // in case, the label display type is Inside Textbox.
            controlLabel = $(element).find("[data-relationship-name]").attr("data-relationship-name");
        }
        controlLabel = controlLabel + " is required.";
        // custom validation message for consent checkbox control. "This field is required" .
        var $dx1Consent = $(element).find(selectors.consentCheckboxSection);
        if ($dx1Consent.length > 0) {
            var questionMappedKeyName = $(element).attr("data-question-mapped-key-name").toLowerCase();
            controlLabel = validationMessage.ccpaIsRequired;
            if (questionMappedKeyName === "istcpa") {
                controlLabel = validationMessage.tcpaIsRequired;
            }
        }
        return controlLabel;
    }
    function initCustomValidatorMethods() {
        jQuery.validator.addMethod("dxRequired", function (value, element) {
            if ($(element).is(".form-control")) {
                return value && value.trim();
            }
            if ($(element).closest(".multi-choice").length > 0) {
                return $(element).closest(".multi-choice").find(":checked").length > 0;
            }
            if ($(element).closest(".dx1-rating").length > 0) {
                return $(element).closest(".dx1-rating").find(":button").val() > 0;
            }
            var $dx1Consent = $(element).closest(selectors.consentCheckboxSection);
            if ($dx1Consent.length > 0) {
                var checkboxCount = $dx1Consent.find("input:checkbox:visible").length;
                if (checkboxCount == 0) {
                    return true;
                }
                var checkedCount = $dx1Consent.find("input:checkbox:checked:visible").length;
                return checkboxCount === checkedCount;
            }
            return undefined;
        }, jQuery.validator.format("{0}"));
        jQuery.validator.addMethod("dxEmail", function (value) {
            if (!value || !value.trim()) {
                return true;
            }
            return /^[a-zA-Z0-9._%\-+']+@(?:[a-zA-Z0-9\-]+\.)+(?:[a-zA-Z]{2}|[Aa][Ee][Rr][Oo]|[Aa][Rr][Pp][Aa]|[Aa][Ss][Ii][Aa]|[Bb][Ii][Zz]|[Cc][Aa][Tt]|[Cc][Oo][Mm]|[Cc][Oo][Oo][Pp]|[Ee][dD][Uu]|[Gg][Oo][Vv]|[Ii][Nn][Ff][Oo]|[Ii][Nn][Tt]|[Jj][Oo][Bb][Ss]|[Mm][Ii][Ll]|[Mm][Oo][Bb][Ii]|[Mm][Uu][Ss][Ee][Uu][Mm]|[Nn][Aa][Mm][Ee]|[Nn][Ee][Tt]|[Oo][Rr][Gg]|[Pp][Rr][Oo]|[Rr][Oo][Oo][Tt]|[Tt][Ee][Ll]|[Tt][Rr][Aa][Vv][Ee][Ll]|[Cc][Yy][Mm]|[Gg][Ee][Oo]|[Pp][Oo][Ss][Tt])(?:,\\s?[a-zA-Z0-9._%\-+']+@(?:[a-zA-Z0-9\\-]+\\.)+(?:[a-zA-Z]{2}|[Aa][Ee][Rr][Oo]|[Aa][Rr][Pp][Aa]|[Aa][Ss][Ii][Aa]|[Bb][Ii][Zz]|[Cc][Aa][Tt]|[Cc][Oo][Mm]|[Cc][Oo][Oo][Pp]|[Ee][dD][Uu]|[Gg][Oo][Vv]|[Ii][Nn][Ff][Oo]|[Ii][Nn][Tt]|[Jj][Oo][Bb][Ss]|[Mm][Ii][Ll]|[Mm][Oo][Bb][Ii]|[Mm][Uu][Ss][Ee][Uu][Mm]|[Nn][Aa][Mm][Ee]|[Nn][Ee][Tt]|[Oo][Rr][Gg]|[Pp][Rr][Oo]|[Rr][Oo][Oo][Tt]|[Tt][Ee][Ll]|[Tt][Rr][Aa][Vv][Ee][Ll]|[Cc][Yy][Mm]|[Gg][Ee][Oo]|[Pp][Oo][Ss][Tt]))*$/.test(value);
        }, validationMessage.emailInvalidFormat);
        jQuery.validator.addMethod("dxPhone", function (value) {
            if (!value || !value.trim()) {
                return true;
            }
            return /^[\d+_.() \-]+$/.test(value);
        }, validationMessage.phoneInvalidFormat);
        jQuery.validator.addMethod("dxDate", function (value) {
            if (!value || !value.trim()) {
                return true;
            }
            return /^(0[1-9]|1[0-2])\/(0[1-9]|1\d|2\d|3[01])\/(19|20)\d{2}$/.test(value);
        }, validationMessage.dateInvalidFormat);
        jQuery.validator.addMethod("dxBirthdate", function (value) {
            if (value === null || value === '') {
                return true;
            }
            var today = new Date();
            var validDate = new Date(today.getFullYear(), 1 - 1, 1);
            var selectedDate = new Date(value);
            return selectedDate < validDate;
        }, validationMessage.birthdateIsInvalid);
    }
    function getJqueryValidationRules(validationRules, controlLabelText) {
        var mappedValidationRules = {
            "required": "dxRequired",
            "email": "dxEmail",
            "phone": "dxPhone",
            "date": "dxDate",
            "birthdate": "dxBirthdate"
        };
        if (!validationRules || !validationRules.length) {
            return null;
        }
        var rules = {};
        validationRules.forEach(function (validationRule) {
            var ruleName = mappedValidationRules[validationRule];
            if (ruleName) {
                if (validationRule === "required") {
                    rules[ruleName] = [controlLabelText];
                }
                else {
                    rules[ruleName] = true;
                }
            }
        });
        return rules;
    }
    function removeDefaultValidationRules($control) {
        if (!$control || !$control.length || !$control.rules) {
            return;
        }
        var rules = $control.rules();
        if (rules && rules["email"]) {
            $control.rules("add", { email: false });
        }
    }
    function initFormValidation() {
        var $form = getFormElement();
        $form.validate({
            onsubmit: false,
            onkeyup: false,
            wrapper: "span",
            errorElement: "span",
            errorClass: "error-text",
            highlight: function (element, errorClass, validClass) {
                $(element).removeClass(errorClass).removeClass(validClass);
            },
            unhighlight: function (element, errorClass, validClass) {
                $(element).removeClass(errorClass).addClass(validClass);
            },
            errorPlacement: function ($error, $element) {
                $error.addClass("error-message");
                if ($element.is(".form-control")) {
                    $error.insertAfter($element);
                }
                else {
                    if ($element.closest(".multi-choice").length > 0) {
                        $error.insertAfter($element.closest(".multi-choice"));
                    }
                    if ($element.closest(".dx1-rating").length > 0) {
                        $error.insertAfter($element.parents().eq(1));
                    }
                    if ($element.closest(selectors.consentCheckboxSection).length > 0) {
                        $error.insertAfter($element.closest(selectors.consentCheckboxSection));
                    }
                }
            }
        });
    }
    function initValidationRules() {
        initCustomValidatorMethods();
        initFormValidation();
        var $validationRules = container.find("[data-question-validation-rules]");
        if (!$validationRules || !$validationRules.length) {
            return;
        }
        $validationRules.each(function (index, element) {
            var validationRules = $(element).data("question-validation-rules");
            var controlLabel = getValidationMessage(element);
            var $control = getValidationControl(element);
            if ($control && $control.length) {
                var rules = getJqueryValidationRules(validationRules, controlLabel);
                removeDefaultValidationRules($control);
                $control.rules("add", rules);
            }
        });
    }
    function initModelDropdownControls() {
        var opts = self.options;
        if (opts.productId !== undefined && opts.productId !== '00000000-0000-0000-0000-000000000000') {
            self.modelControl.hide();
            self.modelControl.siblings().hide();
            return;
        }
        if (self.modelControl !== undefined) {
            initModelControlValue().always(function () {
                initCategoryDropDownEventHandler();
                initManufacturerDropdDownEventHandler();
                initYearDropDownEventHandler();
                initModelDropDownEventHandler();
            }).fail(function () {
                if (self.categoryDropDown.val() === '') {
                    self.manufacturerDropDown.prop('disabled', true);
                    self.yearDropDown.prop('disabled', true);
                    self.modelDropDown.prop('disabled', true);
                }
            });
        }
    }
    function initControls() {
        container.find('.error-message').hide();
        container.find('.em-message').text(self.options.finalMessage).hide();
        if (container.find(".datepicker").length > 0) {
            // init datepicker
            container.find(".datepicker").datepicker({
                changeMonth: true,
                changeYear: true,
            });
            // set year range for expire date
            var $expireDateElements = container.find(".datepicker.expiredate");
            $expireDateElements.datepicker("option", "yearRange", "-80:+35");
            // set mindate for birthdate 
            var $birthdatelDatepickerElements = container.find(".datepicker.birthdate");
            $birthdatelDatepickerElements.datepicker("option", "yearRange", "-100:-1");
            $birthdatelDatepickerElements.datepicker("option", "defaultDate", "-1y");
            // set year range for normal datepicker
            var $normalDatepickerElements = container.find(".datepicker.normaldate");
            $normalDatepickerElements.datepicker("option", "yearRange", "-80:+10");
        }
        // Rating
        container.find(".rating-star").on("click", function () {
            var $dx1Rating = $(this).parents(".dx1-rating");
            $dx1Rating.find(".rating-star").removeClass("checked");
            $(this).addClass('checked');
            var submitStars = $(this).attr('data-value');
            $dx1Rating.find(":button").val(submitStars);
            $dx1Rating.find(":button").valid();
        });
        self.modelControl = container.find('.model-control');
        self.categoryDropDown = container.find('.category-control');
        self.manufacturerDropDown = container.find('.manufacturer-control');
        self.yearDropDown = container.find('.year-control');
        self.modelDropDown = container.find('.model-dropdown-control');
        initSubmitButton();
        initValidationRules();
        var opts = self.options;
        initModelDropdownControls();
        initPreferredContact();
        self.locationQuestion = container.find("[data-question-mapped-key-name='DealershipId']");
        if (self.locationQuestion === undefined) {
            return;
        }
        if (opts.productId !== undefined && opts.productId !== '00000000-0000-0000-0000-000000000000') {
            self.locationQuestion.hide();
        }
        initFormPrepopulate();
    }
    function initJointApplication() {
        var jointApplication = container.find('.joint-application-wrapper');
        if (!jointApplication) {
            return;
        }
        var checkbox = container.find(".joint-application-control");
        var jointQuestion = container.find('.joint-application-question');
        var jointSubmitButton = container.find('.joint-application-submit-button');
        var submitButton = container.find('.submit-button');
        jointQuestion.hide();
        jointSubmitButton.hide();
        jointApplication.on('change', function () {
            if (checkbox.prop("checked") === true) {
                jointQuestion.show();
                jointSubmitButton.show();
                submitButton.hide();
            }
            else {
                jointQuestion.hide();
                jointSubmitButton.hide();
                submitButton.show();
            }
        });
        jointSubmitButton.on("click", function () {
            jointSubmitButton.prop("disabled", true);
            return validate(this)
                .fail(function () {
                jointSubmitButton.removeAttr('disabled');
            });
        });
    }
    function onPreferredContactChanged(preferredContact) {
        var $isCcpaSection = container.find(selectors.isCcpaSection);
        var $isTcpaSection = container.find(selectors.isTcpaSection);
        var $cellPhoneSection = container.find(selectors.cellPhoneSection);
        switch (preferredContact.toLowerCase()) {
            case "email":
                $isCcpaSection.show();
                $isTcpaSection.hide();
                $cellPhoneSection.hide();
                break;
            case "phone":
            case "sms":
            case "text":
                $isCcpaSection.show();
                $isTcpaSection.show();
                $cellPhoneSection.show();
                break;
            default:
                $isCcpaSection.hide();
                $isTcpaSection.hide();
                $cellPhoneSection.hide();
        }
    }
    function initPreferredContact() {
        var $preferredContactMethodSection = container.find(selectors.preferredContactSection);
        if ($preferredContactMethodSection.length === 0) {
            return;
        }
        // initial event on change.
        $preferredContactMethodSection.find(".multi-choice input").change(function () {
            var selectedPreferredContact = $(this).val().toString();
            onPreferredContactChanged(selectedPreferredContact);
        });
        // trigger event on change.
        var currentPreferredContact = $preferredContactMethodSection.find(".multi-choice input:checked").val();
        onPreferredContactChanged(currentPreferredContact ? currentPreferredContact.toString() : "");
    }
    function setRecaptchaAriaLabel(containerSelector, intervalId) {
        var textarea = $(containerSelector).find(".g-recaptcha-response");
        if (textarea.length > 0) {
            if (!$(textarea).attr("aria-label")) {
                $(textarea).attr("aria-label", "Google Captcha");
            }
            if (intervalId) {
                clearInterval(intervalId);
            }
        }
    }
    function initRecaptchaAriaLabel(containerSelector) {
        setRecaptchaAriaLabel(containerSelector, undefined);
        var intervalId = setInterval(function () {
            setRecaptchaAriaLabel(containerSelector, intervalId);
        }, 50);
    }
    function initInvisibleRecaptcha() {
        window.ReCaptchaUtil.overrideStyleForGoogleRecaptchaBadgeZIndex();
        var invisibleRecaptcha = "<div id='" + self.clientId + "-invisible-recaptcha'></div>";
        $(invisibleRecaptcha).insertAfter(container);
        self.widgetId = grecaptcha.render(self.clientId + '-invisible-recaptcha', {
            sitekey: self.options.reCaptchaSiteKey,
            callback: submitForm,
            size: "invisible"
        });
        var containerSelector = "div#" + self.clientId + "-invisible-recaptcha";
        initRecaptchaAriaLabel(containerSelector);
    }
    function initCheckboxRecaptcha() {
        var wrappers = container.find('.recaptcha-wrapper');
        if (wrappers.length > 0) {
            var $wrapper = $(wrappers[0]);
            if ($wrapper.attr("widget-id")) {
                // already init
                return;
            }
            self.widgetId = grecaptcha.render($wrapper.prop("id"), {
                sitekey: self.options.reCaptchaSiteKey,
                callback: setReCaptchaTimeout
            });
            $wrapper.attr("widget-id", self.widgetId);
            var containerSelector = ".recaptcha-wrapper[widget-id='" + self.widgetId + "']";
            initRecaptchaAriaLabel(containerSelector);
        }
    }
    function initReCaptcha() {
        if (self.options.reCaptchaType === "invisible") {
            initInvisibleRecaptcha();
            return;
        }
        initCheckboxRecaptcha();
    }
    function getBrpActionByFormName(formName) {
        switch (formName) {
            case 'Quick Request More Information':
            case 'Request More Information':
            case 'Price on Request':
            case 'Price Alert':
            case 'Model Wanted':
                return 'get_a_quote|regular';
            case 'Schedule a Test Drive':
                return 'dealer_demo_std';
            case 'Quick Secure Finance Application':
            case 'Secure Finance Application':
                return 'financing';
            case 'Contact Us':
                return 'contact us';
            case 'Free Trade-In Evaluation':
                return 'get_a_quote|trade-in';
            default:
                return false;
        }
    }
    function isProductEmpty(productId) {
        return productId == undefined || productId == guidEmpty;
    }
    function sendFormSubmissionEventToBrpAnalytics(formName, opts) {
        var action = getBrpActionByFormName(formName);
        if (!window.brpDataLayer ||
            !window.brpAnalyticData ||
            !action ||
            (!isProductEmpty(opts.productId) && !opts.isBrpBrand)) {
            return;
        }
        var data = {
            "event": "userAction",
            "page": {
                "siteType": "dealer marketing",
                "vendor": "dx1"
            },
            "interaction": {
                "category": 'form submit',
                "action": action,
                "label": "from dealer"
            },
            "dealer": window.brpAnalyticData.dealer,
            "brand": {
                "brandName": opts.brpBrand.toLowerCase()
            }
        };
        window.brpDataLayer.push(data);
    }
    function isFormRequireSendToBrpAnalytic(formName) {
        switch (formName) {
            case "Secure Finance Application":
            case "Contact Us":
            case "Parts Request":
            case "Service Request":
            case "Model Wanted":
            case "Free Trade-In Evaluation":
            case "VIN Checking Service":
            case "Quick Secure Finance Application":
                return true;
        }
        return false;
    }
    function hasBrpPageviewSubmitted() {
        return window.brpDataLayer.find(function (p) { return p.event == "PV"; });
    }
    function initPageViewEventToBrpAnalytics() {
        var formName = exports.ViewFormUtil.getFormName(self.clientId);
        var requireForm = isFormRequireSendToBrpAnalytic(formName);
        var data = window.brpAnalyticData;
        if (!window.brpDataLayer ||
            !window.brpAnalyticData ||
            !requireForm ||
            data.page.pageType != "" ||
            hasBrpPageviewSubmitted()) {
            return;
        }
        window.brpDataLayer.push(data);
    }
    function initFormPrepopulate() {
        var prevSubmissionId = self.options.prevSubmissionId;
        var data = formPrepopulate.getFormData(prevSubmissionId);
        if (data) {
            var $form = container.find("form").first();
            setInputValue("FirstName", data.firstName);
            setInputValue("LastName", data.lastName);
            setInputValue("Email", data.email);
            setInputValue("Phone", data.phone);
            setInputValue("ZipCode", data.zipCode);
        }
    }
    function setInputValue(propertyName, value) {
        var $control = container.find("[data-question-mapped-key-name=\"" + propertyName + "\"] > :input");
        if ($control && $control.length) {
            $control.val(value);
        }
    }
    initControls();
    initJointApplication();
    initReCaptcha();
    if ((shiftDigitalAnalyticsManager_1.default === null || shiftDigitalAnalyticsManager_1.default === void 0 ? void 0 : shiftDigitalAnalyticsManager_1.default.isActivated())
        && self.options
        && !self.options.isSendShiftDigitalAnalyticsFormSubmissionEventOnly) {
        var $root = $("#" + self.clientId);
        var formEventData = {
            formName: exports.ViewFormUtil.getFormName(self.clientId),
            relativeUrl: null,
            productId: self.options.productId,
            shiftDigitalAnalyticsVehicleData: self.options.shiftDigitalAnalyticsVehicleData,
        };
        shiftDigitalAnalyticsManager_1.default.instance().sendFormShownEvent(formEventData);
        shiftDigitalAnalyticsManager_1.default.instance().initFormInitiationEventHandler($root, formEventData);
    }
    initPageViewEventToBrpAnalytics();
    self.updateOptions = function (options) {
        self.options = $.extend({
            submitText: 'Submit',
            submittingText: 'Submitting...',
            submittingClass: 'submitting',
            validationGroup: '',
            moduleId: 0
        }, options);
        initModelDropdownControls();
    };
    return self;
}
exports.Dx1ViewForm = Dx1ViewForm;


/***/ }),

/***/ 134:
/***/ (function(__unused_webpack_module, exports, __webpack_require__) {


var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
    function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
    return new (P || (P = Promise))(function (resolve, reject) {
        function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
        function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
        function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
        step((generator = generator.apply(thisArg, _arguments || [])).next());
    });
};
var __generator = (this && this.__generator) || function (thisArg, body) {
    var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
    return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
    function verb(n) { return function (v) { return step([n, v]); }; }
    function step(op) {
        if (f) throw new TypeError("Generator is already executing.");
        while (_) try {
            if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
            if (y = 0, t) op = [op[0] & 2, t.value];
            switch (op[0]) {
                case 0: case 1: t = op; break;
                case 4: _.label++; return { value: op[1], done: false };
                case 5: _.label++; y = op[1]; op = [0]; continue;
                case 7: op = _.ops.pop(); _.trys.pop(); continue;
                default:
                    if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
                    if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
                    if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
                    if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
                    if (t[2]) _.ops.pop();
                    _.trys.pop(); continue;
            }
            op = body.call(thisArg, _);
        } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
        if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
    }
};
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.ButtonActions = void 0;
var SecondaryActionsApi_1 = __webpack_require__(642);
var ButtonActions = /** @class */ (function () {
    function ButtonActions(portalId, moduleId) {
        this.formList = [
            "request more information",
            "schedule a test drive",
            "quick request more information"
        ];
        this.scheduleTestRideModalId = "ScheduleATestRideModal";
        this.initServiceFramework(moduleId);
        this.service = new SecondaryActionsApi_1.SecondaryActionsApi(this.serviceFramework);
        this.portalId = portalId;
        this.moduleId = moduleId;
    }
    ButtonActions.prototype.getProductDetailUrl = function () {
        if (this.settings
            && this.settings.unitDetailUrl
            && this.settings.unitDetailUrl !== "") {
            return this.settings.unitDetailUrl;
        }
        if (this.settings.productOption) {
            return window.location.protocol + "//" + window.location.hostname + "/dx1inventory/" + this.productId;
        }
        return window.location.href;
    };
    ButtonActions.prototype.onFacebookShareButtonClicked = function (e) {
        e.preventDefault();
        var productUrl = this.getProductDetailUrl();
        var url = "https://www.facebook.com/sharer/sharer.php?display=popup&u=" + productUrl;
        var options = "toolbar=0,status=0,resizable=1,width=626,height=436";
        window.open(url, "sharer", options);
        return false;
    };
    ButtonActions.prototype.onTwitterShareButtonClicked = function (e) {
        e.preventDefault();
        var url = "https://twitter.com/share?text=Check out";
        if (this.settings) {
            if (this.settings.productOption) {
                url = url + " the %23" + this.settings.productOption.make + " " + this.settings.productOption.year + " " + this.settings.productOption.name;
            }
            var productUrl = this.getProductDetailUrl();
            url = url + "&url=" + productUrl;
        }
        var options = "toolbar=0,status=0,resizable=1,width=626,height=436";
        window.open(url, "sharer", options);
        return false;
    };
    ButtonActions.prototype.onFinancialButtonClicked = function (e) {
        if (this.settings.productOption.brpBrand && typeof window.sendByCTAEventToBrpAnalytics === "function") {
            window.sendByCTAEventToBrpAnalytics("click to financing", this.settings.productOption.brpBrand);
        }
    };
    ButtonActions.prototype.onScheduleTestRideButtonClicked = function (e) {
        e.preventDefault();
        if (this.settings.productOption.brpBrand && typeof window.sendByCTAEventToBrpAnalytics === "function") {
            window.sendByCTAEventToBrpAnalytics("click to dealer_demo_std", this.settings.productOption.brpBrand);
        }
        var option = {
            modalId: this.scheduleTestRideModalId,
            modalTitle: "Schedule a Test Ride",
            panelSelector: "#" + this.scheduleTestRideModalId,
            url: "/DesktopModules/Dominion/Common/Forms/ScheduleATestDrive.aspx",
            portalId: this.portalId,
            moduleId: this.moduleId,
            productId: this.productId,
            brpBrand: this.settings.productOption.brpBrand,
            prevSubmissionId: this.prevSubmissionId,
            tabModuleId: this.tabModuleId,
        };
        // add dialog in case it doesn't have
        FormDialog.addDialogContent(option);
        // display dialog
        FormDialog.displayDialog(option);
    };
    ButtonActions.prototype.initFinancingControl = function () {
        var _this = this;
        var $applyFinanceButton = this.$applyFinanceButton;
        var isShowApplyFinanceButton = this.settings
            && this.settings.financingButtonSetting
            && this.settings.financingButtonSetting.isDisplay;
        if (isShowApplyFinanceButton) {
            this.$applyFinanceButton.show();
            var url = this.settings.financingButtonSetting.formUrl;
            if (url && url.indexOf(window.location.host) > -1) {
                url = url + "/PrevSubmissionId/" + this.prevSubmissionId;
            }
            $applyFinanceButton.attr("href", url);
            $applyFinanceButton.off("click").on("click", function (e) {
                _this.onFinancialButtonClicked(e);
            });
            if (this.settings.financingButtonSetting.isExternal) {
                $applyFinanceButton.attr("target", "_blank");
            }
            else {
                $applyFinanceButton.removeAttr("target");
            }
            return;
        }
        this.$applyFinanceButton.hide();
        $applyFinanceButton.off("click");
    };
    ButtonActions.prototype.initSchduleTestRideControl = function () {
        var _this = this;
        var $button = this.$scheduleTestRideButton;
        var isShow = this.isShowSchduleTestRideByFormName(this.reqFormName)
            && this.settings
            && this.settings.scheduleTestRideButtonSetting
            && this.settings.scheduleTestRideButtonSetting.isDisplay;
        if (isShow) {
            $button.show();
            $button.off("click").on("click", function (e) {
                _this.onScheduleTestRideButtonClicked(e);
            });
            return;
        }
        $button.hide();
    };
    ButtonActions.prototype.intSocialControl = function () {
        var _this = this;
        this.$facebokButton.off("click").on("click", function (e) {
            _this.onFacebookShareButtonClicked(e);
        });
        this.$twitterButton.off("click").on("click", function (e) {
            _this.onTwitterShareButtonClicked(e);
        });
        if (this.settings
            && this.settings.productOption) {
            // set mail to url
            var productUrl = this.getProductDetailUrl();
            var productNameEncode = encodeURIComponent(this.settings.productOption.name);
            var subject = "Check out this " + this.settings.productOption.year + " " + productNameEncode;
            var body = "Hi,%0D%0A%0D%0AWhile browsing the showroom, I found this " + this.settings.productOption.year + " " + productNameEncode + " and wanted to share it with you.%0D%0A%0D%0A" + encodeURIComponent(productUrl) + "%0D%0A%0D%0AWhat do you think?";
            var url = "mailto:?subject=" + subject + "&body=" + body;
            this.$mailToButton.attr("href", url);
        }
    };
    ButtonActions.prototype.bindingSettings = function () {
        return __awaiter(this, void 0, void 0, function () {
            var data;
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0: return [4 /*yield*/, this.service.getSettings(this.tabModuleId, this.reqFormName, this.productId)];
                    case 1:
                        data = _a.sent();
                        this.settings = data;
                        return [2 /*return*/];
                }
            });
        });
    };
    ;
    ButtonActions.prototype.loadHtmlContent = function () {
        return __awaiter(this, void 0, void 0, function () {
            var data;
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0: return [4 /*yield*/, this.service.loadContent()];
                    case 1:
                        data = _a.sent();
                        return [2 /*return*/, data];
                }
            });
        });
    };
    ;
    ButtonActions.prototype.initServiceFramework = function (moduleId) {
        this.serviceFramework = $.dnnSF(moduleId);
    };
    ButtonActions.prototype.isShowSchduleTestRideByFormName = function (formName) {
        return formName.toLowerCase() !== this.formList[1];
    };
    ButtonActions.prototype.setDisplaySecondaryActions = function () {
        var isShow = this.settings
            && ((this.settings.financingButtonSetting && this.settings.financingButtonSetting.isDisplay)
                || (this.settings.scheduleTestRideButtonSetting && this.settings.scheduleTestRideButtonSetting.isDisplay));
        this.displaySecondaryActions(isShow);
    };
    ButtonActions.prototype.displaySecondaryActions = function (isShow) {
        if (isShow) {
            this.$secondaryActionsSection.show();
        }
        else {
            this.$secondaryActionsSection.hide();
        }
    };
    ButtonActions.prototype.initElements = function (selector) {
        var scope = ".secondary-actions";
        if (selector && selector != "") {
            scope = selector + " " + scope;
        }
        this.$secondaryActionsSection = $(scope);
        this.$applyFinanceButton = $(scope + " .apply-financing");
        this.$scheduleTestRideButton = $(scope + " .schedule-test-ride");
        this.$facebokButton = $(scope + " .fa-facebook-square").parent("a");
        this.$twitterButton = $(scope + " .x-icon").parent("a");
        this.$mailToButton = $(scope + " .fa-envelope").parent("a");
    };
    ButtonActions.prototype.getScheduleTestRideButton = function () {
        return this.$scheduleTestRideButton;
    };
    ButtonActions.prototype.isShowSecondaryActionsByFormName = function (formName) {
        var findFormName = formName.toLowerCase();
        var index = this.formList.findIndex(function (e) { return e === findFormName; });
        return index > -1;
    };
    ButtonActions.prototype.loadContent = function () {
        return this.loadHtmlContent().then(function (htmlContent) {
            return htmlContent;
        });
    };
    ButtonActions.prototype.init = function (tabModuleId, reqFormName, productId, selector, prevSubmissionId) {
        var _this = this;
        this.tabModuleId = tabModuleId;
        this.reqFormName = reqFormName;
        this.productId = productId;
        this.prevSubmissionId = prevSubmissionId;
        // binding selector
        this.initElements(selector);
        // hide all first
        this.$secondaryActionsSection.hide();
        var isShow = this.isShowSecondaryActionsByFormName(reqFormName);
        if (!isShow) {
            return;
        }
        if (this.tabModuleId === 0
            || !this.productId
            || this.productId === "") {
            this.displaySecondaryActions(false);
            return;
        }
        return this.bindingSettings()
            .then(function () {
            _this.initFinancingControl();
            _this.initSchduleTestRideControl();
            _this.intSocialControl();
            _this.setDisplaySecondaryActions();
        });
    };
    return ButtonActions;
}());
exports.ButtonActions = ButtonActions;


/***/ }),

/***/ 542:
/***/ (function(module) {

module.exports = window["PolarisDigitasManager"];

/***/ }),

/***/ 29:
/***/ (function(module) {

module.exports = window["ShiftDigitalAnalyticsManager"];

/***/ })

/******/ 	});
/************************************************************************/
/******/ 	// The module cache
/******/ 	var __webpack_module_cache__ = {};
/******/ 	
/******/ 	// The require function
/******/ 	function __webpack_require__(moduleId) {
/******/ 		// Check if module is in cache
/******/ 		var cachedModule = __webpack_module_cache__[moduleId];
/******/ 		if (cachedModule !== undefined) {
/******/ 			return cachedModule.exports;
/******/ 		}
/******/ 		// Create a new module (and put it into the cache)
/******/ 		var module = __webpack_module_cache__[moduleId] = {
/******/ 			// no module.id needed
/******/ 			// no module.loaded needed
/******/ 			exports: {}
/******/ 		};
/******/ 	
/******/ 		// Execute the module function
/******/ 		__webpack_modules__[moduleId].call(module.exports, module, module.exports, __webpack_require__);
/******/ 	
/******/ 		// Return the exports of the module
/******/ 		return module.exports;
/******/ 	}
/******/ 	
/************************************************************************/
/******/ 	
/******/ 	// startup
/******/ 	// Load entry module and return exports
/******/ 	// This entry module is referenced by other modules so it can't be inlined
/******/ 	var __webpack_exports__ = __webpack_require__(979);
/******/ 	var __webpack_export_target__ = window;
/******/ 	for(var i in __webpack_exports__) __webpack_export_target__[i] = __webpack_exports__[i];
/******/ 	if(__webpack_exports__.__esModule) Object.defineProperty(__webpack_export_target__, "__esModule", { value: true });
/******/ 	
/******/ })()
;
;;;