var globalStartDate, globalEndDate;
(function initDateRange() {  
 setDefaultDateFilter() 

$('#advance-daterange').daterangepicker({
    format: semusiCommon.getDateFormatt(),
    startDate: moment().subtract(29, 'days'),
    endDate: moment(),
    minDate: '01/01/2012',
    maxDate: new Date(),
    showDropdowns: true,
    showWeekNumbers: false,
    timePicker: false,
    timePickerIncrement: 1,
    timePicker12Hour: true,
    ranges: {
        'Today': [moment(), moment()],
        'Yesterday': [moment().subtract(1, 'days'), moment().subtract(1, 'days')],
        'Last 7 Days': [moment().subtract(6, 'days'), moment()],
        'Last 30 Days': [moment().subtract(29, 'days'), moment()],
        'This Month': [moment().startOf('month'), moment().endOf('month')],
        'Last Month': [moment().subtract(1, 'month').startOf('month'), moment().subtract(1, 'month').endOf('month')]
    },
    opens: 'left',
    drops: 'down',
    buttonClasses: ['btn', 'btn-sm'],
    applyClass: 'btn-primary',
    cancelClass: 'btn-default',
    separator: ' to ',
    locale: {
        applyLabel: 'Submit',
        cancelLabel: 'Cancel',
        fromLabel: 'From',
        toLabel: 'To',
        customRangeLabel: 'Custom',
        daysOfWeek: ['Su', 'Mo', 'Tu', 'We', 'Th', 'Fr', 'Sa'],
        monthNames: ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'],
        firstDay: 1
    }
}, function (start, end, label) {
    var sd = start ; 
    var ed = end;
    if (label != "Custom") {
      if (label == "Today") {
        sd = moment.utc().startOf("day").valueOf();
        ed = moment.utc().endOf("day").valueOf();
      }
      if (label == "Yesterday") {
        sd = moment.utc().subtract(1, "days").startOf("day").valueOf();
        ed = moment.utc().subtract(1, "days").endOf("day").valueOf();
      }
      if (label == "This Month") {
        sd = moment.utc().startOf("month").valueOf();
        ed = moment.utc().endOf("month").valueOf();
      }
      if (label == "Last 30 Days") {
        sd = moment().subtract(29, "days").startOf('day').valueOf();
        ed = moment.utc().endOf("day").valueOf();
      }
      if (label == "Last 7 Days") {
        sd = moment.utc().subtract(6, "days").startOf('day').valueOf();
        ed = moment.utc().endOf("day").valueOf();
      }
      if (label == "Last Month") {
        sd = moment.utc().subtract(1, "month").startOf("month").valueOf();
        ed = moment.utc().subtract(1, "month").endOf("month").valueOf();
      }
    }else{
        sd= moment(sd.format(semusiCommon.getDateFormatt())).unix() *1000;
        ed = moment(ed.format(semusiCommon.getDateFormatt())).unix()*1000 ;
    }  
    globalStartDate =sd
    globalEndDate  =ed
    var totalSelectedRows = $('tr.selected').length;
    if (totalSelectedRows == 0) {
    getCampaigns(campaignStatus,sd,ed);
   }
    labeldate = label.replace(/\s+/g, '').toLowerCase();
    semusiCommon.setDateRange(start, end);
    $('#advance-daterange span').html(start.format(semusiCommon.getDateFormatt()) + ' - ' + end.format(semusiCommon.getDateFormatt()));
    $('.ms-drop').find("ul").remove();

  
})})();

