
//var procesed_bank_name_ids = [];
var all_bank_name_prop_id = [];
var all_same_bank_info = [];
var GLOBAL_COUNTER = 0;
var RECENT_ACCOUNT_DB_KEY_ASSOC = {}
var RECENT_DB_KEY_ACCOUNT_ASSOC = {}

function recent_uploadCreditReportCoreFunction(elem, isVelocity) {

    IS_CHANGE_DROPDOWN = false
    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 ($('#recent-report-area select[name="public_address_dropdown"]').val()) {
        var temp_obj = {
            'creditor_name': $('#recent-report-area select[name="public_address_dropdown"] option:selected').data('key'),
            'creditor_address': $('#recent-report-area select[name="public_address_dropdown"] option:selected').data('value')
        };

        formData['public_record_address'] = temp_obj;
    }
    var creditor_inq_selected_contacts = {};
    $('#recent-report-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;
    }
    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 recent_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 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 recent_uploadHTMLUICode(content, isVelocity = false, report_type = null,history_data) {

    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();
    }
    
    if($('select[name=report_type]').val()){
        source_type = $('select[name=report_type]').val();
    }
    //console.log('after source_type assign', source_type);
    $('.credit-report, .recent-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);
        }
        
        $('#recent-report-area').remove();
        if($('#main-html-area').parent('.row').length > 0){
            $('#main-html-area').parent('.row').prepend('<div id="recent-report-area" class="col-md-6 hide"><div class="recent-view-html open-scroll"></div></div>');
        }else{
            $('#main-html-area').parent().prepend('<div id="recent-report-area" class="col-md-6 hide"><div class="recent-view-html open-scroll"></div></div>');
        }
        
        //console.log('ssssss',$('#main-html-area'));
        $('#recent-report-area .recent-view-html').html(content)
        $('#recent-report-area .recent-view-html #reportTop .content-heading').remove();
        $('#recent-report-area .recent-view-html #reportTop .content-box .alert').remove();
        $('#recent-report-area .recent-view-html #reportTop #_hjRemoteVarsFrame').remove();
        $('#recent-report-area .recent-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();
        
        setUIscrollFloat()
        
        

    } catch (e) {

    }
    
    //console.log('before recent_getSelectedInfo', source_type);
    if ($('.recent-view-html').html()) {
        recent_getSelectedInfo(isVelocity, source_type,history_data);
        $('.loading').hide();
    }

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

    if (isRemovedDropDown) {
        //removeAddressDropDown();
    }

}

function replace_text(str, find, replace) {
    debugger;
    let ex = str.indexOf(find);
    let result = '';
    if(ex>0)
    {
        result = str.replace(str,replace);
    }
    return result;
}



function recent_getSelectedInfo(isVelocity, report_type = null,history_data) {
    //
    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;
    }
    
    //history-checkbox
            $('#full-page-loader').hide();
            $('#full-page-loader h3').text('');
            var info = history_data;
            //console.log('full_json', info)
            
            getRecentAccountValuesByKey(history_data.datadocument.DI);
            console.log('history_data12',RECENT_ACCOUNT_DB_KEY_ASSOC);
            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 = history_data;
            //var hasHistory = true;
            if (isFirstReport && history_id > 0) {
                hasHistory = false;
            }
            //console.log(info);
            //SELECTED_ASSOC = json;

            if (info) {
                 var DB_PUBLIC_RECORD = {};
                var DB_PUBLIC_RECORD = info.publicrecords[0];

            }
            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);
            
            recent_getInquiriesAndPublicSelectedInfo(html, info);
            if (source_type == 1) {
                recent_setDropDownforPersonalInfo(json);
                
                //$('.sub_header').append(html);
                $('#recent-report-area .sub_header').next('table').find('th.headerTUC').append(html_account);
                $('#recent-report-area .sub_header').next('table').find('th.headerEXP').append(html_account);
                $('#recent-report-area .sub_header').next('table').find('th.headerEQF').append(html_account);

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

                $('#recent-report-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;
                                }
                            })
                        }
                    }
                })

                recent_setSelectedBankDropDown(json);

            } else if (source_type == 2) {
                var inq = setDropDownInquiryPrivacyGuard(html, info);
                var bankNameList = [];
                var bankList = [];
                var temp_array = [];
                setDropDownPrivacyGuardPersonalInfo(html, data);
                $('#recent-report-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);
                })

                $('#recent-report-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);

                    $('#recent-report-area #select_pg_exp_' + index).val(value.type2).trigger('change');
                    $('#recent-report-area #select_pg_eqf_' + index).val(value.type3).trigger('change');
                    $('#recent-report-area #select_pg_tuc_' + index).val(value.type).trigger('change');
                });
            } else if (source_type == 3) {
                recent_setSmartCreditDropDownForPersonalInfo(json);
                recent_setSmartCreaditAccountHistory(json);
                recent_setSmartCreditInquiriesDropdown(info);
                recent_setSmartCreditPublicDropdown(info);
                
            }
            recent_setDropdownAndAddressForBank()
            recent_setAllGlobalDropdown();
            
            $('#main-html-area .view-html').addClass('open-scroll')
            $('#recent-report-area .recent-view-html').addClass('open-scroll');
            return false;
    

}

function recent_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 = $("#recent-report-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]) {
                                $('#recent-report-area select[name="public_address_dropdown"]').val(current_text).trigger('change')
                                $('#recent-report-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]) {
                                $('#recent-report-area select[name="public_address_dropdown"]').val(current_text).trigger('change')
                                $('#recent-report-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]) {
                                $('#recent-report-area select[name="public_address_dropdown"]').val(current_text).trigger('change')
                                $('#recent-report-area select[name="public_address_dropdown"]').attr('data-type', $(this).children('select').val());
                            }

                        }
                    }
                }

            }
        })
    })

}


