// test rsync 03
//var REPORT_DATE = "";
var PERSONAL_INFO = [];
var SELECTED_ASSOC = "";
var PRIVACY_GUARD_RESULTS = [];
var DEFAULT_SOURCE_TYPE = 1;
var BANK_ASSOC_BY_ACCOUNT_NUMBER = {};
var SAME_BANK_ASSOC_BY_ACCOUNT_NUMBER = {};
var BANK_ASSOC_ACCOUNT_INFO = {};
var BANK_ASSOC_ACCOUNT_CHANGE_INFO = {};
var SAME_BANK_ACC_NO_TYPE_ASSOC = {};
var isFirstReport = false;
var isTextAreaChanged = 0;
var is_import_show_analyzer = false;
var last_record_history_id = 0;
var ALL_KEY_INFOS = [];
var IS_RECENT_REPORT = false;
var CURRENT_ACCOUNT_DB_KEY_ASSOC = {};
var IS_NEW_REPORT_UPLOAD = 0;
var procesed_bank_name_ids = [];
var only_for_new_report_upload = 0;

$('button[name=checkConsole]').click(function() {
    checkconsoleFunction($(this));
});

function newReportCondition() {
    $('input[name=is_same_code]').val(0);
    $('button[name=credit_analyzer]').show();
    isFirstReport = true;
    IS_CHANGE_DROPDOWN = true;
    only_for_new_report_upload = 1;
}

//keyup paste keypress keydown cut blur textarea[name=html_content]
$('textarea[name=new_html_content]').on('change,keyup paste keypress keydown cut blur', function() {
    newReportCondition()
})

$('button[name=new_process_html]').click(function() {
    IS_NEW_REPORT_UPLOAD = 1;
    var new_html = $('textarea[name=new_html_content]').val();
    if (new_html) {
        $('textarea[name=html_content]').val(new_html);
        uploadHTMLUICode(new_html);
        $('#new-report-modal').modal('hide');
    } else {
        alert("Please put your html code.");
    }
})



function uploadCreditReportCoreFunction(elem, isVelocity) {

    IS_CHANGE_DROPDOWN = false
    currentAnalysis()
    var client_id = $('#client_id').val();
    if ($('#client-contact-id option:selected').data('id') > 0) {
        client_id = $('#client-contact-id option:selected').data('id');
    }
    var source_type = $('select[name=source_type]').val();
    if (isVelocity) {
        source_type = DEFAULT_SOURCE_TYPE;
    }

    var is_save_loder_2 = false;
    var btn_name = $(elem).attr('name');
    var ajax_loader = $(elem).data('loader');
    if (btn_name == 'credit_btn') {
        $('#credit-loader').show();
    } else {
        $('#' + ajax_loader).show();
        is_save_loder_2 = true;
    }
    var credit_score_data = getCreditScoreData();
    var history_code_data = saveCode();

    var formData = {};
    if (client_id == "") {
        alert('Please select Client');
        $('select[name=client_id]').parent().addClass('has-error');
    } else {
        var html_content = "";
        var client_id = $('#client_id').val();
        if (isVelocity && $('#client-contact-id option:selected').data('id') > 0) {
            client_id = $('#client-contact-id option:selected').data('id');
        }
        var tables = document.getElementsByClassName("rpt_content_table");

        var delete_all_input = $('input[name=delete_all]');
        var delete_all = 0;
        if (delete_all_input.prop('checked')) {
            delete_all = 1;
        }

        html_content = $('textarea[name=html_content]').val();
        var current_report_date = getReportDateCurrent();

        var summary = {};
        if (source_type == 1) {
            var pInfo = getPersonalInfoWithDropDownData();
            var bankInfo = getBankTableInfo();
            var inq = getSelectedInquiries();
            var publicInfo = getSelectedPublicInfo();
            summary = getIQSummary();
            var fullsummary = getFullIQSummary();
            //sameKeyBankConstantUpdate()
            formData = {
                'client_id': client_id,
                'delete_all': delete_all,
                'source_type': source_type,
                'PERSONAL_INFO_DATA': pInfo,
                'inquiries': inq,
                'publicInfo': publicInfo,
                'html_content': html_content,
                'outputBankAcc': bankInfo,
                'outputBankInfo': bankInfo,
                'credit_score': credit_score_data,
                'history_code_data': history_code_data,
                'inquires_analysis': INQURIES_RECORD_INFO_CREDIT_ANALYSIS,
                'publicInfo_analysis': PUBLIC_RECORD_INFO_CREDIT_ANALYSIS,
                'credit_analysis_bank': NEGATIVE_ITEM_SELECTED_LIST_CREDIT_ANALYSIS,
                'fullsummary': fullsummary,
                'SAME_BANK_ACC_NO_TYPE_ASSOC': SAME_BANK_ACC_NO_TYPE_ASSOC
            };

        } else if (source_type == 2) {
            var privacyGuard_info = getPrivacyGuardBankTableInfo();
            var personl_info = getDropDownPrivacyGuardPersonalInfo()
            var inq = getDropDownInquiryPrivacyGuard();
            var publicInfo = getDropDownPublicRecordPrivacyGuard()
            formData = {
                'client_id': client_id,
                'delete_all': delete_all,
                'source_type': source_type,
                'inquiries': inq,
                'publicInfo': publicInfo,
                'html_content': html_content,
                'privacyGuardBank': privacyGuard_info,
                'PERSONAL_INFO_DATA': personl_info,
                'credit_score': credit_score_data,
                'history_code_data': history_code_data
            };
        } else if (source_type == 3) {
            var pInfo = getSmartCreditPersonalInfo();
            var bankInfo = getSmartCreditBankInfo();
            summary = getSCSummary();
            var inq = getSmartCreditInquiries();
            var publicInfo = getSmartCreditPublicDropdownData();
            formData = {
                'client_id': client_id,
                'delete_all': delete_all,
                'source_type': source_type,
                'PERSONAL_INFO_DATA': pInfo,
                'inquiries': inq,
                'publicInfo': publicInfo,
                'html_content': html_content,
                'outputBankAcc': bankInfo,
                'outputBankInfo': bankInfo,
                'credit_score': getCreditScoreForSmartCredit(),
                'history_code_data': history_code_data,
                'inquires_analysis': INQURIES_RECORD_INFO_CREDIT_ANALYSIS,
                'publicInfo_analysis': PUBLIC_RECORD_INFO_CREDIT_ANALYSIS,
                'credit_analysis_bank': NEGATIVE_ITEM_SELECTED_LIST_CREDIT_ANALYSIS,
            };
        }
    }

    var creditor_contacts_assoc = getAllCreditorContactsByName();
    formData['creditor_contacts'] = creditor_contacts_assoc;
    if ($('#main-html-area select[name="public_address_dropdown"]').val()) {
        var temp_obj = {
            'creditor_name': $('#main-html-area select[name="public_address_dropdown"] option:selected').data('key'),
            'creditor_address': $('#main-html-area select[name="public_address_dropdown"] option:selected').data('value')
        };

        formData['public_record_address'] = temp_obj;
    }
    var creditor_inq_selected_contacts = {};
    $('#main-html-area select.inq-address-dropdown').each(function() {
        var current_dropdown = $(this).children("option:selected");
        if (current_dropdown.val()) {
            var creditor_name = current_dropdown.data('key');
            var address = current_dropdown.val();
            creditor_inq_selected_contacts[creditor_name] = address;
        }
    })
    formData['creditor_inq_selected_contacts'] = creditor_inq_selected_contacts;
    if (source_type == 3) {
        formData['creditor_contacts'] = getSmartCreditBankNameAddressAssoc()
    }

    formData['summary'] = summary;
    formData['step_status'] = $('input[name=step_status]').val();
    formData['history_id'] = history_id;
    formData['is_from_history'] = is_from_history;
    formData['is_one_report'] = 0;
    formData['is_multiple_report_not_last'] = 0;
    if (typeof(is_one_report) != "undefined" && is_one_report !== null) {
        formData['is_one_report'] = is_one_report;
    }

    if (typeof(is_multiple_report_not_last) != "undefined" && is_multiple_report_not_last !== null) {
        formData['is_multiple_report_not_last'] = is_multiple_report_not_last;
    }

    formData['inserted_history_id'] = $('input[name=temp_history_tbl_id]').val();
    formData['is_same_code'] = $('input[name=is_same_code]').val();

    var saved_report_date = localStorage.getItem('REPORT_DATE');
    if (saved_report_date && current_report_date != saved_report_date) {
        //alert('changed');
        //        console.log('html_content',saved_report_date);
        //        console.log('db_html_content',current_report_date);
        isTextAreaChanged = 1;
        //hasHistory = true;
        //$('button[name=credit_analyzer]').show();
    }

    formData['isTextAreaChanged'] = isTextAreaChanged;
    formData['is_newly_insert'] = 0;
    if($('input[name=isHistory]').prop('checked')){
        formData['is_newly_insert'] = 1;
    }
    if(only_for_new_report_upload){
        formData['history_id'] = 0;
    }
    console.log('formData',formData);
    //return false;
    //alert(saveIdentityID);
    if ($(elem).hasClass('rtg-save-btn-top')) {
        $('#save-loader').show();
    } else {
        if (is_save_loder_2) {
            $('#save-loader-2').show();
        }

    }

    $('#full-page-loader').show();

    $.ajax({
        type: "POST",
        data: formData,
        url: saveIdentityID,
        success: function(data) {
            $('#full-page-loader').hide();
            $('input[name=isHistory]').prop('checked', false).show().parents('.checkbox').first().show();
            if (!hasHistory) {
                //hasHistory = true;
                $('button[name=credit_analyzer]').show();
            }
            //$('input[name=isHistory]').parents('.checkbox').first().show();
            $('#' + ajax_loader).hide();
            $('#save-loader-2').hide();
            $('#credit-loader').hide();
            $('#save-loader').hide();

            data = $.trim(data);
            data = JSON.parse(data);
            //console.log('data',data);
            var inserted_history_id = data.inserted_history_id;
            if (inserted_history_id > 0) {
                $('input[name=is_same_code]').val(1);
            }
            $('input[name=temp_history_tbl_id]').val(inserted_history_id);
            var is_credit_report_uploaded = data.is_credit_report_uploaded;
            data = data.message;

            if (data == "success") {
                setReportDate(html_content)
                if (btn_name == 'credit_btn') {
                    var name = $('select[name=client_id]').children('option:selected').data('name');
                    $('input[name=f_l_name]').val(name);
                    var current_date = new Date();
                    var formatedDate = moment(current_date).format('YYYY-MM-DD');
                    $('input[name=date_audit]').val(formatedDate)
                    $('input[name=credit_client_id]').val(client_id);
                    $('input[name=credit_source_type]').val(source_type);
                    var source_name = "";
                    if (source_type == 1) {
                        source_name = "Identitiy IQ";
                    } else if (source_type == 2) {
                        source_name = "Privacy Guard";
                    }

                    $('input[name=credit_report_and_date]').val(source_name + ' report dated ' + formatedDate + ' per ' + source_name);
                    $('#credit-analaysis').css({ display: 'block', overflow: 'auto' }).addClass('in');
                } else {
                    if (is_credit_report_uploaded) {
                        $('input[name=step_status]').val(1);
                        Swal.fire({
                            width: '40rem',
                            text: "Amazing Job! You have Completed your Initial setup",
                            icon: 'warning',
                            showCancelButton: false,
                            confirmButtonColor: '#3085d6',
                            cancelButtonColor: '#d33',
                            confirmButtonText: 'Ok',
                        }).then((result) => {
                            if (result.value) {
                                window.location.href = SERVER_HTTP_HOST + "statistics";
                            }
                        })
                    } else {

                        var isReload = $('input[name=isReload]').val();
                        alert("Report has been processed successfully!");
                        is_import_show_analyzer = true;
                        if (isReload == 1) {
                            $('#show-credit-report-modal').modal('hide');
                            location.reload();
                        }
                    }
                    if (isVelocity) {
                        //$('#client-html').modal('hide');
                        $('.client-html-close').click();
                    }

                }

            } else if (data == "history") {
                alert("You have " + HTML_SAVE_COUNT + " records saved already for this client.");
            } else {
                alert(data);
            }

        },
        error: function() {
            $('#full-page-loader').hide();
            alert("Failed. Try again later.111");
        }
    });
}


function analyzerClose() {
    $('#credit-analyzer').modal('hide');
    uploadCreditReportCoreFunction($('button[name=checkConsole]'), false)
}

function checkconsoleFunction(elem, isVelocity = false) {
    var is_same_code = $('input[name=is_same_code]').val();
    //    if(is_from_history == 1 && is_one_report == 0){
    //        is_same_code == 0;
    //    }

    if (is_same_code == 0) {
        Swal.fire({
            width: '40rem',
            text: "Congratulations! would you like to create your credit analyzer report now ?",
            icon: 'warning',
            showCancelButton: true,
            confirmButtonColor: '#3085d6',
            cancelButtonColor: '#d33',
            confirmButtonText: 'Yes',
            cancelButtonText: 'No'
        }).then((result) => {

            if (result.value) {
                creditAnalyzer();
            } else {
                uploadCreditReportCoreFunction(elem, isVelocity);
                //                Swal.fire({
                //                    width: '40rem',
                //                    text: "Opps! Are you sure this will eliminate your credit analyzer report ?",
                //                    icon: 'warning',
                //                    showCancelButton: true,
                //                    confirmButtonColor: '#3085d6',
                //                    cancelButtonColor: '#d33',
                //                    confirmButtonText: 'Yes',
                //                    cancelButtonText: 'No'
                //                }).then((result) => {
                //                    
                //                })
            }

        })

    } else {
        Swal.fire({
            width: '40rem',
            text: "Congratulations! You saved your report, would you like to continue ?",
            icon: 'warning',
            showCancelButton: true,
            confirmButtonColor: '#3085d6',
            cancelButtonColor: '#d33',
            confirmButtonText: 'Yes',
            cancelButtonText: 'No'
        }).then((result) => {
            if (result.value) {
                uploadCreditReportCoreFunction(elem, isVelocity)
            }

        })
    }


}


function getCreditScoreForSmartCredit() {
    var obj = {}
    $('#main-html-area #TokenDisplay').children('table').first().each(function(i, el) {
        var tds = $(this).find('td b');
        var tranScore = getTextValueFromTdByColumn(tds, 1);
        var expScore = getTextValueFromTdByColumn(tds, 2);
        var eqfScore = getTextValueFromTdByColumn(tds, 3);
        obj = { 'TransUnion': tranScore, 'Experian': expScore, 'Equifax': eqfScore };
    })
    return obj;
}

function getSmartCreditPersonalInfo() {
    var personal_info = [];
    var personal_info_tbl = $('#main-html-area #personalInfo:contains(Personal Information)').parents('table').next('table');
    var personalInfo = [];
    personal_info_tbl.find('tr').each(function(i, el) {
        if (i == 0)
            return;
        var $tds = $(this).find('td');
        var $key_tds = $(this).find('td span b');
        var key = $key_tds.eq(0).clone().children().remove().end().text().replace(/<(?:.|\n)*?>/gm, '');
        var obj = {};
        var text1 = "";
        var text2 = "";
        var text3 = "";
        if (key != "") {
            var tq_eq_1 = $tds.eq(1);
            text1 = tq_eq_1.clone().children().remove().end().text().replace(/<(?:.|\n)*?>/gm, '');
            if (tq_eq_1.has('span').length) {
                text1 = tq_eq_1.children('span').text().replace(/<(?:.|\n)*?>/gm, '');
            }
            text1 = text1.replace(/\r?\n|\r/g, '');
            text1 = text1.replace('_', '');
            text1 = text1.replace('-', '');
            text1 = text1.replace(/\s+/g, " ");
            text1 = $.trim(text1);
            text1 = text1.replace('updatenegativepositive', '');

            var tq_eq_2 = $tds.eq(2);

            text2 = tq_eq_2.clone().children().remove().end().text().replace(/<(?:.|\n)*?>/gm, '');
            if (tq_eq_2.has('span').length) {
                text2 = tq_eq_2.children('span').text().replace(/<(?:.|\n)*?>/gm, '');
            }
            text2 = text2.replace(/\r?\n|\r/g, '');
            text2 = text2.replace('_', '');
            text2 = text2.replace('-', '');
            text2 = text2.replace(/\s+/g, " ");
            text2 = $.trim(text2);
            text2 = text2.replace('updatenegativepositive', '');

            var tq_eq_3 = $tds.eq(3);
            text3 = tq_eq_3.clone().children().remove().end().text().replace(/<(?:.|\n)*?>/gm, '');
            if (tq_eq_3.has('span').length) {
                text3 = tq_eq_3.children('span').text().replace(/<(?:.|\n)*?>/gm, '');
            }
            text3 = text3.replace(/\r?\n|\r/g, '');
            text3 = text3.replace('_', '');
            text3 = text3.replace('-', '');
            text3 = text3.replace(/\s+/g, " ");
            text3 = $.trim(text3);
            text3 = text3.replace('updatenegativepositive', '');

            var key_name = key.replace(/<(?:.|\n)*?>/gm, '');
            key_name = key.replace(/\r?\n|\r/g, '');
            key_name = key.replace(':', " ");
            key_name = key.replace(/\s+/g, " ");
            key_name = $.trim(key);

            var select_type1 = "3";
            var select_type2 = "3";
            var select_type3 = "3";

            if ($tds.eq(1).children('select').val()) {
                select_type1 = $tds.eq(1).children('select').val();
            }

            if ($tds.eq(2).children('select').val()) {
                select_type2 = $tds.eq(2).children('select').val();
            }

            if ($tds.eq(3).children('select').val()) {
                select_type3 = $tds.eq(3).children('select').val();
            }
            obj = {
                'TransUnion': { data: text1, 'type': select_type1, 'key_name': key_name.replace(':', '') },
                'Experian': { data: text2, 'type': select_type2, 'key_name': key_name.replace(':', '') },
                'Equifax': { data: text3, 'type': select_type3, 'key_name': key_name.replace(':', '') },
            }

            personal_info.push(obj);

        }
    });

    return personal_info;
}


function setbank_address_dropDown_html_smart_credit(elem, len, bank_name, key_bank, db_data) {

    var bankList = [];
    var temp_array = [];
    var final_bank_assoc = [];
    var bank_address_dropDown_html = "<select onchange='addressOnchangeIQ(" + len + ",this)' style='color:black' class='scd' id='bank_address_" + len + "' name='bank_addresses[" + len + "]'>";
    var all_crditors_contacts_smart_credit = creditorContactsSmartCredit()
    var all_crditors_contacts_smart_credit_assoc = [];
    if (all_crditors_contacts_smart_credit) {
        $.each(all_crditors_contacts_smart_credit, function(j, jval) {
            var tbank_name = jval.address;
            tbank_name = tbank_name.replace(/\r?\n|\r/g, '');
            tbank_name = tbank_name.replace('_', '');
            tbank_name = tbank_name.replace('-', '');
            tbank_name = tbank_name.replace(/\s+/g, " ");
            if (jval.bank_name) {
                all_crditors_contacts_smart_credit_assoc.push({ 'bank': jval.bank_name, 'address': $.trim(tbank_name) })
            }
        })
    }

    var checked = '';
    $('#main-html-area .crWhiteTradelineHeader b').each(function(i, el1) {
        var bank = $.trim($(this)
            .clone() //clone the element
            .children() //select all the children
            .remove() //remove all the children
            .end() //again go back to selected element
            .text().replace(/<(?:.|\n)*?>/gm, ''));

        if (bank) {
            bankList.push(bank);
        }

    });

    $('#main-html-area .crWhiteTradelineHeader b').each(function(i, el1) {
        var bank = $.trim($(this)
            .clone() //clone the element
            .children() //select all the children
            .remove() //remove all the children
            .end() //again go back to selected element
            .text().replace(/<(?:.|\n)*?>/gm, ''));
        var temp_bank = bank;
        var endDropdownClass = 'smart-cerdit-subAccount-history-' + i;
        temp_array.push(bank);

        var bank = bank + getKeyIndex(temp_bank, temp_array, bankList);

        if (bank) {
            if (all_crditors_contacts_smart_credit_assoc[temp_bank]) {
                final_bank_assoc[bank] = all_crditors_contacts_smart_credit_assoc[temp_bank];
            }

        }

    });
    console.log('all_crditors_contacts_smart_credit_assoc',all_crditors_contacts_smart_credit_assoc)
    all_crditors_contacts_smart_credit_assoc = all_crditors_contacts_smart_credit_assoc.sort(SortArray)
    bank_address_dropDown_html += '<option data-value="" value="">Please select</option>';
    if (all_crditors_contacts_smart_credit_assoc) {
        $.each(all_crditors_contacts_smart_credit_assoc, function(index, value1) {
            var value = value1.address;
            if (value) {
                checked = "";
                var temp_bank = value1.bank;

                var bankNameArray = temp_bank.split('-');
                $.each(bankNameArray, function(i, value1) {
                    var index1 = value1;
                    if (index1 != null && index1 >= 1 && index1 <= 100) {
                        temp_bank = temp_bank.replace("-" + index1, "");
                        return false;
                    }
                });
                if ($.trim(index) == $.trim(key_bank)) {
                    checked = 'selected';
                }
                bank_address_dropDown_html += '<option data-key="' + index + '" data-value="' + value + '" value="' + value + '" ' + checked + '>' + temp_bank + " - " + value + '</option>';
            }
        });
        bank_address_dropDown_html += '</select>';
    }
    $(elem).append('&nbsp;&nbsp;' + bank_address_dropDown_html);
}

