var C_DELETE_CONTACT_PROSPECT  = "77103";
var C_CONTACT_PROSPECT_FILTERS = "77104";
var C_DELETE_PROSPECT_DELIVERY = "77105";
var C_PROSPECT_DELIVERY_FILTERS = "77106";

var contact_prospect_idx = 0;
var prospect_delivery_idx = 0;
var prospect_contact_name_list = [];
var duplicate_prospect_contact_name_list = [];
var prospect_delivery_code_list = [];
var duplicate_prospect_delivery_code_list = [];
var contact_data = [];

$(document).ready(function () {
	$('#uploading').hide();
	$('#view_doc').hide();

	$('#txtDoc').on('change', function () {
		upload_form = this.form;
	});
	$('#viewDoc').on('change', function () {
		upload_form = this.form;
	});
});
function cancelProspectToDoEntry() {
    prevscreen('Prospect To Do');
}

function addProspect() {
    saveProspectEntry(C_ADD);
}
function updateProspect() {
    saveProspectEntry(C_UPDATE);
}

function saveProspectEntry(type) {
    LoadingScreen("show");
    prospect_contact_name_list = [];
    duplicate_prospect_contact_name_list = [];
    prospect_delivery_code_list = [];
    duplicate_prospect_delivery_code_list = [];
    
    if (validateProspectEntry()) {
        var data = {
            "type": type,
            //general
            "id": $('#txtProspectID').val(),
            "active": ($('#chkProspectActive').is(':checked') ? '1' : '0'),
            "name": $('#txtProspectName').val(),
            "code": $('#txtProspectCode').val(),
            "telephone": $('#txtProspectTelephone').val(),
            "address1": $('#txtProspectAddress1').val(),
            
            "uen": $('#txtProspectUEN').val(),
            // "address3": $('#txtProspectAddress3').val(),
            // "address4": $('#txtProspectAddress4').val(),
            // "address5": $('#txtProspectAddress5').val(),
            "software": $('#txtProspectSoftwareInfo').val(),
            "billing_cycle": $('#txtProspectBillingCycle').val(),
            "remarks": $('#txtProspectRemarks').val(),

            //contact
            "contacts": getProspectContacts(),

            //delivery
            "delivery": getProspectDelivery(),
        };

        if(duplicate_prospect_contact_name_list.length > 0){
            swal.fire("Warning","There is duplicate contact name.","warning");
            LoadingScreen("hide");
            return;
        }

        if(duplicate_prospect_delivery_code_list.length > 0){
            swal.fire("Warning","There is duplicate delivery code.","warning");
            LoadingScreen("hide");
            return;
        }

        var url = "index.pzx?c=" + prospect_url + "&d=" + new Date().getTime();
        callServer(url, "json", data, onResponseProspectEntry, null);
        return false;
    }else{
        LoadingScreen("hide");
    }
}

function getProspectContacts() {
    var arrays = [];
    var data = {};
    var contact_tr = $('#prospect-contact-list-table tr');
    contact_tr.each(function () {
        var idx = $(this).attr('id');
        idx = idx.substring(idx.lastIndexOf('-') + 1);
        if (idx != "filter") {
            var contact_name = $('#txtcolcontactname' + idx).val();
            if(jQuery.inArray(contact_name, prospect_contact_name_list) > -1){
                duplicate_prospect_contact_name_list.push(contact_name);
            } else {
                data = {
                    "id": $('#txtcolcontactid' + idx).val(),
                    "name": contact_name,
                    "dept": $('#txtcolcontactdept' + idx).val(),
                    "position": $('#txtcolcontactposition' + idx).val(),
                    "email": $('#txtcolcontactemail' + idx).val(),
                    "phone": $('#txtcolcontactphone' + idx).val(),
                    "mobile": $('#txtcolcontactmobile' + idx).val(),
                    "reportto": $('#txtcolcontactreportto' + idx).val(),
                    "status": $('#txtcolcontactstatus' + idx).val(),
                };
    
                prospect_contact_name_list.push(contact_name);

                arrays.push(data);
            }
        }
    });

    return arrays;
}

