/* 
 * 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.
 */
// Global variable
var checkboxString = "";
var attcheckboxString = "";

function isDfAddressValid(current_df_address){
       var isDfValidFormat = true; 
        current_df_address = current_df_address.replace(/<(?:.|\n)*?>/gm, '')
        var comma_count = 0;
        if(current_df_address.match(/,/gi)){
            comma_count = current_df_address.match(/,/gi).length;
        }
        if(comma_count != 2){
            isDfValidFormat = false;
        }
        
        return isDfValidFormat;
    }


function isEmptyString(value){
    var result = false;
    
    if(typeof value === "undefined"){
        result = true;
    }else if(value == 0){
        result =  true;
    }else if(value == null){
        result =  true;
    }

    return result;
    
}

$('#inputformId').submit(function (e) {

    e.preventDefault();
    
    $('.download-category').prop('checked', false)
    $('#dest-id').html('');
    $('.choose-download').show();
    /*if (!$('input[name=download_type][value=1]').prop('checked')) {
        $('input[name=download_type][value=1]').click();
    }*/
    $('input[name=is_letterstream_duplex]').prop('checked', false);
    
    if ($('#rtg-before-saving-modal input[name=set_schedule]').prop('checked')) {
        $('#rtg-before-saving-modal input[name=set_schedule]').click();
    }
    
    if ($('#rtg-before-saving-modal input[name=set_automation]').prop('checked')) {
        $('#rtg-before-saving-modal input[name=set_automation]').click();
    }
    
    $('#rtg-before-saving-modal').modal('show');


})