function recent_setSmartCreditInquiriesDropdown(data) {

    var db_inquiry = data.inquiry

    var contactInfo = [];
    var inquries_tbl = $("#recent-report-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 recent_setSmartCreditDropDownForPersonalInfo(data) {
    var personal_info_tbl = $('#recent-report-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 recent_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 = $('#recent-report-area #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 = [];
    $('#recent-report-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);
    });

    $('#recent-report-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');

            recent_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) {
                        $("#recent-report-area #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 recent_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 = '';
    $('#recent-report-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);
        }

    });

    $('#recent-report-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 recent_setDropdownAndAddressForBank() {
    var all_crditors_contacts_smart_credit = recent_creditorContactsSmartCredit()
    var all_crditors_contacts_IQ = recent_getAllCreditorContactsByName()
    
}

function recent_getAllCreditorContactsByName() {
    var table = $("#recent-report-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 recent_creditorContactsSmartCredit() {
    var contactInfo = [];
    var creditor_tbl = $("#recent-report-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 recent_setDropDownforPersonalInfo(data) {
    var assocDB = [];
    console.log('p data',data);
    var table = $('#recent-report-area table.rpt_content_table:eq(1)');
    //var table = $('table.rpt_content_table:eq(0)');

    table = $('#recent-report-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 recent_setSelectedBankDropDown(data) {
    var tables = $("#recent-report-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');
        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);
        }
    });
    var total_bank_count = 0;
    $('#recent-report-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);

            var key_name_new = "";
            var bank_name_with_count_value1 = bank_name_with_count_value;

            if (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) {
                recent_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) {
                        $('#recent-report-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 = findAccountFullInfoFromTableForRecentReport($(this), i, bank_name);
            var trans_dp_val = $('#recent-report-area #selectiq_tuc_' + i).val();
            var exp_dp_val = $('#recent-report-area #selectiq_exp_' + i).val();
            var equif_dp_val = $('#recent-report-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 = $('#recent-report-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');
            $('#recent-report-area #selectiq_tuc_' + index).val(value.type).trigger('change');
            emptyRowSetByUpdatedAndRemoved($('#recent-report-area #selectiq_tuc_' + index), 1)
            $('#recent-report-area #selectiq_exp_' + index).val(value.type2).trigger('change');
            emptyRowSetByUpdatedAndRemoved($('#recent-report-area #selectiq_exp_' + index), 2)
            $('#recent-report-area #selectiq_eqf_' + index).val(value.type3).trigger('change');
            emptyRowSetByUpdatedAndRemoved($('#recent-report-area #selectiq_eqf_' + index), 3)
        }

    })


}


function recent_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 = $("#recent-report-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);
        }
    });

    $('#recent-report-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 {
                    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 recent_setAllGlobalDropdown() {
    $('#recent-report-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;
        }
    });

    $('#recent-report-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))
        }
    });

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

}

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

function recent_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();
    $('#recent-report-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('#recent-report-area 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 recent_setPublicInfoDropDown(html, data) {

    var dataObj = [];
    var publicInfoLabelSelect = $('#recent-report-area #PublicInformation').children('.rpt_fullReport_header').children('select');
    var publicInfoTables = $('#recent-report-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('#recent-report-area 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]) {
                        $('#recent-report-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]) {

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

                    if (all_crditors_contacts_IQ[creditor_bereau]) {

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


            });
        }
    })



}

function twoTableComparison(table1,table2,label_name){
    var is_matched = true
    table1.each(function(){
        var row=$(this).html();
        table2.each(function(){
            if(row != $(this).html()){
                is_matched = false;
                console.log('label_name',label_name);
                return false;
            };
        });
    });
    
    return is_matched;
}


function allTableComparison(main_table,left_label_name){
    var left_label = $('#recent-report-area .sub_header');
    //var left_label_name = left_label.clone().children().remove().end().text();
    //var left_table = $('.sub_header')
    left_label.each(function(){
        var left_table = $(this).next('table.rpt_content_table').first();
        twoTableComparison(left_table,main_table,left_label_name)
    })
 
}

