$(document).bind('click', function(e) {

    var $clicked = $(e.target);
    //alert($clicked);
    if (!$clicked.parents().hasClass("dropdown-x")) {
        $(".dropdown-x dd ul").hide();
    }
});


function deleteAllForm() {

    $('#delete_loading').show();
    var formData = {
        'action': 'DELETE_ALL_LETTER'
    }
    $.ajax({
        type: 'POST',
        url: EPICVELOCITY_AJAX_URL,
        data: formData,
        success: function(data) {
            $('#delete_loading').hide();
            //generateClientFilesModal();
        }

    });
}

function letterLoad(val) {
    if (val > 0) {
        window.location.href = LETTER_VIEW_URL + '/' + val;
    }
}

function deleteLetter(id, elem) {

    var formData = {
        'action': 'CHECK_HAS_AUTOMATION',
        'letter_id': id
    }
    var message = "You're about to permanently delete this file, Do you want to Delete it ?";
    $('.loading').show();
    $.ajax({
        type: 'POST',
        url: EPICVELOCITY_AJAX_URL,
        data: formData,
        success: function(data) {
            $('.loading').hide();
            var response = JSON.parse(data);

            if (response.status) {
                message = response.message;
            }
            deleteLetterPermanently(id, elem, message);
        }

    });
    //    var r = confirm('Are you sure you want to delete this?');
    //    if(!r){
    //        return false;
    //    }


}

function deleteLetterPermanently(id, elem, message) {
    var formData = {
        'action': 'DELETE_LETTER',
        'letter_id': id
    }
    Swal.fire({
        width: '40rem',
        text: message,
        icon: 'warning',
        showCancelButton: true,
        confirmButtonColor: '#3085d6',
        cancelButtonColor: '#d33',
        confirmButtonText: 'Yes',
        cancelButtonText: 'No'
    }).then((result) => {
        if (result.value) {
            $('#delete_loading').show();
            $.ajax({
                type: 'POST',
                url: EPICVELOCITY_AJAX_URL,
                data: formData,
                success: function(data) {
                    $('#delete_loading').hide();
                    Swal.fire({
                        position: 'center',
                        icon: 'success',
                        title: 'Deleted successfully',
                        showConfirmButton: false,
                        timer: 1500
                    })
                    $(elem).parent('td').parent('tr').hide();
                    generateClientFilesModal(-1);

                }

            });
        }
    });
}

function generateClientFilesModal(elem) {
    if (elem != -1) {
        $('#client-file-loader').show();
    }

    var formData = {
        'action': 'GET_CLIENT_FILES_LIST_POPUP'
    }
    $.ajax({
        type: 'POST',
        url: EPICVELOCITY_AJAX_URL,
        //url:'__SERVER_URL__Dashboard/getFormData',
        data: formData,
        success: function(data) {
            $('#client-file-loader').hide();
            var data = JSON.parse(data);

            //console.log('member_id');
            //console.log('dashboard_data',data);
            var table = $('#form-table').DataTable();

            table.clear().draw();
            table.order([6, 'desc'])
            $.each(data, function(index, json) {
                var next_section_date = "";
                if (json.next_section_date) {
                    next_section_date = moment(json.next_section_date).format('YYYY-MM-DD')
                }


                var rows = [json.id, json.personal_info, json.dob, json.ssn, json.source_type, json.slected_letter, moment(json.created_on).format('YYYY-MM-DD'), next_section_date, '<a href="javascript:;" onclick="deleteLetter(' + json.letter_id + ',this)" data-toggle="tooltip" title="Delete" data-id="' + json.id + '" id="formDelete_"' + json.id + '"><span style="color:#dd4b39;padding-left:10px;font-size:18px;"><i class="fa fa-trash" aria-hidden="true"></i></span></a>' + ' ' + '<a href="javascript:;" onclick="letterLoad(' + json.letter_id + ')" data-toggle="tooltip" title="Load" data-id="' + json.id + '" id="formLoad_"' + json.id + '"><span style="color:#00a65a;padding-left:5px;font-size:18px;"><i class="fa fa-external-link-square" aria-hidden="true"></i></span></a>'];
                table.row.add(rows).draw();
            });

            if (elem != -1) {
                $('#formModal').modal('show');
            }

        }

    });


}


