var campaign_idx             = 0;
var campaign_code_list       = [];

var C_LIST_CAMPAIGN          = "78101";
var C_NEW_CAMPAIGN           = "78102";
var C_UPLOAD_CAMPAIGN_FILE   = "78105";
var C_DOWNLOAD_CAMPAIGN_FILE = "78106";
var C_DELETE_ATTACHMENT      = "78107";
var upload_form_attachment   = null;
var upload_file_idx          = 1;

var campaign_id              = 0;

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

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

function deleteCampaign() {
    //get who checked into the list
    var lines = [];
    $("input[name='campaign_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_id' + lines[i]).html();

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

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

function filterCampaign() {
    LoadingScreen("show");
    var data = {
        "type": C_LIST_CAMPAIGN,
        "index": screen_index,
        "sorts": sorts,
    };
    var url = "request.pzx?c=" + campaign_master_url + "&d=" + new Date().getTime();
    callServer(url, "json", data, onResponseCampaign, null);
}

function onResponseCampaign(obj, resp) {
    LoadingScreen("hide");
    if (resp.status != C_OK) {
        swal.fire('Warning', resp.mesg, 'warning');
        return;
    }
    if (resp.type == C_LIST_CAMPAIGN) {
        campaign_code_list = [];
        var myObj = JSON.parse(resp.data);
        showCampaignList(myObj);
    } if (resp.type == C_GET) {
        showContentIndex(resp.data.htmlContent);

        $('#txtCampaignID').val(resp.data.headerData.id);
        $('#txtCampaignName').val(resp.data.headerData.name);
        $('#txtCampaignName2').val(resp.data.headerData.name);

        if(resp.data.headerData.active == 1){
            $('#chkCampaignActive').prop('checked', true);
        }else{
            $('#chkCampaignActive').prop('checked', false);
        }
        $('#txtCampaignDateFrom').val(resp.data.headerData.date_from);
        $('#txtCampaignDateTo').val(resp.data.headerData.date_to);
        $('#txtCampaignCutOff').val(resp.data.headerData.cut_off);
        $('#txtCampaignEmailSubject').val(resp.data.headerData.email_subject);
        $('#txtCampaignEmailContent').val(resp.data.headerData.email_content);
        $('#txtCampaignEmailFooter').val(resp.data.headerData.email_footer);

        $("#campaignEmailHeaderImageDiv").append(resp.data.headerData.header);
        $("#campaign-attach-table-body").html(resp.data.headerData.attach);
        $("#btnCampaignSave").attr("onclick", "updateCampaign();");
    } else if (resp.type == C_DELETE) {
        swal.fire('Success', resp.mesg, 'success');
        filterCampaign();
    } 
    else if (resp.type == C_NEW_CAMPAIGN) {
        showContentIndex(resp.data.htmlContent);
        $("#contentTitle").html(resp.data.headTitle);
        $("#campaignEmailHeaderImageDiv").append(resp.data.emailHeader);

        $("#btnCampaignSave").attr("onclick", "updateCampaign();");
        $("#cmbCampaignDeliveryContact").html(resp.data.contactOption);
    } else if (resp.type == "C_campaign_READ_EXCEL") {
        $('#importCampaignModal').modal('hide');
        swal.fire('Success', resp.mesg, 'success');
        filterCampaign();
    }
}

function showCampaignList(myObj) {
    campaign_idx = 0;
    campaign_id = 0;
    $('#campaign-table-body').html('');

    for (i in myObj) {
        id                      = myObj[i].id;
        campaign_name     = myObj[i].name;
        campaign_status   = myObj[i].status;

        campaign_code_list.push(campaign_name);
        $('#campaign-table-body').append(
            '<tr id="tr_campaign' + campaign_idx + '">' +
            '<td><input type="checkbox" id="campaign_checkbox' + campaign_idx + '" class="campaign_checkbox" value="' + campaign_idx + '" name="campaign_chk[]" ></td>' +
            '<td><label id="campaign_name' + campaign_idx + '" class="campaign_name" value="' + campaign_name + '" >' + campaign_name + '</label></td>' +
            '<td style="display:none" class="campaign_id" id="campaign_id' + campaign_idx + '">' + id + '</td>' +
            '<td style="display:none" class="campaign_idx" id="campaign_idx' + campaign_idx + '">' + campaign_idx + '</td>' +
            '</tr>'
        );

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

        campaign_idx++;
    }
}

function checkCampaignCode(obj){
    if($('#txtCampaignID').val() == ""){
        var code = $(obj).val();
        if(jQuery.inArray(code, campaign_code_list) > -1){
            swal.fire('Warning', "Corporate Gift already existed.", 'warning');
            return;
        }else{
            $("#txtCampaignName2").val($("#txtCampaignName").val());
        }
    }
}

function deleteCampaignItem(item_id){
    $('#lineItem' + item_id).remove();
}

function deleteCampaignDelivery(delivery_id){
    $('#lineDelivery' + delivery_id).remove();
}

function onCampaignAttachmentUpload(obj, idx) {
    upload_form_attachment = obj;
}

function validateUploadFileExtAttachment(file) {
	var extArray = new Array(".png", ".jpg", ".jpeg", ".pdf", ".doc", ".docx", ".xls", ".xlsx"); 
	var validext = false;

	if (!file) 
		return;
   
	while (file.indexOf("\\") != -1)
		file = file.slice(file.indexOf("\\") + 1);

    const invalidChars = /[<>:"/\\|?*]/;

    if(invalidChars.test(file)){
        LoadingScreen("hide");
        swal.fire("Warning","The filename should not contain these special character < > : \" ' / \\ | ? *","warning");
        return false;
    };

    var last_key = file.split('.').length - 1;
	var ext = "." + file.split('.')[last_key].toLowerCase();

	for (var n = 0; n < extArray.length; n++) 
	{
		if (extArray[n] == ext) { validext = true; break; }
	}
	if (validext) {
		return true ;
	} else {
        LoadingScreen("hide");
		// swal.fire("Warning","You can only upload files in .png, .jpg, .jpeg, .pdf, .doc, .docx, .xls, .xlsx format","warning") ;
        swal.fire("Warning","You can only upload files in .png, .jpg, .jpeg, .pdf, .doc, .docx, .xls, .xlsx format","warning");
		return false ;
	}
}

function uploadCampaignAttachment(idx) {
    if($('#txtCampaignAttachment'+idx).val() == "") {
            // swal.fire('Warning','You must select the file to upload.',"warning") ;
            swal.fire("Warning","You must select the file to upload.","warning");
            return ;
    } else {
        var fn = $('#txtCampaignAttachment'+idx).val() ;
        if (validateUploadFileExtAttachment(fn)) {
            LoadingScreen("show");
            var url  = "index.pzx?c=" + campaign_master_url + "&t=" + C_UPLOAD_CAMPAIGN_FILE  + "&d=" + new Date().getTime() + "&campaign_id=" + $("#txtCampaignID").val() + "&attach_field=txtCampaignAttachment" + idx + "&idx=" + idx;
            uploaded = false ;
            ajaxUpload(upload_form_attachment.form,url,onUploadCampaignAttachmentEnd);
        }
    }
}

function onUploadCampaignAttachmentEnd(resp) {
    LoadingScreen("hide");
    var msgArr      = resp.split("*");
    var status      = msgArr[0];
    var centreItems = msgArr[1];
    
    console.log(centreItems);
	if (status==C_OK) {

        var s = centreItems.split("|") ;
        var btnView = "<a title='View Attachment' style='color:green; padding: 5px !important;' href='javascript:' onclick='downloadCampaignFile("+s[3]+", \""+s[1]+"\")'>"+s[0]+"</a>";
        $('#col_attachment'+s[2]).html('');
        $('#col_attachment'+s[2]).append(btnView);

        var btnAction = "<button type='button' class='btn btn btn-icon btn-danger btn-sm btn-icon-md' onclick='removeCampaignAttachment("+s[4]+", "+s[2]+");'><i class='fa fa-trash-o'></i></button>";
        $('#col_action'+s[2]).html('');
        $('#col_action'+s[2]).append(btnAction);

        $('#campaign-attach-table-body').append('<tr id="row_attach_'+(parseInt(s[2]) + 1)+'">' +
                                    '<td id="col_attachment'+(parseInt(s[2]) + 1)+'">'+
                                        '<input type="file" class="form-control" id="txtCampaignAttachment'+(parseInt(s[2]) + 1)+'" name="txtCampaignAttachment'+(parseInt(s[2]) + 1)+'" onchange="onCampaignAttachmentUpload(this, '+(parseInt(s[2]) + 1)+');" />' +
                                        '<input type="hidden" class="form-control" id="txtCampaignAttachmentFilename'+(parseInt(s[2]) + 1)+'"/>' +
                                    '</td>' +
                                    '<td id="col_action'+(parseInt(s[2]) + 1)+'" style="padding: 5px !important;">' +
                                        '<button type="button" class="btn btn btn-icon btn-success btn-sm btn-icon-md" onclick="uploadCampaignAttachment('+(parseInt(s[2]) + 1)+');"><i class="fa fa-upload"></i></button>' + 
                                    '</td>'+
                                '</tr>');
        
        return s[0];
	} else {
        var error   = msgArr[1];
        swal.fire("Error","Failed to upload attachment. " + error,"error");
        return "";
	}
}

function downloadCampaignFile(id, filename){
    var url = "index.pzx?c=" + campaign_master_url + "&id=" + id +
        "&fn=" + filename + "&t=" + C_DOWNLOAD_CAMPAIGN_FILE  + "&r=1";
    showReport(url) ;
}

function removeCampaignAttachment(docId, idx) {
    Swal.fire({
        title: "Delete Confirmatio",
        text: "Are you sure you want to delete the attachment?",
        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"            : C_DELETE_ATTACHMENT,
                "campaign_id"    : $('#txtCampaignID').val(), 
                "doc_id"         : docId,
                "idx"            : idx
            };
            console.log("HEREE DELETE");
            var url   = "index.pzx?c=" + campaign_master_url + "&t=" + C_DELETE_ATTACHMENT  + "&d=" + new Date().getTime() ;
            callServer(url,"json",data,onResponseCampaignAttachment,null) ;
        }
      });
}

function onResponseCampaignAttachment(obj,resp) {
    if (resp.status != C_OK ) {
        swal.fire("Error",resp.mesg,"error");
        return false;
    }

    if(resp.type == C_DELETE_ATTACHMENT) {
        swal.fire("Success", resp.mesg, "success");
        $('#row_attach_' + resp.data).remove();
    } 
}