function setDefaultDateFilter(){
    semusiCommon.setDateRange(null,null);    
    $("#advance-daterange span").html(
        moment().utc()
          .subtract("days", 29)
          .format(semusiCommon.getDateFormatt()) +
          " - " +
          moment().utc().format(semusiCommon.getDateFormatt())
      );
    var _period = [moment(semusiCommon.dateRange.currentStartDate*1000).format('MM/DD/YYYY'),moment(semusiCommon.dateRange.currentEndDate*1000).format('MM/DD/YYYY')];
    semusiCommon.setPeriod(_period);
}
$(document).ready(function() {

    if(semusiCommon.ACTIVE_APP_ID ==undefined || semusiCommon.ACTIVE_APP_ID==""){
		window.location =  "/dashboard";

        $('#divEngagementTools').hide();
    }

    if(semusiCommon.getParameterValues("action").indexOf("campaigns")>=0){
        var wiz = $("#campaignwizard").bwizard({ activeIndexChanged: function (e, ui) {

        }});
        if(semusiCommon.getParameterValues("new")=="true"){
        }
        $("#divToolsSection").hide();
        $("#createNewTool").show();

        $("#campaignStartDate").datepicker({
            todayHighlight: true,
            autoclose: true,
            forceParse: false
        });
        $("#campaignEndDate").datepicker({
            todayHighlight: true,
            autoclose: true,
            forceParse: false
        });
        $("#previewDiv").css("top","20px");
        getAudienceSegments();

        $("#rdbAllWeek").click(function(){
            selectAllWeek();
        });

        $("#rdbSpecificDays").click(function(){
            $("input[name='weekday']").prop('disabled',false);
            $("input[name='weekday']").prop('checked',false);
        });

        $("#rdbAllTime").click(function(){
        });

        $("#rdbSpecificTime").click(function(){
        });

        $("input[name='weekday']").click(function(){
            viewModel.selectedDays([]);
            var days= $("input[name='weekday']");
            for(var x=0;x<days.length; x++){
                if(days[x].checked){
                    viewModel.selectedDays.push(days[x].value);
                }
            }
        });

       const sd = moment.utc().subtract(29, "days").startOf('day').valueOf();
       const ed = moment.utc().endOf("day").valueOf();

        getCampaigns('ACTIVE',sd,ed);
    }
    else{
        getAppTemplates();
    }


});

function getAppTemplates()
{

    var app_id = semusiCommon.ACTIVE_APP_ID;
    $.ajax({
    type:"GET",
    url:semusiCommon.API_PARTS.templates.r + '/getAllTemplates',
    data:{
        api_key: semusiCommon.getActiveUser.api_key,
        app_id: app_id,
        uniqueNumber: semusiCommon.randomNumber(),
    },
     
    success:function (data) {
        $("#tblTemplates > tbody:last").children().remove();
        for(var counter=0;counter<data.length;counter++)
        {
            $('#tblTemplates > tbody:last').append('<tr><td>' + data[counter].template_name +'</td><td>'+ data[counter].template_type  +'</td><td>'+data[counter].createdOn+'</td><td>'+data[counter].modifiedOn+'</td><td width="60px"><button type="button" class="btn btn-success m-r-5 m-b-5" onclick="editTemplate(\''+data[counter]._id +'\',\''+data[counter].template_type +'\');">Select</button><div id="'+data[counter]._id +'" style="display:none">'+ JSON.stringify(data[counter]) +'</div></td><td width="60px"><button type="button" class="btn btn-danger m-r-5 m-b-5" onclick="deleteTemplate(\''+data[counter]._id +'\');">Delete</button></td></tr>');
        }

    }});
}

//handle the click of selectall button 
$('#selectAllCheckbox').on('change', function () {
    var isChecked = $(this).prop('checked');
    
    if (isChecked) {
        $('#tblCampaigns tbody tr').find('.select-row').prop('checked', true);
        $('#tblCampaigns tbody tr').toggleClass('selected', true);
        if(globalEndDate == undefined){
            handleRowSelection()
        }
    } else {
        $('.select-row').prop('checked', false);
        $('#tblCampaigns tbody tr').toggleClass('selected', false);
        setDefaultDateFilter()
    }
});

//This function maitians the order of the columns
function getOrderedColumns(columnVisibility){
    const desiredOrder = ["conversion", "ctr", "clickedTo", "impressionRate", "receivedTo"];
    let orderedColumnVisibility = {};
               
    desiredOrder.forEach(key => {
        orderedColumnVisibility[key] = columnVisibility[key];
    });
    return orderedColumnVisibility
}