function parseBankFromIQ(id,bank_name_selector){
    var tables = $(id+" .crPrint");
   // var bankAdditional = getBankAdditionalInfo();
    var CURRENT_REPORT_ACCOUNT_TABLE_INFO = [];
    var banObj = [];

    var compare_keys = [
        'ACCOUNT #:',			
        'ACCOUNT TYPE:',		
        //'ACCOUNT TYPE - DETAIL:',			
        //'BUREAU CODE:',			
        //'ACCOUNT STATUS:',		
        //'MONTHLY PAYMENT:',	
        //'DATE OPENED:',			
        'BALANCE:',			
        //'NO. OF MONTHS (TERMS):',			
        'HIGH CREDIT:',			
        'CREDIT LIMIT:',			
        //'PAST DUE:',			
        //'PAYMENT STATUS:',		
        //'LAST REPORTED:',			
        //'DATE LAST ACTIVE:',
        //'DATE OF LAST PAYMENT:'
    ];
    //console.log('id',id)
    
    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 subTable = $tds.eq(0).children('ng-include').children('.rpt_content_table');
        var bank_name_id = bank_name_selector+GLOBAL_COUNTER;
        GLOBAL_COUNTER++;
        
        firstTd.prop('id',bank_name_id);
        var curr_key_name = firstTd.clone() //clone the element
                                    .children() //select all the children
                                    .remove() //remove all the children
                                    .end() //again go back to selected element
                                    .text();
        curr_key_name = $.trim(curr_key_name);                            
        //=====================
    //     if(id == "#recent-report-area"){
    //         curr_key_name = $.trim(curr_key_name);
    //         var current_data_from_last_report = {};
    //         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 text0 = $subtds.eq(0).text().replace(/<(?:.|\n)*?>/gm, '');
    //                     text0 = text0.replace(/\r?\n|\r/g, '');
    //                     text0 = text0.replace('_', '');
    //                     text0 = text0.replace('-', '');
    //                     text0 = text0.replace(/\s+/g, " ");
    //                     text0 = text0.trim();
    //                     text0 = text0.replace('updatenegativepositive', '');
                        
    //                     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(':', '')) },
    // //                    }
    //             if(curr_key_name && $.inArray(text0.toUpperCase(), ['ACCOUNT #:']) !== -1){
    //                     current_data_from_last_report[curr_key_name] = {
    //                             'trans':{
    //                                 'acc':text1,
    //                                 // 'accType':JSON.parse(value.value1).accType,
    //                                 // 'status':value.type
    //                             } ,
    //                             'exp':{
    //                                 'acc':text2,
    //                                 // 'accType':JSON.parse(value.value5).accType,
    //                                 // 'status':value.type2
    //                             } ,
    //                             'equif': {
    //                                 'acc':text3,
    //                                 // 'accType':JSON.parse(value.value6).accType,
    //                                 // 'status':value.type3
    //                             },
                                
    //                         }

    //                         return false;
    //                 }
    //             }
    //         });
    //         var current_last_rprt_acc_string = "";
    //         var db_last_rprt_acc_string = "";
    //         if(current_data_from_last_report[curr_key_name] && RECENT_ACCOUNT_DB_KEY_ASSOC[curr_key_name]){
                
    //             current_last_rprt_acc_string = current_data_from_last_report[curr_key_name].trans.acc;
    //             current_last_rprt_acc_string += current_data_from_last_report[curr_key_name].exp.acc;
    //             current_last_rprt_acc_string += current_data_from_last_report[curr_key_name].equif.acc;

    //             db_last_rprt_acc_string = RECENT_ACCOUNT_DB_KEY_ASSOC[curr_key_name].trans.acc;
    //             db_last_rprt_acc_string += RECENT_ACCOUNT_DB_KEY_ASSOC[curr_key_name].exp.acc;
    //             db_last_rprt_acc_string += RECENT_ACCOUNT_DB_KEY_ASSOC[curr_key_name].equif.acc;

    //             if(db_last_rprt_acc_string != current_last_rprt_acc_string){
    //                 curr_key_name = RECENT_DB_KEY_ACCOUNT_ASSOC[current_last_rprt_acc_string];
    //                 // firstTd.next('table').find('th.headerTUC').children('select').val(RECENT_ACCOUNT_DB_KEY_ASSOC[curr_key_name].trans.status).trigger('change');
    //                 // firstTd.next('table').find('th.headerEXP').children('select').val(RECENT_ACCOUNT_DB_KEY_ASSOC[curr_key_name].exp.status).trigger('change');
    //                 // firstTd.next('table').find('th.headerEQF').children('select').val(RECENT_ACCOUNT_DB_KEY_ASSOC[curr_key_name].equif.status).trigger('change');
    //             }
    //         }
            
            
    //         console.log('current_data_from_last_report',curr_key_name,current_last_rprt_acc_string,db_last_rprt_acc_string,RECENT_DB_KEY_ACCOUNT_ASSOC[current_last_rprt_acc_string])
    //     }


        //========================
        
        var curr_children = firstTd.children('select');
        firstTd.find('br').remove();
        
        if(curr_key_name){
            firstTd.html(curr_key_name+'<br/>');
            firstTd.append(curr_children);
        }
        var header_select_tag = firstTd.next('table').find('th.headerTUC').children('select');
        var per_bank_row = 0;
        var trans_select = firstTd.next('table').find('th.headerTUC').children('select');
        var exp_select = firstTd.next('table').find('th.headerEXP').children('select');
        var equif_select = firstTd.next('table').find('th.headerEQF').children('select');
        var transunionType = trans_select.val();
        var experianType = exp_select.val();
        var equifaxType = equif_select.val();

        //console.log('tables',header_select_tag)
        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', '');
        
        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 per_bank_info = {};
            var full_table_string = "";
            var trans_full_table_string = "";
            var exp_full_table_string = "";
            var equif_full_table_string = "";
            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 text0 = $subtds.eq(0).text().replace(/<(?:.|\n)*?>/gm, '');
                    text0 = text0.replace(/\r?\n|\r/g, '');
                    text0 = text0.replace('_', '');
                    text0 = text0.replace('-', '');
                    text0 = text0.replace(/\s+/g, " ");
                    text0 = text0.trim();
                    text0 = text0.replace('updatenegativepositive', '');
                    
                    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(':', '')) },