function getSmartCreditBankInfo() {
    var bankInfo = [];
    // imran bank info
    $('#main-html-area .crWhiteTradelineHeader b').each(function(i, el1) {
        var bank = $.trim($(this)
            .clone() //clone the element
            .children() //select all the children
            .remove() //remove all the children
            .end() //again go back to selected element
            .text());

        var endDropdownClass = 'smart-cerdit-subAccount-history-' + i;

        if (bank) {

            var transType = 3;
            var equfType = 3;
            var expType = 3;
            var creditorObj = getSmartCreditAddressPhoneByBankName(bank);
            var current_bankInfo = [];
            var current_table = $(this).parent().parents('table').first().next('table').find('table.crLightTableBackground');
            current_table.find('tr').each(function(j, el2) {
                var obj = {};
                var tds = $(this).find('td');
                var key_tds = $(this).find('td b');
                var title = $.trim(key_tds.eq(0)
                    .clone() //clone the element
                    .children() //select all the children
                    .remove() //remove all the children
                    .end() //again go back to selected element
                    .text());
                var experian = getTextValueFromTdByColumn(tds, 2);
                var equifax = getTextValueFromTdByColumn(tds, 3);
                var trans = getTextValueFromTdByColumn(tds, 1);
                var text1 = "";
                var text2 = "";
                var text3 = "";

                if (experian && experian != 'Experian') {

                    text2 = tds.eq(2).text().replace(/<(?:.|\n)*?>/gm, '');
                    text2 = text2.replace(/\r?\n|\r/g, '');
                    text2 = replaceAll(text2, '_', '');
                    text2 = replaceAll(text2, '-', '');
                    text2 = text2.replace(/\s+/g, " ");
                    text2 = $.trim(text2);
                    text2 = text2.replace('updatenegativepositive', '');
                } else if (experian && experian == 'Experian') {
                    if (tds.eq(2).children('select').val()) {
                        expType = tds.eq(2).children('select').val();
                    }
                }

                if (equifax && equifax != 'Equifax') {

                    text3 = tds.eq(3).text().replace(/<(?:.|\n)*?>/gm, '');
                    text3 = text3.replace(/\r?\n|\r/g, '');
                    text3 = replaceAll(text3, '_', '');
                    text3 = replaceAll(text3, '-', '');
                    text3 = text3.replace(/\s+/g, " ");
                    text3 = $.trim(text3);
                    text3 = text3.replace('updatenegativepositive', '');
                } else if (equifax && equifax == 'Equifax') {
                    if (tds.eq(3).children('select').val()) {
                        equfType = tds.eq(3).children('select').val();
                    }
                }

                if (trans && trans != 'TransUnion') {

                    text1 = tds.eq(1).text().replace(/<(?:.|\n)*?>/gm, '');
                    text1 = text1.replace(/\r?\n|\r/g, '');
                    text1 = replaceAll(text1, '_', '');
                    text1 = replaceAll(text1, '-', '');
                    text1 = text1.replace(/\s+/g, " ");
                    text1 = $.trim(text1);
                    text1 = text1.replace('updatenegativepositive', '');
                } else if (trans && trans == 'TransUnion') {
                    if (tds.eq(1).children('select').val()) {
                        transType = tds.eq(1).children('select').val();
                    }
                }
                if (title) {
                    obj = {
                        'TransUnion': { account: text1, 'key_name': title },
                        'Experian': { account: text2, 'key_name': title },
                        'Equifax': { account: text3, 'key_name': title },
                    }

                    current_bankInfo.push(obj);
                }
            });
            var address = "";
            var phone = "";
            if (creditorObj.hasOwnProperty('address') && creditorObj.address) {
                address = creditorObj.address
            }
            if ($('#main-html-area select[name="bank_addresses[' + i + ']"]').find('option:selected').data('value')) {
                address = $('#main-html-area select[name="bank_addresses[' + i + ']"]').find('option:selected').data('value');
            }
            if (creditorObj.hasOwnProperty('phone') && creditorObj.phone && creditorObj.phone != "BYM-AIL-ONLY") {
                phone = creditorObj.phone
            }
            var type = {
                'TransUnion': transType,
                'Experian': expType,
                'Equifax': equfType,
            }
            bankInfo.push({ 'bank_name': bank, 'bank_info': current_bankInfo, 'address': address, 'phone': phone, 'type': type });
        }
    });
    return bankInfo;
}

function getSmartCreditBankNameAddressAssoc() {
    var newObj = {};
    var creditorInfo = creditorContactsSmartCredit();
    for (var i in creditorInfo) {
        if (creditorInfo[i].bank_name && creditorInfo[i].address) {
            newObj[creditorInfo[i].bank_name] = creditorInfo[i].address;
        }
    }
    //objectKeySortAlphabetically(result)
    
    return newObj;
}

function getSmartCreditAddressPhoneByBankName(bank_name) {
    var obj = "";
    var creditorInfo = creditorContactsSmartCredit();
    for (var i in creditorInfo) {
        if (creditorInfo[i].bank_name == bank_name) {
            obj = creditorInfo[i];
            break;
        }
    }

    return obj;
}

function creditorContactsSmartCredit() {
    var contactInfo = [];
    var creditor_tbl = $("#main-html-area td").filter(function() {
        var current_text = $(this).text().replace(/<(?:.|\n)*?>/gm, '');
        current_text = current_text.replace(/\r?\n|\r/g, '');
        current_text = $.trim(current_text);
        return current_text == "Creditor Contacts" && $(this).attr('style');
    }).parents('table[border = 1]').first().next('table').next('table');

    creditor_tbl.find('tr').each(function(i, el) {
        var key_tds = $(this).find('td').children('table').each(function() {
            var tds = $(this).find('tr td');
            var obj = {};
            var bank_name = getTextValueFromTdByColumn(tds, 1);
            var address = "";
            var phone = "";
            if (getTextValueFromTdByColumn(tds, 2)) {
                address = getTextValueFromTdByColumn(tds, 2);
            }

            if (getTextValueFromTdByColumn(tds, 3)) {
                phone = getTextValueFromTdByColumn(tds, 3);
            }

            if (bank_name) {
                obj = {
                    'bank_name': bank_name,
                    'address': address,
                    'phone': phone
                }
                contactInfo.push(obj);
            }
        });
    });
    return contactInfo;
}

function getBankAdditionalInfo(bankName) {
    var table = bankName;


}



function setDropDownforPersonalInfo(data) {
    var assocDB = [];

    var table = $('#main-html-area table.rpt_content_table:eq(1)');
    //var table = $('table.rpt_content_table:eq(0)');

    table = $('#main-html-area div.rpt_fullReport_header:contains("Personal Information")').nextAll('table.rpt_content_table').first();
    var personalInfo = [];
    table.find('tr').each(function(i, el) {
        var $tds = $(this).find('td');
        var key = $tds.eq(0).text();
        var key = $tds.eq(0).text();
        if (key != "") {
            var text1 = $tds.eq(1).text().replace(/<(?:.|\n)*?>/gm, '');
            text1 = text1.replace(/\r?\n|\r/g, '');
            text1 = text1.replace('_', '');
            text1 = text1.replace('-', '');
            text1 = text1.replace(/\s+/g, " ");
            text1 = text1.trim();
            text1 = text1.replace('updatenegativepositive', '');
            var text2 = $tds.eq(2).text().replace(/<(?:.|\n)*?>/gm, '');
            text2 = text2.replace(/\r?\n|\r/g, '');
            text2 = text2.replace('_', '');
            text2 = text2.replace('-', '');
            text2 = text2.replace(/\s+/g, " ");
            text2 = text2.trim();
            text2 = text2.replace('updatenegativepositive', '');
            var text3 = $tds.eq(3).text().replace(/<(?:.|\n)*?>/gm, '');
            text3 = text3.replace(/\r?\n|\r/g, '');
            text3 = text3.replace('_', '');
            text3 = text3.replace('-', '');
            text3 = text3.replace(/\s+/g, " ");
            text3 = text3.trim();
            text3 = text3.replace('updatenegativepositive', '');
            var key_name = key.replace(/<(?:.|\n)*?>/gm, '');
            key_name = key.replace(/\r?\n|\r/g, '');
            key_name = key.replace(':', " ");
            key_name = key.replace(/\s+/g, " ");
            key_name = key.trim();
            var status = getStatusByDataKey(key_name.replace(':', ''), data);

            if (text1 != "") {
                $tds.eq(1).append(htmlstring());

                var status3 = 3;
                if (status != "") {
                    status3 = status.status3
                }
                $tds.eq(1).children('select').val(status3).trigger('change');
                $tds.eq(1).children('select').attr('class', 'all-select review_type');
            }
            if (text2 != "") {
                $tds.eq(2).append(htmlstring());
                var status1 = 3;
                if (status != "") {
                    status1 = status.status1
                }
                $tds.eq(2).children('select').val(status1).trigger('change');
                $tds.eq(2).children('select').attr('class', 'all-select review_type');
            }
            if (text3 != "") {
                $tds.eq(3).append(htmlstring());
                var status2 = 3;
                if (status != "") {
                    status2 = status.status2
                }
                $tds.eq(3).children('select').val(status2).trigger('change');
                $tds.eq(3).children('select').attr('class', 'all-select review_type');
            }



        }
    });


}


function getStatusByDataKey(key, data) {
    var info = "";


    $.each(data.DB, function(index, value) {
        if (value.data_key == key) {
            info = value;
            return false;
        }

    });

    return info;
}

function getSelectedInfo(isVelocity, report_type = null) {
    
    SELECTED_ASSOC = "";
    var client_id = $('select[name=client_id]').val();
    var source_type = $('select[name=source_type]').val();

    if (isVelocity) {
        source_type = DEFAULT_SOURCE_TYPE;
        if ($('#client-contact-id option:selected').data('id') > 0) {
            client_id = $('#client-contact-id option:selected').data('id');
        }
    }

    if (client_id == "" || client_id <= 0) {
        return false;
    }

    if (report_type) {
        source_type = report_type;
    }

    var formData = { 'client_id': client_id, 'source_type': source_type }
    formData['history_id'] = history_id;
    formData['is_editable'] = is_editable;
    formData['IS_NEW_REPORT_UPLOAD'] = IS_NEW_REPORT_UPLOAD;
    procesed_bank_name_ids = [];
    $('#full-page-loader').show();
    $.ajax({
        type: "POST",
        data: formData,
        url: select_url,
        //async: true,
        success: function(data) {
            //history-checkbox
            $('#full-page-loader').hide();
            $('#full-page-loader h3').text('');
            IS_NEW_REPORT_UPLOAD = false;
            var info = JSON.parse(data);
            console.log('full_json', info)
            if(info.all_key_info){
                ALL_KEY_INFOS = info.all_key_info;
            }
            
            if(info.history_id > 0){
                history_id = info.history_id
            }
            //var json = info.datadocument;
            var db_dd_id = info.datadocument.dd_id;

            isFirstReport = info.is_first_report;
            $('input[name=is_first_report]').val(info.is_first_report)


            var json = info.datadocument;
            //var hasHistory = true;
            if (isFirstReport && history_id > 0) {
                hasHistory = false;
            }
            //console.log(info);
            SELECTED_ASSOC = json;
            CURRENT_DB_DATA = json;
            getAccountValuesByKey(json.DI);
            //console.log('CURRENT_ACCOUNT_DB_KEY_ASSOC',CURRENT_ACCOUNT_DB_KEY_ASSOC);
            if (info) {
                var DB_PUBLIC_RECORD = info.publicrecords[0];
                if (info.account_num_key_assoc_list) {
                    BANK_ASSOC_BY_ACCOUNT_NUMBER = info.account_num_key_assoc_list;
                }

                if (info.same_account_num_key_assoc_list) {
                    SAME_BANK_ASSOC_BY_ACCOUNT_NUMBER = info.same_account_num_key_assoc_list;
                }

                if (info.account_num_key_assoc_list_without_unique_key) {
                    BANK_ASSOC_ACCOUNT_INFO = info.account_num_key_assoc_list_without_unique_key;
                }
            }
            var html = bankhtmlstring();
            var appent_option = '<option value=\"6\">Repaired Accounts/Now Positive</option>';
            appent_option += '<option value=\"5\">Late Pays / 2 Or Less</option>';

            var html_account = bankhtmlstring(appent_option);
            
            getInquiriesAndPublicSelectedInfo(html, info);
            if (source_type == 1) {
                
                setDropDownforPersonalInfo(json);
                
                //$('.sub_header').append(html);
                $('#main-html-area .sub_header').next('table').find('th.headerTUC').append(html_account);
                $('#main-html-area .sub_header').next('table').find('th.headerEXP').append(html_account);
                $('#main-html-area .sub_header').next('table').find('th.headerEQF').append(html_account);

                $('#main-html-area #PublicInformation .sub_header').next('table').find('th.headerTUC').children('select').remove();
                $('#main-html-area #PublicInformation .sub_header').next('table').find('th.headerEXP').children('select').remove();
                $('#main-html-area #PublicInformation .sub_header').next('table').find('th.headerEQF').children('select').remove();

                $('#main-html-area .sub_header').each(function() {
                    var rf = $(this).clone().children().remove().end().text();
                    rf = rf.replace('updatenegativepositive', '');
                    rf = rf.replace('Please selectnegativepositive', '');
                    rf = $.trim(rf);
                    if (rf == 'Risk Factors') {
                        $(this).children('select').remove();
                    }
                    if (rf == 'Bankruptcy') {
                        $(this).next('table').find('th').children('select').remove();
                    }
                    //console.log('DB_PUBLIC_RECORD',DB_PUBLIC_RECORD,rf)
                    if (DB_PUBLIC_RECORD) {
                        if (rf == DB_PUBLIC_RECORD.public_title) {
                            var public_tbl = $(this).next('table');
                            public_tbl.find('tr.rowAlt').each(function(i1, el) {
                                var tr = $(this);
                                var first_child = tr.find('td.info').eq(0).children('select');
                                if (first_child) {
                                    //tr.find('td.info').eq(0).html('');
                                    //tr.find('td.info').eq(0).append(DB_PUBLIC_RECORD.public_value1).append(first_child);
                                    return false;
                                }
                            })
                        }
                    }
                })
//                IS_CHANGE_DROPDOWN = false;
//                isFirstReport = false;
                setSelectedBankDropDown(json);
                selectPersonalInfoForIQ();
                selectPublicRecordForIQ();
                getPublicInfoForCreditAnalysis();
                getInquiriesDataForCreditAnalysis();
                
                
                // for first report upload condition credit anaylysis
//                IS_CHANGE_DROPDOWN = true;
//                isFirstReport = true;
                currentAnalysis()
                
            } else if (source_type == 2) {
                var inq = setDropDownInquiryPrivacyGuard(html, info);
                var bankNameList = [];
                var bankList = [];
                var temp_array = [];
                setDropDownPrivacyGuardPersonalInfo(html, data);
                $('#main-html-area .FtgCrDarkTradeHead').each(function(i, value) {
                    var currentClass = 'current_IQ_bank_' + i;
                    var individualDropDown = allSelectDropDown(currentClass);
                    $(this).append(individualDropDown);
                    var bank_name = $(this).text();
                    bank_name = $.trim(bank_name);
                    bankNameList.push(bank_name);
                    $(this).parent().next('tr').children('th.FtgCrXPNHead').append(html);
                    $(this).parent().next('tr').children('th.FtgCrEFXHead').append(html);
                    $(this).parent().next('tr').children('th.FtgCrTUCHead').append(html);
                    $(this).parent().next('tr').children('th.FtgCrXPNHead').children('select').attr('class', 'banks review_type ' + currentClass).attr('id', 'select_pg_exp_' + i);
                    $(this).parent().next('tr').children('th.FtgCrEFXHead').children('select').attr('class', 'banks review_type ' + currentClass).attr('id', 'select_pg_eqf_' + i);
                    $(this).parent().next('tr').children('th.FtgCrTUCHead').children('select').attr('class', 'banks review_type ' + currentClass).attr('id', 'select_pg_tuc_' + i);
                })

                $('#main-html-area .FtgCrDarkTradeHead').each(function(i, value) {
                    var bank_name = $(this).text();
                    bank_name = $.trim(bank_name);
                    temp_array.push(bank_name);
                    var obj = { 'index': i, 'bank_name': bank_name + getKeyIndex(bank_name, temp_array, bankNameList) };
                    bankList.push(obj);
                });

                $.each(info.datadocument.DI, function(i, value) {
                    var index = getMatchIndex(value.data_key, bankList);

                    $('#main-html-area #select_pg_exp_' + index).val(value.type2).trigger('change');
                    $('#main-html-area #select_pg_eqf_' + index).val(value.type3).trigger('change');
                    $('#main-html-area #select_pg_tuc_' + index).val(value.type).trigger('change');
                });
            } else if (source_type == 3) {
                setSmartCreditDropDownForPersonalInfo(json);
                setSmartCreaditAccountHistory(json);
                setSmartCreditInquiriesDropdown(info);
                setSmartCreditPublicDropdown(info);
                currentAnalysis()
            }
            setDropdownAndAddressForBank()
            setAllGlobalDropdown();
            

        //recent_report_info
        if(info.recent_report_info){
            getRecentReport(info.recent_report_info);
        }
        
        if($('#main-html-area').hasClass('col-md-6')){
            $('#recent-report-area').removeClass('hide');  
        }
        
        setUIscrollFloat()
        $('#client-html .modal-body').show();
        $('.loading').hide();
        },
        error: function() {
            alert("Failed. Try again later.");
        }
    });


    return SELECTED_ASSOC;
}

function setDropdownAndAddressForBank() {
    var all_crditors_contacts_smart_credit = creditorContactsSmartCredit()
    var all_crditors_contacts_IQ = getAllCreditorContactsByName()
    if (all_crditors_contacts_IQ) {

    } else if (all_crditors_contacts_smart_credit) {

    }
}

