var item_line_idx       = 0;
var delivery_line_idx   = 0;
var recipient_line_idx  = 0;

function cancelCampaignEntry() {
    prevscreen('Campaign');
    corporateGiftFilter();
}

function addCampaign() {
    saveCampaignEntry(C_ADD);
}
function updateCampaign() {
    saveCampaignEntry(C_UPDATE);
}

function saveCampaignEntry(type) {
    if(validateCampaignEntry()){
        LoadingScreen("show");
        var data = {
            "type"              : type,
    
            "id"                : $('#txtCampaignID').val(),
            "name"              : $('#txtCampaignName').val(),
            "active"            : ($('#chkCampaignActive').is(':checked') ? '1' : '0'),
            "date_from"         : $('#txtCampaignDateFrom').val(),
            "date_to"           : $('#txtCampaignDateTo').val(),
    
            "email_subject"     : $('#txtCampaignEmailSubject').val(),
            "email_content"     : $('#txtCampaignEmailContent').val(),
            "email_footer"      : $('#txtCampaignEmailFooter').val(),
    
            "header_images"     : getCompanyCampaignHeaderImage(),
        };
        var url = "index.pzx?c=" + campaign_master_url + "&d=" + new Date().getTime();
        callServer(url, "json", data, onResponseCampaignEntry, null);
        return false;
    }
}

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

    if ($('#txtCampaignEmailSubject').blank()) {
        swal.fire("Warning", "Email Subject cannot be blank", "warning");
        return false;
    }

    return true;
}

function getCompanyCampaignHeaderImage(){
    var arrays = [];
    $('.companyEmailHeaderImage').each(function () {
        var comp_id = $(this).find('.campaignId').val();

        var data = {
            "comp_id"            : comp_id,
            "header_filename"    : $('#txtCampaignHeaderImageFilename'+comp_id).val(),
            "header_file_ext"    : $('#txtCampaignHeaderImageFileExt'+comp_id).val(),
            "header_file_base64" : $('#txtCampaignHeaderImageFileBase64'+comp_id).html()
        }
        arrays.push(data);
    });
    return JSON.stringify(arrays);
}

function showCampaignTestEmailModal(){
    $('#emailTestModal').modal('show');
}

function sendCampaignTestingEmail(){

    var data = {
		"type"		    : "SEND_EMAIL_TESTING",
		"id"		    : $('#txtCampaignID').val(),
		"email_from"    : $('#cobCampaignTestEmailFrom').val(),
		"email_to"	    : $('#cobCampaignTestEmailTo').val(),
	};
	var url = "request.pzx?c=" + campaign_master_entry_url + "&d=" + new Date().getTime();
	callServer(url, "json", data, onResponseCampaignEntry, null);
}

//Header Item
//========================================
function onResponseCampaignEntry(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');
        $("#txtCampaignID").val(resp.data.id);

        data = resp.data.item;
        for(i in data){
            $('#campaign_item_id' + data[i].idx).html(data[i].id);
            $('#campaign_item_image_filename' + data[i].idx).html(data[i].filename);
            $('#lineItem' + data[i].idx).attr('class', 'existing_item');
        }
        
        data = resp.data.delivery;
        for(i in data){
            $('#campaign_delivery_id' + data[i].idx).html(data[i].id);
            $('#lineDelivery' + data[i].idx).attr('class', 'existing_delivery');
        }

        $("#btnSaveDeliveryTime").attr("onclick", "updateCampaign();");
        $("#btnSaveCampaignEmail").attr("onclick", "updateCampaign();");
        $("#btnSaveRecipient").attr("onclick", "updateCampaign();");
    }
    if (resp.type == C_UPDATE) {
        swal.fire('Success', resp.mesg, 'success');

        data = resp.data.item_id;
        for(i in data){
            $('#campaign_item_id' + data[i].idx).html(data[i].id);
            $('#campaign_item_image_filename' + data[i].idx).html(data[i].filename);
            $('#lineItem' + data[i].idx).attr('class', 'existing_item');
        }
        data = resp.data.delivery_id;
        for(i in data){
            $('#campaign_delivery_id' + data[i].idx).html(data[i].id);
            $('#lineDelivery' + data[i].idx).attr('class', 'existing_delivery');
        }
    }
    if(resp.type=="SEND_EMAIL_TESTING") {
        swal.fire("Success",resp.mesg, "success") ;
        $('#emailTestModal').modal('hide');
    }
}
//========================================

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

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

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

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

        var fileReader = new FileReader();

        fileReader.onload = function (fileLoadedEvent) {
            var srcData = fileLoadedEvent.target.result; // <--- data: base64
            $('#txtCampaignHeaderImageFileBase64' + coy_id).html(srcData);
            $('#txtCampaignHeaderImageFileExt' + coy_id).val(fileExt);
            $('#txtCampaignHeaderImageFilename' + coy_id).val(filesSelected[0].name);
        }

        fileReader.readAsDataURL(fileToLoad);
    }

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

function removeCampaignHeaderImage() {
    Swal.fire({
        title: "System Confirmation",
        text: "Confirm you want to remove the company Header Image?",
        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_CORPORATE_GIFT_HEADER_IMAGE", "id": 0, "path": $('#imgCampaignHeaderImage').attr('src') };
            var url = "index.pzx?c=" + campaign_master_entry_url + "&d=" + new Date().getTime();
            callServer(url, "json", data, onResponseCampaignHeaderImage, null);
        }
    });
}

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

    if (resp.type == "DELETE_CORPORATE_GIFT_HEADER_IMAGE") {
        $('#txtCampaignHeaderImageFilename').val("");
        $("#imgCampaignHeaderImage").attr("src", resp.data.src);
    }
}
//========================================