function generatePdf(elem) {
    event.preventDefault();
    var swal = Swal.fire({
        title: 'Credit Counsel Elite',
        text: "Are you sure want to generate letter and send email ?",
        icon: 'info',
        width: '40rem',
        showCancelButton: true,
        confirmButtonColor: '#3085d6',
        cancelButtonColor: '#d33',
        cancelButtonText: "No",
        confirmButtonText: 'Yes',
    })

    swal.then((result)=>{
        if(result.value){
            var formData = new FormData(document.getElementById("lg-form"));
            btnValue = 2;
            formData.append('formaction', 'generate');
            ajaxRequest(formData, btnValue);
        }
    })

    return false;
}
const generateLetterPdf=()=> {
    event.preventDefault();
    var content_count = $('#content-area').children('div').length;
    if(content_count>0) {
        $('#generateLetterModal').modal('show');
    }else {
        alert("You do not have any content.");
    }
    return false;
}
const generateLetter=()=> {
    let checked_data =  $("input[name='download']:checked").val();
    let download_type_value =  $("#download_type_name").val();
    $("input[name='download_type']").remove();
    let btnValue = 0;
    let wave = $('#wave-0').val();
    if(wave!=='') {
        if ((parseInt(checked_data) === 1 && parseInt(download_type_value) > 0)) {
            btnValue = 2;
            $("#lg-form").append(`<input type="hidden" value="2" name="download_type" />`);
            ajaxRequestForValidation(btnValue);
        } else if (parseInt(checked_data) === 0) {
            btnValue = 1;
            $("#lg-form").append(`<input type="hidden" value="1" name="download_type" />`);
            ajaxRequestForValidation(btnValue);
            // document.getElementById("lg-form").submit();
            // return true;
        }
    }
    return false;
}
const submitForm=(btnValue)=>{
    var formData = new FormData(document.getElementById("lg-form"));
    formData.append('formaction', 'generate');
    ajaxRequest(formData, btnValue);
}
function ajaxRequestForValidation(type) {
    var formData = new FormData(document.getElementById("lg-form"));

    var export_type_id = [];

    formData.append('export_type_id', export_type_id);

    $('.loading').show();

    $.ajax({
        type: 'POST',
        url: GENERATED_PDF_URL,
        data: formData,
        contentType: false,
        cache: false,
        processData: false,
        success: function(data) {
            $('.loading').hide();

            var response = JSON.parse(data);

            if (response.status)
            {
                if(response.isGreaterThanFifty) {
                    Swal.fire({
                        // title: response.message,
                        // text: response.message,
                        html: response.message,
                        icon: "warning",
                        width: '60rem',
                        fontsize: '20px',
                        showConfirmButton: true,
                        allowOutsideClick: true,
                        showCancelButton: true,
                        confirmButtonText: 'Yes',
                        cancelButtonText: 'No',
                    }).then((result) => {
                        if (result.isConfirmed) {
                            formSubmit(type);
                        }
                    });
                }else {
                    formSubmit(type);
                }

            }else {
                if (response.message) {
                    Swal.fire({
                        text: response.message,
                        icon: "warning",
                        width: '40rem',
                        padding: '3rem',
                        type: 'warning',
                        fontsize:'2rem',
                        confirmButtonText: 'Ok',
                    })
                    return false;
                }
            }
        }
    });
}

function formSubmit(type){
    if (type == 1) {
        document.getElementById("lg-form").submit();
        return true;
    } else if (type == 2) {
        submitForm(type);
    }
}

function saveOnly(elem) {
    $('.download-area').show();
    var value = $(elem).val();
    if (value == 2) {
        $('#before-save').val(1);
        $('.download-area').hide();
    }
    return true;
}

function saveOnlyEdit(elem) {

    $('input[name=action]').val('edit')
    $('.download-area').show();
    var value = $(elem).val();
    if (value == 2) {
        $('#before-save').val(1);
        $('.download-area').hide();
    } else if (value == 3) {
        $('input[name=action]').val('create_new')
    }

    return true;
}



function chooseDropDown(elem) {
    event.preventDefault();

    $(elem).parent().parent().parent().children('dd').children('div.mutliSelect').children('ul').slideToggle('fast');

    $(".dropdown-x dd ul").hide();
    $(elem).parent().parent().next('dd').children('div').children('ul').show();
    ////console.log();
}

$('input[name=download_type]').click(function() {

    $('.download-box').addClass('not-allowed');
    $('.choosedownload').addClass('disable-elem-download');
    $('input[name=checkallExport]').attr('disabled', true);
    $('input[name=checkallExport]').prop("checked", false);
    $('.download-category').prop("checked", false);
    $('.multi-downloadselect').children('span').remove();
    if ($('.multi-downloadselect').children().length == 0) {
        $(".choose-download").show();
    }
    var value = $(this).val();

    if (value == 2) {
        $('.download-box').removeClass('not-allowed');
        $('.choosedownload').removeClass('disable-elem-download');
        $('input[name=checkallExport]').attr('disabled', false);
    }
});