// this function gives the key for the Campaign column 
function getIndexForKey(key,data) {
   for (let i = 0; i < data.length; i++) {
       if (data[i].mData === key) {
           return i;
       }
   }
   return -1; 
}
// This funtion creates the dynamic column 
// This function also shows and hide the column header
function getDynamicColumnNHandleColumns(orderedColumnVisibility,campaignType){

    let dynamicAoColumn = [
        { "data": null, "sDefaultContent": '<input type="checkbox" class="select-row">' },
        { "data": 't' },
        { "data": 'nm' },
        { "data": 'segmentName' },
        { "data": 'reach' },
        { "data": 'pushedTo' },
       // These are the existing columns
       // others will be added in this place
        {
            "data": "sd", "bSortable": false, "mRender": function (data, type, full) {
                return '<label value="' + data + '">' + semusiCommon.getDateAndTimeFromEpoch(data) + '</label>';
            }
        },
        {
            "data": "ed", "bSortable": false, "mRender": function (data, type, full) {
                return '<label value="' + data + '">' + semusiCommon.getDateAndTimeFromEpoch(data) + '</label>';
            }
        },

        { // Action Buttons
            "data": null,
            "bSortable": false,
            "render": function (data, type, full) {
                if(campaignType=="ACTIVE"){
                    let viewbtn = getViewBtn(full);                                                         
                    var html = '';
                    if(store.get("user_role") == "admin" || store.get("user_role") == "manager") {
                        html = "<button type='button' title='Delete' class='setActiveCampaignD btn btn-danger m-r-5 m-b-5' id='"+full._id +"' value='"+full._id +"'><i class='fa fa-times'></i></button><label id='lblSegmentInfo_"+ full._id +"' style='display:none'>"+full.segmentinfo+"</label><label id='lblSegmentName_"+full._id+"' style='display:none'>"+full.segmentName+"</label>";
                        html += getCopyBtn(full)
                        html += getEditBtn(full)
                    }
                    return html+viewbtn;

                }
                else if(campaignType=="DRAFT"){
                    let viewbtn = getViewBtn(full);                                                        
                    if(full.active == false){
                        return getEditBtn(full) +"<label id='lblSegmentInfo_"+ full._id +"' style='display:none'>"+full.segmentinfo+"</label><label id='lblSegmentName_"+full._id+"' style='display:none'>"+full.segmentName+"</label>"+"<button title='Set Active' type='button' class='setActiveCampaignA btn btn-warning m-r-5 m-b-5' id='"+full._id +"' value='"+full._id +"'><i class='fa fa-check'></i></button>"+viewbtn;
                    }else{
                        var html = '';
                        if(store.get("user_role") == "admin" || store.get("user_role") == "manager") {
                            html = "<button title='Set Active' type='button' class='setActiveCampaignA btn btn-warning m-r-5 m-b-5' id='"+full._id +"' value='"+full._id +"'><i class='fa fa-check'></i></button>";
                            html += getDraftDeleteBtn(full) ;
                        }

                        return html+ getEditBtn(full) + getCopyBtn(full) +"<label id='lblSegmentInfo_"+ full._id +"' style='display:none'>"+full.segmentinfo+"</label><label id='lblSegmentName_"+full._id+"' style='display:none'>"+full.segmentName+"</label>"+viewbtn;

                    }
                }
                if(campaignType=="PAST"){
                    let viewbtn = getViewBtn(full);                                                          
                    var html = '';
                    if(store.get("user_role") == "admin" || store.get("user_role") == "manager") {
                        html = getPastDeleteBtn(full);
                    }
                    return html+ getCopyBtn(full) +"<label id='lblSegmentInfo_"+ full._id +"' style='display:none'>"+full.segmentinfo+"</label><label id='lblSegmentName_"+full._id+"' style='display:none'>"+full.segmentName+"</label>"+viewbtn;
                }
            }
        }
    ];
 
   const indexToInsert = dynamicAoColumn.findIndex(column => column.data === 'pushedTo') + 1;


   // Iterate through each key in columnVisibility object
   $.each(orderedColumnVisibility, function(columnId, isVisible) {
       // If isVisible is true, add the column to dynamicAoColumn at the specified index
       if (isVisible) {
            // add the column in AoColoumn Object
           dynamicAoColumn.splice(indexToInsert, 0, { "data": columnId });
           $(`#${columnId}`).show();          // Show column
       }else{
           $(`#${columnId}`).hide();           // Hide column
       }
   });
   return dynamicAoColumn
}

//handle the click of campaign row 
$('#tblCampaigns tbody').on('click', 'input.select-row', function () {
    var tr = $(this).closest('tr');
    tr.toggleClass('selected');


    // Check/uncheck "Select All" based on the number of selected rows
    var totalSelectedRows = $('tr.selected').length;
    var totalRows = $('#tblCampaigns tbody tr').length;

    if (totalSelectedRows === totalRows ) {
        $('#selectAllCheckbox').prop('checked', true);
    } else {
        $('#selectAllCheckbox').prop('checked', false);
    }

    // Check if any rows are selected
    if (totalSelectedRows == 1  ) {        
        handleRowSelection()

    } else if(totalSelectedRows == 0){

        setDefaultDateFilter()

    }

});
function handleRowSelection() {
    $("#advance-daterange span").html(moment().subtract("days", 29).format(semusiCommon.getDateFormatt()) + " - " + moment().format(semusiCommon.getDateFormatt()));
    globalStartDate = moment.utc().subtract("days", 29).valueOf();
    globalEndDate = moment.utc().endOf("day").valueOf();
}