//                    }
                    
                    per_bank_info[text0] = {
                        'TransUnion':text1,
                        'Experian':text2,
                        'Equifax':text3
                    };
                    
                    //console.log('ssss',text0,compare_keys);
                    if($.inArray(text0.toUpperCase(), compare_keys) !== -1){
                        trans_full_table_string +=text1;
                        exp_full_table_string +=text2;
                        equif_full_table_string +=text3;

                        full_table_string +=text0+text1+text2+text3;
                    }
                    
                    
                    
                   
                }

            });
           
            var key_assoc_obj = {};
            var per_bank_selected_info = {};
            
            per_bank_selected_info['selected_value'] = {};
            per_bank_selected_info['selected_value']['trans'] = transunionType
            per_bank_selected_info['selected_value']['exp'] = experianType
            per_bank_selected_info['selected_value']['equif'] = equifaxType
            
            per_bank_selected_info['selected_ids'] = {};
            per_bank_selected_info['selected_ids']['trans'] = trans_select.prop('id');
            per_bank_selected_info['selected_ids']['exp'] = exp_select.prop('id');
            per_bank_selected_info['selected_ids']['equif'] = equif_select.prop('id');
            
            per_bank_selected_info['bank_name_id'] = bank_name_id;
            
            var key_less_bank_name = bank_name;
            if(key_less_bank_name){
                key_assoc_obj[key_less_bank_name] = {};
                key_assoc_obj[key_less_bank_name]['selected_info'] = per_bank_selected_info;
                key_assoc_obj[key_less_bank_name]['table_info'] = per_bank_info;
                key_assoc_obj[key_less_bank_name]['per_table_string'] = full_table_string;
                key_assoc_obj[key_less_bank_name]['trans_per_table_string'] = trans_full_table_string;
                key_assoc_obj[key_less_bank_name]['exp_per_table_string'] = exp_full_table_string;
                key_assoc_obj[key_less_bank_name]['equif_per_table_string'] = equif_full_table_string;
            }
            
            
            
            CURRENT_REPORT_ACCOUNT_TABLE_INFO.push(key_assoc_obj);
        }
    });


    //console.log('CURRENT_REPORT_ACCOUNT_TABLE_INFO',CURRENT_REPORT_ACCOUNT_TABLE_INFO);
    return CURRENT_REPORT_ACCOUNT_TABLE_INFO;
}

function parseBankFromSC(id,bank_name_selector){
    var bankInfo = [];
    // imran bank info
    var CURRENT_REPORT_ACCOUNT_TABLE_INFO = [];
    $(id+' .crWhiteTradelineHeader b').each(function(i, el1) {
        var bank_name_id = bank_name_selector+GLOBAL_COUNTER;
        GLOBAL_COUNTER++;
        $(this).prop('id',bank_name_id);
        $(this).find('br').remove();
        $(this).append('<br/>');
        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');
            var per_bank_info = {};
            var full_table_string = "";
            var trans_full_table_string = "";
            var exp_full_table_string = "";
            var equif_full_table_string = "";
            var trans_select = null;
            var exp_select = null
            var equif_select = null
            current_table.find('tr').each(function(j, el2) {
                var obj = {};
                var tds = $(this).find('td');
                trans_select = tds.eq(1).children('select');
                exp_select = tds.eq(2).children('select');
                equif_select = tds.eq(3).children('select')
                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 = exp_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 = equif_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 = trans_select.val();
                    }
                }
                if (title) {
                    obj = {
                        'TransUnion': { account: text1, 'key_name': title },
                        'Experian': { account: text2, 'key_name': title },
                        'Equifax': { account: text3, 'key_name': title },
                    }

                    per_bank_info[title] = {
                        'TransUnion':text1,
                        'Experian':text2,
                        'Equifax':text3
                    };
                    
                    trans_full_table_string +=text1;
                    exp_full_table_string +=text2;
                    equif_full_table_string +=text3;
                     
                    full_table_string +=title+text1+text2+text3;
                    //current_bankInfo.push(obj);
                }
            });
            
            var key_assoc_obj = {};
            var per_bank_selected_info = {};
            
            per_bank_selected_info['selected_value'] = {};
            per_bank_selected_info['selected_value']['trans'] = transType
            per_bank_selected_info['selected_value']['exp'] = expType
            per_bank_selected_info['selected_value']['equif'] = equfType
            
            per_bank_selected_info['selected_ids'] = {};
            per_bank_selected_info['selected_ids']['trans'] = trans_select.prop('id');
            per_bank_selected_info['selected_ids']['exp'] = exp_select.prop('id');
            per_bank_selected_info['selected_ids']['equif'] = equif_select.prop('id');
            
            per_bank_selected_info['bank_name_id'] = bank_name_id;
            
            var key_less_bank_name = getBankRealName(bank);
            if(key_less_bank_name){
                key_assoc_obj[key_less_bank_name] = {};
                key_assoc_obj[key_less_bank_name]['selected_info'] = per_bank_selected_info;
                key_assoc_obj[key_less_bank_name]['table_info'] = per_bank_info;
                key_assoc_obj[key_less_bank_name]['per_table_string'] = full_table_string;
                key_assoc_obj[key_less_bank_name]['trans_per_table_string'] = trans_full_table_string;
                key_assoc_obj[key_less_bank_name]['exp_per_table_string'] = exp_full_table_string;
                key_assoc_obj[key_less_bank_name]['equif_per_table_string'] = equif_full_table_string;
            }

            CURRENT_REPORT_ACCOUNT_TABLE_INFO.push(key_assoc_obj);
        }
    });
    //console.log('CURRENT_REPORT_ACCOUNT_TABLE_INFO',CURRENT_REPORT_ACCOUNT_TABLE_INFO)
    return CURRENT_REPORT_ACCOUNT_TABLE_INFO;
}


function getReportBankTableInfo(id,bank_name_selector) { // bank my code
    GLOBAL_COUNTER = 0;
    var source_type = $('select.credit-report-type').val();
    if($('select[name=report_type]').val()){
        source_type = $('select[name=report_type]').val();
    }
    var result = [];
    if(source_type == 1){
        result = parseBankFromIQ(id,bank_name_selector);
    }else if(source_type == 3){
        result = parseBankFromSC(id,bank_name_selector)
    }
    return result;
}


function max_occurence_elements_in_array(array)
{
    if(array.length == 0)
        return null;
    var modeMap = {};
    var maxEl = array[0], maxCount = 1;
    for(var i = 0; i < array.length; i++)
    {
        var el = array[i];
        if(modeMap[el] == null)
            modeMap[el] = 1;
        else
            modeMap[el]++;  
        if(modeMap[el] > maxCount)
        {
            maxEl = el;
            maxCount = modeMap[el];
        }
    }
    return maxEl;
}