function setSmartCreaditAccountHistory(data) {
    var appent_option = '<option value=\"6\">Repaired Accounts/Now Positive</option>';
    appent_option += '<option value=\"5\">Late Pays / 2 Or Less</option>';
    var set_all_appent_option = '<option value=\"6\">Set all items Repaired Accounts/Now Positive</option>';
    set_all_appent_option += '<option value=\"5\">Set all items Late Pays / 2 Or Less</option>';

    var account_history_tables = $('#AccountHistory:contains(Account History)').next('td').html(allSelectSmartCreditDropDown('smart-cerdit-Account-history', set_all_appent_option));
    var all_crditors_contacts_smart_credit = creditorContactsSmartCredit()
    var all_crditors_contacts_smart_credit_addresses = [];
    if (all_crditors_contacts_smart_credit) {
        $.each(all_crditors_contacts_smart_credit, function(j, jval) {
            var tbank_name = jval.address;
            tbank_name = tbank_name.replace(/\r?\n|\r/g, '');
            tbank_name = tbank_name.replace('_', '');
            tbank_name = tbank_name.replace('-', '');
            tbank_name = tbank_name.replace(/\s+/g, " ");
            if (jval.bank_name) {
                all_crditors_contacts_smart_credit_addresses.push($.trim(tbank_name));
            }
        })
    }
    var db_account_history = data.DI;
    var temp_array = [];
    var bankList = [];
    $('#main-html-area .crWhiteTradelineHeader b').each(function(k, elk) {
        var bank = $.trim($(this)
            .clone() //clone the element
            .children() //select all the children
            .remove() //remove all the children
            .end() //again go back to selected element
            .text().replace(/<(?:.|\n)*?>/gm, ''));
        bankList.push(bank);
    });

    $('#main-html-area .crWhiteTradelineHeader b').each(function(i, el1) {
        var bank = $.trim($(this)
                            .clone() //clone the element
                            .children() //select all the children
                            .remove() //remove all the children
                            .end() //again go back to selected element
                            .text().replace(/<(?:.|\n)*?>/gm, ''));
        var temp_bank = bank;
        var endDropdownClass = 'smart-cerdit-subAccount-history-' + i;
        temp_array.push(bank);
        //my bank area

        var bank = bank + getSmartCreditKeyIndex(bank, temp_array)
        var new_bank = temp_bank + getKeyIndex(temp_bank, temp_array, bankList);

        if (bank) {
            $(this).attr('data-bank', temp_bank)


            var current_acc_info = findAccountInfoFromTableForSC($(this).parents('table').first().next('table'));
            var bank_name = bank;

            $(this).text(new_bank);

            $(this).parent().append(allSelectSubDropDown(endDropdownClass, appent_option));
            $(this).parent().children('select').attr('class', 'smart-cerdit-Account-history review_type');

            setbank_address_dropDown_html_smart_credit($(this).parent(), i, temp_bank, new_bank, data.DI)
            $.each(data.DI, function(index, value1) {
                var tbank_name = value1.value2;
                tbank_name = tbank_name.replace(/\r?\n|\r/g, '');
                tbank_name = tbank_name.replace('_', '');
                tbank_name = tbank_name.replace('-', '');
                tbank_name = tbank_name.replace(/\s+/g, " ");
                tbank_name = $.trim(tbank_name);

                var tbank_name_key = value1.data_key;
                tbank_name_key = tbank_name_key.replace(/\r?\n|\r/g, '');
                //tbank_name_key = tbank_name_key.replace('_', '');
                // tbank_name_key = tbank_name_key.replace('-', '');
                tbank_name_key = tbank_name_key.replace(/\s+/g, " ");
                tbank_name_key = $.trim(tbank_name_key);
                if ($.inArray(tbank_name, all_crditors_contacts_smart_credit_addresses) !== -1) {
                    if (tbank_name_key == new_bank) {
                        $("#bank_address_" + i).val(tbank_name).trigger('change');
                        return false;
                    }
                }

            })

            var current_table = $(this).parent().parents('table').first().next('table').find('table.crLightTableBackground');
            current_table.find('tr').each(function(j, el2) {

                var tds = $(this).find('td');
                var title = $.trim(tds.eq(0)
                    .clone() //clone the element
                    .children() //select all the children
                    .remove() //remove all the children
                    .end() //again go back to selected element
                    .text());
                var experian = getTextValueFromTdByColumn(tds, 2);
                var equifax = getTextValueFromTdByColumn(tds, 3);
                var trans = getTextValueFromTdByColumn(tds, 1);
                var types = getSmartCreditAccountHistoryTypeByKeyName(bank, db_account_history);

                if (experian && experian == 'Experian') {
                    tds.eq(2).append(bankhtmlstring(appent_option))
                    tds.eq(2).children('select').attr('class', endDropdownClass + ' smart-cerdit-subAccount-history smart-cerdit-Account-history review_type');
                    tds.eq(2).children('select').val(types.Experian).trigger('change');
                    emptyRowSetByUpdatedAndRemovedForSC(tds.eq(2).children('select'), 2);
                    tds.eq(2).addClass('personal-info-select-sc');
                }

                if (equifax && equifax == 'Equifax') {
                    tds.eq(3).append(bankhtmlstring(appent_option))
                    tds.eq(3).children('select').attr('class', endDropdownClass + ' smart-cerdit-subAccount-history smart-cerdit-Account-history review_type');
                    tds.eq(3).children('select').val(types.Equifax).trigger('change');
                    emptyRowSetByUpdatedAndRemovedForSC(tds.eq(3).children('select'), 3);
                    tds.eq(3).addClass('personal-info-select-sc');
                }

                if (trans && trans == 'TransUnion') {
                    tds.eq(1).append(bankhtmlstring(appent_option))
                    tds.eq(1).children('select').attr('class', endDropdownClass + ' smart-cerdit-subAccount-history smart-cerdit-Account-history review_type');
                    tds.eq(1).children('select').val(types.TransUnion).trigger('change');
                    emptyRowSetByUpdatedAndRemovedForSC(tds.eq(1).children('select'), 1)
                    tds.eq(1).addClass('personal-info-select-sc');
                    var itemTbl = tds.eq(1).parents('table').first();
                    itemTbl.find('tr.crTableHeader > td.accountHistoryColorRow > b').each(function() {
                        if ($(this).text() == "Account Type:") {

                            var accObj = getAccTypeByKey(bank, data.DI);
                            if (accObj.value1) {
                                var json_parse_obj_value1 = JSON.parse(accObj.value1);
                                json_parse_obj_value1 = json_parse_obj_value1.accType
                                if (json_parse_obj_value1) {
                                    $(this).parent('td').next('td').first().text(json_parse_obj_value1);
                                }
                            }
                        }
                    })
                }

            })



        }
    });




}


function emptyRowSetByUpdatedAndRemovedForSC(parent, type) {
    var result = true;
    var table = parent.parents('table').first();
    var final_text = "";
    table.find('tr').each(function(i, el) {
        if (i > 0) {
            var tds = $(this).find('td'); //687945012905318****
            var text = null
            if (type == 1) {
                text = $.trim(tds.eq(1).text().replace(/\r?\n|\r/g, '').replace('--', ''));
            } else if (type == 2) {
                text = $.trim(tds.eq(2).text().replace(/\r?\n|\r/g, '').replace('--', ''));
            } else if (type == 3) {
                text = $.trim(tds.eq(3).text().replace(/\r?\n|\r/g, '').replace('--', ''));
            }

            if (text) {
                final_text = text;
                result = false;
                return false;
            }

        }
    });

    if (result && is_editable) {
        //        if (hasHistory && parent.val() == 1) {
        //            parent.val(4).trigger('change');
        //        } else if (!hasHistory) {
        //            //parent.val(1).trigger('change');
        //        }
        var is_same_code = $('input[name=is_same_code]').val();
        var hasRp = $('input[name=is_first_report]').val();
        if (is_from_history == 0 && is_same_code == 0 && parent.val() == 1) {
            parent.val(4).trigger('change');
        } else if (!hasHistory) {
            //parent.val(1).trigger('change');
        }


    }
}

function getAccTypeByKey(key, data) {
    var result = {};
    $.each(data, function(index, value) {
        if (value.data_key == key) {
            result = value;
            return false;
        }
    });

    return result
}

function getSmartCreditAccountHistoryTypeByKeyName(key, data) {
    var types = {
        'Experian': 3,
        'Equifax': 3,
        'TransUnion': 3,
    };
    if (data) {
        $.each(data, function(index, value) {
            var arr = value.data_key.split('-');
            var strFile = arr[arr.length - 1];
            var intRegex = /^\d+$/;
            var db_data_key = value.data_key;
            //            if(intRegex.test(strFile)){
            //                db_data_key = db_data_key.replace("-"+strFile,"");
            //            }
            if (key && key == db_data_key) {
                types = {
                    'Experian': value.type2,
                    'Equifax': value.type3,
                    'TransUnion': value.type,
                }
                return false;
            }
        })
    }

    return types;
}

function getTextValueFromTdByColumn(tds, col) {
    var text = $.trim(tds.eq(col)
        .clone() //clone the element
        .children() //select all the children
        .remove() //remove all the children
        .end() //again go back to selected element
        .text());
    text = text.replace(/\r?\n|\r/g, '');
    if (text) {
        return text;
    } else {
        return null;
    }
}

function setSmartCreditDropDownForPersonalInfo(data) {
    var personal_info_tbl = $('#main-html-area #personalInfo:contains(Personal Information)').parents('table').next('table');
    personal_info_tbl.find('tr').each(function(i, el) {
        var tds = $(this).find('td');
        var td0_with_child = tds.eq(0).children('span').children('b');
        var key = $.trim(td0_with_child.text());
        if (key) {
            var text1 = tds.eq(1).text().replace(/<(?:.|\n)*?>/gm, '');
            text1 = text1.replace(/\r?\n|\r/g, '');
            text1 = text1.replace('_', '');
            text1 = text1.replace('-', '');
            text1 = text1.replace(/\s+/g, " ");
            text1 = text1.trim();
            text1 = text1.replace('updatenegativepositive', '');
            var text2 = tds.eq(2).text().replace(/<(?:.|\n)*?>/gm, '');
            text2 = text2.replace(/\r?\n|\r/g, '');
            text2 = text2.replace('_', '');
            text2 = text2.replace('-', '');
            text2 = text2.replace(/\s+/g, " ");
            text2 = text2.trim();
            text2 = text2.replace('updatenegativepositive', '');
            var text3 = tds.eq(3).text().replace(/<(?:.|\n)*?>/gm, '');
            text3 = text3.replace(/\r?\n|\r/g, '');
            text3 = text3.replace('_', '');
            text3 = text3.replace('-', '');
            text3 = text3.replace(/\s+/g, " ");
            text3 = text3.trim();
            text3 = text3.replace('updatenegativepositive', '');
            var key_name = key.replace(/<(?:.|\n)*?>/gm, '');
            key_name = key.replace(/\r?\n|\r/g, '');
            key_name = key.replace(':', " ");
            key_name = key.replace(/\s+/g, " ");
            key_name = key.trim();
            var status = getStatusByDataKey(key_name.replace(':', ''), data);
            if (text1 != "") {
                tds.eq(1).append(htmlstring());
                var status3 = 3;
                if (status != "") {
                    status3 = status.status3
                }
                tds.eq(1).children('select').val(status3).trigger('change');
                tds.eq(1).children('select').attr('class', 'smart-cerdit-personal-info review_type');
                tds.eq(1).attr('class', 'personal-info-select-sc');
            }
            if (text2 != "") {
                tds.eq(2).append(htmlstring());
                var status1 = 3;
                if (status != "") {
                    status1 = status.status1
                }
                tds.eq(2).children('select').val(status1).trigger('change');
                tds.eq(2).children('select').attr('class', 'smart-cerdit-personal-info review_type');
                tds.eq(2).attr('class', 'personal-info-select-sc');
            }
            if (text3 != "") {
                tds.eq(3).append(htmlstring());
                var status2 = 3;
                if (status != "") {
                    status2 = status.status2
                }
                tds.eq(3).children('select').val(status2).trigger('change');
                tds.eq(3).children('select').attr('class', 'smart-cerdit-personal-info review_type');
                tds.eq(3).attr('class', 'personal-info-select-sc');
            }
        }



    });
}

function setSmartCreditInquiriesDropdown(data) {

    var db_inquiry = data.inquiry

    var contactInfo = [];
    var inquries_tbl = $("#main-html-area td").filter(function() {
        var result = false;
        var current_text = $(this).clone().children().remove().end().text().replace(/<(?:.|\n)*?>/gm, '')
        current_text = current_text.replace(/\r?\n|\r/g, '');
        current_text = $.trim(current_text);

        if (current_text == "Inquiries" && $(this).attr('style')) {
            $(this).append(allSelectDropDown('smart-credit-inq-dropdown'))
            result = true;
        }
        return result;
    }).parents('table[border = 1]').first().next('table').next('table');

    inquries_tbl.find('tr').each(function(i, el) {
        var key_tds = $(this).find('td').children('table').each(function() {
            var tds = $(this).find('tr td');
            var item_category_id_Obj = {
                Equifax: 2,
                Experian: 1,
                TransUnion: 3
            }
            var item_category_key = getTextValueFromTdByColumn(tds, 3);
            var bank_name = getTextValueFromTdByColumn(tds, 1);
            var date_of_inq = "";
            var creditor_bereau = "";
            if (getTextValueFromTdByColumn(tds, 2)) {
                date_of_inq = getTextValueFromTdByColumn(tds, 2);
            }
            var current_key_name = bank_name + "_" + date_of_inq + "_" + item_category_id_Obj[item_category_key];
            var select_html = setInqAddressDropdownForSmartCredit(bank_name); // SC change imran
            tds.eq(1).append(select_html);
            tds.eq(3).append(htmlstring());
            tds.eq(3).children('select').attr('class', 'smart-credit-inq-dropdown review_type');
            tds.eq(3).children('select').val(getSmartCreditInqTypeByKeyName(current_key_name, db_inquiry)).trigger('change');
        });
    });
}

function setSmartCreditPublicDropdown(data) {
    var contactInfo = [];
    var pb_label_dropdown = "";
    var publicrecords = data.publicrecords;

    var all_crditors_contacts_smart_credit = creditorContactsSmartCredit();

    var address_html = setPublicAddressDropdownForSmartCredit();

    var public_tbl = $("#main-html-area td").filter(function() {
        var result = false;
        var current_text = $(this).clone().children().remove().end().text().replace(/<(?:.|\n)*?>/gm, '')
        current_text = current_text.replace(/\r?\n|\r/g, '');
        current_text = $.trim(current_text);

        if (current_text == "Public Information" && $(this).attr('style')) {
            pb_label_dropdown = $(this);
            $(this).append(address_html + allSelectDropDown('smart-credit-public-dropdown'))
            result = true;
        }
        return result;
    }).parent('tr').first().next('tr').children('td').children('table');
    var value_types_array = [];
    value_types_array[2] = "TransUnion";
    value_types_array[3] = "Experian";
    value_types_array[4] = "Equifax";
    public_tbl.find('tr').each(function(i, el) {
        var tds = $(this).find('td.crLightTableBackground');
        var key_name = "";
        var new_tmp_array = [];
        tds.filter(function(index, value) {
            tds.filter(function(key_index, value) {
                var key_text = $(value).children('b').clone().children().remove().end().text().replace(/<(?:.|\n)*?>/gm, '');
                if (key_text) {
                    key_text.replace(':', '')
                    key_name = $.trim(key_text);
                    new_tmp_array.push(key_name);
                    return false;
                }
            });

            var current_text = $(this).clone().children().remove().end().text().replace(/<(?:.|\n)*?>/gm, '');
            current_text = $.trim(current_text);
            current_text = current_text.toUpperCase();
            var first_row = publicrecords[0]; //public_value3
            if (current_text == "NONE REPORTED") {
                pb_label_dropdown.children('select').remove();
            }

            if (current_text && current_text != "NONE REPORTED") {
                $(this).append(htmlstring());
                $(this).children('select').attr('class', 'smart-credit-public-dropdown');
                //var new_current_text = key_name + getSmartCreditPublicKeyIndex(key_name,new_tmp_array);
                var new_current_text = key_name;
                var type = getSmartCreditFromDB(new_current_text, publicrecords);
                var temp_obj = {};
                if (type) {
                    if (type.public_value3) {
                        if ($.trim(new_current_text) == "Type:") {
                            var select = $(this).children('select').val(type.public_status3).trigger('change');
                            $(this).text(first_row.public_value3);
                            $(this).append(select);
                        }

                        $(this).children('select').val(type.public_status3).trigger('change');

                        if (new_current_text && $.trim(new_current_text).toLowerCase() == "court:") {
                            var current_text = $(this).clone().children().remove().end().text();
                            var all_crditors_contacts = creditorContactsSmartCredit();
                            temp_obj = {};
                            $.each(all_crditors_contacts, function(index, value) {
                                temp_obj[value.bank_name] = value.address;
                            })
                            if (temp_obj[current_text]) {
                                $('#main-html-area select[name="public_address_dropdown"]').val(current_text).trigger('change')
                                $('#main-html-area select[name="public_address_dropdown"]').attr('data-type', $(this).children('select').val());
                            }

                        }

                    }
                    if (type.public_value2) {

                        if ($.trim(new_current_text) == "Type:") {
                            var select = $(this).children('select').val(type.public_status2).trigger('change');
                            $(this).text(first_row.public_value2);
                            $(this).append(select);
                        }



                        $(this).children('select').val(type.public_status2).trigger('change');

                        if (new_current_text && $.trim(new_current_text).toLowerCase() == "court:") {

                            var current_text = $(this).clone().children().remove().end().text();
                            var all_crditors_contacts = creditorContactsSmartCredit();
                            temp_obj = {};
                            $.each(all_crditors_contacts, function(index, value) {
                                temp_obj[value.bank_name] = value.address;
                            })
                            if (temp_obj[current_text]) {
                                $('#main-html-area select[name="public_address_dropdown"]').val(current_text).trigger('change')
                                $('#main-html-area select[name="public_address_dropdown"]').attr('data-type', $(this).children('select').val());
                            }

                        }
                    }
                    if (type.public_value1) {
                        if (new_current_text == "Type:") {
                            var select = $(this).children('select').val(type.public_status1).trigger('change');
                            //$(this).html('');
                            $(this).text(first_row.public_value1);
                            $(this).append(select);
                        }


                        $(this).children('select').val(type.public_status1).trigger('change');

                        if (new_current_text && $.trim(new_current_text).toLowerCase() == "court:") {

                            var current_text = $(this).clone().children().remove().end().text();
                            var all_crditors_contacts = creditorContactsSmartCredit();
                            temp_obj = {};
                            $.each(all_crditors_contacts, function(index, value) {
                                temp_obj[value.bank_name] = value.address;
                            })
                            if (temp_obj[current_text]) {
                                $('#main-html-area select[name="public_address_dropdown"]').val(current_text).trigger('change')
                                $('#main-html-area select[name="public_address_dropdown"]').attr('data-type', $(this).children('select').val());
                            }

                        }
                    }
                }

            }
        })
    })

}


function getSmartCreditFromDB(key_name, db_keys_array) {
    var type = null;
    $.each(db_keys_array, function(index, value) {
        var public_key = value.public_key
        public_key = public_key.split('-');

        var public_k = public_key[0];

        key_name = key_name.replace(':', '');
        if (key_name == public_k) {
            type = value;
            return false;
        }
    })

    return type;
}

function getSmartCreditPublicDropdownData() {
    //debugger
    var contactInfo = [];
    var public_tbl = $("#main-html-area td").filter(function() {
        var result = false;
        var current_text = $(this).clone().children().remove().end().text().replace(/<(?:.|\n)*?>/gm, '')
        current_text = current_text.replace(/\r?\n|\r/g, '');
        current_text = $.trim(current_text);

        if (current_text == "Public Information" && $(this).attr('style')) {

            result = true;
        }
        return result;
    }).parent('tr').first().next('tr').children('td').children('table');

    var finalArray = [];
    var value_types_array = [];
    value_types_array[2] = "TransUnion";
    value_types_array[3] = "Experian";
    value_types_array[4] = "Equifax";
    var table_name = "";
    public_tbl.find('tr').each(function(i, el) {
        var table_name_td = $(this).find('td.crGrantedTradelineHeader');
        var temp_table_name = table_name_td.children('b').clone().children().remove().end().text();
        if (temp_table_name) {
            table_name = temp_table_name;
            return false;
        }
    });

    public_tbl.find('tr').each(function(i, el) {

        var tds = $(this).find('td.crLightTableBackground');

        var obj = { key_name: '', data: '', type: '' };
        var obj2 = {}
        var key_name = ""
        tds.filter(function(key_index, value) {
            var key_text = $(value).children('b').clone().children().remove().end().text().replace(/<(?:.|\n)*?>/gm, '');

            if (key_text) {
                key_text.replace(':', '')
                key_name = $.trim(key_text);
                return false;
            }
        });

        tds.filter(function(index, value) {
            var current_text = "";
            current_text = $(this).clone().children().remove().end().text().replace(/<(?:.|\n)*?>/gm, '');
            var newText = ""
            var type = 3;
            if ($(value).children('select').val() > 0) {
                type = $(value).children('select').val();
            }
            current_text = $.trim(current_text)
            //console.log('test data',current_text)
            if (current_text) {
                obj['type'] = type;
                obj['data'] = current_text;
                obj['key_name'] = key_name;
                obj['table_name'] = $.trim(table_name);

                if (value_types_array[index]) {

                    obj2[value_types_array[index]] = obj;
                    finalArray.push(obj2);
                }

            }
        })



    });

    console.log('finalArray',finalArray)
    return finalArray;

}