var campaignStatus = "ACTIVE";
// This function downloads the default  csv  for all the campaigns
function downloadCampaignCsvFileNow(){
    // get the table information
    const table = $('#tblCampaigns').DataTable();

    // Get pagination and search values
    let pageInfo = table.page.info();
    let start = pageInfo.start;
    let length = pageInfo.length;
    let searchValue = table.search();
    var startDayEpoch = moment.utc(semusiCommon.dateRange.currentStartDateNew).valueOf();
    var endDayEpoch = moment.utc(semusiCommon.dateRange.currentEndDateNew).endOf('day').valueOf() ;
    var span = document.getElementById("dtSpan").textContent
    if(span == "Kindly Select Date Range") {
        window.location.href = appiceEncode.encodePayload(semusiCommon.API_PARTS.templates.r + '/downloadActiveCampaignData?api_key='+semusiCommon.getActiveUser.api_key+'&uniqueNumber='+ semusiCommon.randomNumber()+'&app_id='+semusiCommon.ACTIVE_APP_ID+'&status='+campaignStatus+'&start=' + start +'&length=' + length +'&searchValue=' + searchValue + '&filename=campaign.csv');
    }else{
 window.location.href = appiceEncode.encodePayload(semusiCommon.API_PARTS.templates.r + '/downloadActiveCampaignData?api_key='+semusiCommon.getActiveUser.api_key+'&uniqueNumber='+ semusiCommon.randomNumber()+'&app_id='+semusiCommon.ACTIVE_APP_ID+'&status='+campaignStatus+'&start=' + start +'&length=' + length +'&searchValue=' + searchValue +'&sd='+startDayEpoch+'&ed='+endDayEpoch+'&filename=campaign.csv');
    }
};

var randomString = function (len, bits)
{
    bits = bits || 36;
    var outStr = "", newStr;
    while (outStr.length < len)
    {
        newStr = appiceFloat.generateRandomFloat().toString(bits).slice(2);
        outStr += newStr.slice(0, Math.min(newStr.length, (len - outStr.length)));
    }
    return outStr.toUpperCase();
};
function downloadCsv(selectedRows) {
    if (selectedRows.length == 0) {
        downloadCampaignCsvFileNow()
    } else {
        downloadCampaignClickReports(selectedRows)
    }
}
// Function to handle click events for setActiveCampaignA
function handleSetActiveCampaignA() {
    setActiveCampaign($(this).val(), "ACTIVE");
    // Unbind the click event handler after it's executed once
    $(this).off('click');
}

// Function to handle click events for setActiveCampaignD
function handleSetActiveCampaignD() {
    setActiveCampaign($(this).val(), "DRAFT");
    // Unbind the click event handler after it's executed once
    $(this).off('click');
}

// Function to handle click events for editCampaign
function handleEditCampaign() {
    editCampaign($(this).attr('id'), $(this).val());
    // Unbind the click event handler after it's executed once
    $(this).off('click');
}

// Function to handle click events for viewCampaignDetails
function handleViewCampaignDetails() {
    viewCampaignDetails($(this).val(), "ACTIVE", $(this));
    // Unbind the click event handler after it's executed once
    $(this).off('click');
}

// Function to handle click events for copyCampaign
function handleCopyCampaign() {
    copyCampaign($(this).val());
    // Unbind the click event handler after it's executed once
    $(this).off('click');
}


// Function to handle click events for deletePastCampaign
function handleDeletePastCampaign() {
    deleteCampaign($(this).val(), "PAST");
    // Unbind the click event handler after it's executed once
    $(this).off('click');
}


// Function to handle click events for deleteDraftCampaign
function handleDeleteDraftCampaign() {
    deleteCampaign($(this).val(), "DRAFT");
    // Unbind the click event handler after it's executed once
    $(this).off('click');
}