function getAccOption(elem) {
    var isNotSaved = $('input[name=isNotSaved]').val();

    if (isNotSaved == 1) {
        getallAccLength(elem);
    }

    var value = $(elem).val();
    var flag = false;
    var title = $(elem).parent().text();
    var multiSelP = $(elem).parent().parent().parent().parent().prev('dt').children('div').children('a').children('p.multiSel');
    //alert(title);
    var html = '<span class="hida" title="' + title + '">' + title + '</span>';
    $(elem).parents('dl').next('span.help-block').hide();
    if ($(elem).is(':checked')) {

        multiSelP.prev("span").hide();
        multiSelP.next("span").hide();
        multiSelP.append(html);


        if (value == 73 || value == 72) {
            //alert(1234);
            $(elem).parents('dl').next('span.help-block').show();
        }



        if (value == -1) {
            flag = true;
            $(elem).parent().parent().parent().parent().prev('dt').parent().next('.help-block').show();
        }



    } else {
        multiSelP.children('span[title="' + title + '"]').remove();

    }

    if (!multiSelP.children("span").is(':visible')) {
        //alert(12);
        multiSelP.prev("span").show();
    }

    if (value != -1) {
        //alert(12);
        //$(elem).parent().parent().parent().parent().prev('dt').parent().next('.help-block').hide();
    }

    var isItemBank = $(elem).data('bank');
    if (isItemBank) {
        getBankInfo(elem);
    }

    var isItemNegetive = $(elem).data('negative');
    if (isItemNegetive) {
        getSubCategoryInfo(elem);
    }

    var isInqItemNegetive = $(elem).data('inq_negative');
    if (isInqItemNegetive) {
        getInquiriesSubCategoryInfo(elem);
    }

    var isPublicItemNegetive = $(elem).data('public_negative');
    if (isPublicItemNegetive) {
        getpublicSubCategoryInfo(elem);
    }



}

function seteSelectedDropDownView(elem) {
    var title = $(elem).data('view');
    //alert(title);
    var checkVal = $(elem).val();
    var titleSpan = $(elem).parent().parent().parent().parent().prev('dt').children('div').children('a').children('p.multiSel');

    if ($(elem).is(':checked')) {
        var html = '<span class="hida" title="' + title + '">' + title + '</span>';
        $(elem).parent().parent().parent().parent().prev('dt').children('div').children('a').children('p').append(html);
        titleSpan.prev("span").hide();
    } else {
        $(elem).parent().parent().parent().parent().prev('dt').children('div').children('a').children('p').children('span[title="' + title + '"]').remove();
    }

    if (titleSpan.children('span').length == 0) {
        titleSpan.prev("span").text("Choose Item");
        titleSpan.prev("span").show();
    }
}

function downloadOption(elem) {

    var isFirst = $('input[name=isFirst]').val();
    attAllcheck = '';
    var destCount = $('#maindestination ul li input:checked').length;
    var attLength = destCount;
    if (destCount > 1) {
        attAllcheck = '<input data-id="' + attLength + '" style="margin-left: 10px;" type="checkbox" name=all_att_check_' + attLength + ' id="all_att_check_' + attLength + '" onclick="setAllCheck(this)"><span> Check all</span>';
        //$('.view-allcheck').append(attAllcheck);
    }

    var title = $(elem).data('view');
    var checkVal = $(elem).val();
    var export_type = $(elem).data('type');
    //code change

    var checkboxString = '';
    var attcheckboxString = '';
    var dfClass = '';
    if (checkVal == 11) {
        dfClass = 'dfclass'
    }
    if ($(elem).is(':checked')) {
        var html = '<span class="hida" title="' + title + '">' + title + '</span>';
        $(elem).parent().parent().parent().parent().prev('dt').children('div').children('a').children('p').append(html);
        $(elem).parent().parent().parent().parent().prev('dt').children('div').children('a').children('p.multiSel').prev("span").hide();
    } else {
        var removal = $(elem).val();
        $('#destination_sub_menu_other_' + removal).parents('div#address_other').remove();
        $(elem).parent().parent().parent().parent().prev('dt').children('div').children('a').children('p').children('span[title="' + title + '"]').remove();
        $checkStr = '<li><input onclick="makeAllCheck(this)" class="dest_check_' + removal + ' remove-all ' + dfClass + '" id="dest_check_' + removal + '" name="dest_check_1[]" type="checkbox" value="' + removal + '" /> ' + title + '</li>';
        if (checkVal != 11) {
            $checkAttStr = '<li><input onclick="makeAllCheck(this)" class="att_check_' + removal + ' remove-all" id="att_check_' + removal + '" name="att_check_1[]" type="checkbox" value="' + removal + '" /> ' + title + '</li>';
        }
        checkboxString = checkboxString.replace($checkStr, '');
        attcheckboxString = attcheckboxString.replace($checkAttStr, '');

    }

    if (!$('.hida').is(':visible')) {
        $(".choose-dest").show();
    }

}

