var campaign_profile_idx = 0;
var campaign_profile_code_list = [];

var C_LIST_CAMPAIGN_PROFILE = "78001";
var C_NEW_CAMPAIGN_PROFILE = "78002";

var campaign_profile_id = 0;

function addNewCampaignProfile() {
    LoadingScreen("show");
    screen_index++;
    cust_policy_idx = 0;
    var data = { "type": C_NEW_CAMPAIGN_PROFILE, "index": screen_index };
    var url = "index.pzx?c=" + campaign_profile_entry_url + "&d=" + new Date().getTime();
    callServer(url, "json", data, onResponseCampaignProfile, null);
}

function reviewCampaignProfile() {
    LoadingScreen("show");
    if (campaign_profile_id != 0) {
        screen_index++;
        var data = {
            "type"  : C_GET,
            "index" : screen_index,
            "id"    : campaign_profile_id,
        };
        var url = "index.pzx?c=" + campaign_profile_entry_url + "&d=" + new Date().getTime();
        callServer(url, "json", data, onResponseCampaignProfile, null);
    }else{
        LoadingScreen("hide");
        swal.fire("Warning", "Please select a company profile", "warning")
    }
}

function deleteCampaignProfile() {
    //get who checked into the list
    var lines = [];
    $("input[name='campaign_profile_chk[]']:checked").each(function (i) {
        lines[i] = $(this).val();
    });

    //confirmation and delete column
    if (lines.length > 0) {
       Swal.fire({
            title: "System Confirmation",
            text: "Are you sure you want to delete the selected record line?",
            icon: "warning",
            showCancelButton: true,
            confirmButtonText: "OK",
            cancelButtonText: "Cancel",
            customClass: {
                confirmButton: 'swal-btn-confirm',
                cancelButton: 'swal-btn-cancel'
            }
        }).then(function (result) {
            if (result.isConfirmed) {
                LoadingScreen("show");

                for (var i = 0; i < lines.length; i++) {
                    var id = $('#campaign_profile_id' + lines[i]).html();

                    var data = { "type": C_DELETE, "id": id, "index": screen_index };
                    var url = "index.pzx?c=" + campaign_profile_url + "&d=" + new Date().getTime();

                    callServer(url, "json", data, onResponseCampaignProfile, null);
                }
            }
        });
    } else {
        return;
    }
}

function filterCampaignProfile() {
    LoadingScreen("show");
    var data = {
        "type": C_LIST_CAMPAIGN_PROFILE,
        "index": screen_index,
        "sorts": sorts,
    };

    var url = "request.pzx?c=" + campaign_profile_url + "&d=" + new Date().getTime();
    callServer(url, "json", data, onResponseCampaignProfile, null);
}