function initiateGetCampaigns(status){
    var sd =  moment.utc().subtract(29, 'days').valueOf();
    var ed =  moment.utc().valueOf();
    $('#advance-daterange span').html( moment().subtract(29, 'days').format(semusiCommon.getDateFormatt()) + ' - ' +  moment().format(semusiCommon.getDateFormatt()));
    getCampaigns(status,sd,ed);
}
function transactionalCsvDownload (){
    var startDayEpoch = moment.utc(semusiCommon.dateRange.currentStartDateNew).valueOf();
    var endDayEpoch = moment.utc(semusiCommon.dateRange.currentEndDateNew).endOf('day').valueOf() ;
    var span = document.getElementById("txndtSpan").textContent
    if(span == "Kindly Select Date Range") {
        window.location.href = appiceEncode.encodePayload(semusiCommon.API_PARTS.templates.r + '/downloadTransactionalCampaignData?api_key='+semusiCommon.getActiveUser.api_key+'&app_id='+semusiCommon.ACTIVE_APP_ID+ '&uniqueNumber=' +semusiCommon.randomNumber()+'&cy="t"&status='+campaignStatus+'&filename=txncampaign.csv');
    }else{
    window.location.href = appiceEncode.encodePayload(semusiCommon.API_PARTS.templates.r + '/downloadTransactionalCampaignData?api_key='+semusiCommon.getActiveUser.api_key+'&app_id='+semusiCommon.ACTIVE_APP_ID+ '&uniqueNumber=' +semusiCommon.randomNumber()+'&cy="t"&sd='+startDayEpoch+'&ed='+endDayEpoch+'&status='+campaignStatus+'&filename=txncampaign.csv');
    }
};
function getCampaigns(status,startDayEpoch,endDayEpoch){
    //set checkboxes as false by default
    $('#selectAllCheckbox').prop('checked', false);
    $('#tblCampaigns tbody tr').toggleClass('selected', false);
    if(startDayEpoch == null && endDayEpoch == null )  {
        startDayEpoch = globalStartDate;
        endDayEpoch   = globalEndDate;
    }
    let cmpType = "";
    const params = new Proxy(new URLSearchParams(window.location.search), {
        get: (searchParams, prop) => searchParams.get(prop),
      });
    let value = params.action; 
    if(value == 'transactionalCampaigns'){
        cmpType = "t";
    }
    showAppCampaigns(status,startDayEpoch,endDayEpoch,cmpType)
}




copyCampaign = function(campaignId){
    if(confirm('Are you sure want to copy this campaign')){
        $.ajax({
            type:"GET",
            url:semusiCommon.API_PARTS.templates.w + '/copyCampaign',
            data:{
                args:JSON.stringify({
                     d:true,
                     ud:semusiCommon.getCurrentEpoch(),
                }),
                api_key: semusiCommon.getActiveUser.api_key,
                cid: campaignId,
                app_id: semusiCommon.ACTIVE_APP_ID,
                uniqueNumber: semusiCommon.randomNumber(),
            },
             
            success:function (data) {
                initiateGetCampaigns('DRAFT');
            }
        });
    }

}

// This function downloads the click reports for the selected rows
function downloadCampaignClickReports(selectedRows){
    
    const idArray = selectedRows.map(obj => obj._id);
    $.ajax({
        type:"GET",
        url:semusiCommon.API_PARTS.templates.r + '/initiateCampaignExports',
        data:{
            api_key: semusiCommon.getActiveUser.api_key,
            app_id: semusiCommon.ACTIVE_APP_ID,
            uniqueNumber: semusiCommon.randomNumber(),
            args:JSON.stringify({
                cids:idArray,
                startDayEpoch:parseInt(globalStartDate),
                endDayEpoch:parseInt(globalEndDate)
            }),

        },
         
        success:function (data) {
            $("#messageboxsucess").text("Campaign Export Initiated ")
            $("#messagesucess").show();

            setTimeout(() => {
              $("#messagesucess").hide();
            },3000)   


        },
        error:function(error){
            $('#overlay').hide();
        }
    });
}
function editTemplate(id,templateType){
    var template = $.parseJSON($('#'+id).html());

    switch(templateType){
        case "PUSH":
            fillPushScreen(template);
            break;
        case "IN-APP":
            fillInAppScreen(template);
            break;
        case "SURVEY":
            fillSurveyScreen(template);
            break;
        case "RATING":
            fillRatingScreen(template);
            break;
        case "FEEDBACK":
            fillFeedbackScreen(template);
            break;
    }
}

function deleteTemplate(id){
    if(confirm("Are you sure to delete this template?")) {
        var app_id = semusiCommon.ACTIVE_APP_ID;
        $.ajax({
            type:"GET",
            url:semusiCommon.API_PARTS.templates.w + '/delete',
            data:{
                args:JSON.stringify({
                    isTemplateDeleted:"true",
                    modifiedOn:getCurrentDate()
                }),
                api_key: semusiCommon.getActiveUser.api_key,
                template_id: id,
                app_id: app_id,
                uniqueNumber: semusiCommon.randomNumber(),
            },
             
            success:function (data) {
                   getAppTemplates();
                }});
    }
}

