(function () {

    if (!semusiCommon.isAdmin()) {
        window.location = "/dashboard";
    }
    function loadCapping() {
        $.ajax({
            type: "GET",
            url: semusiCommon.API_PARTS.apps.w + '/getAppFrequencyCapping',
            data: {
                args: JSON.stringify({
                    app_id: semusiCommon.ACTIVE_APP_ID,
                }),
                app_id: semusiCommon.ACTIVE_APP_ID,
                uniqueNumber: semusiCommon.randomNumber(),
                api_key: semusiCommon.getActiveUser.api_key
            },

            success: function (data) {
                var mode = 'prod';
                if ($('#chkDevProSwitch').bootstrapSwitch('state') == true) {
                    mode = 'dev';
                }

                if (data == undefined) {
                    $('#togBtnTotalPush').attr('checked', false);
                    $('#togBtnfrequency').attr('checked', false);
                    $("#divInputTotalPush").addClass("disable-div");
                    $("#subDivBtnfrequency").addClass("disable-div");
                } else {
                    var currentData = data['frequency_capping']['capping_' + mode];
                    if (currentData.is_totalPush && currentData.is_frequency) {
                        $('#togBtnTotalPush').attr('checked', true);
                        $('#togBtnfrequency').attr('checked', true);
                        $("#total_notification_count").val(currentData.total_Push);
                        $("#total_notification_days").val(currentData.total_Days);
                        $("#delay_count").val(currentData.delay_count);
                        $("#selectedtime").val(currentData.freq_Time);
                    } else if (currentData.is_totalPush) {
                        $('#togBtnTotalPush').attr('checked', true);
                        $('#togBtnfrequency').attr('checked', false);
                        $("#total_notification_count").val(currentData.total_Push);
                        $("#total_notification_days").val(currentData.total_Days);
                    } else if (currentData.is_frequency) {
                        $('#togBtnTotalPush').attr('checked', false);
                        $('#togBtnfrequency').attr('checked', true);
                        $("#delay_count").val(currentData.delay_count);
                        $("#selectedtime").val(currentData.freq_Time);
                    } else {
                        $('#togBtnTotalPush').attr('checked', false);
                        $('#togBtnfrequency').attr('checked', false);
                        $("#divInputTotalPush").addClass("disable-div");
                        $("#subDivBtnfrequency").addClass("disable-div");
                    }


                }
            }
        });

    }

    //@params  queueControl :: is the QueueControl key from dnd values. and has the values of Minutes gap
    // This function Updates the Value of minutes gap between messages and is called if there is a gap between messages
    function fillQueueDiv(queueControl) {
        $('#with_gap').prop("checked", true)
        $('#gap_Min').val(queueControl.gap_Min)
    }

    //@params  currentData :-is the send_message key of dnd values
    // This function Updates the Value of queue contol 
    function showCriteria(currentData) {

        if (currentData) {
            if (currentData.oneFromAll == true || currentData.oneFromCampaign == true) {
                (currentData.oneFromAll == true) ? $('#send_only_one').prop("checked", true) : $('#send_one_campaign').prop("checked", true)
                $("#Step_4_1").hide();
                $("#Step_4_1_1").hide();

            } else {

                $('#send_all').prop("checked", true)
                $("#Step_4_1").show();
                $("#Step_4_1_1").show();
                var queueControl = currentData.queueControl;
                currentData = currentData.method;
                (currentData.lifo == true) ? $('#fifo').prop("checked", true) : $('#lifo').prop("checked", true)
                queueControl.all_at_once == true ? $('#all_at_once').prop("checked", true) : fillQueueDiv(queueControl)
            }
        }
    }
    //@params  currentData :-holds all the dnd values 
    // This function Updates the Value of message criteria 
    function showDndUi(currentData) {

        if (currentData.discard_message == true) {
            $('#dnd_discard').prop('checked', true);
            $("#Step_4").hide();
            $("#Step_4_1").hide();
            $("#Step_4_1_1").hide();
        } else {
            $('#dnd_send_later').prop('checked', true);
            showCriteria(currentData.send_message)

        }
    }
    function checkDnd() {

        $.ajax({
            type: "GET",
            url: semusiCommon.API_PARTS.apps.w + '/getAppDndState',
            data: {
                args: JSON.stringify({
                    app_id: semusiCommon.ACTIVE_APP_ID,
                }),
                api_key: semusiCommon.getActiveUser.api_key,
                app_id: semusiCommon.ACTIVE_APP_ID,
                uniqueNumber: semusiCommon.randomNumber(),
            },

            success: function (data) {

                var mode = 'prod';
                if ($('#chkDevProSwitch').bootstrapSwitch('state') == true) {
                    mode = 'dev';
                }
                if (data == undefined || data['DND_Values']['mode_' + mode].is_Dnd == false) {
                    $('#togBtnDnd').attr('checked', false);
                    $("#subDivBtnDnd").addClass("disable-div");
                    $("#Step_4").hide();
                    $("#Step_4_1").hide();
                    $("#Step_4_1_1").hide();
                } else {
                    var currentData = data['DND_Values']['mode_' + mode];
                    $('#togBtnDnd').attr('checked', true);
                    $("#end_Hour").val(currentData.end_Hour);
                    $("#end_Min").val(currentData.end_Min);
                    $("#start_Hour").val(currentData.start_Hour);
                    $("#start_Min").val(currentData.start_Min);
                    $("#end_timeshift").val(currentData.end_timeshift);
                    $("#start_timeshift").val(currentData.start_timeshift);
                    showDndUi(currentData);
                }
            }
        });
    }

    var fb_check = false;
    var google_check = false;
    //  start function for channel account
    function loadChannelAccountData() {
        $.ajax({
            type: "GET",
            url: semusiCommon.API_PARTS.apps.w + '/getChannelAccountData',
            data: {
                args: JSON.stringify({
                    app_id: semusiCommon.ACTIVE_APP_ID,
                }),
                api_key: semusiCommon.getActiveUser.api_key,
                app_id: semusiCommon.ACTIVE_APP_ID,
                uniqueNumber: semusiCommon.randomNumber(),
            },

            success: function (data) {

                if (data != undefined || data != null) {

                    if (data.channel_obj.channel_facebook != null || data.channel_obj.channel_facebook != undefined) {
                        $('#facebook_account').val(data.channel_obj.channel_facebook);
                        $("#btnFacebookDisconnect").attr('class', 'btn btn-sm btn-danger m-r-5 col-md');
                        $("#btnFacebookDisconnect").html('Disconnect');
                        fb_check = true;

                    }
                    if (data.channel_obj.channel_google != null || data.channel_obj.channel_google != undefined) {
                        $('#google_account').val(data.channel_obj.channel_google);
                        $("#btnGoogleDisconnect").attr('class', 'btn btn-sm btn-danger m-r-5 col-md');
                        $("#btnGoogleDisconnect").html('Disconnect');
                        google_check = true
                    }

                }
            }
        });

    }

    //set the app mode retrieved from db
    var mode = ("<%= appmode %>" === "true");
    $('#chkDevProSwitch').bootstrapSwitch('state', !mode);

    // delete webhook
    $("#btnDeletecallbackUrl").click(function () {
        if (confirm("Are you want to delete webhook?")) {
            $.ajax({
                type: "POST",
                url: semusiCommon.API_PARTS.apps.w + '/deleteCallBackUrl',
                data: {
                    api_key: semusiCommon.getActiveUser.api_key,
                    app_id: "<%=appid%>",
                    uniqueNumber: semusiCommon.randomNumber(),
                },
                headers: {
                    'csrf-token': appiceCookies.getCookie('_csrf')
                },

                success: function (data) {
                    semusiCommon.getCsrfToken();
                    $('#txtCallbackUrl').val('');
                    $("#http_method").val('GET');
                    $('#callback_installs').attr("checked", false);
                    $('#callback_events').attr("checked", false);
                    showMessagesucess("Webhook deleted successfully.");
                    location.reload();
                }
            });
        }
    });

    $("#chkDevProSwitch").bootstrapSwitch();
    $('.bootstrap-switch-label').css("background", "#f5f5f5");

    $("#pas").hide();

    document.getElementById('auth_key_type').addEventListener('change', function () {
        var selectedValue = this.value;
        if (selectedValue === 'p8') {
            $("#pas").hide();
            $('#keyid').show('');
            $('#teamid').show('');
            $('#topic').show('');
        } else {
            $('#ios_keyid').val('');
            $('#ios_teamid').val('');
            $('#ios_topic').val('');
            $('#keyid').hide('');
            $('#teamid').hide('');
            $('#topic').hide('');
            $("#pas").show();
        }
    });
    $('#btnUploadCert').click(function () {
        $("#ios_key_id_Error").hide();
        $("#ios_team_id_Error").hide();

        var epnu_key = $('#EPNUKEYS').val();
        var ios_cert3 = $('#certName3').val();
        var ios_keyid = $('#ios_keyid').val();
        var ios_teamid = $("#ios_teamid").val();
        var ios_certPath = $("#certPath3").val();
        var ios_bundleid = $('#ios_bundleid').val();
        var ios_topic = $("#ios_topic").val();
        var ios_key_type = $("#auth_key_type").val();
        var ios_passphrase = $("#ios_passphrase").val();

        const proxyPORT = $("#proxyPORT").val();
        const proxyUrl = $("#proxyUrl").val();

        // Validating the user inputs Key ID and Team ID to contain only alphabet and number
        var regex = /^[a-zA-Z0-9]*$/;
        if (!regex.test(ios_keyid)) {
            $("#ios_key_id_Error").show();
            return false;
        }
        if (!regex.test(ios_teamid)) {
            $("#ios_team_id_Error").show();
            return false;
        }

        const parts = ios_cert3.split(".");
        const extension = parts[parts.length - 1];
        if (extension !== ios_key_type) {
            document.getElementById("auth-error").style.display = "block";
            return;
        }
        var isdev = 'false';
        if ($('#chkDevProSwitch').bootstrapSwitch('state') == true)
            isdev = 'true';

        var ajaxData = {
            app_id: "<%=appid%>",
            ios_cert3: ios_cert3,
            ios_bundleid: ios_bundleid,
            ios_certPath: ios_certPath,
            isdev: isdev,
            // Adding proxy Value for APN
            proxyUrl: proxyUrl,
            proxyPORT: proxyPORT,
            ios_key_type: ios_key_type
        };

        // Conditionally include ios_topic, ios_keyid, ios_teamid based on ios_key_type
        if (ios_key_type === "p8") {
            ajaxData.ios_topic = ios_topic;
            ajaxData.ios_keyid = ios_keyid;
            ajaxData.ios_teamid = ios_teamid;
        }
        if (ios_key_type === "p12") {
            ajaxData.ios_passphrase = ios_passphrase;
        }

        $.ajax({
            type: "POST",
            url: semusiCommon.API_PARTS.apps.w + '/updateIOSCertificates',
            data: {
                args: JSON.stringify(ajaxData),
                app_id: semusiCommon.ACTIVE_APP_ID,
                api_key: semusiCommon.getActiveUser.api_key,
                uniqueNumber: semusiCommon.randomNumber(),
            },
            headers: {
                'csrf-token': appiceCookies.getCookie('_csrf')
            },
            success: function (data) {
                semusiCommon.getCsrfToken();
                showMessagesucess("APNS settings saved.");
                $("#messagesucess").delay(3000).fadeOut(300);
                $("#message").delay(3000).fadeOut(300);
            }
        });
    });

    // functions for global frequnecy column

    function validateUperDiv() {
        if ($('#total_notification_count').val() == "") {
            $('#cappingError').html("Please select notifications count");
            $('#cappingError').show();
            return false;
        }
        if ($('#total_notification_days').val() == "") {
            $('#cappingError').html("Please select Number of days in notification count");
            $('#cappingError').show();
            return false;
        }
        return true

    }
    function validateLowerDiv() {
        if ($('#delay_count').val() == "") {
            $('#cappingError').html("Please select frequency Count");
            $('#cappingError').show();
            return false;
        }
        return true
    }

    $("#togBtnTotalPush").on('change', function () {
        if ($(this).is(':checked')) {
            $("#divInputTotalPush").removeClass("disable-div");
        }
        else {
            $("#divInputTotalPush").addClass("disable-div");
        }
    });
    $("#togBtnfrequency").on('change', function () {
        if ($(this).is(':checked')) {
            $("#subDivBtnfrequency").removeClass("disable-div");
        } else {
            $("#subDivBtnfrequency").addClass("disable-div");

        }
    });
    // Save button 
    $('#btnSaveCapping').click(function () {
        var cappingObj = {};
        $('#cappingError').hide();


        if (!$("#togBtnTotalPush").is(':checked') && !$("#togBtnfrequency").is(':checked')) {
            cappingObj.is_totalPush = false;
            cappingObj.is_frequency = false;

        } else if ($("#togBtnTotalPush").is(':checked') && $("#togBtnfrequency").is(':checked')) {
            if (validateUperDiv() && validateLowerDiv()) {
                cappingObj.total_Push = parseInt($('#total_notification_count').val());
                cappingObj.total_Days = parseInt($('#total_notification_days').val());
                cappingObj.delay_count = parseInt($('#delay_count').val());
                cappingObj.freq_Time = $('#selectedtime').val();
                cappingObj.is_totalPush = true;
                cappingObj.is_frequency = true;
            } else {
                return false
            }
        } else if ($("#togBtnTotalPush").is(':checked')) {

            if (validateUperDiv()) {
                cappingObj.total_Push = parseInt($('#total_notification_count').val());
                cappingObj.total_Days = parseInt($('#total_notification_days').val());
                cappingObj.is_totalPush = true;
                cappingObj.is_frequency = false;
            } else {
                return false
            }
        } else {
            if (validateLowerDiv()) {
                cappingObj.delay_count = parseInt($('#delay_count').val());
                cappingObj.freq_Time = $('#selectedtime').val();
                cappingObj.is_totalPush = false;
                cappingObj.is_frequency = true;
            } else {
                return false
            }
        }

        var mode = 'prod';
        if ($('#chkDevProSwitch').bootstrapSwitch('state') == true) {
            mode = 'dev';
        }
        $.ajax({
            type: "POST",
            url: semusiCommon.API_PARTS.apps.w + '/updateFrequencyCapping',
            data: {
                args: JSON.stringify({
                    app_id: "<%=appid%>",
                    cappingObj: cappingObj,
                    mode: mode
                }),
                app_id: semusiCommon.ACTIVE_APP_ID,
                api_key: semusiCommon.getActiveUser.api_key,
                uniqueNumber: semusiCommon.randomNumber(),
            },
            headers: {
                'csrf-token': appiceCookies.getCookie('_csrf')
            },

            success: function (data) {
                semusiCommon.getCsrfToken();
                showMessagesucess("Frequency Capping Updated!");
                $("#messagesucess").delay(3000).fadeOut(300);
                $("#message").delay(3000).fadeOut(300);
                location.reload();
            }
        });
    });
    // Function For Do Not Disturb

    // Validating the Time Inputs 
    function validateDndDiv() {

        if ($('#start_Hour').val() == "" || $('#start_Min').val() == "") {
            $('#DndError').html("Please select a Valid Start Date");
            $('#DndError').show();
            return false;
        }
        if ($('#end_Hour').val() == "" || $('#end_Min').val() == "") {
            $('#DndError').html("Please select a Valid End Date");
            $('#DndError').show();
            return false;
        }
        if ($('#start_Hour').val() == $('#end_Hour').val() && $('#start_Min').val() == $('#end_Min').val() && $('#end_timeshift').val() == $('#start_timeshift').val()) {
            $('#DndError').html("Start And End Time Can't be same");
            $('#DndError').show();
            return false;
        }

        return true
    }

    // validating the message input
    function validateSubDndDiv() {

        if (!$('#dnd_discard').prop("checked") && !$('#dnd_send_later').prop("checked")) {
            $('#DndError').html("Please select any Option for the messages during the DND period");
            $('#DndError').show();
            return false;
        } else {
            if ($('#dnd_discard').prop("checked")) {
                return true
            } else {
                return validateSaveNSendDiv();
            }
        }
    }

    // validating the Send Criteria Input
    function validateSaveNSendDiv() {

        if (!$('#send_all').prop("checked") && !$('#send_one_campaign').prop("checked") && !$('#send_only_one').prop("checked")) {
            $('#DndError').html("Please select any Option in send criteria");
            $('#DndError').show();
            return false;
        } else {
            if ($('#send_one_campaign').prop("checked") || $('#send_only_one').prop("checked")) {
                return true
            } else {
                return validateOrderDiv();
            }
        }

    }


    // Validating the Queue order Input (LIFO or FIFO)
    function validateOrderDiv() {

        if (!$('#lifo').prop("checked") && !$('#fifo').prop("checked")) {
            $('#DndError').html("Please select any Option for the order of messages");
            $('#DndError').show();
            return false;
        } else {

            return validateControlQueue()

        }
    }

    // validating the behaviour of Queue  Inputs	
    function validateControlQueue() {
        if (!$('#all_at_once').prop("checked") && !$('#with_gap').prop("checked")) {
            $('#DndError').html("Please select any Option for controlling the queue");
            $('#DndError').show();
            return false;
        } else {
            if ($('#with_gap').prop("checked")) {
                if ($('#gap_Min').val() == "") {
                    $('#DndError').html("Please select minutes gap between messages");
                    $('#DndError').show();
                    return false;
                }
            }
        }
        return true

    }

    // This function gets the selected method of user and returns the data 
    function getSelectedMethod() {
        var method = {}
        if ($('#fifo').prop("checked")) {
            method.lifo = true;
            method.lifo = false;
        } else {
            method.lifo = true
            method.lifo = false
        }
        return method
    }

    //set and get data in localstorage
    function store(key, value) {
        if (key && value) {
            localStorage.setItem(key, value)
            return;
        }
        if (key && value == undefined) {
            return localStorage.getItem(key)
        }
        return false;
    }

    //  This function gets the selected queue control from user and returns the data 
    function getQueueData() {
        var queue = {}
        if ($('#all_at_once').prop("checked")) {
            queue.all_at_once = true;
            queue.with_gap = false;
        } else {
            queue.all_at_once = false;
            queue.with_gap = true;
            queue.gap_Min = (parseInt($('#gap_Min').val())).toLocaleString('en-US', { minimumIntegerDigits: 2 })
        }
        return queue;
    }

    // This method Gets the data of sub division Of DND  
    function getSubDndDivData() {
        var obj = {}

        if ($('#dnd_discard').prop("checked")) {
            obj.discard_message = true;
        } else {
            obj.discard_message = false;
            var insideObj = {}
            if ($('#send_one_campaign').prop("checked")) {
                insideObj.sendAll = false;
                insideObj.oneFromCampaign = true;
                insideObj.oneFromAll = false;
            } else if ($('#send_only_one').prop("checked")) {
                insideObj.sendAll = false;
                insideObj.oneFromCampaign = false;
                insideObj.oneFromAll = true;
            } else {
                insideObj.sendAll = true;
                insideObj.oneFromCampaign = false;
                insideObj.oneFromAll = false;
                insideObj.method = getSelectedMethod();
                insideObj.queueControl = getQueueData();
            }
            obj.send_message = insideObj;
        }

        return obj
    }

    // This method Gets the data of Main time division Of DND  
    function getDndDivData() {
        var Obj = {}
        Obj.is_Dnd = true;
        Obj.start_Hour = (parseInt($('#start_Hour').val())).toLocaleString('en-US', { minimumIntegerDigits: 2 });
        Obj.start_Min = (parseInt($('#start_Min').val())).toLocaleString('en-US', { minimumIntegerDigits: 2 });
        Obj.start_timeshift = $('#start_timeshift').val();
        Obj.end_Hour = (parseInt($('#end_Hour').val())).toLocaleString('en-US', { minimumIntegerDigits: 2 });
        Obj.end_Min = (parseInt($('#end_Min').val())).toLocaleString('en-US', { minimumIntegerDigits: 2 })
        Obj.end_timeshift = $('#end_timeshift').val();

        return Obj;
    }

    // saving Dnd Time Inputs   
    $('#btnSaveDnd').click(function () {
        var Dnd_Values = {};
        $('#DndError').hide();

        if (!$("#togBtnDnd").is(':checked')) {
            Dnd_Values.is_Dnd = false;
        } else {
            if (validateDndDiv() && validateSubDndDiv()) {

                Dnd_Values = Object.assign(getDndDivData(), getSubDndDivData());

            } else {
                return false
            }

        }

        var mode = 'prod';
        if ($('#chkDevProSwitch').bootstrapSwitch('state') == true) {
            mode = 'dev';
        }
        // API for Saving Data Into DB
        $.ajax({
            type: "POST",
            url: semusiCommon.API_PARTS.apps.w + '/updateDndValue',
            data: {
                args: JSON.stringify({
                    app_id: "<%=appid%>",
                    Dnd_Values: Dnd_Values,
                    mode: mode
                }),
                app_id: semusiCommon.ACTIVE_APP_ID,
                api_key: semusiCommon.getActiveUser.api_key,
                uniqueNumber: semusiCommon.randomNumber(),
            },
            headers: {
                'csrf-token': appiceCookies.getCookie('_csrf')
            },

            success: function (data) {
                semusiCommon.getCsrfToken();
                showMessagesucess("Do Not Disturb Values Updated");
                $("#messagesucess").delay(3000).fadeOut(300);
                $("#message").delay(3000).fadeOut(300);
                location.reload();
            }
        });
    })

    // toggle button of DND for disabling/enabling the sub division 
    $("#togBtnDnd").on('change', function () {
        if ($(this).is(':checked')) {
            $("#subDivBtnDnd").removeClass("disable-div");
        }
        else {
            $("#subDivBtnDnd").addClass("disable-div");
        }
    });
    $("#dnd_discard").click(function(){
        ShowHideDiv();
    });
    $("#dnd_send_later").click(function () {
        ShowHideDiv();
    });

    $("#send_all").click(function () {
        ShowHideSubDiv();
    });
    $("#send_one_campaign").click(function () {
        ShowHideSubDiv();
    });
    $("#send_only_one").click(function () {
        ShowHideSubDiv();
    });
    $("#lifo").click(function () {
        showControlQueueDiv();
    });
    $("#fifo").click(function () {
        showControlQueueDiv();
    })

    // This function gets called on the click of Messages generated radio Box Inputs
    function ShowHideDiv() {
        if ($('#dnd_discard').prop("checked")) {
            $("#Step_4").hide();
            $("#Step_4_1").hide();
            $("#Step_4_1_1").hide();
        } else if ($('#dnd_send_later').prop("checked")) {
            $("#Step_4").show();
        }
    }

    // This function gets called on the radio box of the queue control and it enables and disables the sub divisons

    function ShowHideSubDiv() {
        if ($('#send_all').prop("checked")) {
            $("#Step_4_1").show();
        } else if ($('#send_one_campaign').prop("checked") || $('#send_only_one').prop("checked")) {
            $("#Step_4_1").hide();
        }
    }

    // This function gets called on the radio box of the queue method 
    function showControlQueueDiv() {
        if ($('#lifo').prop("checked") || $('#fifo').prop("checked")) {
            $("#Step_4_1_1").show();
        } else {
            $("#Step_4_1_1").hide();
        }
    }
    // End Function For Do Not Distrub 

    // save FCM database
    $('#btnUpdateFCMdb').click(function () {

        if ($('#FCMdb').val() == "") {
            $('#FCMdbError').show();
            $("#FCMdbError").css('color', 'red');
            return false;
        } else {
            $('#FCMdbError').hide();
        }
        var mode = 'prod';
        if ($('#chkDevProSwitch').bootstrapSwitch('state') == true) {
            mode = 'dev';
        }
        // Adding proxy Value for FCM
        const http_proxy = $('#http_proxy').val()
        $.ajax({
            type: "POST",
            url: semusiCommon.API_PARTS.apps.w + '/updateGCMKeys',
            data: {
                args: JSON.stringify({
                    app_id: "<%=appid%>",
                    fcmKey: $('#FCMdb').val(),
                    http_proxy: http_proxy,
                    mode: mode

                }),
                app_id: semusiCommon.ACTIVE_APP_ID,
                api_key: semusiCommon.getActiveUser.api_key,
                uniqueNumber: semusiCommon.randomNumber(),
            },
            headers: {
                'csrf-token': appiceCookies.getCookie('_csrf')
            },

            success: function (data) {
                semusiCommon.getCsrfToken();
                showMessagesucess("FCM Key Updated!");
                $("#messagesucess").delay(3000).fadeOut(300);
                $("#message").delay(3000).fadeOut(300);
            }
        });
    });

    // save FCM database
    $('#btnUpdateWebPush').click(function () {
        $('#webPushError').hide();
        if ($('#web_private_key').val() == "") {
            $('#webPushError').html("Please enter private key");
            $('#webPushError').show();
            return false;
        }

        if ($('#web_public_key').val() == "") {
            $('#webPushError').html("Please enter public key");
            $('#webPushError').show();
            return false;
        }

        if ($('#web_subject').val() == "") {
            $('#webPushError').html("Please enter subject");
            $('#webPushError').show();
            return false;
        }

        var mode = 'prod';
        if ($('#chkDevProSwitch').bootstrapSwitch('state') == true) {
            mode = 'dev';
        }

        $.ajax({
            type: "POST",
            url: semusiCommon.API_PARTS.apps.w + '/updateGCMKeys',
            data: {
                args: JSON.stringify({
                    app_id: "<%=appid%>",
                    webPush: {
                        privateKey: $('#web_private_key').val(),
                        publicKey: $('#web_public_key').val(),
                        subject: $('#web_subject').val(),
                    },
                    mode: mode

                }),
                app_id: semusiCommon.ACTIVE_APP_ID,
                api_key: semusiCommon.getActiveUser.api_key,
                uniqueNumber: semusiCommon.randomNumber(),
            },
            headers: {
                'csrf-token': appiceCookies.getCookie('_csrf')
            },

            success: function (data) {
                semusiCommon.getCsrfToken();
                showMessagesucess("Web push keys Updated!");
                $("#messagesucess").delay(3000).fadeOut(300);
                $("#message").delay(3000).fadeOut(300);
            }
        });
    });
    // Channel accounts saving Functions 
    function updateChannel(id, flag) {
        var channelObj = {}
        if (flag == 1) {
            channelObj.type = "facebook";

        } else {
            channelObj.type = "google";
        }

        channelObj.account_id = id


        $.ajax({
            type: "POST",
            url: semusiCommon.API_PARTS.apps.w + '/updateChannelAccount',
            data: {
                args: JSON.stringify({
                    app_id: "<%=appid%>",
                    channelObj: channelObj,
                }),
                app_id: semusiCommon.ACTIVE_APP_ID,
                api_key: semusiCommon.getActiveUser.api_key,
                uniqueNumber: semusiCommon.randomNumber(),
            },
            headers: {
                'csrf-token': appiceCookies.getCookie('_csrf')
            },

            success: function (data) {
                semusiCommon.getCsrfToken();
                if (data == null) {
                    showMessage("Something went wrong");
                    $("#message").delay(3000).fadeOut(300);


                } else {
                    showMessagesucess("Channel Account Updated!");
                    $("#messagesucess").delay(3000).fadeOut(300);
                    $("#message").delay(3000).fadeOut(300);
                }

            }
        });
    }
    // connect/disconnect Button of facebook account
    $("#btnFacebookDisconnect").click(function () {

        if (fb_check) {
            $('#facebook_account').val('');
            $("#btnFacebookDisconnect").attr('class', 'btn btn-sm btn-success m-r-5 col-md');
            $("#btnFacebookDisconnect").html('Connect');
            updateChannel(null, 1);

        } else {
            if ($("#facebook_account").val() == '') {
                $('#adwords_error').html("Please enter Facebook Ads Customer ID");
                $('#adwords_error').show();
                return false;
            }
            $("#btnFacebookDisconnect").attr('class', 'btn btn-sm btn-danger m-r-5 col-md');
            $("#btnFacebookDisconnect").html('Disconnect');
            var str = $("#facebook_account").val();
            updateChannel(str, 1);
        }
    });
    // connect/disconnect Button of Google account
    $("#btnGoogleDisconnect").click(function () {

        if (google_check) {
            $('#google_account').val('');
            $("#btnGoogleDisconnect").attr('class', 'btn btn-sm btn-success m-r-5 col-md');
            $("#btnGoogleDisconnect").html('Connect');
            updateChannel(null, 2);

        } else {
            if ($("#google_account").val() == '') {
                $('#adwords_error').html("Please enter Google Ads Customer ID.");
                $('#adwords_error').show();
                return false;
            }
            $("#btnGoogleDisconnect").attr('class', 'btn btn-sm btn-danger m-r-5 col-md');
            $("#btnGoogleDisconnect").html('Disconnect');
            var str = $("#google_account").val();
            updateChannel(str, 2)
        }
    });


    $('#chkDevProSwitch').on('switchChange.bootstrapSwitch', function (e, state) {
        //Switch app mode
        //For dev env switch has true value
        setAppMode(!state);
        swapPushNotificationSettings(state);
        loadCapping();
        checkDnd();
    });

    $("input[name='appsettings']").focus(function () {
        $(this).select();
    });

    setAppMode = function (state) {
        $.ajax({
            type: "GET",
            url: semusiCommon.API_PARTS.apps.w + '/setAppMode',
            data: {
                app_id: "<%=appid%>",
                api_key: semusiCommon.getActiveUser.api_key,
                uniqueNumber: semusiCommon.randomNumber(),
                mode: state
            },

            success: function (data) {

            }
        });

    }

    swapPushNotificationSettings = function (state) {
        $.ajax({
            type: "GET",
            url: semusiCommon.API_PARTS.apps.w + '/getCurrentAppKeys',
            data: {
                args: JSON.stringify({
                    app_id: semusiCommon.ACTIVE_APP_ID,
                }),
                api_key: semusiCommon.getActiveUser.api_key,
                app_id: semusiCommon.ACTIVE_APP_ID,
                uniqueNumber: semusiCommon.randomNumber(),
            },

            success: function (data) {
                document.getElementById("Certfi3").value = '';
                if (state == true) {
                    var text = $('#chkDevProSwitch').bootstrapSwitch('offText');
                    $('#chkDevProSwitch').bootstrapSwitch('labelText', text);
                    $('#apns').html('Apple Push Notification Service(APNS) -- Development');
                    $('#epnu').html('External Push Notification URL -- Development');
                    $('#fcm').html('Firebase Cloud Messaging (FCM) -- Development');
                    $('#wpn').html('Web Push Notificatoin (WPN) -- Development');
                    $('#mpns').html('Microsoft Push Notification Service (APNS) -- Development');
                    if (data.result != null) {
                        if (data.result[0].epnu_key_dev != 'undefined')
                            $('#EPNUKEYS').val(data.result[0].epnu_key_dev);
                        else
                            $('#EPNUKEYS').val('');
                        if (data.result[0].fcmCert_dev != 'undefined')
                            $("#FCMKeys").attr("value", data.result[0].fcmCert_dev);
                        else
                            $('#FCMKeys').attr("value", '')
                        if (data.result[0].fcmKey_dev != 'undefined')
                            $('#FCMdb').val(data.result[0].fcmKey_dev);
                        else
                            $('#FCMdb').val('');
                        if (data.result[0].webPush_dev && data.result[0].webPush_dev != 'undefined') {
                            $('#web_private_key').val(data.result[0].webPush_dev.privateKey);
                            $('#web_public_key').val(data.result[0].webPush_dev.publicKey);
                            $('#web_subject').val(data.result[0].webPush_dev.subject);
                        }
                        else {
                            $('#web_private_key').val('');
                            $('#web_public_key').val('');
                            $('#web_subject').val('');
                        }
                        if (data.result[0].dev_ios_cert3 != 'undefined') {
                            $('#certName3').val(data.result[0].dev_ios_cert3);

                        } else {
                            $('#certName3').val('');
                        }

                        // For button of UI 
                        if (data.result[0].dev_isJsonEnabled != 'undefined' && data.result[0].dev_isJsonEnabled == true) {

                            $('#optionJSON').closest('label').addClass('active');
                            $("#jsonFile").show();
                            $('#optionServer').closest('label').removeClass('active');
                            $("#serverKey").hide();

                        } else {
                            $('#optionServer').closest('label').addClass('active');
                            $("#serverKey").show();
                            $('#optionJSON').closest('label').removeClass('active');
                            $("#jsonFile").hide();
                        }
                        // For development mode
                        if (data.result[0].dev_android_cert3 != 'undefined') {
                            $('#json-cert-name').val(data.result[0].dev_android_cert3);

                        } else {
                            $('#json-cert-name').val('');
                        }

                        if (data.result[0].dev_ios_bundleid != 'undefined') {
                            $('#ios_bundleid').val(data.result[0].dev_ios_bundleid);
                        } else {
                            $('#ios_bundleid').val('');
                        }
                        if (data.result[0].dev_ios_topic != 'undefined') {
                            $("#ios_topic").val(data.result[0].dev_ios_topic);
                        } else {
                            $("#ios_topic").val('');
                        }
                        if (data.result[0].dev_ios_passphrase != 'undefined') {
                            $("#ios_passphrase").val(data.result[0].dev_ios_passphrase);
                        } else {
                            $("#ios_passphrase").val('');
                        }
                        if (data.result[0].dev_ios_key_type != 'undefined') {
                            $('#ios_key_type').val(data.result[0].dev_ios_key_type);
                            if (data.result[0].dev_ios_key_type === "p12") {
                                $('#keyid').hide('');
                                $('#teamid').hide('');
                                $('#topic').hide('');
                                $("#pas").show();
                            }
                            if (data.result[0].dev_ios_key_type === "p8") {
                                $('#keyid').show('');
                                $('#teamid').show('');
                                $('#topic').show('');
                                $("#pas").hide();
                            }
                        } else {
                            $('#ios_bundleid').val('');
                        }
                        if (data.result[0].dev_ios_keyid != 'undefined') {
                            $('#ios_keyid').val(data.result[0].dev_ios_keyid);
                        } else {
                            $('#ios_keyid').val('');
                        }
                        if (data.result[0].dev_ios_teamid != 'undefined') {
                            $('#ios_teamid').val(data.result[0].dev_ios_teamid);
                        } else {
                            $('#ios_teamid').val('');
                        }
                        if (data.result[0].dev_ios_key_type != 'undefined') {
                            $('#auth_key_type').val(data.result[0].dev_ios_key_type);
                        }
                    }
                }
                else {
                    var text = $('#chkDevProSwitch').bootstrapSwitch('onText');
                    $('#chkDevProSwitch').bootstrapSwitch('labelText', text);
                    $('#apns').html('Apple Push Notification Service(APNS) -- Production');
                    $('#epnu').html('External Push Notification URL -- Production');
                    $('#fcm').html('Firebase Cloud Messaging (FCM) -- Production');
                    $('#wpn').html('Web Push Notificatoin (WPN) -- Production');
                    $('#mpns').html('Microsoft Push Notification Service (APNS) -- Production');
                    if (data.result != null) {
                        if (data.result[0].epnu_key_prod != 'undefined')
                            $('#EPNUKEYS').val(data.result[0].epnu_key_prod);
                        else
                            $('#EPNUKEYS').val('');
                        if (data.result[0].fcmCert_prod != 'undefined')
                            $("#FCMKeys").attr("value", data.result[0].fcmCert_prod);
                        else
                            $('#FCMKeys').attr("value", '');
                        if (data.result[0].fcmKey_prod != 'undefined')
                            $('#FCMdb').val(data.result[0].fcmKey_prod);
                        else
                            $('#FCMdb').val('');
                        if (data.result[0].webPush_prod && data.result[0].webPush_prod != 'undefined') {
                            $('#web_private_key').val(data.result[0].webPush_prod.privateKey);
                            $('#web_public_key').val(data.result[0].webPush_prod.publicKey);
                            $('#web_subject').val(data.result[0].webPush_prod.subject);
                        }
                        else {
                            $('#web_private_key').val('');
                            $('#web_public_key').val('');
                            $('#web_subject').val('');
                        }
                        if (data.result[0].ios_cert3 != 'undefined')
                            $('#certName3').val(data.result[0].ios_cert3);
                        else
                            $('#certName3').val('');


                        // For button of UI 
                        if (data.result[0].prod_isJsonEnabled != 'undefined' && data.result[0].prod_isJsonEnabled == true) {

                            $('#optionJSON').closest('label').addClass('active');
                            $("#jsonFile").show();
                            $('#optionServer').closest('label').removeClass('active');
                            $("#serverKey").hide();
                        } else {
                            $('#optionServer').closest('label').addClass('active');
                            $("#serverKey").show();
                            $('#optionJSON').closest('label').removeClass('active');
                            $("#jsonFile").hide();
                        }
                        // For Production case in Android Certificate
                        if (data.result[0].android_cert3 != 'undefined')
                            $('#json-cert-name').val(data.result[0].android_cert3);
                        else
                            $('#json-cert-name').val('');
                        if (data.result[0].ios_keyid != 'undefined')
                            $('#ios_keyid').val(data.result[0].ios_keyid);
                        else
                            $('#ios_keyid').val('');
                        if (data.result[0].ios_teamid != 'undefined')
                            $('#ios_teamid').val(data.result[0].ios_teamid);
                        else
                            $('#ios_teamid').val('');

                        if (data.result[0].ios_bundleid != 'undefined') {
                            $('#ios_bundleid').val(data.result[0].ios_bundleid);
                        } else {
                            $('#ios_bundleid').val('');
                        }
                        if (data.result[0].ios_topic != 'undefined') {
                            $("#ios_topic").val(data.result[0].ios_topic);
                        } else {
                            $("#ios_topic").val('');
                        }
                        if (data.result[0].ios_passphrase != 'undefined') {
                            $("#ios_passphrase").val(data.result[0].ios_passphrase);
                        } else {
                            $("#ios_passphrase").val('');
                        }
                        if (data.result[0].ios_key_type != 'undefined') {
                            $('#ios_key_type').val(data.result[0].ios_key_type);
                            if (data.result[0].ios_key_type === "p12") {
                                $('#keyid').hide('');
                                $('#teamid').hide('');
                                $('#topic').hide('');
                                $("#pas").show();
                            }
                            if (data.result[0].ios_key_type === "p8") {
                                $('#keyid').show('');
                                $('#teamid').show('');
                                $('#topic').show('');
                                $("#pas").hide();
                            }
                        } else {
                            $('#ios_bundleid').val('');
                        }
                    }
                }

                // Representing UI with the variables if present
                if (data.result[0].proxyUrl) {
                    $('#proxyUrl').val(data.result[0].proxyUrl);
                }
                if (data.result[0].proxyPORT) {
                    $('#proxyPORT').val(data.result[0].proxyPORT);
                }
                if (data.result[0].http_proxy) {
                    $('#http_proxy').val(data.result[0].http_proxy);
                }
                //Set Kill Switch feilds 
                if (data.result[0].kill_switch) {
                    let setting = data.result[0].kill_switch;
                    let state = setting.state;
                    let obj = {};
                    if (setting.android) {
                        let android = setting.android.map(ele => ele.v);
                        obj.android = android;
                    }
                    if (setting.ios) {
                        let ios = setting.ios.map(ele => ele.v);
                        obj.ios = ios;
                    }
                    if (setting.web) {
                        let web = setting.web.map(ele => ele.v);
                        obj.web = web;
                    }

                    let android_ver = obj.android ? obj.android.join(',') : '';
                    let ios_ver = obj.ios ? obj.ios.join(',') : '';
                    let web_ver = obj.web ? obj.web.join(',') : '';


                    //Disable input if state == 0
                    if (state === "0") {
                        $("#switch_android").prop('disabled', true);
                        $("#switch_ios").prop('disabled', true);
                        $("#switch_web").prop('disabled', true);
                    } else {
                        $("#switch_android").val(android_ver);
                        $("#switch_ios").val(ios_ver);
                        $("#switch_web").val(web_ver);
                    }

                }
            }
        });

    }
    
    $("#addCustomKey").on("click", () => {
        const custom_key = $("#custom_key").val();
        const custom_value = $("#custom_value").val();

        if (custom_key !== "" && custom_value !== "") {
            const custom_field_list = $("#custom_field_list");

            let newRow = $("<div>").addClass("form-group row");

            // Create the first column for key input
            let keyColumn = $("<div>").addClass("col-md-3");

            let keyInput = $("<input>").attr({
                type: "text",
                value: custom_key,
                disabled: true,
                class: "form-control form-control-sm",
                name: "custom_key"
            });

            keyColumn.append(keyInput);

            // Create the second column for value input
            let valueColumn = $("<div>").addClass("col-md-5");

            let valueInput = $("<input>").attr({
                type: "text",
                value: custom_value,
                disabled: true,
                class: "form-control form-control-sm",
                name: "custom_value"
            });

            valueColumn.append(valueInput);

            // Create the third column for delete button
            let deleteColumn = $("<div>").addClass("col-md-2 col-sm-2");

            let deleteButton = $("<button>").addClass("btn btn-danger btn-sm").css("marginLeft", "10px").html('<i class="fa fa-minus"></i>');
            deleteButton.on("click", function () {
                newRow.remove();
            });

            deleteColumn.append(deleteButton);

            // Append columns to the row
            newRow.append(keyColumn, valueColumn, deleteColumn);

            // Append the row to the custom field list
            custom_field_list.append(newRow);

            // Clear input fields after adding to the list
            $("#custom_key").val('');
            $("#custom_value").val('');
        } else {
            alert("Please enter a Key and its Reference value.");
        }
    });

    
    // When changing method of FCM either server or json File 
    $('input[type="radio"]').change(function(){
        if ($(this).attr("id") == "optionServer") {
            $("#serverKey").show();
            $("#jsonFile").hide();
        }
        else if ($(this).attr("id") == "optionJSON") {
            $("#serverKey").hide();
            $("#jsonFile").show();
        }
    });



    // Update the status in case of server key is selected for fcm 
    $('#optionServer').change(function(){
        if ($(this).is(':checked')) {
          setFcmAsJSON(false);
        }
      });

       // Update the status in case of json file is selected for fcm 
      $('#optionJSON').change(function(){
        if ($(this).is(':checked')) {
              setFcmAsJSON(true);
        }
      });

      $(".save_custom").on("click", () => {

        // get the customFields 
        let customFields = {};
        $('#custom_field_list input[name="custom_key"]').each(function (index) {
            let key = $(this).val();
            let value = $('#custom_field_list input[name="custom_value"]').eq(index).val();
            customFields[key] = value;
        });

        // get the script 
        let scriptCode = $("#custom_script").val();

        if (scriptCode.trim() === "") {
            scriptCode = undefined;
          }
          
        $.ajax({
            type: "POST",
            url: semusiCommon.API_PARTS.apps.w + '/save_custom',
            data: {
                args: JSON.stringify({
                    app_id: semusiCommon.ACTIVE_APP_ID,
                    customFields: customFields,
                    scriptCode:scriptCode,

                }),
                uniqueNumber: semusiCommon.randomNumber(),
                api_key: semusiCommon.getActiveUser.api_key
            },
            headers: {
                'csrf-token': appiceCookies.getCookie('_csrf')
            },
            success: function (data) {
                showMessagesucess("Saved");
                $("#messagesucess").delay(3000).fadeOut(300);
                $("#message").delay(3000).fadeOut(300);
                location.reload();
            }
        })
    });

/**
 * This function, `setFcmAsJSON`, is responsible for making an AJAX request to the server
 * to set the FCM (Firebase Cloud Messaging) mode to JSON or non-JSON based( server key) on the provided state.
 * @param {boolean} state - The desired state for enabling JSON for FCM.
 */
      function setFcmAsJSON(state) {

        // getting the current mode of app , be it "dev" or "prod"
        let isdev = 'false';
        if ($('#chkDevProSwitch').bootstrapSwitch('state') == true) isdev = 'true';

        $.ajax({
            type:"GET",
            url:semusiCommon.API_PARTS.apps.w + '/setFcmMode',
            data:{
                    app_id :semusiCommon.ACTIVE_APP_ID,
                    api_key:semusiCommon.getActiveUser.api_key,
                    uniqueNumber : semusiCommon.randomNumber(),
                    isJsonEnabled:state,
                    isdev:isdev
                 }, 
                success:function (data){

                          // Show success message in 
                          showMessagesucess('Fcm Mode Updated');
                          $("#messagesucess").delay(3000).fadeOut(300);
                }
          });
    
      }



    // Check For apple Certificate
$('#Certfi3').change(function(evt) {
    uploadCertificate(1);

});


$('#logoImg').on('change', handleFileUpload);

$('#XMLmetadataFile').on('change', handleXmlUpload);

function handleXmlUpload() {
    const fileInput = $('#XMLmetadataFile')[0]; // jQuery object to native element
    const XMLmetadataFileNameInput = $('#XMLmetadataFile_name')[0]; // jQuery object to native element

    if (fileInput.files.length > 0) {
        const file = fileInput.files[0];

        let fd = new FormData();
        fd.append('XMLmetadataFile', file);
        fd.append('XMLmetadataFile_id', file.name);
        fd.append('appid', semusiCommon.ACTIVE_APP_ID);
        fd.append('XML', true);

        $.ajax({
            type: 'POST',
            url: "campaignFiles/campaignimages", // Adjust URL to match your API endpoint for XML upload
            data: fd,
            processData: false,
            contentType: false,
            headers: {
                'csrf-token': appiceCookies.getCookie('_csrf')
            },
            success: function(data) {
                showMessagesucess('XML File Uploaded'); // Update success message as needed
                $("#messagesucess").delay(3000).fadeOut(300);
                XMLmetadataFileNameInput.value = file.name; // Update input field if needed
                semusiCommon.getCsrfToken(); // Ensure CSRF token is updated if needed
            },
            error: function(xhr, status, error) {
                showMessage("Error uploading XML file"); // Show error message to user if needed
                $("#message").delay(3000).fadeOut(300);
            }
        });
    } else {
        showMessage("No XML file selected."); // Inform user if no file selected
    }
}

/**
 * handleFileUpload handles the process of uploading an image file via an HTML form.
 * Validates the file type and dimensions, then sends it to the server via AJAX.
 * Displays success or error messages based on the upload status.
 */

function handleFileUpload() {
    const fileInput = $('#logoImg')[0]; // jQuery object to native element
    const logoNameInput = $('#logo_name')[0]; // jQuery object to native element

    // Check if a file is selected
    if (fileInput.files.length > 0) {
        const file = fileInput.files[0];
        
        // Check if the file is an image
        if (!file.type.startsWith('image/')) {
            showMessage("Please upload an image file.");
            return;
        }
        
        // Create a FileReader to read the uploaded image
        const reader = new FileReader();
        reader.onload = function(e) {
            const image = new Image();
            image.onload = function() {

                // Check if the image dimensions exceed the specified limits (250x250 pixels)
                if (image.width > 250 || image.height > 250) {
                    showMessage("Please upload an image with dimensions up to 800x600 pixels.");
                    $("#message").delay(3000).fadeOut(300);

                } else {
                    // Image dimensions are within limits, proceed with AJAX upload
                    let fd = new FormData();
                    fd.append('image', file);
                    fd.append('image_id', file.name);
                    fd.append('appid', semusiCommon.ACTIVE_APP_ID);
                    fd.append('customLogo', true);

                    $.ajax({
                        type: 'POST',
                        url: "campaignFiles/campaignimages",
                        data: fd,
                        processData: false,
                        contentType: false,
                        headers: {
                            'csrf-token': appiceCookies.getCookie('_csrf')
                        },
                        success: function(data) {
                            showMessagesucess('Campaign Image Uploaded');
                            $("#messagesucess").delay(3000).fadeOut(300);
                            logoNameInput.value = file.name;
                            semusiCommon.getCsrfToken();
                        },
                        error: function(xhr, status, error) {
                            showMessage("Error uploading campaign image");
                            $("#message").delay(3000).fadeOut(300);
                        }
                    });
                }
            };
            image.src = e.target.result;
        };
        reader.readAsDataURL(file);
    } else {
        showMessage("No file selected.");
    }
}


// Check For JSON File of Android Certificate
$('#json-cert').change(function(evt) {
    uploadCertificate(2);
});


// Function to upload a certificate file based on file number
// Params:
//   - filenumber: Number indicating the type of certificate file (1 for iOS, 2 for Android)
// sends a api request to upload the certificate
function uploadCertificate(filenumber) {
    let logofiles =[]
    const flag = true;
    // For IOS Certificate
    if (filenumber == 1) {
        logofiles = $('#Certfi3').get(0).files;
        const fileName = logofiles[0].name.split(".");
        if (fileName.length < 2 || !validateUploadFile(logofiles[0].name) || (fileName[fileName.length - 1] !== 'p8' && fileName[fileName.length - 1] !== 'p12')) {
            showMessage("Please Enter Only .p8 or .p12 Certificate Files");
            $(this).val('')
            $("#message").delay(3000).fadeOut(300);
            flag = false;
            return false;
        }
    }

    // Check For JSON File of Android Certificate
    if (filenumber == 2) {
        logofiles = $('#json-cert').get(0).files;
        const fileName = logofiles[0].name.split(".");
        if (fileName.length < 2 || !validateUploadFile(logofiles[0].name) || fileName[fileName.length - 1] !== 'json') {
            showMessage("Please Enter Json Certificates Files only ");
            $(this).val('')
            $("#message").delay(3000).fadeOut(300);
            flag = false;
            return false;
        }
    }
    if (flag == true) {
        let isdev = 'false';
        if ($('#chkDevProSwitch').bootstrapSwitch('state') == true) isdev = 'true';
        const appid = semusiCommon.ACTIVE_APP_ID;
        if (logofiles.length >= 1) {
            //upload the first logo file
            const fd = new FormData();
            fd.append('app_cert', logofiles[0]);
            fd.append('app_cert_name', logofiles[0].name);
            fd.append('platform', (filenumber == 2 ) ? 'android' : 'ios');
            fd.append('app_cert_id', appid);
            fd.append('isdev', isdev);
            saveCopyToSecondary(fd);
            $.ajax({
                url: '/apps/ioscertificate',
                data: fd,
                headers: {
                'csrf-token': appiceCookies.getCookie('_csrf')
                },
                cache: false,
                contentType: false,
                processData: false,
                type: 'POST',
                success: function(data) {

                    // Show success message in 
                    showMessagesucess('File uploaded successfully');
                    $("#messagesucess").delay(3000).fadeOut(300);


                    if (filenumber == 1) {
                       
                        $("#certName3").attr("value", logofiles[0].name);
                        $("#certPath3").attr("value", data);
                    }
                    if (filenumber == 2) {

                        $("#json-cert-name").attr("value", logofiles[0].name);
                    }
                    
                },
                error: function(){
                    showMessage("Something went wrong");
                    $("#message").delay(3000).fadeOut(300); 
                }
            });
        }
    }
}


function saveCopyToSecondary(fd){
    $.ajax({
        url: '/apps/certificate',
        data: fd,
        headers: {
            'csrf-token': appiceCookies.getCookie('_csrf')
        },
        cache: false,
        contentType: false,
        processData: false,
        type: 'POST',
    success: function(jsdonData){
        }
    });
}
function loadSettingPage() {
    loadCapping();
	checkDnd();
	loadChannelAccountData();
    swapPushNotificationSettings(!mode);
}

window.onload = loadSettingPage;

}());