function getSmartCreditInquiries() {
    var contactInfo = [];
    var inquries_tbl = $("#main-html-area td").filter(function() {
        var current_text = $(this).clone().children().remove().end().text().replace(/<(?:.|\n)*?>/gm, '')
        current_text = $.trim(current_text);
        return current_text == "Inquiries" && $(this).attr('style');
    }).parents('table[border = 1]').first().next('table').next('table');

    inquries_tbl.find('tr').each(function(i, el) {
        var key_tds = $(this).find('td').children('table').each(function() {
            var tds = $(this).find('tr td');
            var obj = {};
            var type = 3;
            var bank_name = getTextValueFromTdByColumn(tds, 1);
            var date_of_inq = "";
            var creditor_bereau = "";
            if (getTextValueFromTdByColumn(tds, 2)) {
                date_of_inq = getTextValueFromTdByColumn(tds, 2);
            }

            if (getTextValueFromTdByColumn(tds, 3)) {
                creditor_bereau = getTextValueFromTdByColumn(tds, 3);
            }

            if (tds.eq(3).children('select').val()) {
                type = tds.eq(3).children('select').val();
            }

            if (bank_name) {
                obj = {
                    'key_name': bank_name + "_" + date_of_inq,
                    'creditor_bereau': creditor_bereau,
                    'type': type
                }
                contactInfo.push(obj);
            }
        });
    });
    return contactInfo;
}


function getSmartCreditInqTypeByKeyName(key, data) {
    var type = 3;

    if (data) {
        $.each(data, function(index, value) {
            if (key && key == value.inquiry_key) {
                type = value.inquiry_type;
                return false;
            }
        });
    }

    return type;
}

function getPersonalInfoWithDropDownData() {
    PERSONAL_INFO = [];
    var personal_info = [];
    var table = $('#main-html-area table.rpt_content_table:eq(1)');;
    var personalInfo = [];
    table.find('tr').each(function(i, el) {

        var $tds = $(this).find('td');
        var key = $tds.eq(0).text();
        var obj = {};

        if (key != "") {
            var text1 = $tds.eq(1).text().replace(/<(?:.|\n)*?>/gm, '');
            text1 = text1.replace(/\r?\n|\r/g, '');
            text1 = text1.replace('_', '');
            text1 = text1.replace('-', '');
            text1 = text1.replace(/\s+/g, " ");
            text1 = text1.trim();
            text1 = text1.replace('updatenegativepositive', '');
            text1 = text1.replace('Please selectnegativepositiveUpdated/Removed', '');
            var text2 = $tds.eq(2).text().replace(/<(?:.|\n)*?>/gm, '');
            text2 = text2.replace(/\r?\n|\r/g, '');
            text2 = text2.replace('_', '');
            text2 = text2.replace('-', '');
            text2 = text2.replace(/\s+/g, " ");
            text2 = text2.trim();
            text2 = text2.replace('updatenegativepositive', '');
            text2 = text2.replace('Please selectnegativepositiveUpdated/Removed', '');

            var text3 = $tds.eq(3).text().replace(/<(?:.|\n)*?>/gm, '');
            text3 = text3.replace(/\r?\n|\r/g, '');
            text3 = text3.replace('_', '');
            text3 = text3.replace('-', '');
            text3 = text3.replace(/\s+/g, " ");
            text3 = text3.trim();
            text3 = text3.replace('updatenegativepositive', '');
            text3 = text3.replace('Please selectnegativepositiveUpdated/Removed', '');

            var key_name = key.replace(/<(?:.|\n)*?>/gm, '');
            key_name = key.replace(/\r?\n|\r/g, '');
            key_name = key.replace(':', " ");
            key_name = key.replace(/\s+/g, " ");
            key_name = key.trim();

            obj = {
                'TransUnion': { data: text1, 'type': $tds.eq(1).children('select').val(), 'key_name': key_name.replace(':', '') },
                'Experian': { data: text2, 'type': $tds.eq(2).children('select').val(), 'key_name': key_name.replace(':', '') },
                'Equifax': { data: text3, 'type': $tds.eq(3).children('select').val(), 'key_name': key_name.replace(':', '') },
            }

            PERSONAL_INFO.push(obj);
            personal_info.push(obj);

        }
    });

    return personal_info;
}



function htmlstring() {
    var string = "<select style=\"width: 100%;\n" + "    padding: 0px;color: black;\n" + "    height: 19px;\n" + "    margin: 0px;\n" + "    float: right;\" name=\"source_type\"  class=\"review_type\"><option value=\"3\">Please select</option><option value=\"1\">negative</option><option value=\"2\">positive</option><option value=\"4\">Updated/Removed</option></select>";
    return string;
}

function bankhtmlstring(appent_option = "") {
    var string = "<select style=\"width:100%;\n" + "    padding: 0px;color: black;\n" + "    height: 19px;\n" + "    margin: 0px;\n" + "    float: right;\" name=\"source_type\"  class=\"banks\"><option value=\"3\">Please select</option><option value=\"1\">negative</option><option value=\"2\">positive</option><option value=\"4\">Updated/Removed</option>" + appent_option + "</select>";
    return string;
}

function htmlDropdownString(len) {
    var string = "<select id='dropdown_" + len + "' style=\"width: 100%;\n" + "    padding: 0px;color: black;\n" + "    height: 19px;\n" + "    margin: 0px;\n" + "    float: right;\" name=\"source_type\"  class=\"review_type\"><option value=\"3\">Please select</option><option value=\"1\">negative</option><option value=\"2\">positive</option><option value=\"4\">Updated/Removed</option></select>";
    return string;
}





function bankCode() {
    var bankCodes = new Map([
        ['Capital One', 'C1'],
        ['Capital One Ltd', 'C1'],
        ['T-MOBILE', 'TMobile'],
        ['SPRINT', 'SPRINT'],
    ]);
    return bankCodes;
}

$('button[name=process_html]').click(function() {
    IS_NEW_REPORT_UPLOAD = 0;
    var content = $('textarea[name=html_content]').val();
    var search = document.getElementById('search').value;
    var client_id = $('select[name=client_id]').val();
    $('button[name=credit_btn]').hide();
    $('button[name=credit_analyzer]').hide();
    if (search == "") {
        $('select[name=source_type]').parent().addClass('has-error');
        //alert('Please select source type')
    } else if (client_id == 0) {
        $('select[name=client_id]').parent().addClass('has-error');
        alert('Please select client')
    } else {
        if (content) {
            uploadHTMLUICode(content);
        } else {
            alert('Credit Report field cannot be empty.')
        }
    }
});



function uploadHTMLUICode(content, isVelocity = false, report_type = null) {

    var source_type = $('select[name=source_type]').val();
    var html = htmlstring();
    $('select[name=client_id]').parent().removeClass('has-error');
    $('select[name=source_type]').parent().removeClass('has-error');
    $('textarea[name=html_content]').parent().removeClass('has-error');
    $('textarea[name=html_content]').parent().hide();
    $('button[name=process_html]').hide();
    $('button[name=checkConsole]').show();
    $('#velocity_link').show();
    $('#client-list-link').show();
    
    if($('select[name=client_id]').val() > 0){
        $('#client-dashboard-link').attr('href',SERVER_HTTP_HOST+'client/clientdashboard/'+$('select[name=client_id]').val());
    }
    
    $('#client-dashboard-link').show();
    
    $('button[name=credit_btn]').show();
    if (hasHistory) {
        $('button[name=credit_analyzer]').show();
    }

    if (content != "") {
        content = content.replace('document.write', "wwwdocument.write");
    }
    // console.log('isVelocity_report_type', report_type);
    var source_type = DEFAULT_SOURCE_TYPE
    if (report_type) {
        source_type = report_type
    } else {
        source_type = $('select[name=source_type]').val();
    }
    //console.log('after source_type assign', source_type);
    $('.credit-report, .view-html').html('');
    try {

        $('#full-page-loader h3').text('');
        $('#full-page-loader h3').text('Processing .....');

        $('#full-page-loader').show();

        if (source_type == 1) {


            content = content.replace('https://www.identityiq.com/Scripts/jquery-3.5.1.min.js', '');
            content = content.replace('href="./Credit Report - IdentityIQ_files/font-awesome.min.css"', 'href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css"');
            content = content.replace('href="./Credit Report - IdentityIQ_files/style.DEFAULT.css"', 'href="https://www.identityiq.com/CreditReportContent/DEFAULT/style.DEFAULT.css"');
            content = content.replace('href="./Credit Report - IdentityIQ_files/CRDownload.css"', 'href="https://www.identityiq.com/css/CRDownload.css"');
            content = content.replace('src="./Credit Report - IdentityIQ_files/CRDownload.js.download"', 'src="https://www.identityiq.com/Scripts/CRDownload.js"');
            content = replaceAll(content, './Credit Report - IdentityIQ_files/info_icon.gif', 'https://www.identityiq.com/images/tu/info_icon.gif');
            content = replaceAll(content, './Credit Report - IdentityIQ_files/legend-icon.gif', 'https://www.identityiq.com/images/tu/legend-icon.gif');
            content = replaceAll(content, 'https://www.identityiq.com/Scripts/jquery-3.0.0.min.js', '');
            content = replaceAll(content, 'https://www.identityiq.com/Scripts/angular.js', '');
            content = replaceAll(content, 'https://www.identityiq.com/Scripts/jquery-1.7.2.min.js', '');
            content = replaceAll(content, 'Ã', '');
            content = replaceAll(content, 'Â', '');
            //            content = replaceAll(content, 'href="https://www.identityiq.com/CreditReportContent/DEFAULT/style.DEFAULT.css"', 'href="/epicvelocity/css/style.DEFAULT.css"');
            //            content = replaceAll(content, 'href="https://member.identityiq.com/CreditReportContent/DEFAULT/style.DEFAULT.css"', 'href="/epicvelocity/css/style.DEFAULT.css"');
            //            content = replaceAll(content, 'href="https://member.identityiq.com/css/CRDownload.css"', 'href="/epicvelocity/css/CRDownload.css"');
            //            content = replaceAll(content, 'href="https://www.identityiq.com/css/CRDownload.css"', 'href="/epicvelocity/css/CRDownload.css"');

        }
        if (source_type == 2) {
            content = content.replace('href="resources', 'href="https://www.privacyguard.com/BCA/Generic/ECD/resources/');
            content = replaceAll(content, 'ScoreAnalysis', 'ScoreAnalysis content-div-hide');
        }

        if (source_type == 3) {
            var link = '<meta charset="utf-8"><link rel="stylesheet" type="text/css" href="https://www.smartcredit.com/combined.css.h1634784381.pack" charset="utf-8"/>' +
                '<link rel="stylesheet" type="text/css" href="https://www.smartcredit.com/combined.css.h1286474662.pack" media="print" charset="utf-8"/>' +
                '<link rel="stylesheet" type="text/css" href="https://www.smartcredit.com/combined.css.h677146085.pack" charset="utf-8"/>'

            content = content.replace('<h1>undefined</h1>', '');

            content = replaceAll(content,'src="https://www.smartcredit.comhttps://www.smartcredit.com/resources/images/','src="/resources/images/');
            content = replaceAll(content,  'src="https://www.smartcredit.com/resources/images/','src="/resources/images/');
            content = replaceAll(content, 'src="/resources/images/', 'src="https://www.smartcredit.com/resources/images/');

            var month_array = ['jan','feb','mar','apr','may','jun','jul','aug','sep','oct','nov','dec'];
            
            for(var i in month_array){
                content = replaceAll(content, './3-Bureau Credit Report &amp; Scores _ Smart Credit_files/'+month_array[i]+'-gray.gif', 'https://www.smartcredit.com/resources/images/shared/tui/creditreport/monthsandyears/'+month_array[i]+'-gray.gif');
            }
            
            content = replaceAll(content, './3-Bureau Credit Report &amp; Scores _ Smart Credit_files/apostrophe-gray.gif', 'https://www.smartcredit.com/resources/images/shared/tui/creditreport/monthsandyears/apostrophe-gray.gif');
            
            for(var i = 0; i < 10; i++){
                content = replaceAll(content, './3-Bureau Credit Report &amp; Scores _ Smart Credit_files/'+i+'-gray.gif', 'https://www.smartcredit.com/resources/images/shared/tui/creditreport/monthsandyears/'+i+'-gray.gif');
            }
            
            
            
            content = replaceAll(content, './3-Bureau Credit Report &amp; Scores _ Smart Credit_files/clear.gif', 'https://www.smartcredit.com/resources/images/shared/tui/clear.gif');
            content = replaceAll(content, './3-Bureau Credit Report &amp; Scores _ Smart Credit_files', 'https://www.smartcredit.com/resources/images/shared/tui/creditreport');
            
            content = link + content;
        }

        if (content) {
            content = remove_non_ascii(content);
        }
        $('.view-html').html(content);
        $('.view-html #reportTop .content-heading').remove();
        $('.view-html #reportTop .content-box .alert').remove();
        $('.view-html #reportTop #_hjRemoteVarsFrame').remove();
        $('.view-html footer.hidden-print').remove();
        
        $('head').append('<meta charset="utf-8">');
        $('#reportTop').removeClass('container');
        $('.top-bottom-area-icon').show();
        $('#client-list-link').show();
        $('#velocity_link').show();
        $('.backtoTopText').remove();
        $('button[name=credit_btn]').show();
        $('button#content-from-api').attr('onclick', 'getHtmlByApi("' + source_type + '","' + $('select[name=client_id]').val() + '")');
        $('button#content-from-api').show();
                    

    } catch (e) {

    }
    //console.log('before getSelectedInfo', source_type);
    if ($('.view-html').html()) {
        getSelectedInfo(isVelocity, source_type);
    }

    disableAllActions(true) // disable = true
    $('select[name=client_id]').addClass('processed')
    removeDropdownCreditScore();

    if (isRemovedDropDown) {
        removeAddressDropDown();
    }
    
    
    
}
function replace_text(str, find, replace) {
    let ex = str.indexOf(find);
    let result = '';
    if(ex>0)
    {
        result = str.replace(str,replace);
    }
    return result;
}
function getReportDateCurrent() {
    var date = "";
    if ($('.view-html').first().length > 0) {
        //console.log('G1');
        var reportTbl = $('.view-html table#reportTop tr td');
        //console.log('G1.1',reportTbl);
        if (reportTbl.length > 0) {
            //console.log('G2');
            date = $.trim(reportTbl.eq(3).children('ng.ng-binding').text().replace(/<(?:.|\n)*?>/gm, ''));
            //console.log('GET_REPORT_DATE',date);
        }
    }

    return date;
}

function setReportDate(html) {
    //$('#temp-hide-area').html(html);

    //    if($('#temp-hide-area').length > 0){
    //        console.log('R1');
    //        var reportTbl = $('#temp-hide-area table#reportTop tr td');
    //        console.log('R1.1',reportTbl);
    //        if(reportTbl.length > 0){
    //            localStorage.removeItem("REPORT_DATE");
    //            console.log('R2');
    //            var date = $.trim(reportTbl.eq(3).children('ng.ng-binding').text().replace(/<(?:.|\n)*?>/gm, ''));
    //            console.log('SET_REPORT_DATE',date)
    //            localStorage.setItem("REPORT_DATE", date);
    //        }
    //    }

    //console.log('R3');

    $('#temp-hide-area').html('')
}

function removeAddressDropDown() {
    $('#main-html-area select').map(function() {
        var name = $(this).attr('name');
        if (name && name.includes("bank_addresse")) {
            $(this).remove();
        }
    }).get();
    $('#main-html-area select.inq-address-dropdown').remove();
    $('#main-html-area select[name="public_address_dropdown"]').remove();
    $('button.rtg-save-btn').remove();
}

$('button[name=paste_html]').click(function() {
    $('.view-html').html('');
    $('textarea[name=html_content]').val('')
    $('textarea[name=html_content]').parent().show();
    $('button[name=process_html]').show();

});



$('button[name=import_html]').click(function() {
    var personal_info_table_td_class = $('.info');

    //$('#mainform').submit();

});


$('button[name=credit_btn1]').click(function() {
    var client_id = $('select[name=client_id]').val();
    var source_type = $('select[name=source_type]').val();
    $('#credit-loader').show();
    if (client_id > 0) {
        $.ajax({
            type: "GET",
            data: { 'action': 'clientInfo', 'client_id': client_id, 'source_type': source_type },
            url: credit_analysis_url,
            success: function(data) {
                //$('button[name=checkConsole]').click();
                $('#credit-loader').hide();
                var jsonParseData = JSON.parse(data);
                $('input[name=f_l_name]').val(jsonParseData.clients.last_name + ", " + jsonParseData.clients.first_name);
                //current_date
                $('input[name=date_audit]').val(jsonParseData.current_date)
                $('input[name=credit_client_id]').val(client_id);
                $('input[name=credit_source_type]').val(source_type);
                //Identity IQ  report dated 11/2/2017 per Identity IQ
                //$('#credit-analaysis').css({display:'block',overflow:'auto'}).addClass('in');
            },
            error: function() {
                $('#credit-loader').hide();
            }
        });
    }
});

function replaceAll(str, find, replace) {
    return str.replace(new RegExp(find, 'g'), replace);
}
$('.modal-close-btn').click(function() {
    $('#credit-analaysis').css({ display: 'none' }).removeClass('in');
})

function getMatchIndex(bank_name, bankList) {
    var result = 3;

    $.each(bankList, function(i, value) {
        bank_name = $.trim(bank_name);
        var current_bank = $.trim(value.bank_name);

        if (bank_name == current_bank) {
            result = value.index;
            return false;
        } else {

        }
    });

    return result;
}


function getMatchKeyIndexIQ(bank_name, bankList) {
    var result = "";

    $.each(bankList, function(i, value) {
        bank_name = $.trim(bank_name);
        var current_bank = $.trim(value.bank_name);

        if (bank_name == current_bank) {
            result = value.index;
            return false;
        } else {

        }
    });

    return result;
}

function count_array_values(my_array, match) {
    var count = 0;

    $.each(my_array, function(i, value) {
        if (value == match) {
            count++;
        }
    })


    return count;
}

function getKeyIndex(value, tmp_array, total_array) {

    var result = "";
    var exist_in_temp = 0;
    var total_exist = count_array_values(total_array, value);

    if (tmp_array == "" || total_array == "" || total_exist < 2) {
        return "";
    } else {

        exist_in_temp = count_array_values(tmp_array, value);
    }

    return "-" + exist_in_temp;

}

function getKeyIndex1(value, tmp_array, total_array) {

    var result = "";
    var exist_in_temp = 0;
    var total_exist = count_array_values(total_array, value);

    if (tmp_array == "" || total_array == "" || total_exist < 2) {
        return "";
    } else {

        exist_in_temp = count_array_values(tmp_array, value);
    }

    return exist_in_temp;

}

function getSmartCreditKeyIndex(value, tmp_array) {
    var total_array = [];
    $('#main-html-area .crWhiteTradelineHeader b').each(function(i, el1) {
        var bank = $.trim($(this)
            .clone()
            .children()
            .remove()
            .end()
            .text().replace(/<(?:.|\n)*?>/gm, ''));
        if (bank) {
            total_array.push(bank);
        }
    });
    var result = "";
    var exist_in_temp = 0;
    var total_exist = count_array_values(total_array, value);

    if (tmp_array == "" || total_array == "" || total_exist < 2) {
        return "";
    } else {

        exist_in_temp = count_array_values(tmp_array, value);
    }

    return "-" + exist_in_temp;

}