function getCurrentDate(){
    var m_names = new Array("January", "February", "March","April", "May", "June", "July", "August", "September","October", "November", "December");
    var d = new Date();
    var curr_date = d.getDate();
    var curr_month = d.getMonth();
    var curr_year = d.getFullYear();
    return (curr_date + "-" + m_names[curr_month]+ "-" + curr_year);
}


function showAppCampaigns(campaignStatus, sd, ed, cmpType) {

        // Destroy existing DataTable instance if it exists
    if ($.fn.DataTable.isDataTable('#tblCampaigns')) {
        $('#tblCampaigns').DataTable().clear().destroy();
    }


    $.ajax({
        url: semusiCommon.API_PARTS.templates.r + '/getCampaignsByStatus',
        dataType: 'json',
        data: {
            "api_key": semusiCommon.getActiveUser.api_key,
            "app_id": semusiCommon.ACTIVE_APP_ID,
            "status": campaignStatus,
            "cmpType": cmpType,
            "sd": sd,
            "ed": ed,
            uniqueNumber: semusiCommon.randomNumber(),
        },
        success: function(response) {

                    // get the  column status for the response 
                const orderedColumnVisibility = getOrderedColumns(response.dynamicColumns)
                    // create dynamic column based on the column status
                const dynamicAoColumn = getDynamicColumnNHandleColumns(orderedColumnVisibility,campaignStatus)

            if (response && dynamicAoColumn) {
                // Initialize DataTable
                $('#tblCampaigns').DataTable({
                    processing: true,
                    serverSide: true,
                    ajax: {
                        url: semusiCommon.API_PARTS.templates.r + '/getCampaignsByStatus',
                        data: function(d) {
                            // Pass additional parameters to the server
                            d.api_key = semusiCommon.getActiveUser.api_key;
                            d.app_id = semusiCommon.ACTIVE_APP_ID;
                            d.status = campaignStatus;
                            d.cmpType = cmpType;
                            d.sd = sd;
                            d.ed = ed;
                            d.uniqueNumber = semusiCommon.randomNumber();
                            d.draw = d.draw; // Pass draw parameter
                        },
                        dataSrc: 'data' // Ensure DataTables reads data from 'data' property
                    },
                    columns: dynamicAoColumn, // Use dynamic columns from the response
                    order: [[1, "desc"]],
                    pageLength: 10,
                    drawCallback: function(settings) {
                        // Bind click events after the table is drawn
                        bindEventHandlers();
                    }
                });
            } else {
                showErrorMsg();
            }
        },
        error: function(jqXHR, textStatus, errorThrown) {
            console.error('Error fetching data:', textStatus, errorThrown);
            showErrorMsg();
        }
    });
}

function bindEventHandlers() {
    // Rebind event handlers after table is drawn
    $('.setActiveCampaignA').on('click', handleSetActiveCampaignA);
    $('.setActiveCampaignD').on('click', handleSetActiveCampaignD);
    $('.editCampaign').on('click', handleEditCampaign);
    $('.viewCampaignDetails').on('click', handleViewCampaignDetails);
    $('.copyCampaign').on('click', handleCopyCampaign);
    $('.deletePastCampaign').on('click', handleDeletePastCampaign);
    $('.deleteDraftCampaign').on('click', handleDeleteDraftCampaign);

    $('#downloadCSV').off('click').on('click', function() {
        var table = $('#tblCampaigns').DataTable();
        var selectedRows = table.rows('.selected').data().toArray();
        downloadCsv(selectedRows);
    });

    $('#downloadTxnCSV').off('click').on('click', function() {
        var table = $('#tblCampaigns').DataTable();
        var selectedRows = table.rows('.selected').data().toArray();
        if (selectedRows.length === 0) {
            transactionalCsvDownload();
        } else {
            downloadCsv(selectedRows);
        }
    });
}

function showErrorMsg() {
    $("#messagebox").text("Something's Wrong Here");
    $("#message").show();
    setTimeout(() => {
        $("#message").hide();
        location.reload(true);
    }, 3000);
}