$('#rtg-before-save').click(function () {
    $('.hidden-class').remove();
    var form = $('#inputformId');
    form.append('<input class="hidden-class" type="hidden" name="next_action_date" value="'+$('input[name=next_section_date]').val()+'"/>');
    form.append('<input class="hidden-class" type="hidden" name="client_id" value="'+$('#client-contact-id option:selected').data('id')+'"/>');
    form.append('<input class="hidden-class" type="hidden" name="dob" value="'+DOB+'"/>');
    form.append('<input class="hidden-class" type="hidden" name="ssn" value="'+SSN+'"/>');
    form.append('<input class="hidden-class" type="hidden" name="client_name" value="'+CLIENT_NAME+'"/>');
    form.append('<input class="hidden-class" type="hidden" name="client_email" value="'+CLIENT_EMAIL+'"/>');
    form.append('<input class="hidden-class" type="hidden" name="HAS_RTG_LS_FAX_ACCESS" value="'+HAS_RTG_LS_FAX_ACCESS+'"/>');
    form.append('<input class="hidden-class" type="hidden" name="letter_type" value="'+$('select[name=letter_type]').val()+'"/>');
    
    $('input[name="stt_pi_letter_set[]"]:checked').each(function(){
        form.append('<input class="hidden-class" type="hidden" name="stt_pi_letter_set[]" value="'+$(this).val()+'"/>');
    })
    
    
    if($('input[name=set_schedule]').prop('checked')){
        form.append('<input class="hidden-class" type="hidden" name="letter_type" value="'+$('select[name=letter_type]').val()+'"/>');
        form.append('<input class="hidden-class" type="hidden" name="set_schedule" value="1"/>');
        form.append('<input class="hidden-class" type="hidden" name="next_sending_email_date" value="'+$('input[name=next_sending_email_date]').val()+'"/>');
        form.append('<input class="hidden-class" type="hidden" name="letter_send_date_tmezone" value="'+$('select[name=letter_send_date_tmezone]').val()+'"/>');
    }else{
        form.append('<input class="hidden-class" type="hidden" name="set_schedule" value="0"/>');
    }
    
    
    
    var lettertypes = {};
    var counter = 0
    $('input[name="lettertypes[]"]').map(function () {
        if($(this).prop('checked')){
            lettertypes[counter]=$(this).val();
            counter++;
        }
    }).get();
   
    if(!$.isEmptyObject(lettertypes)){
        form.append('<input type="hidden" name="lettertypes" value=""/>');
        $('input[name=lettertypes]').val(JSON.stringify(lettertypes));
    }
    
    var download_type = $('input[name=download_type]:checked').val();
    var action_url = form.attr('action');
    var formData = new FormData(document.getElementById("inputformId"));
    
    if ($('#rtg-before-saving-modal input[name=set_schedule]').prop('checked')) {
            var next_sending_email_date = $('#rtg-before-saving-modal input[name=next_sending_email_date]').val();
            var letter_send_date_tmezone = $('#rtg-before-saving-modal select[name=letter_send_date_tmezone]').val();
            var letter_type = $('#rtg-before-saving-modal select[name=letter_type]').val();
            if (isEmptyString(next_sending_email_date)) {
                alert("Please select schedule date/time");
                return
            }
            if (isEmptyString(letter_send_date_tmezone)) {
                alert("Please select timezone");
                return
            }

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

    }
    
    
        //set_automation
    if ($('#rtg-before-saving-modal input[name=set_automation]').prop('checked')) {
        var day_value = $('#rtg-before-saving-modal input[name=day_value]').val();
        var automation_type = $('#rtg-before-saving-modal select[name=automation_type]').val();
        if (day_value) {
            if (day_value == 0 || /\D/g.test(day_value)) {
                alert('Please enter valid days for Setup Automation.');
                return
            }
            
        } else {
            alert("Please enter days of Setup Automation.");
            return
        }
        
        
        form.append('<input class="hidden-class" type="hidden" name="set_automation" value="1"/>');
        form.append('<input class="hidden-class" type="hidden" name="day_value" value="'+day_value+'"/>');
        form.append('<input class="hidden-class" type="hidden" name="automation_type" value="'+automation_type+'"/>');
    }else{
        form.append('<input class="hidden-class" type="hidden" name="set_automation" value="0"/>');
    }

//    alert(next_sending_email_date);
//    alert(letter_send_date_tmezone);
//    alert(letter_type);
//    return false;
    

    if (download_type == 1) {
        
        form.append('<input class="hidden-class" type="hidden" name="form_id" value="'+FORM_ID+'"/>');
        form.append('<input class="hidden-class" type="hidden" name="member_id" value="'+MEMBER_ID+'"/>');
        form.submit();
        
        $('#rtg-before-saving-modal').modal('hide');
        
        return false;
    } else if (download_type == 2) {
        

        if (hasLetterStream()) {
            $("#rtg-letter-stream-modal input[type=checkbox]").prop('checked',false);
            $("#rtg-letter-stream-modal select").hide();
            $("#rtg-letter-stream-modal .letter-address-popup").each(function(index,value){
                if($(this).val() == 1){
                    $(this).prop('checked',true);
                }
            })
            
            var isvalid = letterStreamDfAddressShowInModal()
            if(isvalid){
                $('#rtg-before-saving-modal').modal('hide');
                $('#rtg-letter-stream-modal').modal('show');
            }
        } else {
            var download_category = false;
            var download_category_id_list = [];

            $('.download-category').each(function () {
                if ($(this).prop('checked') && $(this).val() > 0) {
                    download_category = true;
                    download_category_id_list.push($(this).val())

                }
            })

            if (!download_category) {
                alert("Please choose item");
                return false
            }

            formData.append('download_category', JSON.stringify(download_category_id_list))
            rtgAjaxRequest(action_url, formData);
        }
    }else if(download_type == 3){
        formData.append('save_letter', 1)
        rtgAjaxRequest(action_url, formData);
    }
});