function getProspectDelivery() {
    var arrays = [];
    var data = {};
    var delivery_tr = $('#prospect-delivery-list-table tr');
    delivery_tr.each(function () {
        var idx = $(this).attr('id');
        idx = idx.substring(idx.lastIndexOf('-') + 1);
        if (idx != "filter") {
            var delivery_code = $('#txtcoldeliverycode' + idx).val();
            if(jQuery.inArray(delivery_code, prospect_delivery_code_list) > -1){
                duplicate_prospect_delivery_code_list.push(delivery_code);
            } else {
                data = {
                    "id": $('#txtcoldeliveryid' + idx).val(),
                    "code": delivery_code,
                    "address": $('#txtcoldeliveryaddress' + idx).val(),
                    "contact": $('#txtcoldeliverycontact' + idx).val(),
                };
        
                prospect_delivery_code_list.push(delivery_code);

                arrays.push(data);
            }
        }
    });

    return arrays;
}

function onResponseProspectEntry(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');
        $("#btnSaveProspect").attr("onclick", "updateProspect();");
        $("#txtProspectID").val(resp.data);
        $("#cmbColDeliveryContact").html();
        // prevscreen('Prospect');
        // prospectFilter();
        updateProspectContactOption();
        prospectFilter();
    } if (resp.type == C_UPDATE) {
        swal.fire('Success', resp.mesg, 'success');
        filterProspectDelivery();
        filterProspectContact();
        // prevscreen('Prospect');
        // prospectFilter();
    } else if (resp.type == C_DELETE_PROSPECT_DELIVERY) {
        filterProspectDelivery();
        swal.fire("Success", resp.mesg, "success");
    } else if (resp.type == C_PROSPECT_DELIVERY_FILTERS) {
        if ($('#txtProspectID').val() != "") {
            prospect_delivery_idx = resp.data.deliveryIdx;
            $('#prospect-delivery-list-table').html(resp.data.htmlDelivery);
        }
    } else if (resp.type == C_DELETE_CONTACT_PROSPECT) {
        filterProspectContact();
        updateProspectContactOption();
        swal.fire("Success", resp.mesg, "success");
    } else if (resp.type == C_CONTACT_PROSPECT_FILTERS) {
        if ($('#txtProspectID').val() != "") {
            contact_idx = resp.data.contactIdx;

            $('#prospect-contact-list-table').html();

            contact_data = resp.data.sortedContact;
            sortType = resp.data.sortType;

            var unsavedRows = [];

            $('#prospect-contact-list-table tr').each(function () {

                var contactId = $(this).find('[id^=txtcolcontactid]').val();

                if (contactId == "" || contactId == null) {
                    var row = {
                        html: $(this).prop('outerHTML'),
                        values: {}
                    };

                    $(this).find('input, select, textarea').each(function () {
                        row.values[$(this).attr('id')] = $(this).val();
                    });

                    unsavedRows.push(row);
                }
            });

            unsavedRows = unsavedRows.filter(row => {
                const values = row.values;

                const getValue = (prefix) => {
                    const key = Object.keys(values).find(k => k.startsWith(prefix));
                    return key ? values[key] : "";
                };

                const unsavedName = getValue("txtcolcontactname");
                const unsavedEmail = getValue("txtcolcontactemail");

                const alreadySaved = contact_data.some(saved =>
                    saved.PROSPECT_CONTACT_NAME === unsavedName &&
                    saved.PROSPECT_CONTACT_EMAIL_ADDRESS === unsavedEmail
                );

                return !alreadySaved;
            });

            renderContactData(contact_data, unsavedRows, sortType);
        }
    } else if (resp.type == "UPDATE_PROSPECT_CONTACT_OPTION") {
  
        $('#cmbProspectDeliveryContact').html(resp.data);
        // $(".cmbColDeliveryContact").html($("#cmbProspectDeliveryContact").html());
        filterProspectContact();
        filterProspectDelivery();
    } else if(resp.type == "CONVERT_PROSPECT_CUSTOMER"){
        swal.fire('Success', resp.mesg, 'success');
        cancelProspectEntry();
        prospectFilter();
    } else if(resp.type == "C_DELETE_DOCUMENT_PROSPECT"){
        swal.fire('Success', resp.mesg, 'success');
        $('#divDocProspect').hide();
    }
}