//Redirect To campaign Details Page
function viewCampaignDetails(id, type, btn) {
    const sd = $(btn).attr('data-sd');
    if(sd >= semusiCommon.MIN_START_DATE*1000 ) {
        location.href = appiceEncode.encodePayload(window.location.origin+`/dashboard?action=camp#/camp/view/${id}`);
    }
    else{
        alert("Detailed View is not available for this campaign.");
        return;
    }
}


//Return View Button HTML
function getViewBtn(full) {
    let btn =  "<button title='View Details' data-sd='"+full.sd+"' type='button' class='viewCampaignDetails btn btn-success m-r-5 m-b-5' id='"+full._id +"' value='"+full._id +"'><i class='fa fa-eye'></i></button>";
   return btn;
}

// return Copy Button HTML
function getCopyBtn(full){
    let btn = "<button type='button' title='Copy' class='copyCampaign btn btn-info m-r-5 m-b-5' id='"+full._id +"' value='"+full._id +"'><i class='fa fa-files-o'></i></button>"
    return btn
}
function getEditBtn(full){
    let btn ="<button title='Edit' id='"+full._id +"' value='"+full.t+"' type='button' class='editCampaign btn btn-info m-r-5 m-b-5'><i class='fa fa-edit'></i></button>"
    return btn
}
function getDraftDeleteBtn(full){
    let btn = "<button title='Delete' type='button' class='deleteDraftCampaign btn btn-danger m-r-5 m-b-5' id='"+full._id +"' value='"+full._id +"'><i class='fa fa-trash'></i></button>"
    return btn
}
function getPastDeleteBtn(full){
    let btn ="<button title='Delete' type='button' class='deletePastCampaign btn btn-danger m-r-5 m-b-5' id='"+full._id +"' value='"+full._id +"'><i class='fa fa-trash'></i></button>"
    return btn
}




function getAppTemplatesByType(type){

    var app_id = semusiCommon.ACTIVE_APP_ID;
    $.ajax({
    type:"GET",
    url:semusiCommon.API_PARTS.templates.r + '/getTemplatesByType',
    data:{
        api_key: semusiCommon.getActiveUser.api_key,
        app_id: app_id,
        template_type:type,
        uniqueNumber: semusiCommon.randomNumber(),
    },
     
    success:function (data) {
        $("#tblTemplates > tbody:last").children().remove();
        for(var counter=0;counter<data.length;counter++){
            $('#tblTemplates > tbody:last').append('<tr><td>' + data[counter].template_name +'</td><td>'+ data[counter].template_type  +'</td><td>'+data[counter].createdOn+'</td><td>'+data[counter].modifiedOn+'</td><td width="60px"><button type="button" class="btn btn-success m-r-5 m-b-5" onclick="selectSavedEngagementTool(\''+data[counter]._id +'\');">Select</button><div id="'+data[counter]._id +'" style="display:none">'+ JSON.stringify(data[counter]) +'</div></td><td></td></tr>');
        }
        $("#toolsSectionDiv").appendTo("#divSavedTools");
    }});
}
function getAppTemplatesById(id){

    var app_id = semusiCommon.ACTIVE_APP_ID;
    $.ajax({
    type:"GET",
    url:semusiCommon.API_PARTS.templates.r + '/getTemplatesById',
    data:{
        api_key: semusiCommon.getActiveUser.api_key,
        app_id: app_id,
        template_id:id,
        uniqueNumber: semusiCommon.randomNumber(),
    },
     
    success:function (data) {
        switch(data.template_type){
        case "PUSH":
            fillPushScreen(template);
            break;
        case "IN-APP":
            fillInAppScreen(template);
            break;
        case "SURVEY":
            fillSurveyScreen(template);
            break;
        case "RATING":
            fillRatingScreen(template);
            break;
        case "FEEDBACK":
            fillFeedbackScreen(template);
            break;
    }
    }});
}

function submitAction(id){
    if(viewModel.action()=="campaigns"){
        selectSavedEngagementTool(id);
    }
    else{
        switchTemplate('CLOSE');
        getAppTemplates();
    }
}

//$("#btnSaveCampaign").click(function (){
  //  saveCampaign();
//});

function selectSavedEngagementTool(id){
    viewModel.id(id);
    $('#campaignwizard').bwizard('next');
}

