function cancelCampaignProfileEntry() {
    prevscreen('CampaignProfile');
    filterCampaignProfile();
}

function addCampaignProfile() {
    saveCampaignProfileEntry(C_ADD);
}
function updateCampaignProfile() {
    saveCampaignProfileEntry(C_UPDATE);
}

function saveCampaignProfileEntry(type) {
    LoadingScreen("show");
    if (validateCampaignProfileEntry()) {
        var data = {
            "type"              : type,

            "id"                : $('#txtCampaignProfileID').val(),
            "code"              : $('#txtCampaignProfileCode').val(),
            "active"            : ($('#chkCampaignProfileActive').is(':checked') ? '1' : '0'),
            "name"              : $('#txtCampaignProfileName').val(),
            "url"               : $('#txtCampaignProfileUrl').val(),

            "oauth"             : $('#cobCampaignProfileOAuth').val(),
            "tenant_id"         : $('#txtCampaignProfileTenantID').val(),
            "mail_server"       : $('#txtCampaignProfileMailServer').val(),
            "port"              : $('#txtCampaignProfilePort').val(),
            "mail_sender"       : $('#txtCampaignProfileMailSender').val(),
            "mail_password"     : $('#txtCampaignProfileMailPassword').val(),
            "ea"                : ($('#chkCampaignProfileEA').is(':checked') ? '1' : '0'),
            "ssl"               : ($('#chkCampaignProfileSSL').is(':checked') ? '1' : '0'),

            "base64file"        : $('#txtCampaignProfileLogoFileBase64').html(),
            "extension"         : $('#txtCampaignProfileLogoFileExt').val(),
            "filename"          : $('#txtCampaignProfileLogoFilename').val(),
            
            "sig_base64file"    : $('#txtCampaignProfileSignatureFileBase64').html(),
            "sig_extension"     : $('#txtCampaignProfileSignatureFileExt').val(),
            "sig_filename"      : $('#txtCampaignProfileSignatureFilename').val(),
        };
        var url = "index.pzx?c=" + campaign_profile_url + "&d=" + new Date().getTime();
        callServer(url, "json", data, onResponseCampaignProfileEntry, null);
        return false;
    } else {
        LoadingScreen("hide");
    }
}

function validateCampaignProfileEntry() {
    if ($('#txtCampaignProfileCode').blank()) {
        swal.fire("Warning", "Campaign Profile Code cannot be blank", "warning");
        return false;
    }

    if ($('#txtCampaignProfileName').blank()) {
        swal.fire("Warning", "Campaign Profile Name cannot be blank", "warning");
        return false;
    }

    return true;
}

function onResponseCampaignProfileEntry(obj, resp) {
    LoadingScreen("hide");
    if (resp.status != C_OK) {
        swal.fire('Warning', resp.mesg, 'warning');
        return;
    }

    if (resp.type == C_ADD) {
        swal.fire('Success', resp.mesg, 'success');
        $(".btnSaveCampaignProfile").attr("onclick", "updateCampaignProfile();");
        $("#txtCampaignProfileID").val(resp.data.id);

        $('#txtCampaignProfileLogoFilename').val(resp.data.logo);
        $('#txtCampaignProfileSignatureFilename').val(resp.data.signature);
    }
    if (resp.type == C_UPDATE) {
        swal.fire('Success', resp.mesg, 'success');
        $(".btnSaveCampaignProfile").attr("onclick", "updateCampaignProfile();");

        $('#txtCampaignProfileLogoFilename').val(resp.data.logo);
        $('#txtCampaignProfileSignatureFilename').val(resp.data.signature);
    }
}

//logo
//=================================================
function hasExtensionCampaignProfileLogo(inputID, exts) {
    var fileName = document.getElementById(inputID).value;
    return (new RegExp('(' + exts.join('|').replace(/\./g, '\\.') + ')$')).test(fileName.toLowerCase());
}

function getFileExtensionCampaignProfileLogo(filename) {
    var ext = /^.+\.([^.]+)$/.exec(filename);
    return ext == null ? "" : ext[1];
}

function encodeImageFileAsURLCampaignProfileLogo(event) {
    var filesSelected = document.getElementById("txtCampaignProfileLogo").files;
    if (!hasExtensionCampaignProfileLogo('txtCampaignProfileLogo', ['.jpg', '.jpeg', '.png'])) {
        alert("The image format have to be in 'jpg', 'jpeg', 'png' ");
        $("#txtCampaignProfileLogo").val("");
        return;
    }

    if (filesSelected.length > 0) {
        var fileToLoad = filesSelected[0];
        var fileExt = getFileExtensionCampaignProfileLogo(filesSelected[0].name);

        var fileReader = new FileReader();

        fileReader.onload = function (fileLoadedEvent) {
            var srcData = fileLoadedEvent.target.result; // <--- data: base64
            $('#txtCampaignProfileLogoFileBase64').html(srcData);
            $('#txtCampaignProfileLogoFileExt').val(fileExt);
        }

        fileReader.readAsDataURL(fileToLoad);
    }

    src = URL.createObjectURL(event.target.files[0])
    $('#imgCampaignProfileLogo').attr('src', src);
}