function validateProspectEntry() {
    if ($('#txtProspectCode').blank()) {
        swal.fire("Warning","Prospect Code cannot be blank","warning");
        return false;
    }

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

    return true;
}

//==========================================================================
//DELIVERY
function filterProspectDelivery() {
    LoadingScreen("show");
    var data = {
        "type": C_PROSPECT_DELIVERY_FILTERS,
        "cust_id": $('#txtProspectID').val(),
        "sorts": sorts,
    };
    var url = "index.pzx?c=" + prospect_url + "&t=" + C_PROSPECT_DELIVERY_FILTERS + "&d=" + new Date().getTime();
    callServer(url, "json", data, onResponseProspectEntry, null);
    return false;
}

function newProspectDelivery() {
    prospect_delivery_idx++;

    var contactField = "<select id='txtcoldeliverycontact" + prospect_delivery_idx + "' name='input_row' class='form-control cmbColDeliveryContact'>" + $('#cmbProspectDeliveryContact').html() + "</select>";

    var newRow = "<tr data-row='delivery-rows-" + prospect_delivery_idx + "' id='delivery-rows-" + prospect_delivery_idx + "' class='dnd-moved kt-datatable__row' style='left: 0px;'> " +
                    "<td data-field='deliveryid' class='kt-datatable__cell' id='col_deliveryid" + prospect_delivery_idx + "' style='display: none;'>"+
                        "<input type='text' class='form-control' name='input_row' id='txtcoldeliveryid" + prospect_delivery_idx + "' />"+
                    "</td> " +
                    "<td data-field='deliverycode' class='kt-datatable__cell' id='col_deliverycode" + prospect_delivery_idx + "'>"+
                        "<input type='text' class='form-control' name='input_row' id='txtcoldeliverycode" + prospect_delivery_idx + "' />"+
                    "</td> " +
                    "<td data-field='deliveryaddress' class='kt-datatable__cell' id='col_deliveryaddress" + prospect_delivery_idx + "'>"+
                        "<textarea style='overflow-y: auto;' type='text' class='form-control' name='input_row' id='txtcoldeliveryaddress" + prospect_delivery_idx + "'></textarea>"+
                    "</td> " +
                    "<td data-field='deliverycontact' class='kt-datatable__cell' id='col_deliverycontact" + prospect_delivery_idx + "'>" +
                        contactField +
                    "</td> " +
                    "<td data-field='filter' class='kt-datatable__cell' style='width: 50px;' id='col_filter" + prospect_delivery_idx + "'>" +
                        "<button class='btn btn-danger btn-sm btn-icon btn-icon-md' type='button' id='btnRemoveProspectDelivery' onclick='removeProspectDelivery(" + prospect_delivery_idx + ");'><i class='fa fa-trash-o'></i></button>"+
                    "</td> " +
                "</tr>";

    $('#prospect-delivery-list-table').append(newRow);
}

function removeProspectDelivery(idx) {
    $("#delivery-rows-" + idx).remove();
    if (idx == prospect_delivery_idx)
        prospect_delivery_idx--;
}

function deleteProspectDelivery(id, obj) {
    swal.fire("System Confirmation", "Are you sure you want to delete the selected record?", "warning", {
        buttons: {
            ok: true,
            cancel: "Cancel",
        },
    }).then(function (result) {
        if (result) {
            LoadingScreen("show");
            var data = {
                "type": C_DELETE_PROSPECT_DELIVERY,
                "cust_id": $('#txtProspectID').val(),
                "id": id,
            };

            var url = "index.pzx?c=" + prospect_url + "&t=" + C_DELETE_PROSPECT_DELIVERY + "&d=" + new Date().getTime();
            callServer(url, "json", data, onResponseProspectEntry, null);
        }
    });
}

//==========================================================================