function getSmartCreditPublicKeyIndex(value, tmp_array) {
    var total_array = [];
    var public_tbl = $("#main-html-area td").filter(function() {
        var result = false;
        var current_text = $(this).clone().children().remove().end().text().replace(/<(?:.|\n)*?>/gm, '')
        current_text = current_text.replace(/\r?\n|\r/g, '');
        current_text = $.trim(current_text);

        if (current_text == "Public Information" && $(this).attr('style')) {
            $(this).append(allSelectDropDown('smart-credit-public-dropdown'))
            result = true;
        }
        return result;
    }).parent('tr').first().next('tr').children('td').children('table');
    public_tbl.find('tr').each(function(i, el) {
        var tds = $(this).find('#main-html-area td.crLightTableBackground');
        var key_name = "";
        tds.filter(function(key_index, value) {
            var key_text = $(value).children('b').clone().children().remove().end().text().replace(/<(?:.|\n)*?>/gm, '');
            if (key_text) {
                key_text.replace(':', '')
                key_name = $.trim(key_text);
                total_array.push(key_name);
                return false;
            }
        });
    })
    var result = "";
    var exist_in_temp = 0;
    var total_exist = count_array_values(total_array, value);

    if (tmp_array == "" || total_array == "" || total_exist < 2) {
        return "";
    } else {

        exist_in_temp = count_array_values(tmp_array, value);
    }

    return "-" + exist_in_temp;

}

function getInquiriesAndPublicSelectedInfo(html, data) {
    var client_id = $('select[name=client_id]').val();
    if (client_id == "" || client_id <= 0) {
        return false;
    }
    setInquiriesDropDown(html, data);
    setPublicInfoDropDown(html, data);
}


function getHtmlInfo(elem) {
    var html_text = $('textarea[name=html_content]').val();
    var source_type = $('select[name=source_type]').val();
    var client_id = $('select[name=client_id]').val();
    if (source_type == "" || client_id == "") {
        return false;
    }
    if (html_text != "") {
        var r = confirm('Are you sure you want to change client ?');
        if (r) {

        } else {
            return false;
        }
    }
    $('.loading').show();
    //var client_id = $(elem).val();
    $.ajax({
        type: "POST",
        data: { 'action': 'htmlinfo', 'client_id': client_id, 'source_type': source_type },
        url: saveIdentityID,
        success: function(data) {
            //

            $('button#content-from-api').hide();
            if (source_type == 3 || source_type == 1) {
                $('button#content-from-api').attr('onclick', 'getHtmlByApi("' + source_type + '","' + client_id + '")');
                $('button#content-from-api').show();
            }
            var json = JSON.parse(data);
            hasHistory = json.hasHistory;
            //console.log('sssss',hasHistory)
            if (!json.hasHistory) {
                $('.history-checkbox').hide();
                $('.history-checkbox input[type=checkbox]').prop('checked', true);
            }
            if (json.html) {
                $('textarea[name=html_content]').val(json.html);
                setReportDate(json.html)
                changeCreditReports(json.html)
            } else {
                alert('No data found.')
            }

            $('.loading').hide();
        },
        error: function() {
            $('.loading').hide();
        }
    });
}


// HTML from API
function getHtmlByApi(source_type, client_id, request_category = 0) {

    var formData = { 'action': 'HTML_INFO_FROM_API', 'client_id': client_id, 'source_type': source_type };
    var button = "";
    formData['request_category'] = request_category; // 1 = view most recent report for IQ, 2 = refresh date request && get report

    if (request_category == 1) {
        $('#iq-loader').show();
        button = $('button#view-most-recent-btn');
    } else if (request_category == 2) {
        if (!confirm('Are you sure want to refresh report ?')) {
            return false;
        }
        $('#iq-loader').show();
        button = $('#credit-report-modal .refresh-btn button');
    } else {
        button = $('button#content-from-api');
        $('#client-loader').show();
    }
    if (button)
        button.attr('disabled', true);
    $.ajax({
        type: "POST",
        data: formData,
        url: saveIdentityID,
        success: function(data) {
            $('#client-loader').hide();
            $('#iq-loader').hide();
            if (button)
                button.attr('disabled', false);

            var json = JSON.parse(data);
            var status = json.status;
            if (status == 2) {
                if (history_id > 0 || is_import_show_analyzer || hasHistory) {
                    newReportCondition();
                }

                alert('Report imported successfully.');
                var html = json.html;
                
                if(html){
                    IS_NEW_REPORT_UPLOAD = 1;
                }

                if (source_type == 1) {
                    html = replaceAll(html, 'https://www.identityiq.com/Scripts/jquery-3.0.0.min.js', '');
                    html = replaceAll(html, 'https://www.identityiq.com/Scripts/angular.js', '');
                }
                $('textarea[name=html_content]').val(html);
                changeCreditReports(html)
                $('#credit-report-modal').modal('hide');

            } else if (status == 3) {
                alert('There is no credit report credential found.')
            } else if (status == 1) {
                alert('No data found.');
                $('#credit-report-modal').modal('hide');
            } else if (status == 4) {
                var button_type = json.button_type;
                var refresh_date = json.refresh_date;
                //console.log("json",json)
                $('#credit-report-modal .refresh-btn').html('');
                $('#credit-report-modal #view-most-recent-btn').attr('onclick', 'getHtmlByApi("' + source_type + '","' + client_id + '",1)');
                if (refresh_date) {
                    $('#credit-report-modal #refresh-date').text(refresh_date);
                }

                if (button_type == 2) {
                    var refresh_btn_html = '<button class="form-control identity-iq-btn btn-orange-color">Refresh Report >></button>';
                    $('#credit-report-modal .refresh-btn').html(refresh_btn_html);
                    $('#credit-report-modal .refresh-btn button').attr('onclick', 'getHtmlByApi("' + source_type + '","' + client_id + '",2)');
                }
                var textTitle = 'Identity IQ';
                if (source_type == 3) {
                    textTitle = 'SmartCredit';
                }
                $('#credit-report-modal .modal-title').text(textTitle);
                $('#credit-report-modal').modal('show');
            } else if (status == 5) {
                alert("Congratulations! Your Refresh is Complete. Please click the Import to get Your Most Recent Report Now");
                $('#credit-report-modal .refresh-btn').html('');
            } else if (status == 6) {
                alert('Please Refresh again');
            }


        },
        error: function() {
            $('#client-loader').hide();
            $('#iq-loader').hide();
            if (button)
                button.attr('disabled', false);
        }
    });
}
// HTML from API
function changeCreditReports(json) {
    if ($('button[name=checkConsole]').length && json) {
        $('button[name=checkConsole]').prop('disabled', false);
        if ($('select[name=client_id]').hasClass('processed')) {
            uploadHTMLUICode(json);
            disableAllActions(false) // disable = false
        }
    }
}


function addressOnchangeIQ(len, elem) {
    var address = $(elem).find('option:selected');
    $('#bank_address_text_' + len).text(address.data('value'))
}

function setbank_address_dropDown_html(elem, len, bank_name, key_bank, db_data) {

    var bankList = [];
    var temp_array = [];
    var final_bank_assoc = [];
    var bank_address_dropDown_html = "<select onchange='addressOnchangeIQ(" + len + ",this)' style='color:black' id='bank_address_" + len + "' name='bank_addresses[" + len + "]'>";
    var all_crditors_contacts_IQ = getAllCreditorContactsByName()

    var checked = '';
    var tables = $("#main-html-area .crPrint");
    tables.find('tr').each(function(i1, el) {
        var $tds = $(this).find('td');
        var bank_name = "";
        var firstTd = $tds.eq(0).children('ng-include').children('.sub_header');
        bank_name = firstTd.clone().children().remove().end().text().replace(/<(?:.|\n)*?>/gm, '');
        bank_name = bank_name.replace(/\r?\n|\r/g, '');
        bank_name = bank_name.replace('_', '');
        bank_name = bank_name.replace('-', '');
        bank_name = bank_name.replace(/\s+/g, " ");
        bank_name = bank_name.trim();
        bank_name = bank_name.replace('updatenegativepositive', '');
        bank_name = $.trim(bank_name);
        if (bank_name != "") {
            bankList.push(bank_name);
        }
    });

    $('#main-html-area .sub_header').each(function(i, el) {

        var $tds = $(this).find('td');
        var bank_name = "";

        //var firstTd = $tds.eq(0).children('ng-include').children('.sub_header');
        bank_name = $(this).clone().children().remove().end().text().replace(/<(?:.|\n)*?>/gm, '');

        bank_name = bank_name.replace(/\r?\n|\r/g, '');
        bank_name = bank_name.replace('_', '');
        bank_name = bank_name.replace('-', '');
        bank_name = bank_name.replace(/\s+/g, " ");
        bank_name = bank_name.trim();
        bank_name = bank_name.replace('updatenegativepositive', '');
        bank_name = $.trim(bank_name);
        if (bank_name != "" && bank_name != "Bankruptcy" && bank_name != "Risk Factors") {

            temp_array.push(bank_name);
            var bank_name_with_count_value = bank_name + getKeyIndex(bank_name, temp_array, bankList);

            if (!all_crditors_contacts_IQ[bank_name]) {
                all_crditors_contacts_IQ[bank_name] = "";
            }

            if (all_crditors_contacts_IQ[bank_name]) {
                final_bank_assoc[bank_name_with_count_value] = all_crditors_contacts_IQ[bank_name];
            }
        }
    });

    bank_address_dropDown_html += '<option data-value="" value="">Please select</option>';
    if (all_crditors_contacts_IQ) {
        for (var index in all_crditors_contacts_IQ) {
            if (all_crditors_contacts_IQ[index]) {
                var value = all_crditors_contacts_IQ[index];
                checked = "";
                var temp_bank = index;

                var bankNameArray = temp_bank.split('-');
                $.each(bankNameArray, function(i, value1) {
                    var index1 = value1;
                    if (index1 != null && index1 >= 1 && index1 <= 100) {
                        temp_bank = temp_bank.replace("-" + index1, "");
                        return false;
                    }
                });
                
                if (key_bank && $.trim(index) == $.trim(getBankRealName(key_bank))) {
                    checked = 'selected';
                    //console.log('key_bank', key_bank, index)
                    bank_address_dropDown_html += '<option data-key="' + index + '" data-value="' + value + '" value="' + value + '" ' + checked + '>' + temp_bank + " - " + value + '</option>';
                } else {
                    //console.log('address',getBankRealName(key_bank),index)
                    bank_address_dropDown_html += '<option data-key="' + index + '" data-value="' + value + '" value="' + value + '" ' + checked + '>' + temp_bank + " - " + value + '</option>';
                }

            }
        }
        bank_address_dropDown_html += '</select>';
    }
    var temp_html = individualSelectDropDown("current_bank_" + len);
    $(elem).append('&nbsp;' + bank_address_dropDown_html + temp_html);
}

function individualSelectDropDown(className) {

    var html = "";
    html = '<select data-key="banks" data-class="' + className + '" onchange="individualDropdownSelect(this)" style="width: auto;' +
        'padding: 0px;color: black;' +
        'height: 19px;' +
        'margin: 0px;' +
        'float: right;" name="individual_dp" class="review_type"><option value="3">Reset all items</option><option value="1">Set all items negative</option><option value="2">Set all items positive</option><option value=\"4\">Set all items Updated/Removed</option><option value="6">Set all items Repaired Accounts/Now Positive</option><option value=\"5\">Set all items Late Pays / 2 Or Less</option></select>';
    return html;
}

function individualDropdownSelect(elem) {
    var c = confirm('Are you sure want to change ?');
    if (c) {
        $('.' + $(elem).data('class')).val($(elem).val()).trigger('change');
    }
}

function findAccountInfoFromTable(table) {
    var Obj = {};
    var Obj1 = {};
    var Obj2 = {};
    var Obj3 = {};
    table.find('tr').each(function(i1, el) {
        var $tds = $(this).find('td');
        var firstTd = $tds.eq(0);
        var bank_name = unwantedcharremove(firstTd);

        if (bank_name == "Account #:") {
            Obj1['trans'] = unwantedcharremove($tds.eq(1).children('ng-repeat'));
            Obj1['exp'] = unwantedcharremove($tds.eq(2).children('ng-repeat'));
            Obj1['equif'] = unwantedcharremove($tds.eq(3).children('ng-repeat'));
            Obj['acc'] = Obj1;
            //return false;
        } else if (bank_name == "Account Type:") {
            Obj2['trans'] = unwantedcharremove($tds.eq(1).children('ng-repeat'));
            Obj2['exp'] = unwantedcharremove($tds.eq(2).children('ng-repeat'));
            Obj2['equif'] = unwantedcharremove($tds.eq(3).children('ng-repeat'));
            Obj['accType'] = Obj2;
            //return false;
        } else if (bank_name == "Balance:") {
            Obj3['trans'] = unwantedcharremove($tds.eq(1).children('ng-repeat'));
            Obj3['exp'] = unwantedcharremove($tds.eq(2).children('ng-repeat'));
            Obj3['equif'] = unwantedcharremove($tds.eq(3).children('ng-repeat'));
            Obj['balance'] = Obj3;
            return false;
        }
    });

    return Obj;
}

function findAccountInfoFromTableForSC(table) {
    var Obj = {};
    var Obj1 = {};
    var Obj2 = {};
    Obj['acc'] = "";
    Obj['accType'] = "";
    table.find('table.crLightTableBackground').first().find('tr').each(function(i1, el) {
        var $tds = $(this).find('td');
        var $tds_1 = $(this).find('td b');
        var firstTd = $tds_1.eq(0);

        var bank_name = unwantedcharremove(firstTd);
        //console.log('oooo',bank_name);
        Obj1['trans'] = "";
        Obj1['exp'] = "";
        Obj1['equif'] = "";

        Obj2['trans'] = "";
        Obj2['exp'] = "";
        Obj2['equif'] = "";

        if (bank_name == "Account #:") {

            Obj1['trans'] = unwantedcharremoveForSC($tds.eq(1));
            Obj1['exp'] = unwantedcharremoveForSC($tds.eq(2));
            Obj1['equif'] = unwantedcharremoveForSC($tds.eq(3));
            Obj['acc'] = Obj1;

        } else if (bank_name == "High Balance:") {

            Obj2['trans'] = unwantedcharremoveForSC($tds.eq(1));
            Obj2['exp'] = unwantedcharremoveForSC($tds.eq(2));
            Obj2['equif'] = unwantedcharremoveForSC($tds.eq(3));
            Obj['accType'] = Obj2;

            return false;
        }
    });

    return Obj;
}


function unwantedcharremove(firstTd) {
    var result = "";
    if (firstTd) {
        result = $.trim(firstTd.clone().children().remove().end().text().replace(/<(?:.|\n)*?>/gm, ''));
    }
    return result;
}

function unwantedcharremoveForSC(firstTd) {
    var result = "";
    if (firstTd) {
        result = $.trim(firstTd.clone().children().remove().end().text().replace(/<(?:.|\n)*?>/gm, ''));
    }

    if (result == '--') {
        result = ""
    }

    return result;
}

function findAccountAccTypeKey(acc, accType, key) {
    var result = "";
    if (BANK_ASSOC_ACCOUNT_INFO.trans) {
        for (var i in BANK_ASSOC_ACCOUNT_INFO.trans) {
            var current = BANK_ASSOC_ACCOUNT_INFO.trans[i];

            //BANK_ASSOC_ACCOUNT_CHANGE_INFO

            if (current.account == acc.trans && current.accType == accType.trans) {

                if (key != current.key) {
                    BANK_ASSOC_ACCOUNT_CHANGE_INFO[i] = key;
                    return { 'key': key, 'info': current };
                }
            }
        }
    }

    if (BANK_ASSOC_ACCOUNT_INFO.exp) {
        for (var i in BANK_ASSOC_ACCOUNT_INFO.exp) {
            var current = BANK_ASSOC_ACCOUNT_INFO.exp[i];
            //BANK_ASSOC_ACCOUNT_CHANGE_INFO
            if (acc == "11395**") {

            }

            if (current.account == acc.exp && current.accType == accType.exp) {
                if (key != current.key) {
                    //console.log('key_name_new2', key, current.key, acc, accType, current)
                    BANK_ASSOC_ACCOUNT_CHANGE_INFO[i] = key;
                    return { 'key': key, 'info': current };
                }
            }
        }
    }

    if (BANK_ASSOC_ACCOUNT_INFO.equif) {
        for (var i in BANK_ASSOC_ACCOUNT_INFO.equif) {
            var current = BANK_ASSOC_ACCOUNT_INFO.equif[i];
            //BANK_ASSOC_ACCOUNT_CHANGE_INFO

            if (current.account == acc.equif && current.accType == accType.equif) {

                if (key != current.key) {
                    BANK_ASSOC_ACCOUNT_CHANGE_INFO[i] = key;
                    return { 'key': key, 'info': current };
                }
            }
        }
    }

    return result;
}


function sameKeyBankConstantUpdate() {
    var tables = $("#main-html-area .crPrint");
    var bankAdditional = getBankAdditionalInfo();
    var banObj = [];
    var bankArray = [];
    var temp_array = [];
    var bankList = [];
    SAME_BANK_ACC_NO_TYPE_ASSOC = {};
    var all_crditors_contacts_IQ = getAllCreditorContactsByName()
    tables.find('tr').each(function(i1, el) {
        var $tds = $(this).find('td');
        var bank_name = "";
        var firstTd = $tds.eq(0).children('ng-include').children('.sub_header');
        bank_name = firstTd.clone().children().remove().end().text().replace(/<(?:.|\n)*?>/gm, '');
        bank_name = bank_name.replace(/\r?\n|\r/g, '');
        bank_name = bank_name.replace('_', '');
        bank_name = bank_name.replace('-', '');
        bank_name = bank_name.replace(/\s+/g, " ");
        bank_name = bank_name.trim();
        bank_name = bank_name.replace('updatenegativepositive', '');
        bank_name = $.trim(bank_name);
        if (bank_name != "") {
            bankList.push(bank_name);
        }
    });

    $('#main-html-area .sub_header').each(function(i, el) {


        var current_acc_info = findAccountInfoFromTable($(this).next('table.rpt_content_table'));
        var $tds = $(this).find('td');
        var bank_name = "";

        //var firstTd = $tds.eq(0).children('ng-include').children('.sub_header');
        bank_name = $(this).clone().children().remove().end().text().replace(/<(?:.|\n)*?>/gm, '');
        var nested_bank = $.trim($(this).children('ng.ng-binding').clone().children().remove().end().text().replace(/<(?:.|\n)*?>/gm, ''));

        bank_name = bank_name.replace(/\r?\n|\r/g, '');
        bank_name = bank_name.replace('_', '');
        bank_name = bank_name.replace('-', '');
        bank_name = bank_name.replace(/\s+/g, " ");
        bank_name = bank_name.trim();
        bank_name = bank_name.replace('updatenegativepositive', '');
        bank_name = $.trim(bank_name);

        // console.log('current_acc',current_acc_info,bank_name,nested_bank)

        if ((bank_name != "" || nested_bank) && bank_name != "Bankruptcy" && bank_name != "Risk Factors") {

            var currentClass = 'current_bank_' + i;
            var individualDropDown = allSelectDropDown(currentClass);
            var current_elem = null;
            if (!$(this).hasClass('publicrecordinfo')) {
                current_elem = $(this);
                $(this).append(individualDropDown);
            }

            if (!bank_name && nested_bank) {
                bank_name = nested_bank;
            }

            temp_array.push(bank_name);
            var bank_name_with_count_value = bank_name + getKeyIndex(bank_name, temp_array, bankList);
            //            if(bank_name_with_count_value){
            //                 $(this).text(bank_name_with_count_value);
            //            }
            var key_name_new = "";
            var bank_name_with_count_value1 = bank_name;

            if (is_from_history == 0 && current_acc_info.acc && current_acc_info.accType && bank_name) {
                // key_name_new = findAccountAccTypeKey(current_acc_info.acc, current_acc_info.accType, bank_name);
                var acc_trans = "";
                var bal_trans = "";
                var acType_trans = "";

                var acc_exp = "";
                var bal_exp = "";
                var acType_exp = "";

                var acc_equif = "";
                var bal_equif = "";
                var acType_equif = "";

                //console.log('dddcurrent_acc_info',current_acc_info)
                if (current_acc_info['balance']) {
                    bal_trans = current_acc_info.balance.trans;
                    bal_exp = current_acc_info.balance.exp;
                    bal_equif = current_acc_info.balance.equif;
                }

                if (current_acc_info['acc']) {
                    acc_trans = current_acc_info.acc.trans;
                    acc_exp = current_acc_info.acc.exp;
                    acc_equif = current_acc_info.acc.equif;
                }

                if (current_acc_info['accType']) {
                    acType_trans = current_acc_info.accType.trans;
                    acType_exp = current_acc_info.accType.exp;
                    acType_equif = current_acc_info.accType.equif;
                }

                SAME_BANK_ACC_NO_TYPE_ASSOC[bank_name_with_count_value1] = {
                    'trans_acc': acc_trans,
                    'trans_balance': bal_trans,
                    'trans_accType': acType_trans,
                    'exp_acc': acc_exp,
                    'exp_balance': bal_exp,
                    'exp_accType': acType_exp,
                    'equif_acc': acc_equif,
                    'equif_balance': bal_equif,
                    'equif_accType': acType_equif,
                };




            }



        }
    });

    //console.log('latest SAME_BANK_ACC_NO_TYPE_ASSOC',SAME_BANK_ACC_NO_TYPE_ASSOC)
}