// $(".date-only").datetimepicker({
//     format: "YYYY-MM-DD HH:mm",
//     minDate: moment(),
//     ignoreReadonly: true
// });

$('input[name=set_schedule]').click(function() {
        $('.schedule-area').hide();
        if ($(this).prop('checked')) {
            $('.schedule-area').show();
        }
    })
    //function letterStreamModalGenerate() {
    //
    //    var checkedAddressArrayList = [];
    //    var destinationNameList = [];
    //    $("input[name='destination[]']:checked").each(function () {
    //        var dest_id = $(this).val();
    //        var name = {};
    //        var addresses = {'dest_id': dest_id, 'value': getAddressList(dest_id), 'title': $(this).data('view')};
    //        name[dest_id] = $(this).data('view')
    //        destinationNameList.push(name);
    //        checkedAddressArrayList.push(addresses);
    //
    //    });
    //
    //
    //    var letter_stream_html = '<table class="table">' +
    //            '<th>Destinations</th>' +
    //            '<th><div class="checkbox"><label style="font-weight:bold;"><input id="all-check-address" type="checkbox" onclick="letterAddressAllCheck(this)"> Addresses</label></div></th>';
    //
    //    for (var index in checkedAddressArrayList) {
    //        var destination_id = checkedAddressArrayList[index].dest_id
    //        var address_checked_checkbox = $("input[name='destination_sub_menu_" + destination_id + "[]']");
    //        if (checkedAddressArrayList[index].title != 'DATA FURNISHERS' && checkedAddressArrayList[index].title != 'OTHER') {
    //            letter_stream_html += '<tr><td>' + checkedAddressArrayList[index].title + '</td><td>';
    //            var address_checked_checkbox_checked = $("input[name='destination_sub_menu_" + destination_id + "[]']:checked");
    //            if (address_checked_checkbox_checked.length == 0) {
    //                address_checked_checkbox.each(function (index, value) {
    //                    var title = $(this).data('view');
    //                    var data_value = $(this).val();
    //                    var checked = '';
    //                    if (index == 0) {
    //                        checked = 'checked';
    //                    }
    //                    if (title != 'OTHER') {
    //                        letter_stream_html += '<div class="checkbox"><label><input onclick="currentAddress()" class="letter-address-popup" ' + checked + ' type="checkbox" value="' + data_value + '" name="letter_stream_address_' + destination_id + '[]"> ' + title + '</label></div>';
    //                    }
    //                });
    //            } else {
    //                address_checked_checkbox.each(function (index, value) {
    //                    var title = $(this).data('view');
    //                    var data_value = $(this).val();
    //                    var checked = '';
    //                    if ($(this).prop('checked')) {
    //                        checked = 'checked';
    //                    }
    //
    //                    if (title != 'OTHER') {
    //                        letter_stream_html += '<div class="checkbox"><label><input onclick="currentAddress()" class="letter-address-popup" ' + checked + ' type="checkbox" value="' + data_value + '" name="letter_stream_address_' + destination_id + '[]"> ' + title + '</label></div>';
    //                    }
    //                });
    //            }
    //        }
    //    }
    //
    //    letter_stream_html += '</td></tr></table>';
    //    $('.letter-stream-content').html(letter_stream_html);
    //    if ($('.letter-stream-content').children().length == 0) {
    //
    //    }
    //    letterStreamAllCheck();
    //    $('#letter-stream-modal').modal('show');
    //
    //
    //}

function letterStreamAllCheck() {
    $('#all-check-address').prop('checked', false);
    var total_lenght_of_address_checkbox = $('.letter-address-popup').length;
    var selected_lenght_of_address_checkbox = $('.letter-address-popup:checked').length;
    if (total_lenght_of_address_checkbox == selected_lenght_of_address_checkbox) {
        $('#all-check-address').prop('checked', true);
    }
}