//==========================================================================
//CONTACT
function updateProspectContactOption() {
    LoadingScreen("show");
    var data = {
        "type": "UPDATE_PROSPECT_CONTACT_OPTION",
        "cust_id": $('#txtProspectID').val(),
    };
    var url = "index.pzx?c=" + prospect_url + "&t=" + C_CONTACT_PROSPECT_FILTERS + "&d=" + new Date().getTime();
    callServer(url, "json", data, onResponseProspectEntry, null);
    return false;
}

function filterProspectContact(){
    var data = {
            "type": C_CONTACT_PROSPECT_FILTERS,
            "cust_id": $('#txtProspectID').val(),
            "sorts": sorts,
        };
    var url  = "index.pzx?c=" + prospect_url + "&t=" + C_CONTACT_PROSPECT_FILTERS  + "&d=" + new Date().getTime() ;
    callServer(url,"json",data,onResponseProspectEntry,null) ;
    return false;
}

function newProspectContact() {
    contact_prospect_idx++;

    var newRow = "<tr data-row='contact-rows-" + contact_prospect_idx + "' id='contact-rows-" + contact_prospect_idx + "' class='dnd-moved kt-datatable__row' style='left: 0px;'> " +
                    "<td data-field='contactid' class='kt-datatable__cell' id='col_contactid" + contact_prospect_idx + "' style='display: none; '>"+
                        "<input type='text' class='form-control' name='input_row' id='txtcolcontactid" + contact_prospect_idx + "' />"+
                    "</td> " +
                    "<td data-field='contactname' class='kt-datatable__cell' id='col_contactname" + contact_prospect_idx + "' style=''>"+
                        "<input type='text' class='form-control' name='input_row' id='txtcolcontactname" + contact_prospect_idx + "' />"+
                    "</td> " +
                    "<td data-field='contactdept' class='kt-datatable__cell' id='col_contactdept" + contact_prospect_idx + "' style=''>"+
                        "<input type='text' class='form-control' name='input_row' id='txtcolcontactdept" + contact_prospect_idx + "' />"+
                    "</td> " +
                    "<td data-field='contactposition' class='kt-datatable__cell' id='col_contactposition" + contact_prospect_idx + "' style=''>"+
                        "<input type='text' class='form-control' name='input_row' id='txtcolcontactposition" + contact_prospect_idx + "' />"+
                    "</td> " +
                    "<td data-field='contactemail' class='kt-datatable__cell' id='col_contactemail" + contact_prospect_idx + "' style=''>"+
                        "<input type='text' class='form-control' name='input_row' id='txtcolcontactemail" + contact_prospect_idx + "' />"+
                    "</td> " +
                    "<td data-field='contactphone' class='kt-datatable__cell' id='col_contactphone" + contact_prospect_idx + "' style=''>"+
                        "<input type='text' class='form-control' name='input_row' id='txtcolcontactphone" + contact_prospect_idx + "' />"+
                    "</td> " +
                    "<td data-field='contactmobile' class='kt-datatable__cell' id='col_contactmobile" + contact_prospect_idx + "' style=''>"+
                        "<input type='text' class='form-control' name='input_row' id='txtcolcontactmobile" + contact_prospect_idx + "' />"+
                    "</td> " +
                    "<td data-field='contactreportto' class='kt-datatable__cell' id='col_contactreportto" + contact_prospect_idx + "' style=''>"+
                        "<input type='text' class='form-control' name='input_row' id='txtcolcontactreportto" + contact_prospect_idx + "' />"+
                    "</td> " +
                    "<td data-field='contactstatus' class='kt-datatable__cell' id='col_contactstatus" + contact_prospect_idx + "' style=''>" +
                        "<select class='form-control' name='input_row' id='txtcolcontactstatus" + contact_prospect_idx + "'>" +
                            "<option value='1'>Active</option>" +
                            "<option value='0'>Inactive</option>" +
                        "</select>" +
                    "</td> " +
                    "<td data-field='filter' class='kt-datatable__cell' style='width: 50px;' id='col_filter" + contact_prospect_idx + "'>" +
                        "<button class='btn btn-danger btn-sm btn-icon btn-icon-md' type='button' id='btnRemoveContact' style='' onclick='removeProspectContact(" + contact_prospect_idx + ");'><i class='fa fa-trash-o'></i></button>"+
                    "</td> " +
                "</tr>";

    $('#prospect-contact-list-table').append(newRow);
}