function is_same_bank(current_key,recent_report_key,recent_report_values,current_value){
    
    var current_string_array = [];
    var result = 0;
    if(current_value.trans_per_table_string)
    current_string_array.push(current_value.trans_per_table_string);
    
    if(current_value.exp_per_table_string)
    current_string_array.push(current_value.exp_per_table_string);
    
    if(current_value.equif_per_table_string)
    current_string_array.push(current_value.equif_per_table_string);

    console.log('current_value',current_value,recent_report_values);

    var final_max_occurrence_string = max_occurence_elements_in_array(current_string_array);
    var x = 0;
    
    var prev_name = $('#'+recent_report_values.selected_info.bank_name_id).clone().children().remove().end().text();
    if(recent_report_values.trans_per_table_string && recent_report_values.trans_per_table_string == final_max_occurrence_string){
        x = 1;
        
        result = 1;            
    }else if(recent_report_values.exp_per_table_string && recent_report_values.exp_per_table_string == final_max_occurrence_string){
        x = 2;
        
        result = 2;             
    }else if(recent_report_values.equif_per_table_string && recent_report_values.equif_per_table_string == final_max_occurrence_string){
        x = 3;
       
        result = 3;                 
    }
    
    //

    if(current_key === "TELECOM SELFREPORTED-3" || current_key === "ONEMAIN-2"){
        //var current_id = $(`#main-html-area .sub_header:contains('${current_key}')`);
        console.log('=============');
        console.log('x',x);
        console.log('prev_name',prev_name);
        console.log('select_id_exp',current_value.selected_info.selected_ids.exp);
        console.log('ssss',current_key,current_value,recent_report_values);
        console.log('findmax',final_max_occurrence_string);
        console.log('=============');
    }

    return result;
}

function compareWithCurrentReportByRecentReportKeys(recent_report_key,recent_report_values){
    var current_info = getReportBankTableInfo('#main-html-area','main-bank_name');
    
    $.each(current_info,function(key,value){
        var keys = Object.keys(value);
        var values = Object.values(value);
        if(keys.length > 0 && values.length > 0){
            var current_key = keys[0];
            var current_value = values[0];
              
              //
              
            
            if($.inArray(current_value.selected_info.bank_name_id, procesed_bank_name_ids) == -1){
                var is_allowed = false;
                
                if(getBankRealName(current_key) == getBankRealName(recent_report_key)){
                    is_allowed = true;
                }else if(isReplaceNameByComparingAccount(current_value,recent_report_values)){
                    is_allowed = true;
                }

                if(is_allowed){
                    var type = 0;
                    type = is_same_bank(current_key,recent_report_key,recent_report_values,current_value);

                    if(type > 0){
                        
                        var current_id = current_value.selected_info.bank_name_id;
                        var select_html = $('#'+current_id).children();
                        var prev_name = $('#'+recent_report_values.selected_info.bank_name_id).clone().children().remove().end().text();
                        prev_name = $.trim(prev_name);

                        $('#'+current_id).html(select_html);
                        $('#'+current_id).prepend(prev_name);
                       // console.log('select_html',select_html)
                        if(type == 1){
                            // for 1
                            //console.log('1',current_key,prev_name,current_value.selected_info.selected_ids,CURRENT_ACCOUNT_DB_KEY_ASSOC[prev_name])
                            if(CURRENT_ACCOUNT_DB_KEY_ASSOC[prev_name]){
                                //console.log('ai',current_key,prev_name)
                                if(CURRENT_ACCOUNT_DB_KEY_ASSOC[prev_name].exp)
                                $('#main-html-area #'+current_value.selected_info.selected_ids.exp).val(CURRENT_ACCOUNT_DB_KEY_ASSOC[prev_name].exp).trigger('change');
                                
                                if(CURRENT_ACCOUNT_DB_KEY_ASSOC[prev_name].trans)
                                $('#main-html-area #'+current_value.selected_info.selected_ids.trans).val(CURRENT_ACCOUNT_DB_KEY_ASSOC[prev_name].trans).trigger('change');
                                
                                if(CURRENT_ACCOUNT_DB_KEY_ASSOC[prev_name].equif)
                                $('#main-html-area #'+current_value.selected_info.selected_ids.equif).val(CURRENT_ACCOUNT_DB_KEY_ASSOC[prev_name].equif).trigger('change');
                            }
                            if(!current_value.trans_per_table_string && recent_report_values.selected_info.selected_value.trans == 1){
                                $('#main-html-area #'+current_value.selected_info.selected_ids.trans).val(4).trigger('change')
                            }

                            if(!current_value.exp_per_table_string && recent_report_values.selected_info.selected_value.exp == 1){
                                $('#main-html-area #'+current_value.selected_info.selected_ids.exp).val(4).trigger('change')
                            }

                            if(!current_value.equif_per_table_string && recent_report_values.selected_info.selected_value.equif == 1){
                                $('#main-html-area #'+current_value.selected_info.selected_ids.equif).val(4).trigger('change')
                            }
                        }else if(type == 2){
                            // for 2
                            //console.log('2',current_key,prev_name,current_value.selected_info.selected_ids,CURRENT_ACCOUNT_DB_KEY_ASSOC[prev_name])
                            if(CURRENT_ACCOUNT_DB_KEY_ASSOC[prev_name]){

                                if(CURRENT_ACCOUNT_DB_KEY_ASSOC[prev_name].exp)
                                $('#main-html-area #'+current_value.selected_info.selected_ids.exp).val(CURRENT_ACCOUNT_DB_KEY_ASSOC[prev_name].exp).trigger('change');
                                
                                if(CURRENT_ACCOUNT_DB_KEY_ASSOC[prev_name].trans)
                                $('#main-html-area #'+current_value.selected_info.selected_ids.trans).val(CURRENT_ACCOUNT_DB_KEY_ASSOC[prev_name].trans).trigger('change');
                                
                                if(CURRENT_ACCOUNT_DB_KEY_ASSOC[prev_name].equif)
                                $('#main-html-area #'+current_value.selected_info.selected_ids.equif).val(CURRENT_ACCOUNT_DB_KEY_ASSOC[prev_name].equif).trigger('change');
                            }
                            if(!current_value.trans_per_table_string && recent_report_values.selected_info.selected_value.trans == 1){
                                $('#main-html-area #'+current_value.selected_info.selected_ids.trans).val(4).trigger('change')
                            }
                    
                            if(!current_value.exp_per_table_string && recent_report_values.selected_info.selected_value.exp == 1){
                                $('#main-html-area #'+current_value.selected_info.selected_ids.exp).val(4).trigger('change')
                            }
                    
                            if(!current_value.equif_per_table_string && recent_report_values.selected_info.selected_value.equif == 1){
                                $('#main-html-area #'+current_value.selected_info.selected_ids.equif).val(4).trigger('change')
                            }
                        }else if(type == 3){
                            // for 3
                            //console.log('3',current_key,prev_name,current_value.selected_info.selected_ids,CURRENT_ACCOUNT_DB_KEY_ASSOC[prev_name])
                            if(CURRENT_ACCOUNT_DB_KEY_ASSOC[prev_name]){

                                if(CURRENT_ACCOUNT_DB_KEY_ASSOC[prev_name].exp)
                                $('#main-html-area #'+current_value.selected_info.selected_ids.exp).val(CURRENT_ACCOUNT_DB_KEY_ASSOC[prev_name].exp).trigger('change');
                                
                                if(CURRENT_ACCOUNT_DB_KEY_ASSOC[prev_name].trans)
                                $('#main-html-area #'+current_value.selected_info.selected_ids.trans).val(CURRENT_ACCOUNT_DB_KEY_ASSOC[prev_name].trans).trigger('change');
                                
                                if(CURRENT_ACCOUNT_DB_KEY_ASSOC[prev_name].equif)
                                $('#main-html-area #'+current_value.selected_info.selected_ids.equif).val(CURRENT_ACCOUNT_DB_KEY_ASSOC[prev_name].equif).trigger('change');
                            }
                            if(!current_value.trans_per_table_string && recent_report_values.selected_info.selected_value.trans == 1){
                                $('#main-html-area #'+current_value.selected_info.selected_ids.trans).val(4).trigger('change')
                            }
                    
                            if(!current_value.exp_per_table_string && recent_report_values.selected_info.selected_value.exp == 1){
                                $('#main-html-area #'+current_value.selected_info.selected_ids.exp).val(4).trigger('change')
                            }
                    
                            if(!current_value.equif_per_table_string && recent_report_values.selected_info.selected_value.equif == 1){
                                $('#main-html-area #'+current_value.selected_info.selected_ids.equif).val(4).trigger('change')
                            }
                        }

                        if($.inArray(current_id, all_bank_name_prop_id) == -1){
                            all_bank_name_prop_id.push(current_id);
                            all_same_bank_info.push({
                                'id':current_id,
                                'old_name':current_key
                            });
                        }
                    }

                }
                if(current_id)
                procesed_bank_name_ids.push(current_id);
            }    
        }
            
   })

   //console.log('all_bank_name_prop_id',all_bank_name_prop_id)
}

