/* 
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
var NEGATIVE_ITEM_SELECTED_LIST_CREDIT_ANALYSIS = {};
var PUBLIC_RECORD_INFO_CREDIT_ANALYSIS = {};
var INQURIES_RECORD_INFO_CREDIT_ANALYSIS = {};
var summary_inq_label = "";




function currentAnalysis() {
    var source_type = $('select[name=source_type]').val();

    if (source_type == 1) {
        selectNegativeForBankForIQ();
        selectPersonalInfoForIQ();
        selectPublicRecordForIQ();
        getPublicInfoForCreditAnalysis();
        getInquiriesDataForCreditAnalysis();
    } else if (source_type == 3) {
        setSmartCreditPersonalInfoForAnalysis();
        setSmartCreaditAccountHistoryForAnalysis();
        setSmartCreditPublicRecortForAnalysis();
        getSmartCreditInquiriesForAnalysis()
        getSmartCreditPublicRecortForAnalysis();
    }
}



function creditAnalyzer(type = 1) {
    IS_CHANGE_DROPDOWN = false
    currentAnalysis()
    var source_type = $('select[name=source_type]').val();
    var client_id = $('select[name=client_id]').val();
    var template_id = $('select[name=template_id]').val();
    var credit_score_data = getCreditScoreData();
    var formData = {};

    var summary = {};

    var total_public_record = 0;
    var total_inq_record = 0;
    var total_acc_record = 0;
    var total_deleted = 0;
    $('#main-html-area select.banks').each(function() {
        //('ssss1',$(this).children("option:selected").val())
        if ($(this).children("option:selected").val() == 4) {
            total_acc_record++;
        }
    });

    $('#main-html-area select.inquiries').each(function() {
        //console.log('ssss2',$(this).children("option:selected").val())
        if ($(this).children("option:selected").val() == 4) {
            total_inq_record++;
        }
    });

    $('#main-html-area select.publicrecord').each(function() {
        //('ssss3',$(this).children("option:selected").val())
        if ($(this).children("option:selected").val() == 4) {
            total_public_record++;
            return false;
        }
    });

    total_deleted = parseInt(total_deleted) + parseInt(total_public_record);
    total_deleted = parseInt(total_deleted) + parseInt(total_inq_record);
    total_deleted = parseInt(total_deleted) + parseInt(total_acc_record);

    if (source_type == 1) {
        var pInfo = getPersonalInfoWithDropDownData();
        var bankInfo = getBankTableInfo();
        summary = getFullIQSummary();
        credit_score_data = getCreditScoreData();
        //return false;

    } else if (source_type == 3) {
        var pInfo = getSmartCreditPersonalInfo();
        var bankInfo = getSmartCreditBankInfo();
        credit_score_data = getCreditScoreForSmartCredit();
        summary = getSCSummaryForAnalysis();
    }

    formData = {
        'action': 'VIEW_ANALYZE_REPORT',
        'total_deleted': total_deleted,
        'client_id': client_id,
        'source_type': source_type,
        'personal_info': pInfo,
        'summaryInfo': summary,
        'outputBankAcc': bankInfo,
        'inquires': INQURIES_RECORD_INFO_CREDIT_ANALYSIS,
        'publicInfo': PUBLIC_RECORD_INFO_CREDIT_ANALYSIS,
        'credit_score': credit_score_data,
        'credit_analysis': NEGATIVE_ITEM_SELECTED_LIST_CREDIT_ANALYSIS,
        'template_id': template_id,
        'is_from_history': is_from_history
    };

    //    if (source_type == 1) {
    //        var pInfo = getPersonalInfoWithDropDownData();
    //        var bankInfo = getBankTableInfo();
    //        summary = getFullIQSummary();
    //       //return false;
    //        
    //    }
    //console.log('is_from_history',is_from_history);
    $('#credit-loader').show();
    $('#credit-loader2').show();
    $('#full-page-loader').show();
    //alert(CREDIT_ANALYSIS_URL);

    console.log('formData', formData)
    $.ajax({
        type: "POST",
        data: formData,
        url: CREDIT_ANALYSIS_URL,
        success: function(data) {
            $('#full-page-loader').hide();
            $('#credit-loader').hide();
            $('#credit-loader2').hide();
            var json = JSON.parse(data);
            //var credit_score_data = getCreditScoreData();
            //alert(credit_score_data.TransUnion);

            //updatePieData(credit_score_data.TransUnion,credit_score_data.Experian,credit_score_data.Equifax)
            if (json.status) {
                var server_content = json.html;
                $('#chart-area').html(server_content);
                server_content = $('#chart-area').html();
                //server_content = colorSet(server_content);
                //server_content = server_content.replace('[CREDIT_SCORE]',$('#container-creadit-score-outer1').html());
                tinyMCE.get('report-analyzer').setContent(server_content);
                tinyMCE.get('report-analyzer2').setContent(server_content);
                $('#report-analyzer2').next('.tox-tinymce').first().css({'height':'560px'})
                $('#report-analyzer').next('.tox-tinymce').first().css({'height':'560px'})
                
                $('#chart-area').html('');
            }
            //console.log('credit_analysis', json);
            $('#show-credit-report-modal').modal('hide');
            if (type == 1) {
                $('#credit-analyzer').modal('show');
            } else {
                $('#credit-analyzer2').modal('show');
            }
        }
    })

}

function getFullIQSummary() {

    var result = {};

    var account_history_tables = $('#main-html-area #Summary:contains(Summary)').nextAll('table.rpt_content_table').first();

    var negative_items_values = {};
    var DELINQUENT_VALUES = {};
    var DEROGATORY_VALUES = {};
    var COLLECTION_VALUES = {};
    var OPEN_ACCOUNTS_VALUES = {};
    var CLOSE_ACCOUNTS_VALUES = {};
    var TOTAL_ACCOUNTS_VALUES = {};
    var BALANCES_VALUES = {};
    var PAYMENTS_VALUES = {};
    var inquiries_values = {};
    var public_records_values = {};

    var trans_val = 0;
    var exp_val = 0;
    var equif_val = 0;
    account_history_tables.find('tr').each(function(i, el) {
        var tds = $(this).find('td');
        var label_name_td = $(this).find('td.label');
        var other_td = $(this).find('td');
        var label_name = $.trim(label_name_td.eq(0)
            .clone() //clone the element
            .children() //select all the children
            .remove() //remove all the children
            .end() //again go back to selected element
            .text()).replace(':', '');
        var td_text_1 = $.trim(other_td.eq(1)
            .clone() //clone the element
            .children() //select all the children
            .remove() //remove all the children
            .end() //again go back to selected element
            .text()).replace('$', '');
        //td_text_1 = parseInt(td_text_1);                        
        var td_text_2 = $.trim(other_td.eq(2)
            .clone() //clone the element
            .children() //select all the children
            .remove() //remove all the children
            .end() //again go back to selected element
            .text()).replace('$', '');
        //td_text_2 = parseInt(td_text_2);                                         
        var td_text_3 = $.trim(other_td.eq(3)
            .clone() //clone the element
            .children() //select all the children
            .remove() //remove all the children
            .end() //again go back to selected element
            .text()).replace('$', '');
        //td_text_3 = parseInt(td_text_3);                                        
        var old_label_name = label_name;
        label_name = label_name.toUpperCase();
        //console.log('oooo',label_name,td_text_1);
        if (label_name == "DELINQUENT") {
            DELINQUENT_VALUES['trans'] = td_text_1;
            DELINQUENT_VALUES['exp'] = td_text_2;
            DELINQUENT_VALUES['equif'] = td_text_3;
        }

        if (label_name == "DEROGATORY") {
            DEROGATORY_VALUES['trans'] = td_text_1;
            DEROGATORY_VALUES['exp'] = td_text_2;
            DEROGATORY_VALUES['equif'] = td_text_3;
        }

        if (label_name == "COLLECTION") {
            COLLECTION_VALUES['trans'] = td_text_1;
            COLLECTION_VALUES['exp'] = td_text_2;
            COLLECTION_VALUES['equif'] = td_text_3;
        }

        if (SUMMARY_PUBLIC_RECORD == label_name) {
            public_records_values['trans'] = td_text_1;
            public_records_values['exp'] = td_text_2;
            public_records_values['equif'] = td_text_3;
        }

        if (SUMMARY_INQUIRY == label_name) {
            inquiries_values['trans'] = td_text_1;
            inquiries_values['exp'] = td_text_2;
            inquiries_values['equif'] = td_text_3;
            summary_inq_label = $.trim(old_label_name);
        }



        if ("TOTAL ACCOUNTS" == label_name) {
            TOTAL_ACCOUNTS_VALUES['trans'] = td_text_1;
            TOTAL_ACCOUNTS_VALUES['exp'] = td_text_2;
            TOTAL_ACCOUNTS_VALUES['equif'] = td_text_3;
        }

        if ("OPEN ACCOUNTS" == label_name) {
            OPEN_ACCOUNTS_VALUES['trans'] = td_text_1;
            OPEN_ACCOUNTS_VALUES['exp'] = td_text_2;
            OPEN_ACCOUNTS_VALUES['equif'] = td_text_3;
        }

        if ("CLOSED ACCOUNTS" == label_name) {
            CLOSE_ACCOUNTS_VALUES['trans'] = td_text_1;
            CLOSE_ACCOUNTS_VALUES['exp'] = td_text_2;
            CLOSE_ACCOUNTS_VALUES['equif'] = td_text_3;
        }

        if ("BALANCES" == label_name) {
            BALANCES_VALUES['trans'] = td_text_1;
            BALANCES_VALUES['exp'] = td_text_2;
            BALANCES_VALUES['equif'] = td_text_3;
        }


        if ("PAYMENTS" == label_name) {
            td_text_1 = $.trim(other_td.eq(1).children('span')
                .clone() //clone the element
                .children() //select all the children
                .remove() //remove all the children
                .end() //again go back to selected element
                .text()).replace('$', '');
            //td_text_1 = parseInt(td_text_1);                        
            td_text_2 = $.trim(other_td.eq(2).children('span')
                .clone() //clone the element
                .children() //select all the children
                .remove() //remove all the children
                .end() //again go back to selected element
                .text()).replace('$', '');
            //td_text_2 = parseInt(td_text_2);                                         
            td_text_3 = $.trim(other_td.eq(3).children('span')
                .clone() //clone the element
                .children() //select all the children
                .remove() //remove all the children
                .end() //again go back to selected element
                .text()).replace('$', '');

            PAYMENTS_VALUES['trans'] = td_text_1;
            PAYMENTS_VALUES['exp'] = td_text_2;
            PAYMENTS_VALUES['equif'] = td_text_3;
        }



    })

    result['DELINQUENT_VALUES'] = DELINQUENT_VALUES;
    result['DEROGATORY_VALUES'] = DEROGATORY_VALUES;
    result['COLLECTION_VALUES'] = COLLECTION_VALUES;
    result['OPEN_ACCOUNTS_VALUES'] = OPEN_ACCOUNTS_VALUES;
    result['CLOSE_ACCOUNTS_VALUES'] = CLOSE_ACCOUNTS_VALUES;
    result['TOTAL_ACCOUNTS_VALUES'] = TOTAL_ACCOUNTS_VALUES;
    result['BALANCES_VALUES'] = BALANCES_VALUES;
    result['PAYMENTS_VALUES'] = PAYMENTS_VALUES;
    result['public_record_summary'] = public_records_values;
    result['inquiry_summary'] = inquiries_values;

    return result;
}


function creditAnalysisActions(form, type = 2, content_tag_id = "") {
    currentAnalysis()
    var url = $(form).attr('action');
    var button_val = $('input[name=submit_type]').val();

    var formData = {}
    var client_id = $('select[name=client_id]').val();
    formData['client_id'] = client_id;
    if (type == 2) {
        formData['content'] = tinyMCE.get('report-html').getContent();
    } else if (type == 1) {
        content_tag_id = content_tag_id.replace('#', '');
        formData['content'] = tinyMCE.get(content_tag_id).getContent();
    }
    if (button_val == 1) { // print
        event.preventDefault();
        formData['action'] = 'PRINT';
    } else if (button_val == 2) { // send email
        event.preventDefault();
        if (!confirm('Are you sure want to send email ?')) {
            return false;
        }
        formData['action'] = 'SEND_EMAIL';
    } else if (button_val == 3) { // generate pdf
        formData['action'] = 'GENERATE_PDF';
        $(form).append('<input type="hidden" name="client_id" value="' + client_id + '">');
        //$('#analysis-form').submit();
        return true;
    }

    $('#credit-loader2').show();
    $('#full-page-loader').show();
    $('.loading').show();
    formData['type'] = type

    $.ajax({
        type: "POST",
        data: formData,
        url: url,
        success: function(data) {
            $('#full-page-loader').hide();
            $('#credit-loader2').hide();
            $('.loading').hide();
            var json = JSON.parse(data);
            if (json.status) {
                if (button_val == 2) {
                    alert('Email sent succesfully.')
                }
            }
            //console.log('credit_analysis', json);


        }
    })


}


function analysisButton() {
    var source_type = $('select[name=source_type]').val();
    var client_id = $('select[name=client_id]').val();
    var template_id = $('select[name=template_id]').val();
    var credit_score_data = getCreditScoreData();
    var formData = {};

    var summary = {};

    if (source_type == 1) {
        var pInfo = getPersonalInfoWithDropDownData();
        var bankInfo = getBankTableInfo();
        summary = getFullIQSummary();
        credit_score_data = getCreditScoreData();

    } else if (source_type == 3) {
        var pInfo = getSmartCreditPersonalInfo();
        var bankInfo = getSmartCreditBankInfo();
        credit_score_data = getCreditScoreForSmartCredit();
        summary = getSCSummaryForAnalysis();
    }

    formData = {
        'action': 'GENERATE_ANALYSIS_REPORT',
        'personal_info': pInfo,
        'summaryInfo': summary,
        'client_id': client_id,
        'source_type': source_type,
        'outputBankAcc': bankInfo,
        'inquires': INQURIES_RECORD_INFO_CREDIT_ANALYSIS,
        'publicInfo': PUBLIC_RECORD_INFO_CREDIT_ANALYSIS,
        'credit_score': credit_score_data,
        'credit_analysis': NEGATIVE_ITEM_SELECTED_LIST_CREDIT_ANALYSIS,
        'template_id': template_id,
        'is_from_history': is_from_history
    };
    $('.loading').show();
    $('#credit-loader').show();
    $('#credit-loader2').show();
    //alert(CREDIT_ANALYSIS_URL);
    $('#full-page-loader').show();
    console.log('formData', formData);
    //return false
    $.ajax({
        type: "POST",
        data: formData,
        url: CREDIT_ANALYSIS_URL,
        success: function(data) {
            $('#credit-loader').hide();
            $('#credit-loader2').hide();
            var json = JSON.parse(data);
            $('#full-page-loader').hide();
            $('.loading').hide();
            if (json.status) {
                //var credit_score_data = getCreditScoreData();
                console.log('json',json)
                //updatePieData(credit_score_data.TransUnion,credit_score_data.Experian,credit_score_data.Equifax)
                $('.template-list').html(json.template_list_html);
                var server_content = json.html;
                var trans_html = $('#container-creadit-score-outer1').html();
                var exp_html = $('#container-creadit-score-outer2').html();
                var equif_html = $('#container-creadit-score-outer3').html();
                $('#chart-area').html(server_content);
                server_content = $('#chart-area').html();
                server_content = colorSet(server_content);
                //server_content = server_content.replace('[CREDIT_SCORE]',$('#container-creadit-score-outer1').html());
                tinyMCE.get('report-html').setContent(server_content);
                $('#report-html').next('.tox-tinymce').first().css({'height':'560px'})
                
                $('#chart-area').html('');
                //$('#report-html').html(json.html);
            }
            //console.log('credit_analysis', json);
            $('#show-credit-report-modal').modal('hide');
            //$('iframe #container-score').html('<h1>RTG Project</h1>');
            $('#credit-analaysis').modal('show');

            //pieLoad()
        }
    })

}


function selectPersonalInfoForIQ() {
    if (IS_CHANGE_DROPDOWN && isFirstReport) {
        $('#main-html-area select.all-select').val(1).trigger('change');
    }
}

function selectPublicRecordForIQ() {
    if (IS_CHANGE_DROPDOWN && isFirstReport) {
        $('#main-html-area select.publicrecord').val(1).trigger('change');
    }
}



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

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

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

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

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

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

            getObj['selected_values'] = selected_values;

            NEGATIVE_ITEM_SELECTED_LIST_CREDIT_ANALYSIS[bank_name] = getObj;
        }
    })

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



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

    if (result) {
        result = toLowerCase(result);
    }
    return result;
}

function unwantedcharremoveforCommentsIQ(firstTd) {
    var result = "";
    if (firstTd.children('ng-repeat')) {
        //result = $.trim(firstTd.children('ng-repeat').clone().children().remove().end().text().replace(/<(?:.|\n)*?>/gm, ''));
        result = firstTd.text().replace(/[\r\n\t]+/gm, "").replace(/\s+/g, ' ').trim();
    } else {
        //result = $.trim(firstTd.clone().children().remove().end().text().replace(/<(?:.|\n)*?>/gm, ''));
    }

    //    if (result) {
    //        result = toLowerCase(result);
    //    }

    //console.log('comments',result,firstTd.text().replace( /[\r\n\t]+/gm, "" ).replace(/\s+/g,' ').trim());

    return result;
}


function setBankTransNegative(index) {
    var is_same_code = $('input[name=is_same_code]').val();
    $('#main-html-area #selectiq_tuc_' + index).val(1).trigger('change');
    if (IS_CHANGE_DROPDOWN && isFirstReport) {
        //console.log('Bank Neg', $('#selectiq_tuc_' + index))

    }
}

function setBankExpNegative(index) {
    var is_same_code = $('input[name=is_same_code]').val();
    $('#main-html-area #selectiq_exp_' + index).val(1).trigger('change');
    if (IS_CHANGE_DROPDOWN && isFirstReport) {

    }
}

function setBankEquifNegative(index) {
    var is_same_code = $('input[name=is_same_code]').val();
    $('#main-html-area #selectiq_eqf_' + index).val(1).trigger('change');
    if (IS_CHANGE_DROPDOWN && isFirstReport) {

    }
}



function findAccountFullInfoFromTable(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"))) {
                        setBankTransNegative(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"))) {
                        setBankExpNegative(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"))) {
                        setBankEquifNegative(index);
                        paymentStatus['equif'] = trans_val;
                    }


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

                if (trans_val)
                    if (trans_val == toLowerCase("Derogatory")) {
                        derogetory['trans'] = "Derogatory";
                        setBankTransNegative(index);
                    } else {
                        accountStatus['trans'] = trans_val;
                    }
                if (exp_val)
                    if (exp_val == toLowerCase("Derogatory")) {
                        setBankExpNegative(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";
                        setBankEquifNegative(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;
                        setBankTransNegative(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;

                        setBankExpNegative(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;

                        setBankEquifNegative(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") {
                    setBankTransNegative(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") {
                    setBankExpNegative(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") {
                    setBankEquifNegative(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 findAccountFullInfoFromTableForAnalysis(table) {
    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 = true;


    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"))) {

                        paymentStatus['trans'] = trans_val;
                    }
                if (exp_val)
                    if (exp_val == toLowerCase("Collection/ChargeOff") || exp_val == toLowerCase("Late Payment") || exp_val.toLowerCase().includes(toLowerCase("late"))) {

                        paymentStatus['exp'] = trans_val;
                    }
                if (equif_val)
                    if (equif_val == toLowerCase("Collection/ChargeOff") || equif_val == toLowerCase("Late Payment") || equif_val.toLowerCase().includes(toLowerCase("late"))) {

                        paymentStatus['equif'] = trans_val;
                    }


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

                if (trans_val)
                    if (trans_val == toLowerCase("Derogatory")) {
                        derogetory['trans'] = "Derogatory";

                    } else {
                        accountStatus['trans'] = trans_val;
                    }
                if (exp_val)
                    if (exp_val == toLowerCase("Derogatory")) {

                        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";

                    } 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;


                    }
                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;


                    }
                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;


                    }

            } 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") {

                }

                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") {

                }

                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") {

                }

                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 toLowerCase(str) {
    return str.toString().toLowerCase();
}

function toUppeerCase(str) {
    return str.toString().toUpperCase()
}


function getPublicInfoForCreditAnalysis() {
    var Obj = {}
    var objDate = {}
    var type_value_name = {}
    var values = {}
    var main_key_name = "";
    var isFirstTable = true;
    if (1) {
        $('#main-html-area .sub_header.publicrecordinfo').each(function() {
            if (isFirstTable) {
                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();
                }
                var public_tbl = $(this).next('table');
                public_tbl.find('tr.rowAlt').each(function(i1, el) {
                    var tr = $(this);

                    var trans = $.trim(tr.find('td.info').eq(0).children('ng-repeat').clone().children().remove().end().text().replace(/<(?:.|\n)*?>/gm, ''));
                    var selected_trans = 3;
                    var selected_exp = 3;
                    var selected_equif = 3;
                    if (!trans) {
                        trans = $.trim(tr.find('td.info').eq(0).clone().children().remove().end().text().replace(/<(?:.|\n)*?>/gm, ''));

                    }

                    var exp = $.trim(tr.find('td.info').eq(1).children('ng-repeat').clone().children().remove().end().text().replace(/<(?:.|\n)*?>/gm, ''));

                    var equif = $.trim(tr.find('td.info').eq(2).children('ng-repeat').clone().children().remove().end().text().replace(/<(?:.|\n)*?>/gm, ''));

                    var key_name = $.trim(tr.find('td.label').clone().children().remove().end().text().replace(/<(?:.|\n)*?>/gm, ''));

                    if (key_name) {
                        if (toLowerCase(key_name) == toLowerCase("DATE FILED/REPORTED:")) {
                            objDate['trans'] = trans;
                            objDate['exp'] = exp;
                            objDate['equif'] = equif;
                        } else if (toLowerCase(key_name) == toLowerCase("TYPE:")) {
                            type_value_name['trans'] = trans;
                            type_value_name['exp'] = exp;
                            type_value_name['equif'] = equif;

                            values['trans'] = tr.find('td.info').eq(0).children('select').val();
                            values['exp'] = tr.find('td.info').eq(1).children('select').val();
                            values['equif'] = tr.find('td.info').eq(2).children('select').val();

                            main_key_name = key_name.replace(':', '');
                        }
                        //return false;
                    }
                });

                Obj['key_name'] = main_key_name;
                Obj['values'] = values;
                Obj['objDate'] = objDate;
                Obj['type_value_name'] = type_value_name;

                isFirstTable = false;
            }
        });

    }
    PUBLIC_RECORD_INFO_CREDIT_ANALYSIS = Obj;
    return Obj;
}

function getInquiriesDataForCreditAnalysis() {
    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 data = $('#main-html-area div#Inquiries .rpt_fullReport_header');

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

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

    table.find('tr').each(function(i, el) {
        var tds = $(this).find('td');
        var creditor_name = $.trim(tds.eq(0).clone().children().remove().end().text());
        var date_of_inq = $.trim(tds.eq(2).clone().children().remove().end().text());
        var current_type = tds.eq(3).children('select').val();
        var creditor_bereau = $.trim(tds.eq(3).clone().children().remove().end().text());

        var item_category_id_Obj = {
            Equifax: 2,
            Experian: 1,
            TransUnion: 3
        }

        if (creditor_bereau) {
            var obj = {};
            // var data_key = creditor_name + "_" + date_of_inq+"_"+item_category_id_Obj[creditor_bereau];
            obj['bank_name'] = creditor_name
            obj['date'] = date_of_inq
            obj['type'] = creditor_bereau //item_category_id_Obj[creditor_bereau];
            obj['selected_value'] = current_type //item_category_id_Obj[creditor_bereau];

            dataObj.push(obj)
        }
    });

    INQURIES_RECORD_INFO_CREDIT_ANALYSIS = dataObj;
    return dataObj;

}

function getInquiriesDataForCreditAnalysisPrevious() {
    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>";

    $('#main-html-area .rpt_fullReport_header').each(function() {
        var inq = $(this).clone().children().remove().end().text();

        inq = $.trim(inq);

        if (inq == 'Inquiries') {

            var table = $(this).nextAll('table.rpt_content_table').first();

            table.find('tr').each(function(i, el) {
                var tds = $(this).find('td');
                var creditor_name = $.trim(tds.eq(0).clone().children().remove().end().text());
                var date_of_inq = $.trim(tds.eq(2).clone().children().remove().end().text());
                var current_type = tds.eq(3).children('select').val();
                var creditor_bereau = $.trim(tds.eq(3).clone().children().remove().end().text());

                var item_category_id_Obj = {
                    Equifax: 2,
                    Experian: 1,
                    TransUnion: 3
                }

                if (creditor_bereau) {
                    var obj = {};
                    // var data_key = creditor_name + "_" + date_of_inq+"_"+item_category_id_Obj[creditor_bereau];
                    obj['bank_name'] = creditor_name
                    obj['date'] = date_of_inq
                    obj['type'] = creditor_bereau //item_category_id_Obj[creditor_bereau];
                    obj['selected_value'] = current_type //item_category_id_Obj[creditor_bereau];

                    dataObj.push(obj)
                }
            });
        }
    });

    INQURIES_RECORD_INFO_CREDIT_ANALYSIS = dataObj;
    return dataObj;

}