function removeProspectContact(idx) {
    $("#contact-rows-" + idx).remove();
    if (idx == contact_prospect_idx)
        contact_prospect_idx--;
}

function deleteProspectContact(id, obj) {
    swal.fire("System Confirmation", "Are you sure you want to delete the selected record?", "warning", {
        buttons: {
            ok: true,
            cancel: "Cancel",
        },
    }).then(function (result) {
        if (result) {
            var data = {
                "type": C_DELETE_CONTACT_PROSPECT,
                "cust_id": $('#txtProspectID').val(),
                "id": id,
            };
            var url = "index.pzx?c=" + prospect_url + "&t=" + C_DELETE_CONTACT_PROSPECT + "&d=" + new Date().getTime();
            callServer(url, "json", data, onResponseProspectEntry, null);
        }
    });
}

function renderContactData(savedData, unsavedRows, sortType) {
    let html = "";
    let counter = 0;

    const fieldMap = {
        col_contactname: {
            saved: "PROSPECT_CONTACT_NAME",
            unsaved: "txtcolcontactname"
        },
        col_contactdept: {
            saved: "PROSPECT_CONTACT_DEPARTMENT",
            unsaved: "txtcolcontactdept"
        },
        col_contactposition: {
            saved: "PROSPECT_CONTACT_DESIGNATION",
            unsaved: "txtcolcontactposition"
        },
        col_contactemail: {
            saved: "PROSPECT_CONTACT_EMAIL_ADDRESS",
            unsaved: "txtcolcontactemail"
        },
        col_contactphone: {
            saved: "PROSPECT_CONTACT_TELEPHONE",
            unsaved: "txtcolcontactphone"
        },
        col_contactmobile: {
            saved: "PROSPECT_CONTACT_MOBILE",
            unsaved: "txtcolcontactmobile"
        },
        col_contactreportto: {
            saved: "PROSPECT_CONTACT_REPORT_TO",
            unsaved: "txtcolcontactreportto"
        },
        col_contactstatus: {
            saved: "PROSPECT_CONTACT_STATUS_ACTIVE",
            unsaved: "txtcolcontactstatus"
        }
    };

    sortType = sortType || ["col_contactname", "asc"];
    const sortColumn = sortType[0] || "col_contactname";
    const sortOrder = sortType[1] || "asc";

    const combined = [
        ...savedData.map(item => ({
            type: "saved",
            original: item,
            sortValue: item[fieldMap[sortColumn].saved] || ""
        })),

        ...unsavedRows.map(item => {

            // find dynamic key
            const unsavedKeyPrefix = fieldMap[sortColumn].unsaved;

            const actualKey = Object.keys(item.values).find(key =>
                key.startsWith(unsavedKeyPrefix)
            );

            return {
                type: "unsaved",
                original: item,
                sortValue: actualKey
                    ? item.values[actualKey]
                    : ""
            };
        })
    ];

    combined.sort((a, b) => {
        let valA = (a.sortValue || "").toLowerCase();
        let valB = (b.sortValue || "").toLowerCase();

        return sortOrder === "asc"
            ? valA.localeCompare(valB)
            : valB.localeCompare(valA);
    });

    combined.forEach(row => {
        counter++;

        let item;

        if (row.type === "saved") {
            item = {
                id: row.original.PROSPECT_CONTACT_ID || "",
                name: row.original.PROSPECT_CONTACT_NAME || "",
                dept: row.original.PROSPECT_CONTACT_DEPARTMENT || "",
                position: row.original.PROSPECT_CONTACT_DESIGNATION || "",
                email: row.original.PROSPECT_CONTACT_EMAIL_ADDRESS || "",
                phone: row.original.PROSPECT_CONTACT_TELEPHONE || "",
                mobile: row.original.PROSPECT_CONTACT_MOBILE || "",
                reportto: row.original.PROSPECT_CONTACT_REPORT_TO || "",
                status: row.original.PROSPECT_CONTACT_STATUS_ACTIVE || "1",
                isSaved: true
            };

        } else {
            const values = row.original.values;

            const getDynamicValue = (prefix) => {
                const key = Object.keys(values).find(k => k.startsWith(prefix));
                return key ? values[key] : "";
            };

            item = {
                id: "",
                name: getDynamicValue("txtcolcontactname"),
                dept: getDynamicValue("txtcolcontactdept"),
                position: getDynamicValue("txtcolcontactposition"),
                email: getDynamicValue("txtcolcontactemail"),
                phone: getDynamicValue("txtcolcontactphone"),
                mobile: getDynamicValue("txtcolcontactmobile"),
                reportto: getDynamicValue("txtcolcontactreportto"),
                status: getDynamicValue("txtcolcontactstatus") || "1",
                isSaved: false
            };
        }

        html += `
        <tr data-row="contact-rows-${counter}" id="contact-rows-${counter}" class="dnd-moved kt-datatable__row" style="left: 0px;">
            <td data-field="contactid" class="kt-datatable__cell" style="display:none;" id="col_contactid${counter}">
                <input type="text" class="form-control" name="input_row" id="txtcolcontactid${counter}" value="${item.id}" />
            </td>
            <td data-field="contactname" class="kt-datatable__cell" id="col_contactname${counter}">
                <input type="text" class="form-control" name="input_row" id="txtcolcontactname${counter}" value="${item.name}" />
            </td>
            <td data-field="contactdept" class="kt-datatable__cell" id="col_contactdept${counter}">
                <input type="text" class="form-control" name="input_row" id="txtcolcontactdept${counter}" value="${item.dept}" />
            </td>
            <td data-field="contactposition" class="kt-datatable__cell" id="col_contactposition${counter}">
                <input type="text" class="form-control" name="input_row" id="txtcolcontactposition${counter}" value="${item.position}" />
            </td>
            <td data-field="contactemail" class="kt-datatable__cell" id="col_contactemail${counter}">
                <input type="text" class="form-control" name="input_row" id="txtcolcontactemail${counter}" value="${item.email}" />
            </td>
            <td data-field="contactphone" class="kt-datatable__cell" id="col_contactphone${counter}">
                <input type="text" class="form-control" name="input_row" id="txtcolcontactphone${counter}" value="${item.phone}" />
            </td>
            <td data-field="contactmobile" class="kt-datatable__cell" id="col_contactmobile${counter}">
                <input type="text" class="form-control" name="input_row" id="txtcolcontactmobile${counter}" value="${item.mobile}" />
            </td>
            <td data-field="contactreportto" class="kt-datatable__cell" id="col_contactreportto${counter}">
                <input type="text" class="form-control" name="input_row" id="txtcolcontactreportto${counter}" value="${item.reportto}" />
            </td>
            <td data-field="contactstatus" class="kt-datatable__cell" id="col_contactstatus${counter}">
                <select class="form-control" name="input_row" id="txtcolcontactstatus${counter}">
                    <option value="1" ${item.status == 1 ? 'selected' : ''}>Active</option>
                    <option value="0" ${item.status == 0 ? 'selected' : ''}>Inactive</option>
                </select>
            </td>
            <td data-field="filter" class="kt-datatable__cell" id="col_filter${counter}">
                ${
                    item.isSaved
                    ?
                    `<button class="btn btn-danger btn-sm btn-icon btn-icon-md"
                        type="button"
                        title="Delete"
                        onclick="deleteProspectContact(${item.id},this);">
                        <i class="fa fa-trash-o"></i>
                    </button>`
                    :
                    `<button class="btn btn-danger btn-sm btn-icon btn-icon-md"
                        type="button"
                        onclick="removeProspectContact(${counter});">
                        <i class="fa fa-trash-o"></i>
                    </button>`
                }
            </td>
        </tr>`;
    });

    $("#prospect-contact-list-table").html(html);
}