function ajaxRequest(formData, type) {
    var export_type_id = [];
    /*$("input[name='download_category[]']:checked").each(function() {
        var type = $(this).data('type');
        export_type_id.push(type)
    });*/
    formData.append('export_type_id', export_type_id);
    console.log('formData', formData);
    $('#letter-stream-btn, #before-save').attr('disabled', true);
    //$('#client-loader2').show();
    $('.loading').show();
    $('#saveloading-letter').show();
    $.ajax({
        type: 'POST',
        url: GENERATE_PDF_URL,
        data: formData,
        contentType: false,
        cache: false,
        processData: false,
        success: function(data) {
            $('#client-loader2').hide();
            $('#letter-stream-btn, #before-save').attr('disabled', false);
            //console.log(data);
            $('.loading').hide();
            $('#saveloading-letter').hide();
            $('#before-saving-modal').modal('hide');
            $('#letter-stream-modal').modal('hide');
            var response = JSON.parse(data);
            //console.log('data', response);
            if (type == 1) {
                if (response.status == 1) {
                    alert('Saved Successfully');
                    $('#create-new-btn').show();

                }
                if (response.status == 2) {
                    alert('Update Successfully');


                }
                $('input[name=update_id]').val(response.id);
            } else {

                if (response.message) {
                    Swal.fire({
                        title: 'Credit Counsel Elite',
                        text: response.message,
                        icon: 'info',
                        width: '40rem',
                        padding: '3rem',
                        type: 'warning',
                        fontsize:'2rem',
                        confirmButtonText: 'Close',
                    })
                    return false;
                }
            }
        },
        error: function(jqXHR, exception) {
            $('#client-loader2').hide();
        }
    });
}

function hasLetterStream() {
    var result = false;
    var isLetterStream = $('input[name=isLetterStream]').val();
    if (isLetterStream == 0) {
        $("input[name='download_category[]']:checked").each(function() {
            var type = $(this).data('type');
            if (type == 6) {
                result = true;
                return false;
            }
        })
    }
    return result;
}

function letterStreamAllCheck() {
    $('#all-check-address').prop('checked', false);
    var total_lenght_of_address_checkbox = $('.letter-address-popup').length;
    var selected_lenght_of_address_checkbox = $('.letter-address-popup:checked').length;
    if (total_lenght_of_address_checkbox == selected_lenght_of_address_checkbox) {
        $('#all-check-address').prop('checked', true);
    }
}


function destinationNameById(dest_id) {
    var destination = ['', 'EXPERIAN DESTINATIONS', 'EQUIFAX DESTINATIONS', 'TRANS UNION DESTINATIONS', 'INNOVIS DESTINATIONS', 'LEXISNEXIS DESTINATIONS', 'SAGESTREAM LLC DESTINATIONS', 'CHEX SYSTEMS DESTINATIONS', 'MIB INC DESTINATIONS', 'FACTOR TRUST DESTINATIONS', 'OTHER'];
    return destination[dest_id];
}

function destinationIdByAddressName(name) {
    var array = [];
    var destination_id = 0;
    array[1] = ['EXPERIAN PO BOX 9701, ALLEN, TX 75013',
        'EXPERIAN PO BOX 4500, ALLEN, TX 75013',
        'EXPERIAN PO BOX 2002, ALLEN, TX 75013',
        'OTHER'
    ];

    array[2] = ['EQUIFAX PO Box740256, ATLANTA,GA 30374-0256',
        'EQUIFAX PO Box740241, ATLANTA,GA 30374-0241',
        'OTHER'
    ];

    array[3] = ['Trans Union PO Box 2000, CHESTER, PA 19016-2000',
        'Trans Union PO Box 1000, CHESTER, PA 19022-1000',
        'Trans Union PO Box 2000, CHESTER, PA 19022-2000',
        'OTHER'

    ];

    array[4] = ['INNOVIS PO Box 1640, Pittsburgh, PA 15230-1640',
        'Innovis Consumer Assistance PO Box 530088, Atlanta, GA 30353-0088'
    ];

    array[5] = ['LexisNexis PO Box 105108, Atlanta, GA 30348'];

    array[6] = ['SageStream, LLC, LexisNexis Risk Solutions Consumer Center P. O. Box 105108. Atlanta, Georgia 30348-5108'];

    array[7] = ['Chex Systems ATTN: Consumer Relations, 7805 Hudson Rd., Ste. 100, Woodbury, MN 55125'];

    array[8] = [
        '(US RESIDENTS) MIB Inc 50 Braintree Hill Park, Suite 400, Braintree, MA 02184-8734',

        '(CANADIAN RESIDENTS) MIB Inc 330 university Avenue, Suite 501, Toronto, Canada M5G 1R7'
    ];

    array[9] = ['FactorTrust PO Box 3653,Alpharhetta, GA 30023'];

    if (array) {
        $.each(array, function(dest_id, subArray) {
            if ($.inArray(name, subArray) !== -1) {
                destination_id = dest_id;
                return false;
            }
        })
    }

    return { 'name': destinationNameById(destination_id), 'id': destination_id };
}