function setSelectedBankDropDown(data) {
    
    var tables = $("#main-html-area .crPrint");
    var bankAdditional = getBankAdditionalInfo();
    var banObj = [];
    var bankArray = [];
    var temp_array = [];
    var bankList = [];


    var all_crditors_contacts_IQ = getAllCreditorContactsByName()
    tables.find('tr').each(function(i1, el) {
        var $tds = $(this).find('td');
        var bank_name = "";
        var firstTd = $tds.eq(0).children('ng-include').children('.sub_header');
        var inner_text_only = $.trim(firstTd.clone().children().remove().end().text().replace(/<(?:.|\n)*?>/gm, ''));
        //console.log('inner_text_only',inner_text_only);
        if(inner_text_only){
            bank_name = inner_text_only;
        }else{
            if(firstTd.children('ng').length > 0){
                bank_name = firstTd.children('ng').clone().children().remove().end().text().replace(/<(?:.|\n)*?>/gm, '');
            }else{
               bank_name = firstTd.clone().children().remove().end().text().replace(/<(?:.|\n)*?>/gm, '');
            }
        }
        
        
        bank_name = bank_name.replace(/\r?\n|\r/g, '');
        bank_name = bank_name.replace('_', '');
        bank_name = bank_name.replace('-', '');
        bank_name = bank_name.replace(/\s+/g, " ");
        bank_name = bank_name.trim();
        bank_name = bank_name.replace('updatenegativepositive', '');
        bank_name = $.trim(bank_name);
        
        if (bank_name != "") {
            bankList.push(bank_name);
        }
        
        
    });
    console.log('dddddd',bankList)
            
    var total_bank_count = 0;
    $('#main-html-area .sub_header').each(function(i, el) {


        //var current_acc_info = findAccountInfoFromTable($(this).next('table.rpt_content_table'));
        var $tds = $(this).find('td');
        var bank_name = "";

        //var firstTd = $tds.eq(0).children('ng-include').children('.sub_header');
        bank_name = $(this).clone().children().remove().end().text().replace(/<(?:.|\n)*?>/gm, '');
        var nested_bank = $.trim($(this).children('ng.ng-binding').clone().children().remove().end().text().replace(/<(?:.|\n)*?>/gm, ''));

        bank_name = bank_name.replace(/\r?\n|\r/g, '');
        bank_name = bank_name.replace('_', '');
        bank_name = bank_name.replace('-', '');
        bank_name = bank_name.replace(/\s+/g, " ");
        bank_name = bank_name.trim();
        bank_name = bank_name.replace('updatenegativepositive', '');
        bank_name = $.trim(bank_name);

        // console.log('current_acc',current_acc_info,bank_name,nested_bank)

        if ((bank_name != "" || nested_bank) && bank_name != "Bankruptcy" && bank_name != "Risk Factors") {

            var currentClass = 'current_bank_' + i;
            var individualDropDown = allSelectDropDown(currentClass);
            var current_elem = null;
            if (!$(this).hasClass('publicrecordinfo')) {
                current_elem = $(this);
                $(this).append(individualDropDown);
            }

            if (!bank_name && nested_bank) {
                bank_name = nested_bank;
            }

            temp_array.push(bank_name);
            var bank_name_with_count_value = bank_name + getKeyIndex(bank_name, temp_array, bankList);
            //            if(bank_name_with_count_value){
            //                 $(this).text(bank_name_with_count_value);
            //            }
            var key_name_new = "";
            var bank_name_with_count_value1 = bank_name_with_count_value;
/*
            if (is_from_history == 0 && current_acc_info.acc && current_acc_info.accType && bank_name) {
                // key_name_new = findAccountAccTypeKey(current_acc_info.acc, current_acc_info.accType, bank_name);
                var acc_trans = "";
                var bal_trans = "";
                var acType_trans = "";

                var acc_exp = "";
                var bal_exp = "";
                var acType_exp = "";

                var acc_equif = "";
                var bal_equif = "";
                var acType_equif = "";

                total_bank_count++;

                if (current_acc_info['balance']) {
                    bal_trans = current_acc_info.balance.trans;
                    bal_exp = current_acc_info.balance.exp;
                    bal_equif = current_acc_info.balance.equif;
                }

                if (current_acc_info['acc']) {
                    acc_trans = current_acc_info.acc.trans;
                    acc_exp = current_acc_info.acc.exp;
                    acc_equif = current_acc_info.acc.equif;
                }

                if (current_acc_info['accType']) {
                    acType_trans = current_acc_info.accType.trans;
                    acType_exp = current_acc_info.accType.exp;
                    acType_equif = current_acc_info.accType.equif;
                }

                SAME_BANK_ACC_NO_TYPE_ASSOC[bank_name_with_count_value1] = {
                    'trans_acc': acc_trans,
                    'trans_balance': bal_trans,
                    'trans_accType': acType_trans,
                    'exp_acc': acc_exp,
                    'exp_balance': bal_exp,
                    'exp_accType': acType_exp,
                    'equif_acc': acc_equif,
                    'equif_balance': bal_equif,
                    'equif_accType': acType_equif,
                };

                if (bank_name_with_count_value1.includes("US DEP ED")) {
                    //console.log('db SAME_BANK_ACC_NO_TYPE_ASSOC',current_acc_info,bank_name_with_count_value1,SAME_BANK_ACC_NO_TYPE_ASSOC)
                }

//                if (SAME_BANK_ASSOC_BY_ACCOUNT_NUMBER[current_acc_info.acc.trans + "_" + current_acc_info.accType.trans + "_" + bank_name_with_count_value1]) {
//                    bank_name_with_count_value1 = SAME_BANK_ASSOC_BY_ACCOUNT_NUMBER[current_acc_info.acc.trans + "_" + current_acc_info.accType.trans + "_" + bank_name_with_count_value1];
//                } else if (SAME_BANK_ASSOC_BY_ACCOUNT_NUMBER[current_acc_info.acc.exp + "_" + current_acc_info.accType.exp + "_" + bank_name_with_count_value1]) {
//                    bank_name_with_count_value1 = SAME_BANK_ASSOC_BY_ACCOUNT_NUMBER[current_acc_info.acc.exp + "_" + current_acc_info.accType.exp + "_" + bank_name_with_count_value1];
//                } else if (SAME_BANK_ASSOC_BY_ACCOUNT_NUMBER[current_acc_info.acc.equif + "_" + current_acc_info.accType.equif + "_" + bank_name_with_count_value1]) {
//                    bank_name_with_count_value1 = SAME_BANK_ASSOC_BY_ACCOUNT_NUMBER[current_acc_info.acc.equif + "_" + current_acc_info.accType.equif + "_" + bank_name_with_count_value1];
//                } else if (BANK_ASSOC_BY_ACCOUNT_NUMBER[current_acc_info.acc.trans + "_" + current_acc_info.accType.trans]) {
//                    bank_name_with_count_value1 = BANK_ASSOC_BY_ACCOUNT_NUMBER[current_acc_info.acc.trans + "_" + current_acc_info.accType.trans];
//                    //$(this).text(BANK_ASSOC_BY_ACCOUNT_NUMBER[current_acc_info.acc.trans+"_"+current_acc_info.accType.trans+"_"+bank_name]);
//                } else if (BANK_ASSOC_BY_ACCOUNT_NUMBER[current_acc_info.acc.exp + "_" + current_acc_info.accType.exp]) {
//                    bank_name_with_count_value1 = BANK_ASSOC_BY_ACCOUNT_NUMBER[current_acc_info.acc.exp + "_" + current_acc_info.accType.exp];
//                    //$(this).text(BANK_ASSOC_BY_ACCOUNT_NUMBER[current_acc_info.acc.exp+"_"+current_acc_info.accType.exp+"_"+bank_name]);
//                } else if (BANK_ASSOC_BY_ACCOUNT_NUMBER[current_acc_info.acc.equif + "_" + current_acc_info.accType.equif]) {
//                    bank_name_with_count_value1 = BANK_ASSOC_BY_ACCOUNT_NUMBER[current_acc_info.acc.equif + "_" + current_acc_info.accType.equif];
//                    //$(this).text(BANK_ASSOC_BY_ACCOUNT_NUMBER[current_acc_info.acc.equif+"_"+current_acc_info.accType.equif+"_"+bank_name]);
//                }



            }
            */
            if (key_name_new) {
                //$(this).text(key_name_new.key);
                // console.log('key_name_new',key_name_new);
            }

            if (bank_name_with_count_value1) {
                $(this).text(bank_name_with_count_value1);
            }



            var obj = { 'index': i, 'bank_name': bank_name_with_count_value1 };
            
            if (!all_crditors_contacts_IQ[bank_name]) {
                all_crditors_contacts_IQ[bank_name] = "";
            }
            if (current_elem) {
                setbank_address_dropDown_html(current_elem, i, bank_name, bank_name_with_count_value, data.DI);
            }

            $(this).nextAll('table').first().find('th').eq(0).attr('id', 'bank_address_text_' + i).css({ 'color': 'black' }).text(all_crditors_contacts_IQ[bank_name]);
            // my change code
            $.each(data.DI, function(db_i, db_value) {
                var db_bank_key = db_value.data_key.replace(/\r?\n|\r/g, '');
                db_bank_key = db_bank_key.replace(/\s+/g, " ");
                //db_bank_key = db_bank_key.replace('_', '');
                //db_bank_key = db_bank_key.replace('-', '');
                db_bank_key = $.trim(db_bank_key);
                var mybank = bank_name_with_count_value.replace('_', '');
                mybank = mybank.replace('-', '');

                var new_address = db_value.value2.replace(/\r?\n|\r/g, '');
                new_address = new_address.replace(/\s+/g, " ");

                if (bank_name_with_count_value == db_bank_key) {
                    if (new_address) {
                        new_address = $.trim(new_address);
                    }
                    if (new_address) {
                        $('#main-html-area #bank_address_' + i).val(new_address).trigger('change');
                        return false;
                    }
                }
            })

            $(this).nextAll('table').first().find('th.headerTUC').children('select').attr('id', 'selectiq_tuc_' + i);
            $(this).nextAll('table').first().find('th.headerTUC').children('select').attr('class', 'banks review_type ' + currentClass);
            $(this).nextAll('table').first().find('th.headerEXP').children('select').attr('id', 'selectiq_exp_' + i);
            $(this).nextAll('table').first().find('th.headerEXP').children('select').attr('class', 'banks review_type ' + currentClass);
            $(this).nextAll('table').first().find('th.headerEQF').children('select').attr('id', 'selectiq_eqf_' + i);
            $(this).nextAll('table').first().find('th.headerEQF').children('select').attr('class', 'banks review_type ' + currentClass);
            //$(this).children('select').attr('class','banks review_type');


            //            /acctype_tr.find('td.info').eq(0).append('dddddd');
            bankArray.push(obj);
        }

        if (bank_name != "" && bank_name != "Bankruptcy" && bank_name != "Risk Factors") {
            var getObj = findAccountFullInfoFromTable($(this), i, bank_name);
            var trans_dp_val = $('#main-html-area #selectiq_tuc_' + i).val();
            var exp_dp_val = $('#main-html-area #selectiq_exp_' + i).val();
            var equif_dp_val = $('#main-html-area #selectiq_eqf_' + i).val();

            var selected_values = {};
            selected_values['trans'] = trans_dp_val;
            selected_values['exp'] = exp_dp_val;
            selected_values['equif'] = equif_dp_val;

            getObj['selected_values'] = selected_values;

            NEGATIVE_ITEM_SELECTED_LIST_CREDIT_ANALYSIS[bank_name] = getObj;
        }
    });

    $.each(data.DI, function(i, value) {
        var index = getMatchKeyIndexIQ(value.data_key, bankArray);
        if (index) {
            var acctype_tr = $('#main-html-area #selectiq_tuc_' + index).parents('tr').first().next('tr.rowAlt').next('tr');
            var db_accType_value = value.value1;
            if (value.isJson == 1) {
                db_accType_value = JSON.parse(value.value1).accType;
            }
            if (db_accType_value) {
                // acctype_tr.find('td.info').eq(0).text(db_accType_value);
            }
            //$('#bank_address_'+index).val(value.value2).trigger('change');
            $('#main-html-area #selectiq_tuc_' + index).val(value.type).trigger('change');
            emptyRowSetByUpdatedAndRemoved($('#main-html-area #selectiq_tuc_' + index), 1)
            $('#main-html-area #selectiq_exp_' + index).val(value.type2).trigger('change');
            emptyRowSetByUpdatedAndRemoved($('#main-html-area #selectiq_exp_' + index), 2)
            $('#main-html-area #selectiq_eqf_' + index).val(value.type3).trigger('change');
            emptyRowSetByUpdatedAndRemoved($('#main-html-area #selectiq_eqf_' + index), 3)
        }

    })

    //alert(isFirstReport);

    //    console.log('total_bank_count',total_bank_count);
    //    console.log('SAME_BANK_ACC_NO_TYPE_ASSOC', SAME_BANK_ACC_NO_TYPE_ASSOC);
    //    console.log('NEGATIVE_ITEM_SELECTED_LIST_CREDIT_ANALYSIS', NEGATIVE_ITEM_SELECTED_LIST_CREDIT_ANALYSIS);



}


function emptyRowSetByUpdatedAndRemoved(parent, type) {
    var result = true;
    var table = parent.parents('table').first();

    table.find('tr').each(function(i, el) {
        if (i > 0) {
            var tds = $(this).find('td.info'); //687945012905318****
            var text = null
            if (type == 1) {
                text = $.trim(tds.eq(0).text().replace(/\r?\n|\r/g, ''));
            } else if (type == 2) {
                text = $.trim(tds.eq(1).text().replace(/\r?\n|\r/g, ''));
            } else if (type == 3) {
                text = $.trim(tds.eq(2).text().replace(/\r?\n|\r/g, ''));
            }

            if (text) {
                result = false;
                return false;
            }


        }
    });
    //if(result)

    if (result && is_editable) {
        //alert(hasHistory);
        var is_same_code = $('input[name=is_same_code]').val();
        var hasRp = $('input[name=is_first_report]').val();
        if (is_from_history == 0 && is_same_code == 0 && parent.val() == 1) {
            parent.val(4).trigger('change');
        } else if (isTextAreaChanged) {
            //parent.val(1).trigger('change');
        }

        //parent.val(4).trigger('change');
    }
}

function pushPrivacyGuardValues(array, key) {
    PRIVACY_GUARD_RESULTS.push({ 'bank_name': key, 'bank_info': array });
}

function getPrivacyGuardBankTableInfo() {
    var tables = $("#main-html-area #FtgCrTabContent5 .FtgCrContentRowTable");
    var banObj = [];


    var selectval = {};
    var objArray = [];

    tables.find('tr').each(function(i, el) {
        var obj = {};
        var obj1 = [];
        var $tds = $(this).find('td');
        var th = $(this).find('th');
        var expAccType = "";
        var equiFaxAccType = "";
        var transAccType = "";
        var key_name = "";
        var firstTh = th.eq(0).clone().children().remove().end().text();


        var bank_name = "";
        if (firstTh != "" && th.hasClass('FtgCrDarkTradeHead')) {
            bank_name = firstTh;
            var tr = th.parent();
            var trIQExp = th.parent().next('tr').children('th.FtgCrXPNHead');
            var trIQEqufx = th.parent().next('tr').children('th.FtgCrEFXHead');
            var trIQTransu = th.parent().next('tr').children('th.FtgCrTUCHead');
            var ExpType = 3;
            var EqufxType = 3;
            var TransuType = 3;
            if (trIQExp.children().has('select')) {
                ExpType = trIQExp.children('select').val();
            }

            if (trIQEqufx.children().has('select')) {
                EqufxType = trIQEqufx.children('select').val();
            }

            if (trIQTransu.children().has('select')) {
                TransuType = trIQTransu.children('select').val();
            }

            var trPGExp = th.parent().next('tr').children('th.FtgCrXPNHead');
            var trPGEqufx = th.parent().next('tr').children('th.FtgCrEFXHead');
            var trPGTransu = th.parent().next('tr').children('th.FtgCrTUCHead');

            if (trPGExp.children().has('select')) {
                ExpType = trPGExp.children('select').val();
            }

            if (trPGEqufx.children().has('select')) {
                EqufxType = trPGEqufx.children('select').val();
            }

            if (trPGTransu.children().has('select')) {
                TransuType = trPGTransu.children('select').val();
            }

            selectval = { 'Experian': ExpType, 'Equifax': EqufxType, 'TransUnion': TransuType };

            tr.next('tr').each(function() {

                var tr = $(this);
                var key = tr.children('th').eq(0).text();
                var text1 = $.trim(tr.children('td').eq(0).clone().children().remove().end().text());
                var text2 = $.trim(tr.children('td').eq(1).clone().children().remove().end().text());
                var text3 = $.trim(tr.children('td').eq(2).clone().children().remove().end().text());
                expAccType = text1;
                equiFaxAccType = text2;
                transAccType = text3;

                if (key != 'Date:' && key != "") {
                    obj1.push({
                        'Experian': { 'account': expAccType, 'key_name': key },
                        'Equifax': { 'account': equiFaxAccType, 'key_name': key },
                        'TransUnion': { 'account': transAccType, 'key_name': key },
                    });
                }
            });
            if ($.trim(bank_name) == "") {
                bank_name = "Unknown Company Name";
            }
            if (obj1 != "") {
                obj = {
                    'bank_name': $.trim(bank_name),
                    'address': "",
                    'phone': "",
                    'bank_info': obj1,
                    'type': selectval
                }


                objArray.push(obj);
            }
        }

    });

    return objArray;
}

function getStatusByDataKey1(key, data) {

    $.each(data.DB, function(index, value) {
        if (value.data_key == key) {
            info = value;
            return false;
        }

    });

    return info;
}


function setDropDownPrivacyGuardPersonalInfo(html, data) {
    var tables = $('#main-html-area .FtgCrContentRowTable').first();
    tables.find('tr').each(function(i, el) {
        var $ths = $(this).find('th');
        var firstTh = $ths.eq(0);
        var title = firstTh.text();
        var secondTd = firstTh.parent().children('td');
        title = title.replace(/\r?\n|\r/g, '');
        title = title.replace('_', '');
        title = title.replace('-', '');
        title = title.replace(/\s+/g, " ");
        title = title.replace(":", "");
        title = $.trim(title);

        var bank_name = "";
        bank_name = secondTd.eq(0).text().replace(/<(?:.|\n)*?>/gm, '');
        bank_name = bank_name.replace(/\r?\n|\r/g, '');
        bank_name = bank_name.replace('_', '');
        bank_name = bank_name.replace('-', '');
        bank_name = bank_name.replace(/\s+/g, " ");
        bank_name = bank_name.replace('updatenegativepositive', '');
        bank_name = bank_name.trim();
        var status = getStatusByDataKey1(title, data);


        if (bank_name != "") {
            secondTd.eq(0).append(html);
            var status3 = 3;
            if (status != "") {
                status3 = status.status3
            }
            secondTd.eq(0).children('select').val(status3).trigger('change');
            secondTd.eq(0).children('select').attr('class', 'all-select review_type');
        }

        bank_name = secondTd.eq(1).text().replace(/<(?:.|\n)*?>/gm, '');
        bank_name = bank_name.replace(/\r?\n|\r/g, '');
        bank_name = bank_name.replace('_', '');
        bank_name = bank_name.replace('-', '');
        bank_name = bank_name.replace(/\s+/g, " ");
        bank_name = bank_name.replace('updatenegativepositive', '');
        bank_name = bank_name.trim();

        if (bank_name != "") {
            secondTd.eq(1).append(html);
            var status1 = 3;
            if (status != "") {
                status1 = status.status1
            }
            secondTd.eq(1).children('select').val(status1).trigger('change');
            secondTd.eq(1).children('select').attr('class', 'all-select review_type');
        }

        bank_name = secondTd.eq(2).text().replace(/<(?:.|\n)*?>/gm, '');
        bank_name = bank_name.replace(/\r?\n|\r/g, '');
        bank_name = bank_name.replace('_', '');
        bank_name = bank_name.replace('-', '');
        bank_name = bank_name.replace(/\s+/g, " ");
        bank_name = bank_name.replace('updatenegativepositive', '');
        bank_name = bank_name.trim();

        if (bank_name != "") {
            secondTd.eq(2).append(html);
            var status2 = 3;
            if (status != "") {
                status2 = status.status2
            }

            secondTd.eq(2).children('select').val(status2).trigger('change');
            secondTd.eq(2).children('select').attr('class', 'all-select review_type');
        }

    });
}