//=====================================================================
//PROSPECT ACCOUNT

function HideShowProspectAccountField() {
    $("#txtProspectAccountId").val("");
    $("#txtProspectAccountNew").val("");
    $("#txtProspectAccount").val("");
    $("#txtProspectAccountType").val("");
    $("#txtProspectAccountGroup").val("");
    $("#txtProspectAccountPaymentTerms").val("");
    $("#txtProspectAccountCoyReg").val("");
    $("#txtProspectAccountTaxReg").val("");
    $("#txtProspectAddress1").val("");
    $("#txtProspectAccountDesc").val("");
    $("#txtProspectAccountStatus").val("");

    if ($("#txtProspectToggle").prop("checked")) {
        //new
        $("#divCustAccountNew").attr('style', '');
        $("#divCustAccountExisting").attr('style', 'display:none;');
    } else {
        //existing
        $("#divCustAccountExisting").attr('style', '');
        $("#divCustAccountNew").attr('style', 'display:none;');
    }
}

function convertProspectCustomer() {
    LoadingScreen("show");
    var data = { "type": "CONVERT_PROSPECT_CUSTOMER", "id": $('#txtProspectID').val(), };
    var url = "index.pzx?c=" + prospect_url + "&t=" + "CONVERT_PROSPECT_CUSTOMER" + "&d=" + new Date().getTime();
    callServer(url, "json", data, onResponseProspectEntry, null);
}

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

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


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

    if (filesSelected.length > 0) {
       	var fileToLoad = filesSelected[0];
	   	var fileExt = getFileExtensionAddProspect(filesSelected[0].name);
		  
      	var fileReader = new FileReader();

      	fileReader.onload = function(fileLoadedEvent) {
			var srcData = fileLoadedEvent.target.result; // <--- data: base64
			// var base64String = window.btoa(srcData);
			$('#txtAddProspectAttachmentFileBase64').html(srcData);
			$('#txtAddProspectAttachmentFileExt').val(fileExt);
			$('#txtAddProspectAttachmentFilename').val(filesSelected[0].name);
      	}
      fileReader.readAsDataURL(fileToLoad);
    }

	src= URL.createObjectURL(event.target.files[0])
	$('#view_doc').show();
	$('#frame').attr('src', src);
	$('#viewDoc').html(filesSelected[0].name);
	
}