function onResponseCampaignProfile(obj, resp) {
    LoadingScreen("hide");
    if (resp.status != C_OK) {
        swal.fire('Warning', resp.mesg, 'warning');
        return;
    }
    if (resp.type == C_LIST_CAMPAIGN_PROFILE) {
        campaign_profile_code_list = [];
        var myObj = JSON.parse(resp.data);
        showCampaignProfileList(myObj);
    } if (resp.type == C_GET) {
        showContentIndex(resp.data.htmlContent);
        $(".btnSaveCampaignProfile").attr("onclick", "updateCampaignProfile();");
        //change button to Update
        $('.btnSaveCampaignProfile').html('Update');

        $('#txtCampaignProfileID').val(resp.data.headerData.id);
        $('#txtCampaignProfileCode').val(resp.data.headerData.code);
        if (resp.data.headerData.status == '1') {
            $('#chkCustomerActive').prop('checked', true);
        } else {
            $('#chkCustomerActive').prop('checked', false);
        }

        $('#txtCampaignProfileName').val(resp.data.headerData.name);
        $('#txtCampaignProfileUrl').val(resp.data.headerData.url);
        $('#cobCampaignProfileOAuth').val(resp.data.headerData.oauth);
        $('#cobCampaignProfileOAuth').trigger('change');
        $('#txtCampaignProfileTenantID').val(resp.data.headerData.tenant_id);
        $('#txtCampaignProfileMailServer').val(resp.data.headerData.mail_server);
        $('#txtCampaignProfilePort').val(resp.data.headerData.port);
        $('#txtCampaignProfileMailSender').val(resp.data.headerData.mail_sender);
        $('#txtCampaignProfileMailPassword').val(resp.data.headerData.mail_password);
        if (resp.data.headerData.ea == '1') {
            $('#chkCampaignProfileEA').prop('checked', true);
        } else {
            $('#chkCampaignProfileEA').prop('checked', false);
        }
        if (resp.data.headerData.ssl == '1') {
            $('#chkCampaignProfileSSL').prop('checked', true);
        } else {
            $('#chkCampaignProfileSSL').prop('checked', false);
        }

        var src = resp.data.headerData.src;
		var path_picture = resp.data.headerData.path_picture;
        
        if (src != "") {
            $("#imgCampaignProfileLogo").attr('src', path_picture);
            $("#txtCampaignProfileLogoFilename").val(resp.data.headerData.filename);
            // $('#txtFixedAssetPicture').val(resp.data.headerData.path_picture);
        }
        
        var src_signature  = resp.data.headerData.signature;
		var path_signature = resp.data.headerData.path_signature;

        if (src_signature != "") {
            $("#imgCampaignProfileSignature").attr('src', path_signature);
            $("#txtCampaignProfileSignatureFilename").val(resp.data.headerData.signature);
            // $('#txtFixedAssetPicture').val(resp.data.headerData.path_picture);
        }

    } else if (resp.type == C_DELETE) {
        swal.fire('Success', resp.mesg, 'success');
        filterCampaignProfile();
    } 
    else if (resp.type == C_NEW_CAMPAIGN_PROFILE) {
        showContentIndex(resp.data.htmlContent);
        $("#contentTitle").html(resp.data.headTitle);

        $(".btnSaveCampaignProfile").attr("onclick", "addCampaignProfile();");
        $("#cmbCampaignProfileDeliveryContact").html(resp.data.contactOption);
    } else if (resp.type == "C_CAMPAIGN_PROFILE_READ_EXCEL") {
        $('#importCampaignProfileModal').modal('hide');
        swal.fire('Success', resp.mesg, 'success');
        filterCampaignProfile();
    }
}

function showCampaignProfileList(myObj) {
    campaign_profile_idx = 0;
    campaign_profile_id = 0;
    $('#campaignprofile-table-body').html('');

    for (i in myObj) {
        id              = myObj[i].id;
        code            = myObj[i].code;
        campaign_profile_name   = myObj[i].name;
        campaign_profile_status = myObj[i].status;

        campaign_profile_code_list.push(code);

        $('#campaignprofile-table-body').append(
            '<tr id="tr_campaign_profile' + campaign_profile_idx + '">' +
            '<td><input type="checkbox" id="campaign_profile_checkbox' + campaign_profile_idx + '" class="campaign_profile_checkbox" value="' + campaign_profile_idx + '" name="campaign_profile_chk[]" ></td>' +
            '<td><label id="campaign_profile_code' + campaign_profile_idx + '" class="campaign_profile_code" value="' + code + '" >' + code + '</label></td>' +
            '<td><label id="campaign_profile_name' + campaign_profile_idx + '" class="campaign_profile_name" value="' + campaign_profile_name + '" >' + campaign_profile_name + '</label></td>' +
            '<td style="display:none" class="campaign_profile_id" id="campaign_profile_id' + campaign_profile_idx + '">' + id + '</td>' +
            '<td style="display:none" class="campaign_profile_idx" id="campaign_profile_idx' + campaign_profile_idx + '">' + campaign_profile_idx + '</td>' +
            '</tr>'
        );

        //set highlight function and get the journal type ID
        $("#campaignprofile-table-body tr").click(function () {
            campaign_profile_id = $(this).find('td').eq(3).html();
            $(this).addClass('highlight').siblings().removeClass('highlight');
        });

        campaign_profile_idx++;
    }
}

function onchangeCampaignOAuth(){
    var use_graph_api = $("#cobCampaignProfileOAuth").val();

	if(use_graph_api == "YES"){
		$(".showOAuth").css("display", "");
		$(".showNormal").css("display", "none");
		// $("#LedgerSettingSalesQuotationMailSender").attr('class', 'col-sm-3');
	}else{
        $(".showOAuth").css("display", "none");
		$(".showNormal").css("display", "");
		// $("#LedgerSettingSalesQuotationMailSender").attr('class', 'col-sm-4');
	}
}

function checkCampaignProfileCode(obj){
    if($('#txtCampaignProfileID').val() == ""){
        var code = $(obj).val();
        if(jQuery.inArray(code, campaign_profile_code_list) > -1){
            swal.fire('Warning', "Company Profile Code is exist.", 'warning');
            return;
        }
    }
}