function removeCampaignProfileLogo() {
    Swal.fire({
        title: "System Confirmation",
        text: "Confirm you want to remove the company logo?",
        icon: "warning",
        showCancelButton: true,
        confirmButtonText: "OK",
        cancelButtonText: "Cancel",
        customClass: {
            confirmButton: 'swal-btn-confirm',
            cancelButton: 'swal-btn-cancel'
        }
    }).then(function (result) {
        if (result.isConfirmed) {
            var data = { "type": "DELETE_CAMPAIGN_PROFILE_LOGO", "id": 0, "path": $('#imgCampaignProfileLogo').attr('src') };
            var url = "index.pzx?c=" + campaign_profile_url + "&d=" + new Date().getTime();
            callServer(url, "json", data, onResponseCampaignProfileLogo, null);
        }
    });
}

function onResponseCampaignProfileLogo(obj, resp) {
    if (resp.status != C_OK) {
        swal.fire("Warning", resp.mesg, 'warning');
        return;
    }

    if (resp.type == "DELETE_CAMPAIGN_PROFILE_LOGO") {
        $('#txtCampaignProfileLogoFilename').val("");
        $("#imgCampaignProfileLogo").attr("src", resp.data.src);
    }
}
//=================================================

//signature
//=================================================
function hasExtensionCampaignProfileSignature(inputID, exts) {
    var fileName = document.getElementById(inputID).value;
    return (new RegExp('(' + exts.join('|').replace(/\./g, '\\.') + ')$')).test(fileName.toLowerCase());
}

function getFileExtensionCampaignProfileSignature(filename) {
    var ext = /^.+\.([^.]+)$/.exec(filename);
    return ext == null ? "" : ext[1];
}

function encodeImageFileAsURLCampaignProfileSignature(event) {
    var filesSelected = document.getElementById("txtCampaignProfileSignature").files;
    if (!hasExtensionCampaignProfileSignature('txtCampaignProfileSignature', ['.jpg', '.jpeg', '.png', '.gif'])) {
        alert("The image format have to be in 'jpg', 'jpeg', 'png', 'gif' ");
        $("#txtCampaignProfileSignature").val("");
        return;
    }

    if (filesSelected.length > 0) {
        var fileToLoad = filesSelected[0];
        var fileExt = getFileExtensionCampaignProfileSignature(filesSelected[0].name);

        var fileReader = new FileReader();

        fileReader.onload = function (fileLoadedEvent) {
            var srcData = fileLoadedEvent.target.result; // <--- data: base64
            $('#txtCampaignProfileSignatureFileBase64').html(srcData);
            $('#txtCampaignProfileSignatureFileExt').val(fileExt);
        }

        fileReader.readAsDataURL(fileToLoad);
    }

    src = URL.createObjectURL(event.target.files[0])
    $('#imgCampaignProfileSignature').attr('src', src);
}

function removeCampaignProfileSignature() {
    Swal.fire({
        title: "System Confirmation",
        text: "Confirm you want to remove the company Signature?",
        icon: "warning",
        showCancelButton: true,
        confirmButtonText: "OK",
        cancelButtonText: "Cancel",
        customClass: {
            confirmButton: 'swal-btn-confirm',
            cancelButton: 'swal-btn-cancel'
        }
    }).then(function (result) {
        if (result.isConfirmed) {
            var data = { "type": "DELETE_CAMPAIGN_PROFILE_SIGNATURE", "id": 0, "path": $('#imgCampaignProfileSignature').attr('src') };
            var url = "index.pzx?c=" + campaign_profile_url + "&d=" + new Date().getTime();
            callServer(url, "json", data, onResponseCampaignProfileSignature, null);
        }
    });
}

function onResponseCampaignProfileSignature(obj, resp) {
    if (resp.status != C_OK) {
        swal.fire("Warning", resp.mesg, 'warning');
        return;
    }

    if (resp.type == "DELETE_CAMPAIGN_PROFILE_SIGNATURE") {
        $('#txtCampaignProfileSignatureFilename').val("");
        $("#imgCampaignProfileSignature").attr("src", resp.data.src);
    }
}
//=================================================

function settingGrantPermission(){
    var tenantID = $('#cobCampaignProfileTenantID').val();
    var clientID = $('#cobCampaignProfileClientID').val();
    var url = "https://login.microsoftonline.com/" + tenantID + "/adminconsent?client_id=" + clientID

    window.open(url, "_blank");
}

// Email Test ==============================================================>
function showEmailTestModal() {
    $('#emailTestModal').modal('show');
}

function submitCampaignEmailTest() {
    LoadingScreen("show");
    if($('#emailTestSubmitTo').val() == ""){
        swal.fire("Warning", "Email cannot be blank.", "warning");
        return;
    } else {
        var data = {
            "type"          : "SEND_EMAIL_TESTING",
            "id"            : $('#txtCampaignProfileID').val(),
            "to_email"      : $('#emailTestSubmitTo').val(),
        };
        var url = "index.pzx?c=" + campaign_profile_entry_url + "&d=" + new Date().getTime() ;
        callServer(url,"json",data,onResponseEmailTest,null) ;
    }
}

function onResponseEmailTest(obj,resp) {
    LoadingScreen("hide");
    if (resp.status != C_OK){
        swal.fire("Warning",resp.mesg,'warning');
        return;
    }

    if (resp.type == "SEND_EMAIL_TESTING"){
        swal.fire("Success",resp.mesg,'success');
        $('#emailTestModal').modal('hide');
    }
}