function getAddressList(dest_id) {
    var array = [];
    array[1] = ['EXPERIAN PO BOX 9701, ALLEN, TX 75013',
        'EXPERIAN PO BOX 4500, ALLEN, TX 75013',
        'EXPERIAN PO BOX 2002, ALLEN, TX 75013',
        'OTHER'
    ];

    array[2] = ['EQUIFAX PO Box740256, ATLANTA,GA 30374-0256',
        'EQUIFAX PO Box740241, ATLANTA,GA 30374-0241',
        'OTHER'
    ];

    array[3] = ['Trans Union PO Box 2000, CHESTER, PA 19016-2000',
        'Trans Union PO Box 1000, CHESTER, PA 19022-1000',
        'Trans Union PO Box 2000, CHESTER, PA 19022-2000',
        'OTHER'

    ];

    array[4] = ['INNOVIS PO Box 1640, Pittsburgh, PA 15230-1640',
        'Innovis Consumer Assistance PO Box 530088, Atlanta, GA 30353-0088'
    ];

    array[5] = ['LexisNexis PO Box 105108, Atlanta, GA 30348'];

    array[6] = ['SageStream, LLC, LexisNexis Risk Solutions Consumer Center P. O. Box 105108. Atlanta, Georgia 30348-5108'];

    array[7] = ['Chex Systems ATTN: Consumer Relations, 7805 Hudson Rd., Ste. 100, Woodbury, MN 55125'];

    array[8] = [
        '(US RESIDENTS) MIB Inc 50 Braintree Hill Park, Suite 400, Braintree, MA 02184-8734',

        '(CANADIAN RESIDENTS) MIB Inc 330 university Avenue, Suite 501, Toronto, Canada M5G 1R7'
    ];

    array[9] = ['FactorTrust PO Box 3653,Alpharhetta, GA 30023'];

    return array[dest_id];
}

function hasLetterStream() {
    var result = false;
    var isLetterStream = $('input[name=isLetterStream]').val();
    if (isLetterStream == 0) {
        $("input[name='download_category[]']:checked").each(function() {
            var type = $(this).data('type');
            if (type == 6) {
                result = true;
                return false;
            }
        })
    }
    return result;
}

function currentAddress() {
    letterStreamAllCheck();
}

function letterStreamSubmit() {
    if ($('input[name=isDFchecked]').prop('checked')) {

    } else {
        if ($('.letter-address-popup:checked').length == 0) {
            alert('Please select at least one  address');
            return false;
        }
    }
    $('input[name=isLetterStream]').val(1);
    $('#saveloading-letter').show();
    $('#before-save').click();
}

function letterAddressAllCheck(elem) {
    $('.letter-address-popup').prop('checked', false);
    $('input[name=isDFchecked]').prop('checked', false);
    if ($(elem).prop('checked')) {
        $('.letter-address-popup').prop('checked', true);
        $('input[name=isDFchecked]').prop('checked', true);
    }

}

function array_unique(array) {
    return array.filter(function(el, index, arr) {
        return index === arr.indexOf(el);
    });
}

function getSelectedAddressByDestId(destId, list) {
    var address = "";
    $.each(list, function(i, value) {
        if (value.dest_id == destId) {
            address = value.address;
            return false;
        }
    });

    return address;
}

function setEnableDisableReturnAddress(elem) {
    var destination_id = $(elem).val();
    var dropdown = $('select[name=return_address_' + destination_id + ']');
    dropdown.hide();
    if ($(elem).prop('checked')) {
        dropdown.show();
    }
}


function hasDF() {
    var result = false;
    $('.check-df').each(function(index, value) {
        if ($(this).prop('checked')) {
            result = true;
            return false;
        }
    });
    return result;
}