function comapareBetweenCurrentAndLastReport(){
  
   var recent_info = getReportBankTableInfo('#recent-report-area','recent-bank_name');
   $.each(recent_info,function(key,value){
       compareWithCurrentReportByRecentReportKeys(Object.keys(value)[0],Object.values(value)[0]);
   })
    console.log('all_same_bank_info',all_same_bank_info)
    console.log('procesed_bank_name_ids',procesed_bank_name_ids)
   $.each(procesed_bank_name_ids,function(x,y){
        var replaced_name = getBankNameByPropId(y);
        $.each(all_same_bank_info,function(i,value){
            var old_name = value.old_name;
            if(replaced_name == old_name){
                var replacable_prop_id = value.id;
                /*$.each(all_same_bank_info,function(i,value1){

                })*/
                if(y == value.id){
                    var select_html = $('#'+replacable_prop_id).children();
                    $('#'+replacable_prop_id).html(select_html);
                    $('#'+replacable_prop_id).prepend(old_name);
                    console.log('y=value1.id',y);
                    console.log('post',replacable_prop_id,value.old_name,old_name,replaced_name);
                    return false;
                }
            }
        });
    })
}


function getBankNameByPropId(id){
    return $(`#${id}`).clone().children().remove().end().text().replace(/<(?:.|\n)*?>/gm, '')
}

function getRecentAccountValuesByKey(json){
    $.each(json,function(index,value){
        var trans_acc = JSON.parse(value.value1).account;
        var exp_acc = JSON.parse(value.value5).account;
        var equif_acc = JSON.parse(value.value6).account;
        RECENT_ACCOUNT_DB_KEY_ASSOC[value.data_key] = {
            'trans':{
                'acc':trans_acc,
                'accType':JSON.parse(value.value1).accType,
                'status':value.type
            } ,
            'exp':{
                'acc':exp_acc,
                'accType':JSON.parse(value.value5).accType,
                'status':value.type2
            } ,
            'equif': {
                'acc':equif_acc,
                'accType':JSON.parse(value.value6).accType,
                'status':value.type3
            },
            
        }
        var final_string = "";
        if(trans_acc){
            final_string = trans_acc
        }

        if(exp_acc){
            final_string += exp_acc
        }

        if(equif_acc){
            final_string += equif_acc
        }

        if(final_string){
            RECENT_DB_KEY_ACCOUNT_ASSOC[final_string] = value.data_key;
        }
        
    })
}