function letterStreamDfAddressShowInModal(){
    var address = "";
    var address_value = "";
    var isDfValidFormat = true;
    var creditor_name = "";
    var letter_stream_html = ""; 
    var current_df_address = null;
    if(hasDfAddressApplicable()){
        
        $('.letter-address-popup').parents('tr').show();
        if($('textarea[name=credit_bureau_name_address]').length > 0){
            current_df_address = $('textarea[name=credit_bureau_name_address]').val();
        }
        
        $('.letter-address-popup').prop('checked',false);
        $('.letter-address-popup').parents('tr').hide();

        if(current_df_address){
            if(!isDfAddressValid(current_df_address)){
                alert('Please enter valid creditor address')
                isDfValidFormat = false;
                return isDfValidFormat;
            }

            
            current_df_address = current_df_address.replace(/<(?:.|\n)*?>/gm, '')
            var first_part = current_df_address.split(',')
            creditor_name = first_part[0];
            creditor_name = $.trim(creditor_name);
            address = current_df_address.substring(current_df_address.indexOf(',') + 1)
            address_value = current_df_address;
            address_value = $.trim(address_value);
            var checked = "checked";
            $('#all-check-address').prop('checked',true);

            letter_stream_html += '<tr><td style="font-weight: bold;"> DATA FUNISHERS</td><td>';
            letter_stream_html += '<div class="checkbox"><label><input onclick="currentAddress()" ' + checked + ' name="letter_stream_address_11[]" class="letter-address-popup"  type="checkbox" value="' + address_value + '"> <strong>' + creditor_name + "</strong> " + address + '</label></div>';
            letter_stream_html += '</td><td></td></tr>';

            
        }else if(FORM_ID == 63){
            var checked = "checked";
            letter_stream_html += '<tr><td style="font-weight: bold;"> SAGESTREAM LLC DESTINATIONS</td><td>';
            letter_stream_html += '<div class="checkbox"><label><input onclick="currentAddress()" ' + checked + ' name="letter_stream_address_6[]" class="letter-address-popup"  type="checkbox" value="1"> SageStream LLC LexisNexis Risk Solutions Consumer Center P. O. Box 105108, Atlanta, Georgia 30348-5108</label></div>';
            letter_stream_html += '</td><td></td></tr>';
        }
        
        $('.letter-stream-content table tbody').append(letter_stream_html)
    }
    return isDfValidFormat;
}

function getExportIdlist(){
    var download_category_id_list = [];

    $('.download-category').each(function () {
        if ($(this).prop('checked') && $(this).val() > 0) {
            download_category_id_list.push($(this).val())
        }
    })
    
    return download_category_id_list;
}

function letterStreamSubmit() {
    var form = $('#inputformId');
    var action_url = form.attr('action');
    var formData = new FormData(document.getElementById("inputformId"));

    var download_category_id_list = getExportIdlist();
    var destAssocAddress = getSelectedDestinationAddressAssoc();

    if($.isEmptyObject(destAssocAddress)){
        alert('Please select at least one  address.');
        return false;
    }
    formData.append('destAssocAddress', JSON.stringify(destAssocAddress));
    formData.append('destAssocReturnAddress', JSON.stringify(getSelectedDestinationReturnAddressAssoc()));
    formData.append('download_category', JSON.stringify(download_category_id_list));
    
   
    
    $('#saveloading-letter').show();
    
    rtgAjaxRequest(action_url, formData);
}


function currentAddress() {
    letterStreamAllCheck();
}

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


function getSelectedDestinationReturnAddressAssoc(){
    var obj = {}
    
    for(var i = 1; i<=3; i++){
        var current_address_list = [];
        $('input[name="checkbox_return_address_'+i+'"]').each(function(index,value){
            if($(this).prop('checked')){
                var address = $('select[name=return_address_'+i+']').val();
                current_address_list.push(address);
            }
            
        });
        
        if(current_address_list.length > 0){
            obj[i] = current_address_list
        }
        
    }
    
    return obj;
}

function getSelectedDestinationAddressAssoc(){
    var obj = {}
    
    for(var i = 1; i<=3; i++){
        var current_address_list = [];
        $('input[name="letter_stream_address_'+i+'[]"]').each(function(index,value){
            if($(this).prop('checked')){
                current_address_list.push($(this).val());
            }
            
        });
        
        if(current_address_list.length > 0){
            obj[i] = current_address_list
        }
        
    }
    
    if($.isEmptyObject(obj)){
         var current_address_list = [];
            $('input[name="letter_stream_address_11[]"]').each(function(index,value){
                if($(this).prop('checked')){
                    current_address_list.push($(this).val());
                }

            });

            if(current_address_list.length > 0){
                obj[11] = current_address_list
            }
    }
    if($.isEmptyObject(obj)){
        var current_address_list = [];
            $('input[name="letter_stream_address_6[]"]').each(function(index,value){
                if($(this).prop('checked')){
                    current_address_list.push($(this).val());
                }

            });

            if(current_address_list.length > 0){
                obj[6] = current_address_list
            }
    }
    return obj;
}

