var CompanyInfoView = Backbone.View.extend({
    events: {
        'click .next-page-button' : 'onNextPageClick',
        'click .prev-page-button' : 'onPrevPageClick',
        'click .save-button': 'saveChanges',
        'click .reRegister-button': 'reRegister',
        'keyup #transactionNumber' : 'validateForm',
        'keyup #priceLimit' : 'validateForm',
        'keyup #invoiceNumber' : 'validateForm',
        'keyup #quantityLimit' : 'validateForm',
        'keyup #siteName' : 'validateForm',
        'keyup #classExports' : 'validateForm',
        'click .agreement-button' : 'openAgreement',
        'click #agreeCheckbox' : 'enableSerialNumber',
        'click #image img' : 'browseFile',
        'change #image input' : 'showSelectedFile',
        // 'keyup #serviceFeePercent' : 'onServiceFeePercentChange',
        'change #serviceFeeByPercent' : 'onServiceFeeByPercentChange',
    },

    data: {},
    breadcrumb: {},
    currentPage: 0,

    initialize: async function (options) {
        this.options = options;
        this.template = _.template(options.template);
        this.breadcrumb = options.breadcrumb;
        this.model = options.model;
        this.hasAccounting = options.hasAccounting;
        this.taxCodes = [];
        this.listenTo(this.model, 'change', this.render);
        this.getData();
    },

    onNextPageClick: function() {
        const pageElList = document.querySelectorAll('#company-info-form-content form');
        const pageLen = pageElList.length;

        if(this.currentPage == pageLen -1)
            return;
        var pageTitle = '';
        this.currentPage++;
        pageElList.forEach( (pageEl, index) => {
            if(index == this.currentPage) {
                pageTitle = pageEl.name;
                pageEl.style.display = 'block';
            }
            else
                pageEl.style.display = 'none';
        });

        document.getElementById('page-title').innerHTML = pageTitle;
        document.getElementById('page-number').innerHTML = `{Literal}Page{/Literal} ${this.currentPage + 1} {Literal}of{/Literal} ` + pageLen;
    },

    onPrevPageClick: function() {
        if(this.currentPage == 0)
            return;
        const pageElList = document.querySelectorAll('#company-info-form-content form');
        const pageLen = pageElList.length;
        var pageTitle = '';
        this.currentPage--;
        pageElList.forEach( (pageEl, index) => {
            if(index == this.currentPage) {
                pageTitle = pageEl.name;
                pageEl.style.display = 'block';
            }
            else
                pageEl.style.display = 'none';
        });

        document.getElementById('page-title').innerHTML = pageTitle;
        document.getElementById('page-number').innerHTML = `{Literal}Page{/Literal} ${this.currentPage + 1} {Literal}of{/Literal} ` + pageLen;
    },

    render: function () {    
        this.$el.html(this.template({
            companyInfo: this.model.toJSON(),
            taxCodes: this.taxCodes,
            hasAccounting: this.hasAccounting
        }));

        App.breadCrumbToolTip = "Set POS and Management settings";
        
        App.setBreadcrumbs(this.breadcrumb);

        var that = this;
        $(document).ready(function () {
            $('.tooltipped').tooltip({delay: 0});
            that.$el.find(".company-info-button").trigger("click");
            that.$el.find('select').formSelect();
        });

        $(document).on('keydown', 'input, select', function(e) {
            var self = $(this)
              , form = self.parents('form:eq(0)')
              , focusable
              , next
              ;
            if (e.key == 13) {
                focusable = form.find('input,a,select,button,select').filter(':visible');
                next = focusable.eq(focusable.index(this)+1);
                if (next.length) {
                    next.trigger("focus");
                } else {
                    form.trigger("submit");
                }
                return false;
            }
        });
        return this;
    },

    getData: function() {
        if (App.serverInfo.hasVatTax) {
            this.getVatTaxData();
        }
        else {
            this.getTaxCodesData();
        }
        
    },

    getVatTaxData: function () {
        var that = this;
        var sessionToken = this.getCookie();
        $.ajax({
            url: '/data/get-vat-list',
            data: {
                token: sessionToken
            },
            dataType: 'json',
            type: 'POST',
            success: function (data) {
                for (var i = 0; i < data.results.length; i++) {
                    data.results[i].value = data.results[i].description
                    data.results[i].id = data.results[i].code
                }
                that.taxCodes = data.results;
                
                that.getCompanyInfoData();
            },
            error: function (e) {
                if (e.status == 523) {
                    window.location.href = "#/log-in";
                    location.reload();
                }
                else {
                    M.toast({ html: '{Literal}There was a problem fetching tax codes from the server{/Literal}' });
                }
            }
        });
    },

    getTaxCodesData: function () {
        var that = this;
        var sessionToken = this.getCookie();
        $.ajax({
            url: '/data/get-tax-codes',
            data: {
                token: sessionToken
            },
            dataType: 'json',
            type: 'POST',
            success: function (data) {
                that.taxCodes = data.results;
                that.getCompanyInfoData();
            },
            error: function (e) {
                if (e.status == 523) {
                    window.location.href = "#/log-in";
                    location.reload();
                }
                else {
                    M.toast({ html: '{Literal}There was a problem fetching tax codes from the server{/Literal}' });
                }
            }
        });
    },

    getCookie: function() {
        var nameEQ = "sessionCookie" + "=";
        var ca = document.cookie.split(';');
        for(var i=0;i < ca.length;i++) {
            var c = ca[i];
            while (c.charAt(0)==' ') c = c.substring(1,c.length);
            if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
        }
    },

    getCompanyInfoData: function () {
        var that = this;
        var sessionToken = this.getCookie();
        $.ajax({
            url: '/data/get-company-info',
            data: {
                token: sessionToken
            },
            dataType: 'json',
            type: 'POST',
            success: function (data) {
                that.companyInfo = data;
                that.getSystemSettings();
            },
            error: function (e) {
                if (e.status == 523) {
                    window.location.href = "#/log-in";
                    location.reload();
                }
                else {
                    M.toast({ html: '{Literal}There was a problem retrieving data from the server{/Literal}.' });
                }
            }
        });
    },

    getSystemSettings: function () {
        var that = this;
        var sessionToken = this.getCookie();
        $.ajax({
            url: '/data/get-system-settings',
            data: {
                token: sessionToken
            },
            dataType: 'json',
            type: 'POST',
            success: function (data) {
                that.companyInfo.countryCode = data.countryCode;
                if (data.businessType == "true") {
                    that.companyInfo.businessType = "RT"
                }
                else {
                    that.companyInfo.businessType = "FS"
                }
                that.companyInfo.countryCode = data.countryCode;
                if (data.reportDirection == "true") {
                    that.companyInfo.reportDirection = "Yes"
                }
                else {
                    that.companyInfo.reportDirection = "No"
                }
                that.model.set(that.companyInfo);

                that.$el.find('#company-info-form').show();
            },
            error: function (e) {
                if (e.status == 523) {
                    window.location.href = "#/log-in";
                    location.reload();
                }
                else {
                    M.toast({ html: '{Literal}There was a problem retrieving data from the server{/Literal}.' });
                }
            }
        });
    },


    openAgreement: function () {
        var full = location.protocol+'//'+location.hostname+(location.port ? ':'+location.port: '');
        window.open(full + "/license_files/license.html");
        $("#agreeCheckbox").removeAttr('disabled');
    },

    enableSerialNumber: function () {
        if (!$("#agreeCheckbox").hasClass('disabled')) {
            $("#serialNumber").removeAttr('disabled');
        }
    },

    getFormValues: function () {
        var transactionNumber = this.$el.find('#transactionNumber').val();
        var priceLimit = this.$el.find('#priceLimit').val();
        var dayStart = this.$el.find('#day-start-form-dropdown').val();
        var invoiceNumber = this.$el.find('#invoiceNumber').val();
        var returnNumber = this.$el.find('#returnNumber').val();
        var quantityLimit = this.$el.find('#quantityLimit').val();
        var defaultTax = this.$el.find('#default-tax-form-dropdown option:selected').val();

        if(this.hasAccounting) {
            var tenderSummaryAccount = this.$el.find('#tenderSummaryAccount').val();
            var siteName = this.$el.find('#siteName').val();
            var sendTips = this.$el.find('.sendTips:checked').length > 0;
            var classExports = this.$el.find('#classExports').val();
            var vatGlAccount = this.$el.find('#vatGlAccount').val();
        }
        
        var creditSlip = this.$el.find('#credit-slip-dropdown option:selected').text();
        var gratHandling = this.$el.find('.gratHandling:checked').length > 0;
        var autoGrat = this.$el.find('#autoGrat').val();
        var serviceFeeLimit = this.$el.find('#serviceFeeLimit').val();
        if(document.getElementById('serviceFeeByPercent').checked){
            var serviceFeePercent = this.$el.find('#serviceFeePercent').val();
            var serviceFeeAmount = 0;
        }
        else {
            var serviceFeeAmount = this.$el.find('#serviceFeeAmount').val();
            serviceFeePercent = 0;
        }

        if(serviceFeePercent > 0)
            serviceFeePercent = serviceFeePercent / 100;
        var defaultPrice = this.$el.find('#default-price-form-dropdown option:selected').text();
        var alwaysInclude = this.$el.find('.alwaysInclude:checked').length > 0;
        var credsOnFile = this.$el.find('#credsOnFile:checked').length > 0;
        var includeServiceFeeInAmount = this.$el.find('#includeServiceFeeInAmount:checked').length > 0;

        var serialNumber = this.$el.find('#serialNumber').val();
        var countryCode = this.$el.find('#countryCode option:selected').text();
        var businessType = this.$el.find('#businessType option:selected').text();
        var reportDirection = this.$el.find('#reportDirection').val();

        var smsAuth1 = this.$el.find('#smsAuth1').val();
        var smsAuth2 = this.$el.find('#smsAuth2').val();
        var smsAuth3 = this.$el.find('#smsAuth3').val();
        var smsPhone = this.$el.find('#smsPhone').val();
        var orderReadySMSMessage = this.$el.find('#orderReadySMSMessage').val();
        
        var roundUpAmount1 = this.$el.find('#roundUpAmount1').val();
        var roundUpAmount2 = this.$el.find('#roundUpAmount2').val();
        var roundUpAmount3 = this.$el.find('#roundUpAmount3').val();
        var roundUpAmount4 = this.$el.find('#roundUpAmount4').val();

        var emailAccount = this.$el.find('#emailAccount').val();
        var emailPassword = this.$el.find('#emailPassword').val();
        var smtpServer = this.$el.find('#smtpServer').val();
        var smtpPort = this.$el.find('#smtpPort').val();

        if (reportDirection == "0") {
            reportDirection = true;
        }
        else {
            reportDirection = false;
        }

        if (this.hasAccounting && App.israCardBuild) {
            var updatedModel = {
                company_info: {
                    transactionNumber: transactionNumber,
                    priceLimit: priceLimit,
                    dayStart: dayStart,
                    invoiceNumber: invoiceNumber,
                    returnNumber: returnNumber,
                    quantity: quantityLimit,
                    taxCode: defaultTax,
                    country: "IL"
                },
                accounting_integration: {
                    tenderSummary: tenderSummaryAccount,
                    siteName: siteName,
                    sendTips: sendTips,
                    classSales: classExports,
                    vatGlAccount: vatGlAccount
                },
                credit_card: {
                    slipLimit: creditSlip,
                    gratuityHandling: gratHandling,
                    gratutityInclusion: autoGrat,
                    defaultPrice: defaultPrice,
                    alwaysInclude: alwaysInclude,
                    serviceFeeAmount: serviceFeeAmount,
                    serviceFeeLimit: serviceFeeLimit,
                    serviceFeePercent: serviceFeePercent,
                    credsOnFile: credsOnFile,
                    includeServiceFeeInAmount: includeServiceFeeInAmount
                },
                smsAuth: {
                    SmsAuth1: smsAuth1,
                    SmsAuth2: smsAuth2,
                    SmsAuth3: smsAuth3,
                    SmsPhone: smsPhone,
                    OrderReadySMSMessage: orderReadySMSMessage
                },
                roundUp: {
                    roundUpAmount1: roundUpAmount1,
                    roundUpAmount2: roundUpAmount2,
                    roundUpAmount3: roundUpAmount3,
                    roundUpAmount4: roundUpAmount4
                },
                smtpSetup: {
                    emailAccount: emailAccount,
                    emailPassword: emailPassword,
                    smtpServer: smtpServer,
                    smtpPort: smtpPort
                },

                serialNumber: serialNumber,
                countryCode: "IL",
                businessType: "RT",
                reportDirection: true
            };
        }
        else if (this.hasAccounting && !App.israCardBuild) {
            var updatedModel = {
                company_info: {
                    transactionNumber: transactionNumber,
                    priceLimit: priceLimit,
                    dayStart: dayStart,
                    invoiceNumber: invoiceNumber,
                    returnNumber: returnNumber,
                    quantity: quantityLimit,
                    taxCode: defaultTax,
                    country: countryCode
                },
                accounting_integration: {
                    tenderSummary: tenderSummaryAccount,
                    siteName: siteName,
                    sendTips: sendTips,
                    classSales: classExports,
                    vatGlAccount: vatGlAccount
                },
                credit_card: {
                    slipLimit: creditSlip,
                    gratuityHandling: gratHandling,
                    gratutityInclusion: autoGrat,
                    defaultPrice: defaultPrice,
                    alwaysInclude: alwaysInclude,
                    serviceFeeAmount: serviceFeeAmount,
                    serviceFeeLimit: serviceFeeLimit,
                    serviceFeePercent: serviceFeePercent,
                    credsOnFile: credsOnFile,
                    includeServiceFeeInAmount: includeServiceFeeInAmount
                },
                smsAuth: {
                    SmsAuth1: smsAuth1,
                    SmsAuth2: smsAuth2,
                    SmsAuth3: smsAuth3,
                    SmsPhone: smsPhone,
                    OrderReadySMSMessage: orderReadySMSMessage
                },
                roundUp: {
                    roundUpAmount1: roundUpAmount1,
                    roundUpAmount2: roundUpAmount2,
                    roundUpAmount3: roundUpAmount3,
                    roundUpAmount4: roundUpAmount4
                },
                smtpSetup: {
                    emailAccount: emailAccount,
                    emailPassword: emailPassword,
                    smtpServer: smtpServer,
                    smtpPort: smtpPort
                },

                serialNumber: serialNumber,
                countryCode: countryCode,
                businessType: businessType,
                reportDirection: reportDirection
            };
        }
        else if (!this.hasAccounting && !App.israCardBuild) {
            var updatedModel = {
                company_info: {
                    transactionNumber: transactionNumber,
                    priceLimit: priceLimit,
                    dayStart: dayStart,
                    invoiceNumber: invoiceNumber,
                    returnNumber: returnNumber,
                    quantity: quantityLimit,
                    taxCode: defaultTax,
                    country: countryCode
                },
                accounting_integration: {
                    tenderSummary: null,
                    siteName: null,
                    sendTips: null,
                    classSales: null
                },
                credit_card: {
                    slipLimit: creditSlip,
                    gratuityHandling: gratHandling,
                    gratutityInclusion: autoGrat,
                    defaultPrice: defaultPrice,
                    alwaysInclude: alwaysInclude,
                    serviceFeeAmount: serviceFeeAmount,
                    serviceFeeLimit: serviceFeeLimit,
                    serviceFeePercent: serviceFeePercent,
                    credsOnFile: credsOnFile,
                    includeServiceFeeInAmount: includeServiceFeeInAmount
                },
                smsAuth: {
                    SmsAuth1: smsAuth1,
                    SmsAuth2: smsAuth2,
                    SmsAuth3: smsAuth3,
                    SmsPhone: smsPhone,
                    OrderReadySMSMessage: orderReadySMSMessage
                },
                roundUp: {
                    roundUpAmount1: roundUpAmount1,
                    roundUpAmount2: roundUpAmount2,
                    roundUpAmount3: roundUpAmount3,
                    roundUpAmount4: roundUpAmount4
                },
                smtpSetup: {
                    emailAccount: emailAccount,
                    emailPassword: emailPassword,
                    smtpServer: smtpServer,
                    smtpPort: smtpPort
                },
                serialNumber: serialNumber,
                countryCode: countryCode,
                businessType: businessType,
                reportDirection: reportDirection
            };
        }
        else if (!this.hasAccounting && App.israCardBuild) {
            var updatedModel = {
                company_info: {
                    transactionNumber: transactionNumber,
                    priceLimit: priceLimit,
                    dayStart: dayStart,
                    invoiceNumber: invoiceNumber,
                    returnNumber: returnNumber,
                    quantity: quantityLimit,
                    taxCode: defaultTax,
                    country: countryCode
                },
                accounting_integration: {
                    tenderSummary: null,
                    siteName: null,
                    sendTips: null,
                    classSales: null
                },
                credit_card: {
                    slipLimit: creditSlip,
                    gratuityHandling: gratHandling,
                    gratutityInclusion: autoGrat,
                    defaultPrice: defaultPrice,
                    alwaysInclude: alwaysInclude,
                    serviceFeeAmount: serviceFeeAmount,
                    serviceFeeLimit: serviceFeeLimit,
                    serviceFeePercent: serviceFeePercent,
                    credsOnFile: credsOnFile,
                    includeServiceFeeInAmount: includeServiceFeeInAmount
                },
                smsAuth: {
                    SmsAuth1: smsAuth1,
                    SmsAuth2: smsAuth2,
                    SmsAuth3: smsAuth3,
                    SmsPhone: smsPhone,
                    OrderReadySMSMessage: orderReadySMSMessage
                },
                roundUp: {
                    roundUpAmount1: roundUpAmount1,
                    roundUpAmount2: roundUpAmount2,
                    roundUpAmount3: roundUpAmount3,
                    roundUpAmount4: roundUpAmount4
                },
                smtpSetup: {
                    emailAccount: emailAccount,
                    emailPassword: emailPassword,
                    smtpServer: smtpServer,
                    smtpPort: smtpPort
                },
                serialNumber: serialNumber,
                countryCode: "IL",
                businessType: "RT",
                reportDirection: true
            };
        }

        return (new CompanyInfo(updatedModel)).toJSON();
    },

    validateForm: function () {
        var valid = true;
        
        var validateTransactionNumber = this.$el.find("#transactionNumber").val();
        if (validateTransactionNumber.trim().length < 1 || validateTransactionNumber < 1 || validateTransactionNumber > 999999999 || validateTransactionNumber.indexOf("-") > -1 || validateTransactionNumber.indexOf('e') > -1) {
            this.$el.find("#transactionNumber").addClass("invalid");
            valid = false;
        }

        if(validateTransactionNumber < this.companyInfo.company_info.transactionNumber)
        {
            this.$el.find("#transactionNumber").addClass("invalid");
            valid = false;
        }
        
        var validatePriceLimit = this.$el.find("#priceLimit").val();
        var originalValue = document.getElementById('priceLimit').dataset.value;
        if(originalValue != validatePriceLimit) {
            if (validatePriceLimit.trim().length < 1 || validatePriceLimit < 1 || validatePriceLimit > 99999 || validatePriceLimit.indexOf("-") > -1 || validatePriceLimit.indexOf('e') > -1) {
                this.$el.find("#priceLimit").addClass("invalid");
                valid = false;
            }
        }
            
        var validateInvoiceNumber = this.$el.find("#invoiceNumber").val();
        if (validateInvoiceNumber.trim().length < 1 || validateInvoiceNumber < 1 || validateInvoiceNumber > 999999999 || validateInvoiceNumber.indexOf("-") > -1 || validateInvoiceNumber.indexOf('e') > -1) {
            this.$el.find("#invoiceNumber").addClass("invalid");
            valid = false;
        }

        if(validateInvoiceNumber < this.companyInfo.company_info.invoiceNumber)
        {
            this.$el.find("#invoiceNumber").addClass("invalid");
            valid = false;
        }
        
        var validateQuantityLimit = this.$el.find("#quantityLimit").val();
        if (validateQuantityLimit.trim().length < 1 || validateQuantityLimit < 1 || validateQuantityLimit > 99999 || validateQuantityLimit.indexOf("-") > -1 || validateQuantityLimit.indexOf('e') > -1) {
            this.$el.find("#quantityLimit").addClass("invalid");
            valid = false;
        }

        var validateAutoGrat = this.$el.find("#autoGrat").val();
        if (validateAutoGrat < 0 || validateAutoGrat > 99999 || validateAutoGrat.indexOf("-") > -1 || validateAutoGrat.indexOf('e') > -1) {
            this.$el.find("#autoGrat").addClass("invalid");
            valid = false;
        }
        var serviceFeeAmount = this.$el.find('#serviceFeeAmount').val();
        var serviceFeeLimit = this.$el.find('#serviceFeeLimit').val();
        var serviceFeePercent = this.$el.find('#serviceFeePercent').val();

        if (serviceFeeAmount < 0 || serviceFeeAmount > 99999 || serviceFeeAmount.indexOf("-") > -1 || serviceFeeAmount.indexOf('e') > -1) {
            this.$el.find("#serviceFeeAmount").addClass("invalid");
            valid = false;
        }

        if (serviceFeeLimit < 0 || serviceFeeLimit > 99999 || serviceFeeLimit.indexOf("-") > -1 || serviceFeeLimit.indexOf('e') > -1) {
            this.$el.find("#serviceFeeLimit").addClass("invalid");
            valid = false;
        }

        if (serviceFeePercent < 0 || serviceFeePercent > 100 || serviceFeePercent.indexOf("-") > -1 || serviceFeePercent.indexOf('e') > -1) {
            this.$el.find("#serviceFeePercent").addClass("invalid");
            valid = false;
        }

        if(this.hasAccounting) {

        
            var validateTenderSummeryAccount = this.$el.find("#tenderSummaryAccount").val();
            if (validateTenderSummeryAccount == "" && this.companyInfo.accounting_integration.tenderSummary != "") {
                this.$el.find("#tenderSummaryAccount").addClass("invalid");
                valid = false;
            }

            var validateSiteName = this.$el.find("#siteName").val();
            var iChars = "<>#%{}|^~[]`\"";
            for (var i = 0; i < validateSiteName.length; i++) {
                if (iChars.indexOf(validateSiteName.charAt(i)) != -1) {
                    this.$el.find("#siteName").addClass("invalid");
                    valid = false;
                    break;
                }
            }
        
            var validateTenderSummary = this.$el.find("#tenderSummaryAccount").val();
            var iChars = "`~!@#$%^&*()_+=[]{}:;,<>/?*\\\'\"";
            for (var i = 0; i < validateTenderSummary.length; i++) {
                if (iChars.indexOf(validateTenderSummary.charAt(i)) != -1) {
                    this.$el.find("#tenderSummaryAccount").addClass("invalid");
                    valid = false;
                    break;
                }
            }
            
            var validateClassExports = this.$el.find("#classExports").val();
            var iChars = "`~!@#$%^&*()_+=[]{}:;,<>./?*\\\'\"";
            for (var i = 0; i < validateClassExports.length; i++) {
                if (iChars.indexOf(validateClassExports.charAt(i)) != -1) {
                    this.$el.find("#classExports").addClass("invalid");
                    valid = false;
                    break;
                }
            }
        }

        var validateSerialNumber = this.$el.find("#serialNumber").val();

        if (validateSerialNumber.trim().length < 1) {
            this.$el.find("#serialNumber").addClass("invalid");
            valid = false;
        }
        else {
            var iChars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ`~!@#$%^&*()_+=[]{}:;,<>./?*\\\'\"";
            for (var i = 0; i < validateSerialNumber.length; i++) {
                if (iChars.indexOf(validateSerialNumber.charAt(i)) != -1) {
                    this.$el.find("#serialNumber").addClass("invalid");
                    valid = false;
                    break;
                }
            }
        }

        if(this.file && this.file.size > 100 * 1024) {
            M.toast({ html: '{Literal}File size larger than 100KB{/Literal}' });
            valid = false;
        }

        var iChars = "`~!@#$%^&*()_+[]{}:;,<>/?*\\\'\"";
        var smsAuth1 = this.$el.find("#smsAuth1").val();
        for (var i = 0; i < smsAuth1.length; i++) {
            if (iChars.indexOf(smsAuth1.charAt(i)) != -1) {
                this.$el.find("#smsAuth1").addClass("invalid");
                valid = false;
                break;
            }
        }

        var iChars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ`~!@#$%^&*()_+=[]{}:;,<>/?*\\\'\"";
        var smsAuth2 = this.$el.find("#smsAuth2").val();
        for (var i = 0; i < smsAuth2.length; i++) {
            if (iChars.indexOf(smsAuth2.charAt(i)) != -1) {
                this.$el.find("#smsAuth2").addClass("invalid");
                valid = false;
                break;
            }
        }

        var iChars = "`~!@#$%^&*()_+=[]{}:;,<>/?*\\\'\"";
        var smsAuth3 = this.$el.find("#smsAuth3").val();
        for (var i = 0; i < smsAuth3.length; i++) {
            if (iChars.indexOf(smsAuth3.charAt(i)) != -1) {
                this.$el.find("#smsAuth3").addClass("invalid");
                valid = false;
                break;
            }
        }

        var iChars = "`~!@#$%^&*()_=[]{}:;,<>/?*\\\'\"";
        var smsAuth3 = this.$el.find("#smsAuth3").val();
        for (var i = 0; i < smsAuth3.length; i++) {
            if (iChars.indexOf(smsAuth3.charAt(i)) != -1) {
                this.$el.find("#smsAuth3").addClass("invalid");
                valid = false;
                break;
            }
        }

        return valid;
    },

    saveChanges: function () {
        var companyInfo;
        var that = this;
        var validation = this.validateForm();
        if (validation) {
            var formData = this.getFormValues();
            this.saveSystemSettings(formData);
            var sessionToken = this.getCookie();
            App.serverInfo.isAutoCreateMenuButtons = this.$el.find('.autoCreateMenuKeys:checked').length > 0;
            $.ajax({
                url: '/data/save-company-info',
                data: {
                    companyInfo: JSON.stringify(formData),
                    autoCreateMenuKeys: App.serverInfo.isAutoCreateMenuButtons,
                    token: sessionToken
                },
                dataType: 'json',
                type: 'POST',
                
                success: function (data) {
                    var success = false;
                    if (typeof data.results !== 'undefined' && typeof data.results.success !== 'undefined') {
                        success = data.results.success;
                    }
                    
                    M.toast({ html: '{Literal}Settings saved successfully{/Literal}' });
                },

                error: function (e) {
                    if (e.status == 523) {
                        window.location.href = "#/log-in";
                        location.reload();
                    }
                    else {
                        M.toast({ html: '{Literal}Settings saved successfully{/Literal}' });
                    }
                }
            });
        } else {
            M.toast({html: '{Literal}Some of the required fields are missing or invalid{/Literal}'});
        }
    },

    saveSystemSettings: function (formData) {
        var that = this;
        var sessionToken = this.getCookie();
        $.ajax({
            url: '/data/save-system-settings',
            data: {
                countryCode: formData.countryCode,
                businessType: formData.businessType,
                reportDirection: formData.reportDirection,
                token: sessionToken
            },
            dataType: 'json',
            type: 'POST',
            
            success: function (data) {
                that.uploadFile();

            },

            error: function (e) {
                if (e.status == 523) {
                    window.location.href = "#/log-in";
                    location.reload();
                }
                else {
                    M.toast({ html: '{Literal}There was a problem saving company information settings{/Literal}.' });
                }
            }
        });
    },

    browseFile: function() {
        this.$el.find("#image input").click();
    },

    showSelectedFile: function() {
        var that = this;
        const input = document.querySelectorAll("#image input")[0];
        this.file = input.files[0];
        if (input.files && input.files[0]) {
            var reader = new FileReader();
            
            reader.onload = function (e) {
                that.$el.find('#image img')
                    .attr('src', e.target.result)
                    .removeClass("logo-image-placeholder");
            };

            reader.readAsDataURL(input.files[0]);
        }
    },

    uploadFile: function() {
        // const file = document.querySelectorAll("#image input")[0]?.files[0];
        if(!this.file)
            return;

        var data = new FormData();
        var sessionToken = this.getCookie();
        data.append('fileSize:' + this.file.size, this.file);
        data.append('token', sessionToken);
        $.ajax({
            url: '/data/upload-logo-image',
            data: data,
            contentType: false,
            processData: false,
            type: 'POST',

            success: data => {
                if(!data.success)
                    M.toast({ html: '{Literal}Error: Image not saved{/Literal}' });
                else {
                    M.toast({ html: '{Literal}Image saved{/Literal}' });
                }
            },

            error: function (e) {
                if (e.status == 523) {
                    window.location.href = "#/log-in";
                    location.reload();
                }
            }
        });
    },

    reRegister: function() {
        var sessionToken = this.getCookie();

        $.ajax({
            url: '/data/re-register',
            type: 'POST',
            data: {
                token: sessionToken
            },

            success: data => {
                if(!data.success)
                    M.toast({ html: '{Literal}There was a problem re-registering {/Literal}' });
                else {
                    M.toast({ html: '{Literal}Re-registered successfully{/Literal}' });
                }
            },

            error: function (e) {
                if (e.status == 523) {
                    window.location.href = "#/log-in";
                    location.reload();
                }
            }
        });
    },

    // onServiceFeePercentChange(e) {
    //     var value = Number.parseFloat(e.currentTarget.value);
    //     if(value != NaN)
    //     {   
    //         if(value > 100)
    //            value = 100;
    //         if(value < 0)
    //             value = 0;

    //         e.currentTarget.value = value;
    //     }
    //     else
    //         e.currentTarget.value = '';
    // },

    onServiceFeeByPercentChange(e) {
        var by = document.getElementById('serviceFeeByPercent').checked == true ? 'Percent' : 'Amount';

        if(by == 'Amount'){   
            document.getElementById('serviceFeeAmount').parentElement.style.display = 'block';
            document.getElementById('serviceFeePercent').parentElement.style.display = 'none';
        }
        else if(by == 'Percent'){   
            document.getElementById('serviceFeeAmount').parentElement.style.display = 'none';
            document.getElementById('serviceFeePercent').parentElement.style.display = 'block';
        }
    },

});