function getDropDownPrivacyGuardPersonalInfo() {
    var tables = $('#main-html-area .FtgCrContentRowTable').first();
    var mainObj = [];
    tables.find('tr').each(function(i, el) {
        var $ths = $(this).find('th');
        var firstTh = $ths.eq(0);
        var title = firstTh.text();
        var experian = "";
        var experianType = 3;
        var equifax = "";
        var equifaxType = 3;
        var transunion = "";
        var transunionType = 3;
        var everyObj = {};
        var secondTd = firstTh.parent().children('td');
        title = title.replace(/\r?\n|\r/g, '');
        title = title.replace('_', '');
        title = title.replace('-', '');
        title = title.replace(/\s+/g, " ");
        title = title.replace(":", "");
        title = $.trim(title);

        var bank_name = "";
        bank_name = secondTd.eq(0).clone().children().remove().end().text().replace(/<(?:.|\n)*?>/gm, '');
        bank_name = bank_name.replace(/\r?\n|\r/g, '');
        bank_name = bank_name.replace('_', '');
        bank_name = bank_name.replace('-', '');
        bank_name = bank_name.replace(/\s+/g, " ");
        bank_name = $.trim(bank_name);
        bank_name = bank_name.replace('updatenegativepositive', '');
        if (bank_name != "") {
            experian = $.trim(bank_name);
            experianType = secondTd.eq(0).children('select').val();
        }

        bank_name = secondTd.eq(1).clone().children().remove().end().text().replace(/<(?:.|\n)*?>/gm, '');
        bank_name = bank_name.replace(/\r?\n|\r/g, '');
        bank_name = bank_name.replace('_', '');
        bank_name = bank_name.replace('-', '');
        bank_name = bank_name.replace(/\s+/g, " ");
        bank_name = bank_name.trim();
        bank_name = bank_name.replace('updatenegativepositive', '');

        if (bank_name != "") {
            equifax = $.trim(bank_name);
            equifaxType = secondTd.eq(1).children('select').val();
        }

        bank_name = secondTd.eq(2).clone().children().remove().end().text().replace(/<(?:.|\n)*?>/gm, '');
        bank_name = bank_name.replace(/\r?\n|\r/g, '');
        bank_name = bank_name.replace('_', '');
        bank_name = bank_name.replace('-', '');
        bank_name = bank_name.replace(/\s+/g, " ");
        bank_name = bank_name.trim();
        bank_name = bank_name.replace('updatenegativepositive', '');

        if (bank_name != "") {
            transunion = $.trim(bank_name);
            transunionType = secondTd.eq(2).children('select').val();
        }

        if (title != "") {
            everyObj = {
                'Experian': {
                    'data': experian,
                    'key_name': title,
                    'type': experianType
                },
                'Equifax': {
                    'data': equifax,
                    'key_name': title,
                    'type': equifaxType
                },
                'TransUnion': {
                    'data': transunion,
                    'key_name': title,
                    'type': transunionType
                }
            };
            mainObj.push(everyObj);
        }

    });

    return mainObj;
}




function getBankTableInfo() { // bank my code
    var tables = $("#main-html-area .crPrint");
    var bankAdditional = getBankAdditionalInfo();

    var banObj = [];
    tables.find('tr').each(function(i1, el) {
        var $tds = $(this).find('td');
        var bank_name = "";
        var firstTd = $tds.eq(0).children('ng-include').children('.sub_header');
        var header_select_tag = firstTd.next('table').find('th.headerTUC').children('select');
        var per_bank_row = 0;
        var transunionType = firstTd.next('table').find('th.headerTUC').children('select').val();
        var experianType = firstTd.next('table').find('th.headerEXP').children('select').val();
        var equifaxType = firstTd.next('table').find('th.headerEQF').children('select').val();

        bank_name = firstTd.clone().children().remove().end().text().replace(/<(?:.|\n)*?>/gm, '');
        bank_name = bank_name.replace(/\r?\n|\r/g, '');
        //bank_name = bank_name.replace('_', '');
        //bank_name = bank_name.replace('-', '');
        bank_name = bank_name.replace(/\s+/g, " ");
        bank_name = $.trim(bank_name);
        if (bank_name) {
            per_bank_row = parseInt(header_select_tag.prop('id').replace('selectiq_tuc_', ''));;
        }
        bank_name = bank_name.replace('updatenegativepositive', '');
        var subTable = $tds.eq(0).children('ng-include').children('.rpt_content_table');
        if (bank_name === "") {
            var bank_creditor_name = firstTd.children('ng').clone().children().remove().end().text();
            if (bank_creditor_name != "") {
                bank_name = $.trim(bank_creditor_name);
            }
        }

        if (bank_name != "") {

            var banObj1 = [];
            var obj1 = {};

            subTable.find('tr').each(function(i, el) {
                var obj = {};
                var $subtds = $(this).find('td');
                var key = $subtds.eq(0).text();
                var key_name = key.replace(/<(?:.|\n)*?>/gm, '');
                key_name = key.replace(/\r?\n|\r/g, '');
                key_name = key.replace(':', " ");
                key_name = key.replace(/\s+/g, " ");
                key_name = key.replace(" ", "");
                key_name = key.trim();
                if (key_name != "") {

                    var text1 = $subtds.eq(1).text().replace(/<(?:.|\n)*?>/gm, '');
                    text1 = text1.replace(/\r?\n|\r/g, '');
                    text1 = text1.replace('_', '');
                    text1 = text1.replace('-', '');
                    text1 = text1.replace(/\s+/g, " ");
                    text1 = text1.trim();
                    text1 = text1.replace('updatenegativepositive', '');

                    var text2 = $subtds.eq(2).text().replace(/<(?:.|\n)*?>/gm, '');
                    text2 = text2.replace(/\r?\n|\r/g, '');
                    text2 = text2.replace('_', '');
                    text2 = text2.replace('-', '');
                    text2 = text2.replace(/\s+/g, " ");
                    text2 = text2.trim();
                    text2 = text2.replace('updatenegativepositive', '');

                    var text3 = $subtds.eq(3).text().replace(/<(?:.|\n)*?>/gm, '');
                    text3 = text3.replace(/\r?\n|\r/g, '');
                    text3 = text3.replace('_', '');
                    text3 = text3.replace('-', '');
                    text3 = text3.replace(/\s+/g, " ");
                    text3 = text3.trim();
                    text3 = text3.replace('updatenegativepositive', '');

                    obj = {
                        'TransUnion': { account: text1, 'key_name': $.trim(key_name.replace(':', '')) },
                        'Experian': { account: text2, 'key_name': $.trim(key_name.replace(':', '')) },
                        'Equifax': { account: text3, 'key_name': $.trim(key_name.replace(':', '')) },
                    }

                    banObj1.push(obj);
                }

            });


            var bankInfo = getInfoByKey(bank_name, bankAdditional);
            var name = "";
            var address = "";
            var phone = "";
            if (bankInfo.bank_name != null) {
                name = bankInfo.bank_name
            }

            if (bankInfo.address != null) {
                //address = bankInfo.address
            }

            if ($('#main-html-area select[name="bank_addresses[' + per_bank_row + ']"]').find('option:selected').data('value')) {
                address = $('#main-html-area select[name="bank_addresses[' + per_bank_row + ']"]').find('option:selected').data('value');
            }

            if (bankInfo.phone != null) {
                phone = bankInfo.phone
            }
            if (bank_name == "") {
                bank_name = "Unknown Company Name";
            }
            banObj.push({
                'bank_name': bank_name,
                'address': address,
                'phone': phone,
                'type': {
                    'TransUnion': transunionType,
                    'Experian': experianType,
                    'Equifax': equifaxType
                },
                'bank_info': banObj1
            });
        }
    });


    var bankMergedData = [];
    $.each(banObj, function(index, value) {
        var currentObj = {};
        var isExist = isInfoExist($.trim(value.bank_name), bankAdditional, banObj);

        var dropDownType = 3;
        var current_address = "";
        var current_phone = "";
        var bank_info = "";
        if (value.address != "") {
            current_address = value.address;
        }

        if (value.phone != "") {
            current_phone = value.phone;
        }

        if (!isEmpty(value.type)) {
            dropDownType = value.type;
        }

        if (value.bank_info != null) {
            bank_info = value.bank_info;
        }
        currentObj = {
            'bank_name': value.bank_name,
            'address': current_address,
            'phone': current_phone,
            'bank_info': bank_info,
            'type': dropDownType
        }
        if (isExist.status == 1) {
            if (isExist.bankInfo.type > 0) {
                dropDownType = isExist.bankInfo.type;
            }

            if (isExist.bankInfo.address != "") {
                current_address = isExist.bankInfo.address;
            }

            if (isExist.bankInfo.phone != "") {
                current_phone = isExist.bankInfo.phone;
            }


            currentObj = {
                'bank_name': isExist.bankInfo.bank_name,
                'address': current_address,
                'phone': current_phone,
                'bank_info': bank_info,
                'type': dropDownType
            }
        }
        bankMergedData.push(currentObj);
    })


    return bankMergedData;
}

function isEmpty(obj) {
    for (var prop in obj) {
        if (obj.hasOwnProperty(prop))
            return false;
    }

    return true;
}

function getInfoByKey(key_name, arrayObj) {
    var bankInfo = {}
    var sanitizeKeyName = $.trim(key_name);

    if (arrayObj != null) {
        $.each(arrayObj, function(index, value) {
            if (sanitizeKeyName.indexOf($.trim(value.bank_name)) != -1) {
                bankInfo = value;
                return false;
            }
        });
    }
    return bankInfo;
}

function isInfoExist(key_name, arrayObj, mainArray) {
    var result = 0;
    var bankInfo = {}
    var sanitizeKeyName = $.trim(key_name);
    //alert(sanitizeKeyName);

    if (arrayObj != null) {

        $.each(arrayObj, function(index, value) {
            var add_bank_name = $.trim(value.bank_name);
            if (sanitizeKeyName.indexOf(add_bank_name) != -1) {
                result = 1;
                bankInfo = getBankArrayInfoBy(sanitizeKeyName, mainArray) //value;
                return false;
            }
        });
    }
    var obj = { 'status': result, 'bankInfo': bankInfo };
    return obj;
}

function getBankArrayInfoBy(key_name, mainArray) {
    var info = {};
    $.each(mainArray, function(index, value) {
        var bank_name = $.trim(value.bank_name);
        if (bank_name == key_name) {
            info = value;
            return false;
        }
    });

    return info;
}

function getBankAdditionalInfo() {
    var table = $('#main-html-area table.rpt_content_table:last');
    var bankObj = [];
    var obj = {};
    table.find('tr').each(function(i, el) {

        var $tds = $(this).find('td');
        var bank_name = "";
        bank_name = $tds.eq(0).text().replace(/<(?:.|\n)*?>/gm, '');
        bank_name = bank_name.replace(/\r?\n|\r/g, '');
        bank_name = bank_name.replace('_', '');
        bank_name = bank_name.replace('-', '');
        bank_name = bank_name.replace(/\s+/g, " ");
        bank_name = bank_name.trim();
        //alert(bank_name);return false;
        if (bank_name != "") {
            var $tds = $(this).find('td');
            var key = $tds.eq(0).text();

            var text1 = $tds.eq(1).text().replace(/<(?:.|\n)*?>/gm, '');
            text1 = text1.replace(/\r?\n|\r/g, '');
            text1 = text1.replace('_', '');
            text1 = text1.replace('-', '');
            text1 = text1.replace(/\s+/g, " ");
            text1 = text1.trim();
            text1 = text1.replace('updatenegativepositive', '');
            var text2 = $tds.eq(2).text().replace(/<(?:.|\n)*?>/gm, '');
            text2 = text2.replace(/\r?\n|\r/g, '');
            text2 = text2.replace('_', '');
            text2 = text2.replace('-', '');
            text2 = text2.replace(/\s+/g, " ");
            text2 = text2.trim();
            text2 = text2.replace('updatenegativepositive', '');
            var text3 = $tds.eq(3).text().replace(/<(?:.|\n)*?>/gm, '');
            text3 = text3.replace(/\r?\n|\r/g, '');
            text3 = text3.replace('_', '');
            text3 = text3.replace('-', '');
            text3 = text3.replace(/\s+/g, " ");
            text3 = text3.trim();
            text3 = text3.replace('updatenegativepositive', '');


            obj = {
                'bank_name': bank_name,
                'address': text1,
                'phone': text2
            }


            bankObj.push(obj);
        }

    });

    return bankObj;
}

function getTypeByDataKey(key, data) {
    var info = "";
    $.each(data.DI, function(index, value) {
        var newKey = getBankRealName(value.data_key);
        if ($.trim(key).indexOf(newKey) != -1) {
            info = value;
            return false;
        }

    });

    return info;
}


function getBankRealName(bank_name) {
    var realName = bank_name;
    var bankNameArray = bank_name.split('-');
    if (!bankNameArray) {
        realName = bank_name;
    }
    $.each(bankNameArray, function(i, value) {
        var index = value;
        if (index != null && index >= 1 && index <= 100) {
            realName = bank_name.replace("-" + index, "");
            return false;
        }
    });
    return realName;
}

function setInquiriesDropDown(html, data) {
    var dataObj = [];
    //imran changes
    //var html = "<select style=\"width: 120px;\n" +"padding: 0px;color: black;\n" +"height: 19px;\n" +"    margin: 0px;\n" +"    float: right;\" name=\"source_type\"  class=\"review_type\"><option value=\"3\">update</option><option value=\"1\">negative</option><option value=\"2\">positive</option></select>";
    var all_crditors_contacts_IQ = getAllCreditorContactsByName();
    $('#main-html-area .rpt_fullReport_header').each(function() {
        var inq = $(this).text();
        inq = $.trim(inq);

        if (inq == 'Inquiries') {
            $(this).children('select').remove();
            $(this).append(allSelectDropDown('inquiries'));
            var table = $(this).nextAll('table.rpt_content_table').first();
            table.find('tr').each(function(i, el) {
                var tds = $(this).find('td');
                var creditor_name = $.trim(tds.eq(0).text());
                var date_of_inq = $.trim(tds.eq(2).text());
                var creditor_bereau = $.trim(tds.eq(3).text());

                var item_category_id_Obj = {
                    Equifax: 2,
                    Experian: 1,
                    TransUnion: 3
                }
                if (creditor_bereau != "") {
                    var data_key = creditor_name + "_" + date_of_inq + "_" + item_category_id_Obj[creditor_bereau];
                    var type = getInquiryTypeByDataKey(data_key, data);
                    tds.eq(3).append(html);
                    var select_html = setInqAddressDropdownForIQ(creditor_name)
                    tds.eq(0).append(select_html);
                    if (type > 0) {

                        tds.eq(3).children('select').val(type).trigger('change');
                        tds.eq(3).children('select').attr('class', 'inquiries review_type');
                    }
                }
            });
        }
    });

}


function getInquiryTypeByDataKey(data_key, data) {

    var inquiry_type = 3;
    $.each(data.inquiry, function(index, value) {
        var key = value.inquiry_key;
        if (key == data_key) {
            inquiry_type = value.inquiry_type;
            //alert(inquiry_type);
            return false;
        }
    });

    return inquiry_type;
}

function getPublicTypeByDataKey(data_key, data) {
    var public_types = {
        'status1': 3,
        'status2': 3,
        'status3': 3
    };
    $.each(data.publicrecords, function(index, value) {
        var key = value.public_key;
        if (key == data_key) {
            public_types = {
                'status1': value.public_status1,
                'status2': value.public_status2,
                'status3': value.public_status3
            };
            return false;
        }
    });

    return public_types;
}

function setPublicInfoDropDown(html, data) {

    var dataObj = [];
    var publicInfoLabelSelect = $('#main-html-area #PublicInformation').children('.rpt_fullReport_header').children('select');
    var publicInfoTables = $('#main-html-area #PublicInformation .sub_header');

    var pb_count = 0;
    var all_crditors_contacts_IQ = getAllCreditorContactsByName();
    // console.log('public record',all_crditors_contacts_IQ);
    var address_html = "<select name='public_address_dropdown' style='text-align:left;color:black'>";
    address_html += '<option value="">Please select</option>';
    $.each(all_crditors_contacts_IQ, function(creaditor, address) {
        if (creaditor && address)
            address_html += '<option data-key="' + creaditor + '" data-value="' + address + '" value="' + creaditor + '">' + creaditor + " - " + address + '</option>';
    });
    address_html += '</select>';
    publicInfoTables.each(function(i, el) {
        if (!$(this).parent().hasClass('ng-hide')) {
            var pb_table_title = $(this).clone().children().remove().end().text();
            pb_count++;
            var dd_key = "individual_" + i;
            var string = "<select data-key='" + dd_key + "' onchange=\"selectAllPersonalinfoDropdown(this)\" style=\"width: auto;\n" + "    padding: 0px;color: black;\n" + "    height: 19px;\n" + "    margin: 0px;\n" + "    float: right;\" name=\"source_type\"  class=\"review_type\"><option value=\"3\">Reset all items</option><option value=\"1\">Set all items negative</option><option value=\"2\">Set all items positive</option><option value=\"4\">Set all items Updated/Removed</option></select>";
            $(this).addClass('publicrecordinfo');
            $(this).append(address_html + string);
            $(this).next('table.rpt_content_table').find('tr').each(function(i, el) {
                var tds = $(this).find('td');
                var key_name = $.trim(tds.eq(0).text()).replace('-', '');
                var creditor_name = $.trim(tds.eq(1).text()).replace('-', '');
                var date_of_inq = $.trim(tds.eq(2).text()).replace('-', '');

                var creditor_bereau = $.trim(tds.eq(3).text()).replace('-', '');
                key_name = key_name.replace(':', '');



                if (key_name != "") {
                    var types = getPublicTypeByDataKey(key_name + "-" + pb_count, data);
                }


                if (creditor_name != "") {
                    tds.eq(1).append(html);
                    tds.eq(1).children('select').val(types.status3).trigger('change');
                    tds.eq(1).children('select').attr('class', 'publicrecord review_type');
                    tds.eq(1).children('select').attr('class', 'publicrecord review_type ' + dd_key);
                }
                if (date_of_inq != "") {
                    tds.eq(2).append(html);
                    tds.eq(2).children('select').val(types.status1).trigger('change');
                    tds.eq(2).children('select').attr('class', 'publicrecord review_type ' + dd_key);
                }

                if (creditor_bereau != "") {
                    tds.eq(3).append(html);
                    tds.eq(3).children('select').val(types.status2).trigger('change');
                    tds.eq(3).children('select').attr('class', 'publicrecord review_type ' + dd_key);
                }


                if (key_name && key_name.toLowerCase() == "court") {
                    //console.log('creditor_name', all_crditors_contacts_IQ[creditor_name], all_crditors_contacts_IQ[date_of_inq], all_crditors_contacts_IQ[creditor_bereau])
                    //console.log('creditor_name111', creditor_name, date_of_inq, creditor_bereau)
                    if (all_crditors_contacts_IQ[creditor_name]) {
                        $('#main-html-area select[name="public_address_dropdown"]').val(creditor_name).trigger('change');
                        // $('select[name="public_address_dropdown"]').attr('data-type',$(this).children('select').val());
                    }

                    if (all_crditors_contacts_IQ[date_of_inq]) {

                        $('#main-html-area select[name="public_address_dropdown"]').val(date_of_inq).trigger('change');
                    }

                    if (all_crditors_contacts_IQ[creditor_bereau]) {

                        $('#main-html-area select[name="public_address_dropdown"]').val(creditor_bereau).trigger('change');
                    }
                    //tds.eq(1)
                }


            });
        }
    })



}