//rtg-letter-stream-modal

function hasLetterStream() {
    var hasLS = false;
    $('.download-category').each(function () {
        if ($(this).prop('checked') && $(this).val() > 0) {
            if ($(this).data('type') == 6) {
                hasLS = true;
                return false;
            }

        }
    });

    return hasLS;
}

function rtgAjaxRequest(action_url, formData) {
    $('#letter-stream-btn, #rtg-before-save').attr('disabled',true);
    formData.append('ajax', 1);
    formData.append('form_id', FORM_ID);
    formData.append('member_id', MEMBER_ID)
    formData.append('CLIENT_NAME', CLIENT_NAME);
    
    $('#saveloading').show();

    
    var is_letterstream_duplex = "N";
    if ($('input[name=is_letterstream_duplex]').is(':visible') && $('input[name=is_letterstream_duplex]:checked').val()) {
        is_letterstream_duplex = $('input[name=is_letterstream_duplex]:checked').val();
    }


    formData.append('mailType', $('input[name=mailType]:checked').val())
    formData.append('is_letterstream_duplex', is_letterstream_duplex)
    formData.append('client_id', $('#client-contact-id option:selected').data('id'))
    
    if($('input[name=set_automation]').val() == 1){
        formData.append('set_automation', $('input[name=set_automation]').val())
        formData.append('set_schedule', $('input[name=set_schedule]').val())
        formData.append('day_value', $('input[name=day_value]').val())
        formData.append('automation_type', $('input[name=automation_type]').val())
    }else{
        formData.append('set_automation', 0)
    }
    
    formData.append('letter_type',$('select[name=letter_type]').val());
    $.ajax({
        type: 'POST',
        url: action_url,
        data: formData,
        contentType: false,
        cache: false,
        processData: false,
        success: function (data) {
            $('#letter-stream-btn, #rtg-before-save').attr('disabled',false);
            $('#saveloading').hide();
            $('#saveloading-letter').hide();
            var response = JSON.parse(data);

            var link = "";
            if(response.url){
                link = response.url;
            }
            Swal.fire({
                title: 'RTG Letter',
                icon: 'info',
                width: '450px',
                padding: '3rem',
                html: response.message + link,
                type: 'warning',
                fontsize:'1.6rem',
                confirmButtonText: 'Close',
            })
            //alert(response.message);
            $('#rtg-before-saving-modal').modal('hide');
            $('#rtg-letter-stream-modal').modal('hide');
        }

    });
}


function downloadOption(elem) {

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

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

    var download_category_type_list = [];
    $('.download-category').each(function () {
        if ($(this).prop('checked') && $(this).val() > 0) {
            download_category_type_list.push($(this).data('type'))
        }
    })


    $('.duplex-hide').hide();
    if ($.inArray(6, download_category_type_list) !== -1) {
        $('.duplex-hide').show();
    }

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

    }

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

}


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

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

    if (value == 2) {
        $('.download-box').removeClass('not-allowed');
        $('.choosedownload').removeClass('disable-elem-download');
        $('input[name=checkallExport]').attr('disabled', false);
        if($('.multiSel').children().length == 0)
        $('#rtg-before-saving-modal .choose-dest').show();
    }
})


function checkAllExport(elem) {

    $('.download-category').prop("checked", false);
    $('.multi-downloadselect').children('span').remove();
    if ($(elem).prop('checked')) {
        $('.download-category').click();
    } else {
        $(".choose-download").hide();
        if ($('.multi-downloadselect').children('span').length == 0) {
            $(".choose-download").show();
        }
    }


}


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

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

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

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

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

function letterAddressAllCheck(elem) {

    $('.letter-address-popup').prop('checked', false);
    if ($(elem).prop('checked')) {
        $('.letter-address-popup').prop('checked', true);
    }

}


$('input[name=set_schedule]').click(function () {
    $('.schedule-area').hide();
    if ($(this).prop('checked')) {
        $('.schedule-area').show();
    }
});