function letterStreamModalGenerate() {
    var checkedAddressArrayList = [];
    var destinationIdList = [];
    var destinationAssocAddress = []

    $('.lbl-dest input[type=checkbox]').each(function(index, inputInstance) {
        if (inputInstance.value && inputInstance.name.indexOf('info_item[dest]') >= 0) {
            if ($(this).prop('checked')) {

                checkedAddressArrayList.push(inputInstance.value);
                var obj = {};
                var destination_id = destinationIdByAddressName(inputInstance.value).id;
                obj = { 'dest_id': destination_id, 'address': inputInstance.value };
                destinationIdList.push(destination_id)
                destinationAssocAddress.push(obj);
            }
        }
    });



    destinationIdList = array_unique(destinationIdList)

    var letter_stream_html = '<table class="table table-bordered">' +
        '<th style="width:2%;padding: 3px 15px !important;">\n\
                                            <label style="font-weight:bold;">\n\
                                            Destinations</label>\n\
                                        </th>' +
        '<th style="width:5%;padding: 3px 15px !important;">\n\
                                            <div class="checkbox">\n\
                                                <label style="font-weight:bold;">\n\
                                                    <input id="all-check-address" checked type="checkbox" onclick="letterAddressAllCheck(this)"> Addresses</label>\n\
                                            </div>\n\
                                        </th>' +
        '<th style="width:8%">\n\
                                            <div class="checkbox">\n\
                                                <label style="font-weight:bold;">\n\
                                                    Return Addresses</label>\n\
                                            </div>\n\
                                        </th>';


    $.each(destinationIdList, function(i, destId) {
        letter_stream_html += '<tr><td style="font-weight: bold;">';
        letter_stream_html += destinationNameById(destId);
        letter_stream_html += '</td><td>';
        var everyAddress = getAddressList(destId);
        var dropdownHTML = '';
        $.each(everyAddress, function(destIndex, destinationInfo) {
            if (destinationInfo != 'OTHER') {
                if (destIndex > 0) {
                    dropdownHTML += '<option value="' + destinationInfo + '">' + destinationInfo + '</option>';
                }
                var checked = ''
                var current_dest_id = destinationIdByAddressName(destinationInfo).id;
                var selectedAddress = getSelectedAddressByDestId(current_dest_id, destinationAssocAddress);
                if (selectedAddress == destinationInfo) {
                    checked = 'checked';
                }
                var data_value = destinationInfo;
                var title = destinationInfo;
                letter_stream_html += '<div class="checkbox"><label><input onclick="currentAddress()" class="letter-address-popup" ' + checked + ' type="checkbox" value="' + data_value + '" name="letter_stream_address[]"> ' + title + '</label></div>';
            }
        });

        letter_stream_html += '</td><td>';
        letter_stream_html += '<div class="row">';
        letter_stream_html += '<div class="col-md-5">';

        letter_stream_html += '<div class="checkbox">' +
            '<label style="font-weight:bold;">' +
            '<input value="' + destId + '" name="checkbox_return_address_' + destId + '" type="checkbox" onclick="setEnableDisableReturnAddress(this)"> Set return address\n\
                                    </label>' +
            '</div>';

        letter_stream_html += '</div>';
        letter_stream_html += '<div class="col-md-7" style="margin-top:7px">';
        letter_stream_html += '<select name="return_address_' + destId + '" class="form-control" style="height: 27px;padding: 3px 10px;border-radius: 0;display:none;">'
        letter_stream_html += dropdownHTML;
        letter_stream_html += '</select>';
        letter_stream_html += '</div>';
        letter_stream_html += '</div>';
        letter_stream_html += '</td></tr>';
    });

    if (hasDF()) {
        letter_stream_html += '<tr><td style="font-weight: bold;">';
        letter_stream_html += 'Data Furnisher';
        letter_stream_html += '</td><td>';
        letter_stream_html += '<div class="checkbox"><label><input checked type="checkbox" value="1" name="isDFchecked"> All Data Furnisher Addresses</label></div>';
        letter_stream_html += '</td><td></td></tr>';
    }

    letter_stream_html += '</table>';
    $('.letter-stream-content').html(letter_stream_html);
    if ($('.letter-stream-content').children().length == 0) {}
    letterStreamAllCheck();
    $('#letter-stream-modal').modal('show');
}

$('#before-save').click(function(e) {

    if ($('input[name=set_schedule]').prop('checked')) {
        var next_sending_email_date = $('input[name=next_sending_email_date]').val();
        var letter_send_date_tmezone = $('select[name=letter_send_date_tmezone]').val();
        var letter_type = $('select[name=letter_type]').val();
        if (!next_sending_email_date) {
            alert("Please select schedule date/time");
            return
        }
        if (letter_send_date_tmezone == 0) {
            alert("Please select timezone");
            return
        }

        if (letter_type == 0) {
            alert("Please select a letter set");
            return
        }

    }

    if ($('input[name=set_automation]').prop('checked')) {
        var day_value = $('input[name=day_value]').val();
        if (day_value) {
            if (day_value == 0 || /\D/g.test(day_value)) {
                alert('Please enter valid days for Setup Automation.');
                return
            }
        } else {
            alert("Please enter days of Setup Automation.");
            return
        }
    }

    if (hasLetterStream()) {
        $('#before-saving-modal').modal('hide');
        letterStreamModalGenerate();
    } else {

        $('input[name=isLetterStream]').val(0);
        var btnValue = $(this).val();
        var formData = new FormData(document.getElementById("lg-form"));
        var download_type = $('input[name=download_type]:checked').val();
        var download_category = false;
        $('.download-category').each(function() {
            if ($(this).prop('checked') && $(this).val() > 0) {
                download_category = true;
                return false;
            }
        })

        console.log(download_type)
        console.log(download_category)
        console.log(btnValue)

        //return false;
        if (btnValue == 3) { // save & generate

            $('#lg-form').append('<input type="hidden" name="formAction" value="generate"/>');

            if (download_type == 1) { // zip download
                $('#before-saving-modal').modal('hide');
                $('#lg-form').data('id', 1);
                $('#lg-form').submit();
                return true
            } else if (download_type == 2 && download_category) { // sent ur resource
                formData.append('formaction', 'generate');
                ajaxRequest(formData, btnValue);
                return false;
            } else if(download_type == 3){
                formData.append('save_letter', 1);
                formData.append('formaction', 'generate');
                ajaxRequest(formData, 0);

            } else {
                alert("Please choose item");
            }
        } else if (btnValue == 2) { // create new copy
            $('#lg-form').append('<input type="hidden" name="action" value="create_new"/>');
            if (download_type == 1) { // zip download
                $('#before-saving-modal').modal('hide');
                //$('#lg-form').submit();
                return false;
            } else if (download_type == 2 && download_category) { // sent ur resource
                formData.append('formaction', 'create_new');
                ajaxRequest(formData, btnValue);

            } else {
                alert("Please select category");
            }

        } else if (btnValue == 1) { // only save
            formData.append('formaction', 'ajax');
            formData.append('download_type', '0');
            ajaxRequest(formData, btnValue);
        }

    }


});