function getSelectedPublicInfo() {

    var dataObj = [];

    var html = "<select style=\"width: 120px;\n" + "padding: 0px;color: black;\n" + "height: 19px;\n" + "    margin: 0px;\n" + "    float: right;\" name=\"source_type\"  class=\"review_type\"><option value=\"3\">update</option><option value=\"1\">negative</option><option value=\"2\">positive</option></select>";

    $('#main-html-area #PublicInformation .sub_header').each(function() {
        var pb = $(this).text();


        pb = $(this).clone() //clone the element
            .children() //select all the children
            .remove() //remove all the children
            .end() //again go back to selected element
            .text();
        pb = $.trim(pb);

        if (pb) {
            var table_name = "";
            if ($(this).hasClass('publicrecordinfo')) {
                table_name = pb;
            }


            var table = $(this).nextAll('table.rpt_content_table').first();
            table.find('tr').each(function(i, el) {
                var replace_var = "Please selectnegativepositiveUpdated/Removed";
                var tds = $(this).find('td');
                var text0 = $.trim(tds.eq(0).text());
                var text1 = $.trim(tds.eq(1).text().replace(replace_var, ''));
                var text1 = $.trim(tds.eq(1).text().replace(replace_var, ''));
                var text1 = $.trim(tds.eq(1).text().replace(replace_var, ''));
                var text2 = $.trim(tds.eq(2).text().replace(replace_var, ''));
                var text2 = $.trim(tds.eq(2).text().replace(replace_var, ''));
                var text3 = $.trim(tds.eq(3).text().replace(replace_var, ''));
                var text3 = $.trim(tds.eq(3).text().replace(replace_var, ''));
                var type1 = ""
                var type2 = ""
                var type3 = ""

                //alert(text1+"==="+text2+"===="+text3);
                if (tds.eq(1).children('select').val() != null) {
                    var type1 = tds.eq(1).children('select').val();
                }

                if (tds.eq(2).children('select').val() != null) {
                    var type2 = tds.eq(2).children('select').val();
                }

                if (tds.eq(3).children('select').val() != null) {
                    var type3 = tds.eq(3).children('select').val();
                }

                if (table_name) {
                    //console.log('table name', table_name);
                    var obj = {
                        'TransUnion': { data: text1, 'type': type1, 'key_name': text0.replace(':', '') },
                        'Experian': { data: text2, 'type': type2, 'key_name': text0.replace(':', '') },
                        'Equifax': { data: text3, 'type': type3, 'key_name': text0.replace(':', '') },
                        'table_name': table_name
                    }

                    dataObj.push(obj);
                }
            });

            //return false;
        }

    });

    return dataObj;
}

function getSelectedInquiries() {
    var dataObj = [];
    var html = "<select style=\"width: 120px;\n" + "padding: 0px;color: black;\n" + "height: 19px;\n" + "    margin: 0px;\n" + "    float: right;\" name=\"source_type\"  class=\"review_type\"><option value=\"3\">update</option><option value=\"1\">negative</option><option value=\"2\">positive</option></select>";

    var data = $('#main-html-area div#Inquiries .rpt_fullReport_header');

    var previous_data = $('#main-html-area div#Inquiries .rpt_content_wrapper');

    var table = data.nextAll('table.rpt_content_table').first();

    table.find('tr').each(function(i, el) {

        var tds = $(this).find('td');
        var creditor_name = $.trim(tds.eq(0).clone() //clone the element
            .children() //select all the children
            .remove() //remove all the children
            .end() //again go back to selected element
            .text());
        var date_of_inq = $.trim(tds.eq(2).text());
        var creditor_bereau = tds.eq(3).text();
        creditor_bereau = creditor_bereau.replace('updatenegativepositive', '');
        creditor_bereau = creditor_bereau.replace('Please selectnegativepositiveUpdated/Removed', '');
        creditor_bereau = $.trim(creditor_bereau);
        if (creditor_name != "" || date_of_inq != "" || creditor_bereau != "") {
            var type = tds.eq(3).children('select').val();
            if (type == "") {
                type = 3;
            }
            var obj = {
                'key_name': creditor_name + "_" + date_of_inq,
                'creditor_bereau': creditor_bereau,
                'type': type
            };
            dataObj.push(obj);
        }
    });

    return dataObj;
}

function getSelectedInquiriesPrevious() {
    var dataObj = [];
    var html = "<select style=\"width: 120px;\n" + "padding: 0px;color: black;\n" + "height: 19px;\n" + "    margin: 0px;\n" + "    float: right;\" name=\"source_type\"  class=\"review_type\"><option value=\"3\">update</option><option value=\"1\">negative</option><option value=\"2\">positive</option></select>";

    $('#main-html-area .rpt_fullReport_header').each(function() {
        var inq = $(this).clone() //clone the element
            .children() //select all the children
            .remove() //remove all the children
            .end() //again go back to selected element
            .text();

        inq = $.trim(inq);

        if (inq == 'Inquiries') {
            var table = $(this).nextAll('table.rpt_content_table').first();
            table.find('tr').each(function(i, el) {

                var tds = $(this).find('td');
                var creditor_name = $.trim(tds.eq(0).clone() //clone the element
                    .children() //select all the children
                    .remove() //remove all the children
                    .end() //again go back to selected element
                    .text());
                var date_of_inq = $.trim(tds.eq(2).text());
                var creditor_bereau = tds.eq(3).text();
                creditor_bereau = creditor_bereau.replace('updatenegativepositive', '');
                creditor_bereau = creditor_bereau.replace('Please selectnegativepositiveUpdated/Removed', '');
                creditor_bereau = $.trim(creditor_bereau);
                if (creditor_name != "" || date_of_inq != "" || creditor_bereau != "") {
                    var type = tds.eq(3).children('select').val();
                    if (type == "") {
                        type = 3;
                    }
                    var obj = {
                        'key_name': creditor_name + "_" + date_of_inq,
                        'creditor_bereau': creditor_bereau,
                        'type': type
                    };
                    dataObj.push(obj);
                }
            });

            return false;
        }

    });

    return dataObj;
}

function setDropDownPublicRecordPrivacyGuard(html, data) {

    var table = $("#main-html-area div:contains('Public Records')").nextAll('table.FtgCrContentRowTable').first();
    table.find('tr').each(function(i, el) {
        var tds = $(this).find('td');
        var innerTable = tds.eq(0).children('table');

        tds.each(function(j, ele) {
            $(this).children('select').remove();

            if (!$(this).is(':empty')) {

                $(this).append(html.replace('float: right;', ''));
                $(this).children('select').attr('data-category', j);
                $(this).children('select').attr('class', 'public-records review_type');
            }
        });

    });
}


function getDropDownPublicRecordPrivacyGuard() {
    var dataObj = [];
    var table = $("#main-html-area div:contains('Public Records')").nextAll('table.FtgCrContentRowTable').first();
    table.find('tr').each(function(i, el) {
        if (i > 2) {
            var tds = $(this).find('td');
            var th = $(this).find('th');
            var key_name = $.trim(th.text());
            var text1 = "";
            var text2 = "";
            var text3 = "";
            var type1 = "";
            var type2 = "";
            var type3 = "";
            if (!tds.eq(0).is(':empty')) {
                text1 = tds.eq(0).clone().children().remove().end().text();
                type1 = tds.eq(0).children('select').val();
            }
            if (!tds.eq(1).is(':empty')) {
                text2 = tds.eq(1).clone().children().remove().end().text();
                type2 = tds.eq(1).children('select').val();
            }
            if (!tds.eq(2).is(':empty')) {
                text3 = tds.eq(2).clone().children().remove().end().text();
                type3 = tds.eq(2).children('select').val();
            }

            var obj = {
                'Experian': { data: text1, 'type': type1, 'key_name': key_name.replace(':', '') },
                'Equifax': { data: text2, 'type': type2, 'key_name': key_name.replace(':', '') },
                'TransUnion': { data: text3, 'type': type3, 'key_name': key_name.replace(':', '') }
            }
            dataObj.push(obj);
        }


    });


    return dataObj;

}


function setDropDownInquiryPrivacyGuard(html, data) {

    var table = $("#main-html-area div:contains('Credit Inquiries')").nextAll('table.FtgCrContentRowTable').first();
    table.find('tr').each(function(i, el) {
        var tds = $(this).find('td');
        var innerTable = tds.eq(0).children('table');

        tds.next('td.BlueLargeCheck').each(function(j, ele) {
            $(this).children('div').children('select').remove();
            if (!$(this).is(':empty')) {
                $(this).children('div').append(html.replace('float: right;', ''));
                $(this).children('div').children('select').attr('data-category', j);
                $(this).children('div').children('select').attr('class', 'inquries review_type');
            }
        });

    });
    setDropDownPublicRecordPrivacyGuard(html, data);
}


function getDropDownInquiryPrivacyGuard() {

    var table = $("#main-html-area div:contains('Credit Inquiries')").nextAll('table.FtgCrContentRowTable').first();
    var mainObjArray = [];
    table.find('tr').each(function(i, el) {
        var tds = $(this).find('td');
        //var innerTable = tds.eq(0).children('table');
        var experian = 3
        var equifax = 3;
        var transunion = 3;

        if (i > 0) {
            var innerTable = $(this).children('td').has('table');
            var dataTable = $(this).children('td').children('table');
            var innerTrs = innerTable.find('tr');
            var innerThs = innerTrs.eq(0).children('th');
            var innerObjTempArray = [];
            innerTable.find('tr').each(function(i, el) {
                var innerThs = $(this).find('th');
                var innerTds = $(this).find('td');
                var key_name = $.trim(innerThs.text());
                var innerTrs = innerThs.parent().next('tr').next('tr');
                var innerObjArray = [];
                innerTrs.each(function(i, el) {
                    var everyTds = $(this).children('td');
                    if (key_name != "") {
                        var parentTr = dataTable.parent('td').parent('tr');
                        var typeInfo = "";
                        var typeName = "";
                        parentTr.find('td.BlueLargeCheck').each(function() {

                            if ($(this).children('div').has('select').length) {
                                typeInfo = $(this).children('div').children('select').attr('id', 'pinq_' + i);
                                return false;
                            }
                        });

                        if (typeInfo.data('category') == 0) {
                            typeName = "Experian";
                        } else if (typeInfo.data('category') == 1) {
                            typeName = "Equifax";
                        } else if (typeInfo.data('category') == 2) {
                            typeName = "TransUnion";
                        }

                        mainObjArray.push({ 'key_name': key_name + "_" + $.trim(everyTds.eq(0).text()), 'creditor_bereau': typeName, 'type': typeInfo.val() });
                    }
                })

            })

        }
    });

    return mainObjArray;
}

function selectAllPersonalinfoDropdown(elem) {
    var value = $(elem).val();
    var className = $(elem).data('key');
    var r = confirm("Are you  sure to change all items?");
    if (r) {
        $('.' + className).val(value).trigger('change');
    }
}

function selectSmartCreditAllMainDropdown(elem) {
    var value = $(elem).val();
    var className = $(elem).data('key');
    var r = confirm("Are you  sure to change all items?");
    if (r) {
        $('.' + className).data('enable', 0);
        $('.' + className).val(value).trigger('change');
    }
}

function changeAllSmartCreditDropdown(elem) {
    var value = $(elem).val();
    var className = $(elem).data('key');
    var r = true;
    if ($(elem).data('enable') == 1) {
        r = confirm("Are you  sure to change all items?");
    }
    if (r) {
        $('.' + className).val(value).change();
    }
}

function allSelectDropDown(key, appent_option = "") {
    var string = "<select data-key='" + key + "' onchange=\"selectAllPersonalinfoDropdown(this)\" style=\"width: auto;\n" + "    padding: 0px;color: black;\n" + "    height: 19px;\n" + "    margin: 0px;\n" + "    float: right;\" name=\"source_type\"  class=\"review_type\"><option value=\"3\">Reset all items</option><option value=\"1\">Set all items negative</option><option value=\"2\">Set all items positive</option><option value=\"4\">Set all items Updated/Removed</option>'" + appent_option + "'</select>";
    return string;
}

function allSelectSubDropDown(key, appent_option = "") {
    var string = "<select data-key='" + key + "' data-enable='1' onchange=\"changeAllSmartCreditDropdown(this)\" style=\"width: auto;\n" + "    padding: 0px;color: black;\n" + "    height: 19px;\n" + "    margin: 0px;\n" + "    float: right;\" name=\"source_type\"  class=\"review_type\"><option value=\"3\">Reset all items</option><option value=\"1\">Set all items negative</option><option value=\"2\">Set all items positive</option><option value=\"4\">Set all items Updated/Removed</option>" + appent_option + "</select>";
    return string;
}

function allSelectSmartCreditDropDown(key, appent_option = "") {
    var string = "<select data-key='" + key + "' onchange=\"selectSmartCreditAllMainDropdown(this)\" style=\"width: auto;\n" + "    padding: 0px;color: black;\n" + "    height: 19px;\n" + "    margin: 0px;\n" + "    float: right;\" name=\"source_type\"  class=\"review_type\"><option value=\"3\">Reset all items</option><option value=\"1\">Set all items negative</option><option value=\"2\">Set all items positive</option><option value=\"4\">Set all items Updated/Removed</option>" + appent_option + "</select>";
    return string;
}



function setAllGlobalDropdown() {
    $('#main-html-area .rpt_fullReport_header').each(function() {
        var currentText = $(this).text();
        currentText = $.trim(currentText);
        if (currentText == 'Personal Information') {
            $(this).append(allSelectDropDown('all-select'))
        }

        if (currentText == 'Public Information') {
            $(this).append(allSelectDropDown('publicrecord'));
            //return false;
        }

        if (currentText == 'Account History') {

            var appent_option = '<option value=\"6\">Repaired Accounts/Now Positive</option>';
            appent_option += '<option value=\"5\">Late Pays / 2 Or Less</option>';
            $(this).append(allSelectDropDown('banks', appent_option));
            //return false;
        }
    });

    $('#main-html-area .FtgFullReportHeader').each(function() {
        var currentText = $.trim($(this).text());
        if (currentText == 'Personal Profile') {
            $(this).append(allSelectDropDown('all-select'))
        }

        if (currentText == 'Credit Inquiries') {
            $(this).append(allSelectDropDown('inquries'))
        }

        if (currentText == 'Public Records') {
            $(this).append(allSelectDropDown('public-records'))
        }

        if (currentText == 'Account History') {
            var appent_option = '<option value=\"6\">Repaired Accounts/Now Positive</option>';
            appent_option += '<option value=\"5\">Late Pays / 2 Or Less</option>';
            $(this).append(allSelectDropDown('banks', appent_option))
        }
    });

    $('#main-html-area #personalInfo').append(allSelectDropDown('smart-cerdit-personal-info'));

}

function getCreditScoreData() {
    var obj = {};
    var credit_score = $('#main-html-area #CreditScore');
    if (credit_score.length > 0) {
        let score_selector = $('#main-html-area #CreditScore table.rpt_content_table').first().find('tr');
        let previous_selector = $('#main-html-area #CreditScore').nextAll('table.rpt_content_table').first().find('tr');
        if(previous_selector.length>0){
            score_selector = previous_selector;
        }
        score_selector.each(function() {
            var td0 = $(this).children('td').eq(0);
            var td1 = $(this).children('td').eq(1);
            var td2 = $(this).children('td').eq(2);
            var td3 = $(this).children('td').eq(3);
            var text0 = $.trim(td0.clone().children().remove().end().text());
            var TransUnion = $.trim(td1.clone().children().remove().end().text());
            var Experian = $.trim(td2.clone().children().remove().end().text());
            var Equifax = $.trim(td3.clone().children().remove().end().text());
            //console.log('pre text0',text0)
            if (text0) {
                //console.log('text0',text0)
                if (text0 == "Credit Score:" || text0 == "FICO Score 8:") {
                    obj = { 'TransUnion': TransUnion, 'Experian': Experian, 'Equifax': Equifax };
                    //alert("TransUnion: "+TransUnion+" Experian : "+Experian+" Equifax : "+Equifax);
                    return false;
                }
            }
        })

    }

    return obj;
}

function removeDropdownCreditScore() {
    var obj = {};
    var credit_score = $('#main-html-area #CreditScore');

    if (credit_score.length > 0) {

        let score_selector = $('#main-html-area #CreditScore table.rpt_content_table').first().find('tr');
        let previous_selector = $('#main-html-area #CreditScore').nextAll('table.rpt_content_table').first().find('tr');
        if(previous_selector.length>0){
            score_selector = previous_selector;
        }
         score_selector.each(function() {

            var td0 = $(this).children('td').eq(0).children('select').remove();
            var td1 = $(this).children('td').eq(1).children('select').remove();
            var td2 = $(this).children('td').eq(2).children('select').remove();
            var td3 = $(this).children('td').eq(3).children('select').remove();

        })

    }


}


function saveCode() {
    var formData = {};
    var history_checkbox = $('input[name=isHistory]');
    if (history_checkbox.prop('checked')) {
        var client_id = $('select[name=client_id]').val();
        formData = {
                member_id: MEMBER_ID,
                client_id: client_id,
                export_type: $('select[name=source_type]').val()
            }
            //alert("You have three records saved already for this client.")

    }

    return formData;
}

function getAllCreditorContactsByName() {
    var table = $("#main-html-area #CreditorContacts .rpt_content_table");
    var result = {};

    table.find('tr').each(function(i, el) {
        var $tds = $(this).find('td');
        var key = $tds.eq(0).text();
        var key = $tds.eq(0).text();
        if (key != "") {
            var name = $tds.eq(0).text().replace(/<(?:.|\n)*?>/gm, '');
            name = name.replace(/\r?\n|\r/g, '');
            name = name.replace('_', '');
            name = name.replace('-', '');
            name = name.replace(/\s+/g, " ");
            name = name.trim();


            var address = $tds.eq(1).text().replace(/<(?:.|\n)*?>/gm, '');
            address = address.replace(/\r?\n|\r/g, '');
            address = address.replace('_', '');
            address = address.replace('-', '');
            address = address.replace(/\s+/g, " ");
            address = address.trim();

            result[name] = address;
        }
    });
    
    result = objectKeySortAlphabetically(result)
   
    return result;
}



function objectKeySortAlphabetically(result){
   return Object.keys(result).sort().reduce(
                (obj, key) => { 
                  obj[key] = result[key]; 
                  return obj;
                }, 
                {}
        );
}

function SortArray(x, y){
    if (x.bank < y.bank) {return -1;}
    if (x.bank > y.bank) {return 1;}
    return 0;
}


function setUIscrollFloat(){
    
    // $('#recent-report-area .recent-view-html').removeClass('open-scroll');
    // $('#main-html-area .view-html').removeClass('open-scroll');
    
    $('#recent-report-area select').removeClass('float-reset');
    $('#main-html-area select').removeClass('float-reset');
    
    if($('#recent-report-area').hasClass('col-md-6')){
        $('#recent-report-area select').addClass('float-reset');
        $('#recent-report-area .recent-view-html').addClass('open-scroll')
    }
        
    if($('#main-html-area').hasClass('col-md-6')){
        $('#main-html-area select').addClass('float-reset');
        $('#main-html-area .view-html').addClass('open-scroll')
    }
}

function getRecentReport(response) {
    var loader = $('.loading');
    //loader.show();
    var formData = {};
    formData['action'] = "HTML_HISTORY_INFO";
    formData['client_id'] = $('select[name=client_id]').val();
    formData['source_type'] = $('select[name=source_type]').val();


    if (response.html_content) {
        //$("#recent-report-area select").remove();
        recent_uploadHTMLUICode(response.html_content, false, null, response);

        comapareBetweenCurrentAndLastReport()
        $('#plus').removeClass('hide');
        $('#plus').show();
    } else {
        //alert('No previous report found.')
    }

}


function getAccountValuesByKey(json){
    $.each(json,function(index,value){
        CURRENT_ACCOUNT_DB_KEY_ASSOC[value.data_key] = {
            'trans': value.type,
            'exp': value.type2,
            'equif': value.type3,
        }
    })
}