function isReplaceNameByComparingAccount(current_value,recent_value){
    var result = false;
    var recent_report_account_list = makeAccountList(recent_value);
    var current_report_account_list = makeAccountList(current_value);
    var count = 0;
    
    for(var i in current_report_account_list){
        if($.inArray(current_report_account_list[i], recent_report_account_list) !== -1){
            count++;
        }
    }

    if(count >= 2){
        result = true;
    }

    if(result){
        console.log('test2',current_report_account_list,recent_report_account_list);  
        console.log('test1',count,result);
    }
    

    return result;
}

function makeAccountList(info){
    var accountlist = [];
    if(info.table_info['Account #:']['TransUnion']){
        accountlist.push(info.table_info['Account #:']['TransUnion']);
    }
    
    if(info.table_info['Account #:']['Equifax']){
        accountlist.push(info.table_info['Account #:']['Equifax']);
    }
    
    if(info.table_info['Account #:']['Experian']){
        accountlist.push(info.table_info['Account #:']['Experian']);
    }

    return accountlist;
}



function findAccountFullInfoFromTableForRecentReport(table, index, key_name) {
    var Obj = {};
    var date_opened = {};
    var day_count = {};
    var derogetory = {};
    var comments = {};
    var paymentStatus = {};
    var credit_limit = {};
    var balance = {};
    var accountType = {};
    var accountStatus = {};
    var accountno = {};

    var next_table = table.next('table.rpt_content_table');
    var is_new_bank = false;

    if (IS_CHANGE_DROPDOWN && isFirstReport) {
        // if not in array that means new bank check here
        if ($.inArray(key_name, ALL_KEY_INFOS['account_history_info']) == -1) {
            is_new_bank = true;
        }
    }
    //console.log('New Bank', is_new_bank, key_name, IS_CHANGE_DROPDOWN, isFirstReport, ALL_KEY_INFOS['account_history_info'])

    next_table.find('tr').each(function (i1, el) {

        var $tds = $(this).find('td');
        var firstTd = $tds.eq(0);
        var bank_name = unwantedcharremove(firstTd);
        var trans_val = "";
        var exp_val = "";
        var equif_val = "";

        if (bank_name && is_new_bank) {
            trans_val = unwantedcharremoveforIQ($tds.eq(1));
            exp_val = unwantedcharremoveforIQ($tds.eq(2));
            equif_val = unwantedcharremoveforIQ($tds.eq(3));

            var isSelectedItem = false;
            var accType = "Account Type:";
            var payment_status = "PAYMENT STATUS:";
            if (bank_name.toLowerCase() == toLowerCase("Account #:")) {
                if (trans_val) {
                    accountno['trans'] = trans_val;
                }

                if (exp_val) {
                    accountno['exp'] = exp_val;
                }

                if (equif_val) {
                    accountno['equif'] = equif_val;
                }

            } else if (bank_name.toLowerCase() == accType.toLowerCase()) {
                if (trans_val) {
                    accountType['trans'] = trans_val;
                }

                if (exp_val) {
                    accountType['exp'] = exp_val;
                }

                if (equif_val) {
                    accountType['equif'] = equif_val;
                }

            } else if (bank_name.toLowerCase() == payment_status.toLowerCase()) {

                if (trans_val)
                    if (trans_val == toLowerCase("Collection/Chargeoff") || trans_val == toLowerCase("Late Payment") || trans_val.toLowerCase().includes(toLowerCase("late"))) {
                        setBankTransNegativeForRecentReport(index);
                        paymentStatus['trans'] = trans_val;
                    }
                if (exp_val)
                    if (exp_val == toLowerCase("Collection/ChargeOff") || exp_val == toLowerCase("Late Payment") || exp_val.toLowerCase().includes(toLowerCase("late"))) {
                        setBankExpNegativeForRecentReport(index);
                        paymentStatus['exp'] = trans_val;
                    }
                if (equif_val)
                    if (equif_val == toLowerCase("Collection/ChargeOff") || equif_val == toLowerCase("Late Payment") || equif_val.toLowerCase().includes(toLowerCase("late"))) {
                        setBankEquifNegativeForRecentReport(index);
                        paymentStatus['equif'] = trans_val;
                    }


            } else if (bank_name.toLowerCase() == toLowerCase("ACCOUNT STATUS:")) {

                if (trans_val)
                    if (trans_val == toLowerCase("Derogatory")) {
                        derogetory['trans'] = "Derogatory";
                        setBankTransNegativeForRecentReport(index);
                    } else {
                        accountStatus['trans'] = trans_val;
                    }
                if (exp_val)
                    if (exp_val == toLowerCase("Derogatory")) {
                        setBankExpNegativeForRecentReport(index);
                        derogetory['exp'] = "Derogatory";
                    } else {
                        accountStatus['exp'] = exp_val;
                    }
                if (equif_val)
                    if (equif_val == toLowerCase("Derogatory")) {
                        //$('#selectiq_eqf_'+index).val(1).trigger('change');
                        derogetory['equif'] = "Derogatory";
                        setBankEquifNegativeForRecentReport(index);
                    } else {
                        accountStatus['equif'] = equif_val;
                    }

            } else if (bank_name.toLowerCase() == toLowerCase("Comments:")) {

                trans_val = unwantedcharremoveforCommentsIQ($tds.eq(1));
                exp_val = unwantedcharremoveforCommentsIQ($tds.eq(2));
                equif_val = unwantedcharremoveforCommentsIQ($tds.eq(3));

                if (trans_val)
                    if (trans_val.toLowerCase().includes(toLowerCase("Charge Off")) || trans_val.toLowerCase().includes(toLowerCase("Late")) || trans_val.toLowerCase().includes(toLowerCase("Bankruptcy"))) {
                        //$('#selectiq_tuc_'+index).val(1).trigger('change');
                        comments['trans'] = trans_val;
                        setBankTransNegativeForRecentReport(index);

                    }
                if (exp_val)
                    if (exp_val.toLowerCase().includes(toLowerCase("Charge Off")) || exp_val.toLowerCase().includes(toLowerCase("Late")) || exp_val.toLowerCase().includes(toLowerCase("Bankruptcy"))) {
                        //$('#selectiq_exp_'+index).val(1).trigger('change');
                        comments['exp'] = exp_val;

                        setBankExpNegativeForRecentReport(index);
                    }
                if (equif_val)
                    if (equif_val.toLowerCase().includes(toLowerCase("Charge Off")) || equif_val.toLowerCase().includes(toLowerCase("Late")) || equif_val.toLowerCase().includes(toLowerCase("Bankruptcy"))) {
                        //$('#selectiq_eqf_'+index).val(1).trigger('change');
                        comments['equif'] = equif_val;

                        setBankEquifNegativeForRecentReport(index);
                    }

            } else if (bank_name.toLowerCase() == toLowerCase("DATE OPENED:")) {
                if (trans_val) {
                    date_opened['trans'] = trans_val;
                }

                if (exp_val) {
                    date_opened['exp'] = exp_val;
                }

                if (equif_val) {
                    date_opened['equif'] = equif_val;
                }
            } else if (bank_name.toLowerCase() == toLowerCase("CREDIT LIMIT:")) {
                if (trans_val) {
                    credit_limit['trans'] = trans_val;
                }

                if (exp_val) {
                    credit_limit['exp'] = exp_val;
                }

                if (equif_val) {
                    credit_limit['equif'] = equif_val;
                }
            } else if (bank_name.toLowerCase() == toLowerCase("BALANCE:")) {
                if (trans_val) {
                    balance['trans'] = trans_val;
                }

                if (exp_val) {
                    balance['exp'] = exp_val;
                }

                if (equif_val) {
                    balance['equif'] = equif_val;
                }
            }
        }
    });


    var two_yr_history_tbl = table.parent('ng-include').nextAll('.addr_hsrty').first();
    // console.log('type_name_start',two_yr_history_tbl)
    two_yr_history_tbl.find('tr').each(function (i2, el1) {

        //if(i2 > 1){
        var tds = $(this).find('td.label');
        var type_name = $.trim(tds.text());
        //console.log('type_name',type_name)
        var day_count_array = [];
        if (type_name == "TransUnion") {
            tds.nextAll('td.info').each(function (i3, el3) {
                var trans_val_text = $.trim($(this).text());
                if (trans_val_text && trans_val_text != "OK") {
                    console.log('trans_val_text', trans_val_text, key_name, '#recent-report-area #selectiq_tuc_' + index)
                    setBankTransNegativeForRecentReport(index);
                }

                if (trans_val_text && trans_val_text != "OK" && trans_val_text != "CO") {
                    day_count_array.push(trans_val_text)
                }
            })
            if (day_count_array)
                day_count['trans'] = day_count_array;
        }

        if (type_name == "Experian") {
            day_count_array = [];
            tds.nextAll('td.info').each(function (i3, el3) {
                var exp_val_text = $.trim($(this).text());
                if (exp_val_text && exp_val_text != "OK") {
                    setBankExpNegativeForRecentReport(index);
                }

                if (exp_val_text && exp_val_text != "OK" && exp_val_text != "CO") {
                    day_count_array.push(exp_val_text)
                }
            })
            if (day_count_array)
                day_count['exp'] = day_count_array;
        }

        if (type_name == "Equifax") {
            day_count_array = [];
            tds.nextAll('td.info').each(function (i3, el3) {
                var equif_val_text = $.trim($(this).text());
                if (equif_val_text && equif_val_text != "OK") {
                    setBankEquifNegativeForRecentReport(index);
                }

                if (equif_val_text && equif_val_text != "OK" && equif_val_text != "CO") {
                    day_count_array.push(equif_val_text)
                }
            })
            if (day_count_array)
                day_count['equif'] = day_count_array;
        }

        // }
    })

    Obj['paymentStatus'] = paymentStatus;
    Obj['date_opened'] = date_opened;
    Obj['day_count'] = day_count;
    Obj['derogetory'] = derogetory;
    Obj['comments'] = comments;
    Obj['balance'] = balance;
    Obj['credit_limit'] = credit_limit;
    Obj['accountType'] = accountType;
    Obj['accountStatus'] = accountStatus;
    Obj['accountno'] = accountno;

    return Obj;
}

function setBankTransNegativeForRecentReport(index) {
    var is_same_code = $('input[name=is_same_code]').val();
    $('#recent-report-area #selectiq_tuc_' + index).val(1).trigger('change');
}

function setBankExpNegativeForRecentReport(index) {
    var is_same_code = $('input[name=is_same_code]').val();
    $('#recent-report-area #selectiq_exp_' + index).val(1).trigger('change');
}

function setBankEquifNegativeForRecentReport(index) {
    var is_same_code = $('input[name=is_same_code]').val();
    $('#recent-report-area #selectiq_eqf_' + index).val(1).trigger('change');
}