function uploadphotos(elem, isAccount = true) {
    // Read in file

    var url = $(elem).val();
    var image_file_id = $(elem).prop('id');
    if (isAccount) {
        var image_file_only_id_no = image_file_id.replace('content_file_', '');
        $('input[name=letter_image_' + image_file_only_id_no + ']').val('');
        $('#isImageChange_' + image_file_only_id_no).val(0);
    } else {
        var image_file_only_id_no = image_file_id.replace('attachment_img_', '');
        $('input[name=attach_image_file_' + image_file_only_id_no + ']').val('');
        $('#isAttImageChange_' + image_file_only_id_no).val(0);
    }
    var file = "";
    if (url != "") {
        file = event.target.files[0];
        let text_type = 'Oops! Please upload a jpeg or Png type of image only.';
        if (file.type.match(/image.*/)) {
            ////console.log('An image has been loaded');
            //alert(12);
            // Load the image
            var reader = new FileReader();
            reader.onload = function(readerEvent) {
                var image = new Image();
                image.onload = function(imageEvent) {

                    // Resize the image
                    var canvas = document.createElement('canvas'),
                        max_size = 300, // TODO : pull max size from a site config
                        width = image.width,
                        height = image.height;

                    canvas.width = width;
                    canvas.height = height;
                    canvas.getContext('2d').drawImage(image, 0, 0, width, height);
                    var dataUrl = canvas.toDataURL('image/jpeg');
                    if (isAccount) {
                        $("#letter_img_" + image_file_only_id_no).attr('src', dataUrl);
                        $('#letter_image_file_' + image_file_only_id_no).val(dataUrl)
                        $('#isImageChange_' + image_file_only_id_no).val(2);
                    } else {
                        $('#att_image_' + image_file_only_id_no).attr('src', dataUrl);
                        $('#attach_image_file_' + image_file_only_id_no).val(dataUrl);
                        $('#isAttImageChange_' + image_file_only_id_no).val(2);
                        $('#isUploadMedia_' + image_file_only_id_no).val(0);
                    }
                }
                image.src = readerEvent.target.result;
            }
            reader.readAsDataURL(file);
        } else {
            Swal.fire({icon: 'error',title: text_type,width: 450});
            $(elem).val('');
        }
    }
}

function clearAttImage(value) {

    $('#att_image_' + value).attr('src', '');
    $('#attachment_img_' + value).val('');
    $('#attach_image_file_' + value).val('');
    $('#isAttImageChange_' + value).val(1);
    $('#isUploadMedia_' + value).val(0);
}


function setSelectDataForEdit() {
    var letter_types = $('select[name="info_item[letter_type][]"]').map(function() {
        if (!$(this).val()) {
            var id = $(this).prop('id');
            var key = id.replace('dtype-', '');
            showTemplate(this, key)
        }
        //return $(this).val()
    }).get();
    console.log('letter_types', letter_types);

}

function waveChange(url) {
    var client_id = $('select[name=client_id]').val();
    var choose_work = $('select[name=choose_work]').val();
    if (client_id && choose_work) {
        getClient(url);
    }
}

$('input[name=set_automation]').click(function() {
    $('.setup-automation').hide();
    $('input[name=day_value]').val('');
    $('select[name=automation_type]').val(1).trigger('change');
    if ($(this).prop('checked')) {
        $('.setup-automation').show();
    }
})