function showCampaignHome(){
    $("#createCampaignDiv").hide();
    $("#homeCampaignDiv").show();
}
function cancelCampaign(){
    window.location= appiceEncode.encodePayload("/dashboard?action=campaigns");
}
function showChooseEngagementTool(){
    $("#divChooseTool").show();
    $("#divToolSelection").hide();
}
$("#btnActive").click(function(){
    campaignStatus = "ACTIVE";
    getCampaigns('ACTIVE',null,null);
});
$("#btnDraft").click(function(){
    campaignStatus = "DRAFT";
    getCampaigns('DRAFT',null,null);
});
$("#btnPast").click(function(){
    getCampaigns('PAST',null,null);
    campaignStatus = "PAST";
});
setActiveCampaign = function(id,status){
    $.ajax({
        type:"GET",
        url:appiceEncode.encodePayload(semusiCommon.API_PARTS.templates.w + '/setActiveCampaign'),
        data:{
            args:JSON.stringify({
                a:true,
                ud:semusiCommon.getCurrentEpoch(),
                st:status
            }),
            api_key: semusiCommon.getActiveUser.api_key,
            cid: id,
            app_id: semusiCommon.ACTIVE_APP_ID,
            uniqueNumber: semusiCommon.randomNumber(),
        },
         
        success:function (data) {
            if(data.status=="ERROR"){
                alert(data.message);
                return;
            }
            semusiCommon.setDateRange(null,null);
            $("#advance-daterange span").html("Kindly Select Date Range");       
            getCampaigns('ACTIVE',null,null);
        }
    });
}
deleteCampaign =  function(id,type){
    if(confirm("Are you sure you want to delete this campaign.?")) {
        $.ajax({
            type:"GET",
            url:semusiCommon.API_PARTS.templates.w + '/deleteCampaign',
            data:{
                args:JSON.stringify({
                    isdelete:true,
                    ud:semusiCommon.getCurrentEpoch(),
                }),
                api_key: semusiCommon.getActiveUser.api_key,
                cid: id,
                app_id: semusiCommon.ACTIVE_APP_ID,
                uniqueNumber: semusiCommon.randomNumber(),
            },
             
            success:function (data) {
                $("#messageboxsucess").text("Campaign Successfully Deleted")
                $("#messagesucess").show();
                $("#messagesucess").delay(3000).fadeOut(300);
                location.reload()
                // initiateGetCampaigns(type)
            }
        });
    }
}
editCampaign = function(id, type){
    window.location.href =appiceEncode.encodePayload("dashboard?action=camp#/camp/edit/"+id+"?type="+type);
}

bindWeekDaysOnEdit = function(){
    if(viewModel.daySelector()=="SPECIFICDAYS"){
        $(".weekday").prop('disabled',false);
        $(".weekday").prop('checked',false);

    }
    var days = $(".weekday");
    for(var x=0;x<days.length;x++){
        if($.inArray(days[x].value, viewModel.selectedDays()) > -1){
            days[x].checked=true;
        }
    }

}

getAudienceSegments = function(){
    var app_id =
    $.ajax({
    type:"GET",
    url:semusiCommon.API_PARTS.audienceSegment.r+"/getAudienceSegments",
    data:{
        api_key: semusiCommon.getActiveUser.api_key,
        app_id: semusiCommon.ACTIVE_APP_ID,
        method: "getAudienceSegments",
        uniqueNumber: semusiCommon.randomNumber(),
    },
     
    success:function (data) {
        if(data && data.result){
            data.result.forEach(function(item){
            });
        }
        //select the audience segment if segment id exists in Url.
        var id = semusiCommon.getParameterValues("segmentid");
        if(id && id.length>0){
            selectAudienceSegment(id,true);
        }
    }});
}

selectAudienceSegment = function (id,value){
    $("[name='audiencelist']").prop("checked",false);
    $("#"+id).prop("checked",value);
    if(value){
        viewModel.audienceSegmentId(id);
    }
    else{
        viewModel.audienceSegmentId('');
    }
}

setPushStyle=function(value){
    viewModel.isBasic(value);
    viewModel.isExpanded(!value);
}

navigateToAudienceSegmanet = function(){
    window.location= appiceEncode.encodePayload("/dashboard?action=aud#/aud/create/true");
}

checkActionStyle=function(value){
    viewModel.notificationActions(value);
    if(viewModel.notificationActions() == 'yes'){
        viewModel.notificationActionsFlag(true);
    }
    else{
        viewModel.notificationActionsFlag(false);
    }
}

refreshActionFields = function(){
        viewModel.actionsNameToAdd('');
        viewModel.actionsTypeToAdd('dl');
        viewModel.actionsUrlToAdd('');
        viewModel.actionsUpdate(-1);
}