function openPreview(){
	var iframe = $("#frame"); 
	var newWindow = window.open(iframe.attr(src), 'Dynamic Popup', 'height=800, width=800, scrollbars=auto, resizable=no, location=no, status=no');
	newWindow.document.write(iframe[0].outerHTML);
	newWindow.document.close();
}

function onAddProspectImageResponse(obj,resp) {
	if (resp.status != C_OK ) {
        alert(resp.mesg);
        return false;
    }
}

function openPreviewPortal() {
    var url = "index.pzx?c=" + prospect_url + "&id=" + $('#txtProspectID').val() +
     "&t=" + "C_DOWNLOAD_PROSPECT_DOCUMENT" + "&r=1";
    showReport(url) ;
}

function deleteProspectDocument () {
    swal.fire("System Confirmation", "Are you sure you want to delete the selected record?", "warning", {
        buttons: {
            ok: true,
            cancel: "Cancel",
        },
    })
    .then(function(result) {
    switch (result) {
      case "ok":
        var data = {
            "type": "C_DELETE_DOCUMENT_PROSPECT",
            "id": $('#txtProspectID').val(),
         
        };
        var url = "index.pzx?c=" + prospect_url + "&t=" + "C_DELETE_DOCUMENT_PROSPECT" + "&d=" + new Date().getTime();
        callServer(url, "json", data, onResponseProspectEntry, null);
      break;
    }
    });
    
    // swal.fire({
    //     title: "Delete Confirmation",
    //     text: "Confirm you want to delete the record?",
    //     type: "warning",
    //     showCancelButton: true,
    //     confirmButtonText: "Yes",
    //     cancelButtonColor: '#d33',
    // }).then(function (result) {
    //     if (result.value) {
    //         var data = {
    //             "type": "C_DELETE_DOCUMENT_PROSPECT",
    //             "id": $('#txtProspectID').val(),
             
    //         };
    //         var url = "index.pzx?c=" + prospect_url + "&t=" + "C_DELETE_DOCUMENT_PROSPECT" + "&d=" + new Date().getTime();
    //         callServer(url, "json", data, onResponseProspectEntry, null);
    //     }
    // });
}