jQuery('#yearly,#single_payment').hide();
function getUrlParameter(sParam) {
    var sPageURL = window.location.search.substring(1),
        sURLVariables = sPageURL.split('&'),
        sParameterName,
        i;

    for (i = 0; i < sURLVariables.length; i++) {
        sParameterName = sURLVariables[i].split('=');

        if (sParameterName[0] === sParam) {
            return sParameterName[1] === undefined ? true : decodeURIComponent(sParameterName[1]);
        }
    }
    return false;
}
const swalToast = Swal.mixin({
    toast: true,
    animation: true,
    position: 'bottom',
    showConfirmButton: false,
    timer: 4000,
	timerProgressBar: true,
	didOpen: (toast) => {
	  toast.addEventListener('mouseenter', Swal.stopTimer)
	  toast.addEventListener('mouseleave', Swal.resumeTimer)
	}
});
jQuery(document).ready(function($){
	// if( $('.page-id-5642').length > 0 || $('.page-id-6630').length > 0 ){
	// 	var block_config_spinner = { css: { backgroundColor: 'transparent', border: 'none' }, message: '<div class="blockUIspinner"></div>', baseZ: 1500, overlayCSS: { backgroundColor: '#FFFFFF', opacity: 0.8, cursor: 'default' } };
	// 	 	$.blockUI(block_config_spinner);
		
    // }
	if( cipscript.currentPage && cipscript.currentPage != 1307 ){
		var filterCookie = sessionStorage.getItem("tokenholder_table_sa_filter");
		if( filterCookie != "" && filterCookie != null ){
			sessionStorage.removeItem("tokenholder_table_sa_filter");
		}
	}

	if( $('#cip_security_hold_record').length > 0 ){

		$('[data-toggle-tt="tooltip"]').tooltip();

	}

	/* Hall of Fame start */
	if(jQuery('.hall-of-wall-list-body').length > 0){
		var page = 1;
		var searching = false;
		var postsPerPage = 12;

		var csr_split_spinner = $('.csr_split_spinner');

		$(document).on('change','#pagination-dropdown-form #posts_per_page,.search-input-field',function(){
			// postsPerPage = $(this).val();
			if($(this).attr('name')){
				if($(this).attr('name') == 'retire_amount_type' || $(this).attr('name') == 'retire_amount_start'){
					if(jQuery("[name='retire_amount_start']").val() != ""){
						load_hall_of_fame();
					}
				}else{
					load_hall_of_fame();
				}
			}
			
		})
		jQuery(document).on('click','#hall_of_fame_grid_list .Clear-button',function(e){
			jQuery("#search-input,.search-input-field").val("");
			jQuery('#search-input option:first-child').prop('selected',true);
			jQuery('.az-link').removeClass('active'); 
			jQuery('#az-pagination').attr('data-letter','');
			jQuery(".search-input-field").hide();
			jQuery('#pagination').attr('current_page',1);
			retirement_table_update();
			load_hall_of_fame();
		});

		function load_hall_of_fame() {
			var fullname = $('#search-input').val();
			

			csr_split_spinner.show();


			var data = {
				type: "POST", //rest Type
				dataType: 'jsonp', //mispelled
				async: true,
				action: 'load_hall_of_fame',
				contentType: "application/json; charset=utf-8",
				page: parseInt(jQuery('.hall-of-wall-list-body #pagination').attr('current_page')),
				postsPerPage: postsPerPage,
				columnfilter: JSON.stringify({"fullname": fullname,"letter": $('#az-pagination').attr('data-letter')}),
				letter: $('#az-pagination').attr('data-letter'),
				'amountfilterByConditionPoolRef' : convertFormToJSON( '#filter_form_model_form' ),
				// search: $('#search-input').val(),
				// letter: $('#az-pagination').attr('data-letter'),
				cat: $('#az-hall_of_fame-catagory-row').val(),
				// async: true
				// cat: $('#az-hall_of_fame-catagory-row').attr('data-letter'),
			};

			$.post(cipscript.ajax_url, data, function (response) {
				
				// setTimeout(function() {
				// }, 500);
				var response_data = jQuery.parseJSON(response);
				console.log(response_data);
				$('#post-list').html(response_data.html);

				var totalPosts = parseInt(response_data.total_posts);
				var totalPages = Math.ceil(totalPosts / postsPerPage);

				var pagination = $('#pagination');
				pagination.empty();
				console.log(page);
				if (totalPages > 1) {
					if (parseInt(jQuery('.hall-of-wall-list-body #pagination').attr('current_page')) > 1) {
						pagination.append('<a class="prev-page" href="#"><</a>');
					}

					for (var i = 1; i <= totalPages; i++) {
						if (i == parseInt(jQuery('.hall-of-wall-list-body #pagination').attr('current_page'))) {
							pagination.append('<span class="current-page">' + i + '</span>');
						} else {
							pagination.append('<a class="mini-page" href="#" mini-page="' + i + '">' + i + '</a>');
						}
					}

					if (parseInt(jQuery('.hall-of-wall-list-body #pagination').attr('current_page')) < totalPages) {
						pagination.append('<a class="next-page" href="#">></a>');
					}
				}
				$('#retirement_table').bootstrapTable('destroy');
				// $('#retirement_table').bootstrapTable({ data: response_data.rows });
				$('#retirement_table').bootstrapTable({
					data: response_data.rows,
					columns: [
					  {
						field: 'member_logo',
						title: 'Member Logo',
						class: 'member_logo'
					  },
					  {
						field: 'fullname',
						title: 'Full Name',
						class: 'fullname'
					  },
					  {
						field: 'eth_address',
						title: 'ETH Address',
						class: 'eth_address'
					  },
					  {
						field: 'retire_transhash',
						title: 'Transaction Hash',
						class: 'retire_transhash'
					  },
					  {
						field: 'retire_amount',
						title: 'Retire Amount',
						class: 'retire_amount'
					  },
					  {
						field: 'retire_confirm_date',
						title: 'Confirmation Date',
						class: 'retire_confirm_date'
					  }
					]
				});				  
				updatePagination();
				csr_split_spinner.hide();
			});
		}
		function updatePagination() {
		    var fullname = $('#search-input').val();
		    var data = {
				action: 'count_hall_of_fame',
				// search: $('#search-input').val(),
				page: parseInt(jQuery('.hall-of-wall-list-body #pagination').attr('current_page')),
				postsPerPage: postsPerPage,
				columnfilter: JSON.stringify({"fullname": fullname,"letter": $('#az-pagination').attr('data-letter')}),
				letter: $('#az-pagination').attr('data-letter'),
				'amountfilterByConditionPoolRef' : convertFormToJSON( '#filter_form_model_form' ),
				// search: $('#search-input').val(),
				// letter: $('#az-pagination').attr('data-letter'),
				cat: $('#az-hall_of_fame-catagory-row').val(),
			};

		    $.post(cipscript.ajax_url, data, function (response) {
		        var totalPosts = parseInt(response.data.total_posts);
		        var totalPages = Math.ceil(totalPosts / postsPerPage);
		        var currentPage = parseInt(jQuery('.hall-of-wall-list-body #pagination').attr('current_page'));

		        var pagination = $('#pagination');
		        pagination.empty();

		        if (totalPages > 1) {
		            if (currentPage > 1) {
		                pagination.append('<a class="prev-page" href="#"><i class="fa fa-angle-double-left"></i> Previous</a>');
		            }else{
		                pagination.append('<a class="prev-page disabled" href="#"><i class="fa fa-angle-double-left"></i> Previous</a>');
		            }

		            // Show first 5 pages
		            if (currentPage <= 5) {
		                for (var i = 1; i <= Math.min(5, totalPages); i++) {
		                    pagination.append(createPageLink(i, currentPage));
		                }
		                if (totalPages > 5) {
		                    pagination.append('<span class="dots">...</span>');
		                    pagination.append(createPageLink(totalPages, currentPage));
		                }

		            // Show last 5 pages
		            } else if (currentPage > totalPages - 5) {
		                pagination.append(createPageLink(1, currentPage));
		                pagination.append('<span class="dots">...</span>');

		                for (var i = totalPages - 4; i <= totalPages; i++) {
		                    pagination.append(createPageLink(i, currentPage));
		                }

		            // Show the first page, "...", 3 pages around the current page, "...", and the last page
		            } else {
		                pagination.append(createPageLink(1, currentPage)); // First page
		                pagination.append('<span class="dots">...</span>'); // "..."

		                // Show 3 pages centered around the current page
		                for (var i = currentPage - 1; i <= currentPage + 1; i++) {
		                    pagination.append(createPageLink(i, currentPage));
		                }

		                pagination.append('<span class="dots">...</span>'); // "..."
		                pagination.append(createPageLink(totalPages, currentPage)); // Last page
		            }

		            if (currentPage < totalPages) {
		                pagination.append('<a class="next-page" href="#">Next <i class="fa fa-angle-double-right"></i></a>');
		            }else{
		                pagination.append('<a class="next-page disabled" href="#">Next <i class="fa fa-angle-double-right"></i></a>');
		            }
		        }
		    });

		    function createPageLink(pageNumber, currentPage) {
		        if (pageNumber == currentPage) {
		            return '<span class="current-page">' + pageNumber + '</span>';
		        } else {
		            return '<a class="mini-page" href="#" mini-page="' + pageNumber + '">' + pageNumber + '</a>';
		        }
		    }
		}
		function updateAZPagination() {
			var data = {
				action: 'count_az_hall_of_fame',
				search: $('#search-input').val(),
			};

			$.post(cipscript.ajax_url, data, function (response) {
				var letters = response.data.letters;
				var azPagination = $('#az-pagination');
				azPagination.empty();

				// Add a link for all letters and "All" option
				azPagination.append('<a href="#" data-letter="" class="az-link">All</a>');
				letters.forEach(function (letter) {
					azPagination.append('<a href="#" data-letter="' + letter + '" class="az-link">' + letter + '</a>');
				});
			});
		}
		// $('#search-input').on('input', function () {
		// 	searching = true;
		// 	load_hall_of_fame();
		// 	updateAZPagination();
		// });

		$(document).on('click','.az-link', function (e) {
			e.preventDefault();
			$('.az-link').removeClass('active');
			var letter = $(this).attr('data-letter');
			$(this).addClass('active');
			$('#az-pagination').attr('data-letter', letter);
			load_hall_of_fame();
			updatePagination();
		});

		$(document).on('click', '.mini-page', function (e) {
			e.preventDefault();
			page = $(this).attr('mini-page');
			// console.log(page);
			jQuery('#pagination').attr('current_page',page);
			window.scrollTo({top: 99,left: 0,behavior: 'smooth'});
			load_hall_of_fame();
		});

		// $(document).on('click', '.hall_of_fame-catagory-item', function (e) { //#az-hall_of_fame-catagory-row
			$(document).on('change', '#az-hall_of_fame-catagory-row', function (e) { //#az-hall_of_fame-catagory-row
			e.preventDefault();
			jQuery(this).addClass('active');
			// var attrbute = jQuery(this).attr('data-table-item');
			// jQuery('#az-hall_of_fame-catagory-row').attr('data-letter',attrbute);
			load_hall_of_fame();
			updateAZPagination();
		});

		$(document).on('click', '.prev-page', function (e) {
			e.preventDefault();
			window.scrollTo({top: 99,left: 0,behavior: 'smooth'});
			if (page > 1) {
				page--;
				jQuery('#pagination').attr('current_page',page);
				load_hall_of_fame();
			}
		});

		$(document).on('click', '.next-page', function (e) {
			e.preventDefault();
			window.scrollTo({top: 99,left: 0,behavior: 'smooth'});
			page++;
			jQuery('#pagination').attr('current_page',page);
			load_hall_of_fame();
		});
		// jQuery(window).load(function(){
			// load_hall_of_fame();
			updateAZPagination();
			updatePagination();
		// });

		$( "#hall_of_fame_grid_list li:not(.Clear-button)" ).click( function() {
			$( "#hall_of_fame_grid_list li" ).removeClass('active');
			$( this ).addClass('active');
			if( $( this ).hasClass('list') ){
				// $( "#post-list" ).removeClass('nlr_grid_view');
				// $( "#post-list" ).addClass('nlr_list_view');
				$('#post-list').hide();
				$('.fixed-table-pagination').hide();
				$('.hall-of-wall-bot-table').show();
			}else{
				// $( "#post-list" ).removeClass('nlr_list_view');
				// $( "#post-list" ).addClass('nlr_grid_view');
				$('#post-list').show();
				$('.fixed-table-pagination').show();

				$('.hall-of-wall-bot-table').hide();
			}
		});

		jQuery(document).on("change","[name='retire_amount_type']",function(){
			var value = jQuery(this).val();
			if (value == ">") {
				jQuery('[name="retire_amount_start"]').attr("placeholder","Search greater than amount");
			} else if (value == "<") {
				jQuery('[name="retire_amount_start"]').attr("placeholder","Search less than amount");
			} else if (value == "=") {
				jQuery('[name="retire_amount_start"]').attr("placeholder","Search equal amount");
			} else if (value == ">=") {
				jQuery('[name="retire_amount_start"]').attr("placeholder","Search greater than or equal to amount");
			} else if (value == "<=") {
				jQuery('[name="retire_amount_start"]').attr("placeholder","Search less than or equal to amount");
			}
		});
	}
	/* Hall of Fame end */
	
	$(document).on('ppe-accordion-switched', function( $item ){
		var itemElement = $item;
		setTimeout(() => {
			var $thisElement = $('body').find('.pp-accordion-tab-active');
			$('html, body').animate({
				scrollTop: $thisElement.offset().top - 10
			}, 200);
		}, 400);
	});
	
	var notifyErrorOpt = {position:"top",className: 'error',autoHide:true,autoHideDelay: 3000,clickToHide: true};
	var block_config = { message: null,overlayCSS:{ backgroundColor: '#fff',opacity:0.8} };
	if( $('.import_tokenholder_frm').length > 0 ){

		var current_fs, next_fs, previous_fs; //fieldsets
		var opacity;
		var current = 1;
		var steps = $("fieldset").length;
		var $form = $('.import_tokenholder_frm'); 
		setProgressBar(current);

		$(".next").click(function(){

			current_fs = $(this).closest('fieldset');
			next_fs = $(this).closest('fieldset').next();
			
			if( current == 1 ){
				var th_csv_file = $('body').find('.import_tokenholder_frm input[name="th_csv_file"]').val();
				if( typeof th_csv_file  === "undefined" || th_csv_file == "" ){
					$(this).notify( 'Please choose file', notifyErrorOpt );
					return false;
				}
				var data = new FormData( $form[0] );
				data.append("is_fieldmap", 'yes');
				$form.block( block_config );
				$.ajax({
					url			: cipscript.ajax_url,
					type		: 'post',
					data		: data,
					processData	: false,
					contentType	: false,
					success : function(response){
						var obj = $.parseJSON(response);
						console.dir( obj );
						if( obj.error == 0 ){
							$('section.columns_mapping_section').html(obj.html);
							$("#progressbar li").eq( $("fieldset").index(next_fs) ).addClass("active");
							next_fs.show();
							current_fs.animate({opacity: 0}, {
								step: function(now) {
									opacity = 1 - now;

									current_fs.css({
										'display': 'none',
										'position': 'relative'
									});
									next_fs.css({'opacity': opacity});
								},
								duration: 500
							});
							setProgressBar(++current);
						}
						$form.unblock();

					}
				});
				$('#investment_interested_frm').block( block_config );
			}else if( current == 2 ){ //importing or updating user
				var data = new FormData( $form[0] );
				$form.block( block_config );
				$.ajax({
					url			: cipscript.ajax_url,
					type		: 'post',
					data		: data,
					processData	: false,
					contentType	: false,
					success : function(response){
						var obj = $.parseJSON(response);
						console.dir( obj );
						if( obj.error == 0 ){
							$('.import_update_response').html(obj.logs);
							$("#progressbar li").eq( $("fieldset").index(next_fs) ).addClass("active");
							next_fs.show();
							current_fs.animate({opacity: 0}, {
								step: function(now) {
									opacity = 1 - now;

									current_fs.css({
										'display': 'none',
										'position': 'relative'
									});
									next_fs.css({'opacity': opacity});
								},
								duration: 500
							});
							setProgressBar(++current);
						}
						$form.unblock();

					}
				});
				$('#investment_interested_frm').block( block_config );
			}else{
				$("#progressbar li").eq( $("fieldset").index(next_fs) ).addClass("active");
				next_fs.show();
				current_fs.animate({opacity: 0}, {
					step: function(now) {
						opacity = 1 - now;

						current_fs.css({
							'display': 'none',
							'position': 'relative'
						});
						next_fs.css({'opacity': opacity});
					},
					duration: 500
				});
				setProgressBar(++current);
			}
		});

		$(".previous").click(function(){

			current_fs = $(this).closest('fieldset');
			previous_fs = $(this).closest('fieldset').prev();

			//Remove class active
			$("#progressbar li").eq($("fieldset").index(current_fs)).removeClass("active");

			//show the previous fieldset
			previous_fs.show();

			//hide the current fieldset with style
			current_fs.animate({opacity: 0}, {
				step: function(now) {
					// for making fielset appear animation
					opacity = 1 - now;

					current_fs.css({
					'display': 'none',
					'position': 'relative'
					});
					previous_fs.css({'opacity': opacity});
				},
				duration: 500
			});
			setProgressBar(--current);
		});

		function setProgressBar(curStep){
			var percent = parseFloat(100 / steps) * curStep;
			percent = percent.toFixed();
			$(".progress-bar").css("width",percent+"%")
		}

		$("input[name='th_csv_file']").on("change", function(e){
			var is_error = false;
			var this_ext = $(this).val().split('.').pop().toLowerCase();
			// console.log( this_ext );
			if($.inArray(this_ext, ['csv']) == -1) {
				is_error = true;
				$(this).notify( 'Choose valid csv file', notifyErrorOpt );
				$(this).val('');
			}
		});
	}
	
	
	if( $('.sm_import_mi_frm').length > 0 ){

		var current_fs, next_fs, previous_fs; //fieldsets
		var opacity;
		var current = 1;
		var steps = $("fieldset").length;
		var $form = $('.sm_import_mi_frm'); 
		setProgressBar(current);

		$(".next").click(function(){

			current_fs = $(this).closest('fieldset');
			next_fs = $(this).closest('fieldset').next();
			
			if( current == 1 ){
				var mi_csv_file = $('body').find('.sm_import_mi_frm input[name="mi_csv_file"]').val();
				if( typeof mi_csv_file  === "undefined" || mi_csv_file == "" ){
					$(this).notify( 'Please choose file', notifyErrorOpt );
					return false;
				}
				var data = new FormData( $form[0] );
				$form.block( block_config );
				$.ajax({
					url			: cipscript.ajax_url,
					type		: 'post',
					data		: data,
					processData	: false,
					contentType	: false,
					success : function(response){
						var obj = $.parseJSON(response);
						console.dir( obj );
						if( obj.error == 0 ){
							$('.import_update_response').html(obj.logs);
							$("#progressbar li").eq( $("fieldset").index(next_fs) ).addClass("active");
							next_fs.show();
							current_fs.animate({opacity: 0}, {
								step: function(now) {
									opacity = 1 - now;

									current_fs.css({
										'display': 'none',
										'position': 'relative'
									});
									next_fs.css({'opacity': opacity});
								},
								duration: 500
							});
							setProgressBar(++current);
						}
						$form.unblock();

					}
				});
				$('#investment_interested_frm').block( block_config );
			}else{
				$("#progressbar li").eq( $("fieldset").index(next_fs) ).addClass("active");
				next_fs.show();
				current_fs.animate({opacity: 0}, {
					step: function(now) {
						opacity = 1 - now;

						current_fs.css({
							'display': 'none',
							'position': 'relative'
						});
						next_fs.css({'opacity': opacity});
					},
					duration: 500
				});
				setProgressBar(++current);
			}
		});

		$(".previous").click(function(){

			current_fs = $(this).closest('fieldset');
			previous_fs = $(this).closest('fieldset').prev();

			//Remove class active
			$("#progressbar li").eq($("fieldset").index(current_fs)).removeClass("active");

			//show the previous fieldset
			previous_fs.show();

			//hide the current fieldset with style
			current_fs.animate({opacity: 0}, {
				step: function(now) {
					// for making fielset appear animation
					opacity = 1 - now;

					current_fs.css({
					'display': 'none',
					'position': 'relative'
					});
					previous_fs.css({'opacity': opacity});
				},
				duration: 500
			});
			setProgressBar(--current);
		});

		function setProgressBar(curStep){
			var percent = parseFloat(100 / steps) * curStep;
			percent = percent.toFixed();
			$(".progress-bar").css("width",percent+"%")
		}

		$("input[name='th_csv_file']").on("change", function(e){
			var is_error = false;
			var this_ext = $(this).val().split('.').pop().toLowerCase();
			// console.log( this_ext );
			if($.inArray(this_ext, ['csv']) == -1) {
				is_error = true;
				$(this).notify( 'Choose valid csv file', notifyErrorOpt );
				$(this).val('');
			}
		});
	}

	//support manager import script
	if( $('.sm_import_th_frm').length > 0 ){

		var current_fs, next_fs, previous_fs; //fieldsets
		var opacity;
		var current = 1;
		var steps = $("fieldset").length;
		var $form = $('.sm_import_th_frm'); 
		setProgressBar(current);

		$(".next").click(function(){

			current_fs = $(this).closest('fieldset');
			next_fs = $(this).closest('fieldset').next();
			
			if( current == 1 ){
				var th_csv_file = $('body').find('.sm_import_th_frm input[name="th_csv_file"]').val();
				if( typeof th_csv_file  === "undefined" || th_csv_file == "" ){
					$(this).notify( 'Please choose file', notifyErrorOpt );
					return false;
				}
				var data = new FormData( $form[0] );
				data.append("is_fieldmap", 'yes');
				$form.block( block_config );
				$.ajax({
					url			: cipscript.ajax_url,
					type		: 'post',
					data		: data,
					processData	: false,
					contentType	: false,
					success : function(response){
						var obj = $.parseJSON(response);
						console.dir( obj );
						if( obj.error == 0 ){
							$('section.columns_mapping_section').html(obj.html);
							$("#progressbar li").eq( $("fieldset").index(next_fs) ).addClass("active");
							next_fs.show();
							$('body').find('#highestRow').remove();
							$('<input>').attr({type: 'hidden', id: 'highestRow', name: 'highestRow', value: obj.highestRow}).appendTo( $('#sm_import_th_process_frm') );
							current_fs.animate({opacity: 0}, {
								step: function(now) {
									opacity = 1 - now;

									current_fs.css({
										'display': 'none',
										'position': 'relative'
									});
									next_fs.css({'opacity': opacity});
								},
								duration: 500
							});
							setProgressBar(++current);
						}
						$form.unblock();

					}
				});
				$('#investment_interested_frm').block( block_config );
			}else if( current == 2 ){ //importing or updating user
				var data = new FormData( $form[0] );
				$form.block( block_config );
				
				$.ajax({
					url			: cipscript.ajax_url,
					type		: 'post',
					data		: data,
					processData	: false,
					contentType	: false,
					timeout		: 0,
					beforeSend	: function(){
						//$('#sm_import_th_process_frm').submit();
					},
					success : async function(response){
						var obj = $.parseJSON(response);
						console.dir( obj );
						if( obj.error == 0 ){
							// $('.import_update_response').html(obj.logs);
							$("#progressbar li").eq( $("fieldset").index(next_fs) ).addClass("active");
							next_fs.show();
							current_fs.animate({opacity: 0}, {
								step: function(now) {
									opacity = 1 - now;

									current_fs.css({
										'display': 'none',
										'position': 'relative'
									});
									next_fs.css({'opacity': opacity});
								},
								duration: 500
							});
							setProgressBar(++current);
							
							for (let icsv = 0; icsv < obj.loopcount; icsv++) {
								
								var isError = false;
								var data = new FormData($form[0]);
								data.append("is_csv_split", 'yes');
								data.append("is_csv_split_id", icsv);
								var cb = await $.ajax({
									url: cipscript.ajax_url,
									type: 'post',
									data: data,
									processData: false,
									contentType: false,
									timeout: 0,
									async: true,
									success : function(response){
										var obj = $.parseJSON(response);
										// console.log( 'response', obj );
										if( obj.countError > 0 ){
											$('.failed_log_btn').show();
											isError = true;
										}
										$('.import_update_response').append(obj.logs);
									}
								});
								// console.log( 'cb', cb );
								if( isError == true ){
									break;
								}
							}
						}
						$form.unblock();
					}
				});
				// window.location.href = 'https://cip061021.uk100.net/';
				// window.open('https://cip061021.uk100.net/', "_blank")
				$('#investment_interested_frm').block( block_config );
			}else{
				$("#progressbar li").eq( $("fieldset").index(next_fs) ).addClass("active");
				next_fs.show();
				current_fs.animate({opacity: 0}, {
					step: function(now) {
						opacity = 1 - now;

						current_fs.css({
							'display': 'none',
							'position': 'relative'
						});
						next_fs.css({'opacity': opacity});
					},
					duration: 500
				});
				setProgressBar(++current);
			}
		});

		$(".previous").click(function(){

			current_fs = $(this).closest('fieldset');
			previous_fs = $(this).closest('fieldset').prev();

			//Remove class active
			$("#progressbar li").eq($("fieldset").index(current_fs)).removeClass("active");

			//show the previous fieldset
			previous_fs.show();

			//hide the current fieldset with style
			current_fs.animate({opacity: 0}, {
				step: function(now) {
					// for making fielset appear animation
					opacity = 1 - now;

					current_fs.css({
					'display': 'none',
					'position': 'relative'
					});
					previous_fs.css({'opacity': opacity});
				},
				duration: 500
			});
			setProgressBar(--current);
		});

		function setProgressBar(curStep){
			var percent = parseFloat(100 / steps) * curStep;
			percent = percent.toFixed();
			$(".progress-bar").css("width",percent+"%")
		}

		$("input[name='th_csv_file']").on("change", function(e){
			var is_error = false;
			var this_ext = $(this).val().split('.').pop().toLowerCase();
			// console.log( this_ext );
			if($.inArray(this_ext, ['csv']) == -1) {
				is_error = true;
				$(this).notify( 'Choose valid csv file', notifyErrorOpt );
				$(this).val('');
			}
		});
	}

	//partial import section script
	//support manager import script
	if( $('.sm_partial_import_th_frm').length > 0 ){

		var current_fs, next_fs, previous_fs; //fieldsets
		var opacity;
		var current = 1;
		var steps = $("fieldset").length;
		var $form = $('.sm_partial_import_th_frm'); 
		setProgressBar(current);

		$(".next").click(function(){

			current_fs = $(this).closest('fieldset');
			next_fs = $(this).closest('fieldset').next();
			
			if( current == 1 ){
				var th_csv_file = $('body').find('.sm_partial_import_th_frm input[name="th_csv_file"]').val();
				if( typeof th_csv_file  === "undefined" || th_csv_file == "" ){
					$(this).notify( 'Please choose file', notifyErrorOpt );
					return false;
				}
				var data = new FormData( $form[0] );
				data.append("is_fieldmap", 'yes');
				$form.block( block_config );
				$.ajax({
					url			: cipscript.ajax_url,
					type		: 'post',
					data		: data,
					processData	: false,
					contentType	: false,
					success : function(response){
						var obj = $.parseJSON(response);
						console.dir( obj );
						if( obj.error == 0 ){
							$('section.columns_mapping_section').html(obj.html);
							$("#progressbar li").eq( $("fieldset").index(next_fs) ).addClass("active");
							next_fs.show();
							$('body').find('#highestRow').remove();
							$('<input>').attr({type: 'hidden', id: 'highestRow', name: 'highestRow', value: obj.highestRow}).appendTo( $('#sm_import_partial_th_process_frm') );
							current_fs.animate({opacity: 0}, {
								step: function(now) {
									opacity = 1 - now;

									current_fs.css({
										'display': 'none',
										'position': 'relative'
									});
									next_fs.css({'opacity': opacity});
								},
								duration: 500
							});
							setProgressBar(++current);
						}
						$form.unblock();

					}
				});
			}else if( current == 2 ){ //importing or updating user
				var data = new FormData( $form[0] );
				$form.block( block_config );
				
				$.ajax({
					url			: cipscript.ajax_url,
					type		: 'post',
					data		: data,
					processData	: false,
					contentType	: false,
					timeout		: 0,
					beforeSend	: function(){
						//$('#sm_import_th_process_frm').submit();
					},
					success : async function(response){
						var obj = $.parseJSON(response);
						console.dir( obj );
						if( obj.error == 0 ){
							// $('.import_update_response').html(obj.logs);
							$("#progressbar li").eq( $("fieldset").index(next_fs) ).addClass("active");
							next_fs.show();
							current_fs.animate({opacity: 0}, {
								step: function(now) {
									opacity = 1 - now;

									current_fs.css({
										'display': 'none',
										'position': 'relative'
									});
									next_fs.css({'opacity': opacity});
								},
								duration: 500
							});
							setProgressBar(++current);
							
							for (let icsv = 0; icsv < obj.loopcount; icsv++) {
								
								var isError = false;
								var data = new FormData($form[0]);
								data.append("is_csv_split", 'yes');
								data.append("is_csv_split_id", icsv);
								var cb = await $.ajax({
									url: cipscript.ajax_url,
									type: 'post',
									data: data,
									processData: false,
									contentType: false,
									timeout: 0,
									async: true,
									success : function(response){
										var obj = $.parseJSON(response);
										// console.log( 'response', obj );
										if( obj.countError > 0 ){
											$('.failed_log_btn').show();
											isError = true;
										}
										$('.import_update_response').append(obj.logs);
									}
								});
								// console.log( 'cb', cb );
								if( isError == true ){
									break;
								}
							}
						}
						$form.unblock();
					}
				});
			}else{
				$("#progressbar li").eq( $("fieldset").index(next_fs) ).addClass("active");
				next_fs.show();
				current_fs.animate({opacity: 0}, {
					step: function(now) {
						opacity = 1 - now;

						current_fs.css({
							'display': 'none',
							'position': 'relative'
						});
						next_fs.css({'opacity': opacity});
					},
					duration: 500
				});
				setProgressBar(++current);
			}
		});

		$(".previous").click(function(){

			current_fs = $(this).closest('fieldset');
			previous_fs = $(this).closest('fieldset').prev();

			//Remove class active
			$("#progressbar li").eq($("fieldset").index(current_fs)).removeClass("active");

			//show the previous fieldset
			previous_fs.show();

			//hide the current fieldset with style
			current_fs.animate({opacity: 0}, {
				step: function(now) {
					// for making fielset appear animation
					opacity = 1 - now;

					current_fs.css({
					'display': 'none',
					'position': 'relative'
					});
					previous_fs.css({'opacity': opacity});
				},
				duration: 500
			});
			setProgressBar(--current);
		});

		function setProgressBar(curStep){
			var percent = parseFloat(100 / steps) * curStep;
			percent = percent.toFixed();
			$(".progress-bar").css("width",percent+"%")
		}

		$("input[name='th_csv_file']").on("change", function(e){
			var is_error = false;
			var this_ext = $(this).val().split('.').pop().toLowerCase();
			// console.log( this_ext );
			if($.inArray(this_ext, ['csv']) == -1) {
				is_error = true;
				$(this).notify( 'Choose valid csv file', notifyErrorOpt );
				$(this).val('');
			}
		});
	}
	//over partial import script


	if( $('#sm_column_options').length > 0 ){
		
		//sortable script
		$('#sm_column_options tbody').sortable({
	        axis: 'y',
	        cursor: 'move',
	        helper: function(e, ui) {
		        ui.children().each(function() {
					$(this).width($(this).width());
				});
				return ui;
			},
	        stop: function (event, ui) {
		        var data = $(this).sortable('serialize');
		        data = data + '&action=columnorderupdate_act&_micro='+cipscript._microsmco;
	            $.post(cipscript.ajax_url, data, function(response){
					var obj = JSON.parse( response );
				});
			}
	    }).disableSelection();

		//columns management script
		$('body').on('submit', '#sm_column_options', function(){
			$form = $(this);
			var data = $(this).serialize();
			$form.block( block_config );
			$.post(cipscript.ajax_url, data, function(response) {
				var obj = JSON.parse( response );
				$form.unblock();
				$('.form_response').html( obj.msg );
			});
			return false;
		});
		if( $('#sm_column_options table').length > 0 ){
			var $sm_column_options = $('body').find('#sm_column_options table');
			$sm_column_options.bootstrapTable({
				stickyHeader: true,
			});
		}
	}
	//columns sa management script
	$('body').on('submit', '#sa_column_options', function(){
		$form = $(this);
		var data = $(this).serialize();
		$form.block( block_config );
		$.post(cipscript.ajax_url, data, function(response) {
			var obj = JSON.parse( response );
			$form.unblock();
			$('.form_response').html( obj.msg );
		});
		return false;
	});
	if( $('#sa_column_options table').length > 0 ){
		var $sa_column_options = $('body').find('#sa_column_options table');
		$sa_column_options.bootstrapTable({
			stickyHeader: true,
		});
	}
	//columns member management script
	$('body').on('submit', '#th_column_options', function(){
		$form = $(this);
		var data = $(this).serialize();
		$form.block( block_config );
		$.post(cipscript.ajax_url, data, function(response) {
			var obj = JSON.parse( response );
			$form.unblock();
			$('.form_response').html( obj.msg );
		});
		return false;
	});
	if( $('#th_column_options table').length > 0 ){
		var $th_column_options = $('body').find('#th_column_options table');
		$th_column_options.bootstrapTable({
			stickyHeader: true,
		});
	}
	//remove members by sm
	$('body').on('submit', '#smclearth_frm', function(){
		Swal({
		  title: 'Are you sure?',
		  text: "Are you sure you want to clear " + cipscript.alltcnum + " records?",
		  type: 'warning',
		  showCancelButton: true,
		  confirmButtonText: 'Yes'
		}).then((result) => {
		  if (result.value) {
				$form = $(this);
				$form.find('.form_response').html('');
				var data = $(this).serialize();
				$form.block( block_config );
				$.post(cipscript.ajax_url, data, function(response) {
					var obj = JSON.parse( response );
					$form.unblock();
					$form.find('.form_response').html( obj.msg );
				});
		  }
		});
		return false;
	});
	//remove members invoice by sm
	$('body').on('submit', '#smclearmi_frm', function(){
		Swal({
		  title: 'Are you sure?',
		  text: "Are you sure you want to clear " + cipscript.allminum + " records?",
		  type: 'warning',
		  showCancelButton: true,
		  confirmButtonText: 'Yes'
		}).then((result) => {
		  if (result.value) {
				$form = $(this);
				$form.find('.form_response').html('');
				var data = $(this).serialize();
				$form.block( block_config );
				$.post(cipscript.ajax_url, data, function(response) {
					var obj = JSON.parse( response );
					$form.unblock();
					$form.find('.form_response').html( obj.msg );
				});
		  }
		});
		return false;
	});
	//maintenance mode enable/disable
	$('body').on('change', '#routine_maintenance_mode', function(event){
		var checked = $(this).is(':checked');
		var $thisCheck = $(this);
		/*if( checked ){
	        if(!confirm('Are you sure you want to enable maintenance mode?')){         
	            $thisCheck.removeAttr('checked');
	        }else{
	        	$('#routine_maintenance_frm').submit();
	        }
	    }else{
	     	if(!confirm('Are you sure you want to disable maintenance mode?')){
	        	$thisCheck.prop("checked", true);
	        	return false;
	        }else{
	        	$('#routine_maintenance_frm').submit();
	        }
	    }*/
	    $('#routine_maintenance_frm').submit();
 		event.preventDefault();
		event.stopPropagation();
	});
	// MEMBER MAINTENANCE MODE
	$('body').on('change', '#member_maintenance_mode', function(event){
		var checked = $(this).is(':checked');
		var $thisCheck = $(this);
	    $('#member_maintenance_mode').submit();
 		event.preventDefault();
		event.stopPropagation();
	});
	// SITE MAINTENANCE MODE
	$('body').on('change', '#site_maintenance_mode', function(event){
		var checked = $(this).is(':checked');
		var $thisCheck = $(this);
	    $('#site_maintenance_mode').submit();
 		event.preventDefault();
		event.stopPropagation();
	});
	$('body').on('change', '#retirement_maintenance_mode', function(event){
		var checked = $(this).is(':checked');
		var $thisCheck = $(this);
	    $('#retirement_maintenance_mode').submit();
 		event.preventDefault();
		event.stopPropagation();
	});
	// support ticket mode
	$('body').on('change', '#support_ticket_mode', function(event){
		$('#smsupport_endpoint').submit();
	});
	$('body').on('submit', '#smsupport_endpoint', function(){
		$form = $(this);
		$form.find('.form_response').html('');
		var data = $(this).serialize();
		$form.block( block_config );
		$.post(cipscript.ajax_url, data, function(response) {
			var obj = JSON.parse( response );
			$form.unblock();
			$form.find('.form_response').html( obj.msg );
		});
		return false;
	});
	$('body').on('submit', '#routine_maintenance_frm', function(){
		$form = $(this);
		$form.find('.form_response').html('');
		var data = $(this).serialize();
		$form.block( block_config );
		$.post(cipscript.ajax_url, data, function(response) {
			var obj = JSON.parse( response );
			$form.unblock();
			$form.find('.form_response').html( obj.msg );
		});
		return false;
	});
	// MEMBER MAINTENANCE MODE
	$('body').on('submit', '#member_maintenance_frm', function(){
		$form = $(this);
		$form.find('.form_response').html('');
		var data = $(this).serialize();
		$form.block( block_config );
		$.post(cipscript.ajax_url, data, function(response) {
			var obj = JSON.parse( response );
			$form.unblock();
			$form.find('.form_response').html( obj.msg );
		});
		return false;
	});
	// Site MAINTENANCE MODE
	$('body').on('submit', '#site_maintenance_frm', function(){
		$form = $(this);
		$form.find('.form_response').html('');
		var data = $(this).serialize();
		$form.block( block_config );
		$.post(cipscript.ajax_url, data, function(response) {
			var obj = JSON.parse( response );
			$form.unblock();
			$form.find('.form_response').html( obj.msg );
		});
		return false;
	});
	$('body').on('submit', '#retirement_maintenance_frm', function(){
		$form = $(this);
		$form.find('.form_response').html('');
		var data = $(this).serialize();
		$form.block( block_config );
		$.post(cipscript.ajax_url, data, function(response) {
			var obj = JSON.parse( response );
			$form.unblock();
			$form.find('.form_response').html( obj.msg );
		});
		return false;
	});
	$('body').on('change', '#selectallthprofile', function(){
		if( this.checked ){
			$('body').find('.th_alltoggle').prop("checked", true);
		}else{
			$('body').find('.th_alltoggle').prop("checked", false);
		}
	});
	$('body').on('change', '#selectallsaprofile', function(){
		if( this.checked ){
			$('body').find('.sa_alltoggle').prop("checked", true);
		}else{
			$('body').find('.sa_alltoggle').prop("checked", false);
		}
	});
	/* $(window).scroll(function(){
        if( $(this).scrollTop() >= 150 ){
        	$('#sm_column_options table thead, #th_column_options table thead, #sa_column_options table thead').addClass('stickytblheader');
        }else{
        	$('#sm_column_options table thead, #th_column_options table thead, #sa_column_options table thead').removeClass('stickytblheader');
        }
	}); */
	$('#viewMoreModal').on('show.bs.modal', function (event) {
		var button = $(event.relatedTarget);
		var viewmoreContent = button.data('viewmore');
		var modal = $(this);
		modal.find('.modal-body').html('');
		modal.find('.modal-body').html(viewmoreContent);
	});
	if( $('#cip_logs_table').length > 0 ){			
		var $tableTH = $('#cip_logs_table');
		$tableTH.bootstrapTable();
	}
	//#4966
	/* $('#editEthModal').on('show.bs.modal', function (event) {
	  var targetButton = $(event.relatedTarget);
	  var Memberth = targetButton.attr('data-memberth');
	  var modal = $(this);
	  $('<input>').attr({ type: 'hidden', name: '_microid', value: Memberth }).appendTo('body #editethaddressmember');
	});
	$('#editEthModal').on('hide.bs.modal', function (event) {
	  var modal = $(this);
	  modal.find('#editethaddressmember input[name=_microid]').remove();
	}); */

	$('body').on('submit', '#editethaddressmember', function(){
		var csr_wallet_address = $(this).find('#csrwalletaddress').val();
		var csr_wallet_text = "You are adding <br/>" + csr_wallet_address + "<br/> as your CSR Wallet address.";
		Swal({
		  title: '',
		  html: "<h5> " + csr_wallet_text + " <br/> This cannot be changed later. <br/> Please check your address and confirm it is correct.</h5>",
		  type: 'warning',
		  showCancelButton: true,
		  confirmButtonText: 'Confirm'
		}).then((result) => {
		  if (result.value) {
				$form = $(this);
				$form.find('.form_response').html('');
				var data = $(this).serialize();
				if( $(this).find('#csrwalletaddress').val() == "" ){
					return false;
				}
				$form.block( block_config );
				$.post(cipscript.ajax_url, data, function(response) {
					var obj = JSON.parse( response );
					if( obj.error == 0 ){
						window.location.reload();
					}
					$form.unblock();
					$form.find('.form_response').html( obj.msg );
				});
		  }
		});
		return false;
	});
	$('body').on('click','button#show_all',function(){
		$('table.table-borderless tbody').find('tr').css('display','table-row');
	});
	$('body').on('click','button#error_all',function(){
		$('table.table-borderless tbody').find('tr').css('display','none');
		$('table.table-borderless tbody').find('tr.table-danger').css('display','table-row');
	});
	
	var block_config = { message: null,overlayCSS:{ backgroundColor: '#fff',opacity:0.8} };
	$('body').on('change', '.proforma_toggle', function(event){
		var selected_id = $(this).val();
		var this_toggle_status = $(this).parent().find('.proforma_toggle_status');
		var refElem = $(this).parent().find('.ref_val');
		var ref = refElem.val();
		// alert(ref);
		var data = {id:selected_id, ref:ref,action:'proforma_toggle_action'};
		var current_tr = $(this).closest('tr');
		var checked = $(this).is(':checked');
		var $thisCheck = $(this);

		if( !checked ){
			Swal({
			  title: '',
			  html: "<h5> You are about to mark the Invoice as unpaid <br/> Are you sure?</h5>",
			  type: 'warning',
			  showCancelButton: true,
			  confirmButtonText: 'Confirm'
			}).then((result) => {
			  if (result.value) {
					current_tr.block( block_config );
					jQuery.ajax({ 
						type: "post",
						data: data,
						cache: false,
						url: cipscript.ajax_url,
						dataType: "html",
						success: function(response){
							var obj = JSON.parse( response );
							if( obj.error == 0 ){
								this_toggle_status.html( obj.status );
								refElem.val( obj.status );
							}
							current_tr.unblock();
						}
					});
			  }else{
					$thisCheck.prop("checked", true);
					return false;
			  }
			});
		}else{			
			current_tr.block( block_config );
			jQuery.ajax({ 
				type: "post",
				data: data,
				cache: false,
				url: cipscript.ajax_url,
				dataType: "html",
				success: function(response){
					var obj = JSON.parse( response );
					if( obj.error == 0 ){
						this_toggle_status.html( obj.status );
						refElem.val( obj.status );
					}
					current_tr.unblock();
				}
			});
		}
		
	});	

// ARCHIEVE STATUS JS
$('body').on('change', '.archive_toggle', function(event){
	var selected_id = $(this).val();
	var this_toggle_status = $(this).parent().find('.archive_toggle_status');
	var archElem = $(this).parent().find('.arch_val');
	var arch = archElem.val();
	// alert(arch);
	var data = {id:selected_id, arch:arch,action:'archive_toggle_action'};
	var current_tr = $(this).closest('tr');
	var checked = $(this).is(':checked');
	var $thisCheck = $(this);

	if( !checked ){
		Swal({
		  title: '',
		  html: "<h5> You are about to mark the Archive Status as No <br/> Are you sure?</h5>",
		  type: 'warning',
		  showCancelButton: true,
		  confirmButtonText: 'Confirm'
		}).then((result) => {
		  if (result.value) {
				current_tr.block( block_config );
				jQuery.ajax({ 
					type: "post",
					data: data,
					cache: false,
					url: cipscript.ajax_url,
					dataType: "html",
					success: function(response){
						var obj = JSON.parse( response );
						if( obj.error == 0 ){
							this_toggle_status.html( obj.status );
							archElem.val( obj.status );
						}
						current_tr.unblock();
					}
				});
		  }else{
				$thisCheck.prop("checked", true);
				return false;
		  }
		});
	}else{			
		current_tr.block( block_config );
		jQuery.ajax({ 
			type: "post",
			data: data,
			cache: false,
			url: cipscript.ajax_url,
			dataType: "html",
			success: function(response){
				var obj = JSON.parse( response );
				if( obj.error == 0 ){
					this_toggle_status.html( obj.status );
					archElem.val( obj.status );
				}
				current_tr.unblock();
			}
		});
	}
	
});	
// END CODE SECTION
	
	
// 	BECOME PLASTIC NEUTRAL PAGE FUNCTINALITY

jQuery('input[type=range]').on('input', function () {
    jQuery(this).trigger('change');
});

if($(window).width() >= 1024) {
	jQuery('#kgText,#kgText1,#kgText2').css({"display": "block","text-align": "center", "font-size": "90px", "font-weight": "bold","color": "#6050c8"});
}
else{
	jQuery('#kgText,#kgText1,#kgText2').css({"display": "block","text-align": "center", "font-size": "55px", "font-weight": "bold","color": "#6050c8"});
}

var incCsr = cipscript.incCsr;
var selling_price = parseFloat( cipscript.selling_price );
var url = window.location.hostname;
var page_url = url;

var priceAmt = parseInt( $('div#monthly input[type="range"]').val() );
if( priceAmt == 0 ){
	priceAmt = 10;
}
var kgs = cip_convert_kgs_by_price( priceAmt );
jQuery('#monthly_plastic_waste').text( kgs );
jQuery('#yearly_val,#oneTime_val,#monthly_val').text( kgs );
jQuery('#kgPlastic_range').text( priceAmt );
var inclusive_csr = cip_convert_csr_by_price( priceAmt );
jQuery('#inclusive-csr').text(inclusive_csr);
jQuery('#plastic_amt').val( kgs );
jQuery('#total_price').val( priceAmt );

jQuery(".confirmBtn").click(function(){
	jQuery('#buyfrm').submit();
});

// TRIGGER RANGE SLIDER ON CLICK NEXT/PREVIOUS ARROWS
jQuery('.monthly_next').click(function(){
	jQuery('#plasticRange').val( parseInt( jQuery('#plasticRange').val() ) + 10 ).trigger('change');
});

jQuery('.monthly_previous').click(function(){
	jQuery('#plasticRange').val( parseInt( jQuery('#plasticRange').val() ) - 10 ).trigger('change');
});
// END CODE SECTION	 
jQuery(`input[name='plastic_waste']`).change(function(){
	var frequency = $(this).val();
	$('#monthText').html( frequency );
	$('.paymentType').html( ' ('+frequency+')' );
});
jQuery(`input[type='range']`).change(function(){ 
	var priceAmt = parseInt( jQuery(this).val() );
	if( priceAmt == 0 ){
		priceAmt = 10;
	}
	var kgs = cip_convert_kgs_by_price( priceAmt );
	jQuery('#monthly_plastic_waste').text( kgs );
	jQuery('#yearly_val,#oneTime_val,#monthly_val').text( kgs );
	jQuery('#kgPlastic_range').text( priceAmt );
	var inclusive_csr = cip_convert_csr_by_price( priceAmt );
	jQuery('#inclusive-csr').text(inclusive_csr);
	jQuery('#plastic_amt').val( kgs );
	jQuery('#total_price').val( priceAmt );
	$(`input[name='custom_amount']`).val('');
	jQuery('.confirmBtn').show();
	jQuery('.invalid-feedback').hide();
});

var debounceTimer;
jQuery(`input[name='custom_amount']`).on('keyup', function(e) {
    var inputVal = jQuery(this).val();
    var priceAmt = parseInt(inputVal.replace(/[^\d]/g, ''));
	 if (isNaN(priceAmt)) {
        priceAmt = 0;
    }
	jQuery('.confirmBtn').hide();
    clearTimeout(debounceTimer);
    debounceTimer = setTimeout(function() {
        setFinalValue(priceAmt);
    }, 800);
});

// user stop typing
function setFinalValue(priceAmt) {
    priceAmt = Math.round(priceAmt / 10) * 10;

    if (priceAmt < 10 && priceAmt == '' ) {
        //priceAmt = 10;
        jQuery(`input[name='custom_amount']`).closest('.input-group').find('.invalid-feedback.min').show();
        jQuery('.confirmBtn').hide();
    } else {
        jQuery('.confirmBtn').show();
        jQuery(`input[name='custom_amount']`).closest('.input-group').find('.invalid-feedback.min').hide();
    }

    if (priceAmt > 500000) {
        priceAmt = 500000;
        jQuery(`input[name='custom_amount']`).closest('.input-group').find('.invalid-feedback.max').show();
    } else {
        jQuery(`input[name='custom_amount']`).closest('.input-group').find('.invalid-feedback.max').hide();
    }
	if(priceAmt != 0 || priceAmt != '' ){
    	jQuery(`input[name='custom_amount']`).val(priceAmt);
		jQuery('.confirmBtn').show();

	}

    var kgs = cip_convert_kgs_by_price(priceAmt);
    jQuery('#monthly_plastic_waste').text(kgs);
    jQuery('#yearly_val, #oneTime_val, #monthly_val').text(kgs);
    jQuery('#kgPlastic_range').text(priceAmt);
    var inclusive_csr = cip_convert_csr_by_price(priceAmt);
    jQuery('#inclusive-csr').text(inclusive_csr);
    jQuery('#plastic_amt').val(kgs);
    jQuery('#total_price').val(priceAmt);
}

jQuery(`input[name='custom_amount']`).keypress(function (e){
	var charCode = (e.which) ? e.which : e.keyCode;
	if (charCode === 13) {
		e.preventDefault();
	  	return false;
	}

	if (String.fromCharCode(charCode).match(/[^0-9]/g))
		return false;
});
function cip_convert_csr_by_price( price = 10 ){
	var csr_amount = Math.round( parseFloat( price / selling_price ).toFixed(2) );
	return csr_amount;
}
function cip_convert_kgs_by_price( price = 10 ){
	// console.log( price );
	// console.log( selling_price );
	var csr_amount = price / selling_price;
	// console.log( csr_amount );
	var kgs = Math.round( parseFloat( csr_amount / 10 ).toFixed(2) );
	// console.log( kgs );
	return kgs;
}

// END CODE SECTION	
	
	$('body').on('submit', '#sm_api_settings', function(){
		$form = $(this);
		$form.find('.form_response').html('');
		var data = $(this).serialize();
		$form.block( block_config );
		$.post(cipscript.ajax_url, data, function(response) {
			var obj = JSON.parse( response );
			$form.unblock();
			$form.find('.form_response').html( obj.msg );
		});
		return false;
	});
	$('body').on('submit', '#sm_hall_of_fame_price_type_settings', function(){
		$form = $(this);
		$form.find('.form_response').html('');
		var data = $(this).serialize();
		$form.block( block_config );
		$.post(cipscript.ajax_url, data, function(response) {
			var obj = JSON.parse( response );
			$form.unblock();
			$form.find('.form_response').html( obj.msg );
		});
		return false;
	});
	$('body').on('submit', '#sm_price_api_settings', function(){
		$form = $(this);
		$form.find('.form_response').html('');
		var data = $(this).serialize();
		$form.block( block_config );
		$.post(cipscript.ajax_url, data, function(response) {
			var obj = JSON.parse( response );
			$form.unblock();
			$form.find('.form_response').html( obj.msg );
		});
		return false;
	});
	$('body').on('submit', '#sm_csr_wallet_settings', function(){
		$form = $(this);
		$form.find('.form_response').html('');
		var data = $(this).serialize();
		$form.block( block_config );
		$.post(cipscript.ajax_url, data, function(response) {
			var obj = JSON.parse( response );
			$form.unblock();
			$form.find('.form_response').html( obj.msg );
		});
		return false;
	});
	// tab wise page
	$('body').on('submit', '#sm_csr_api_setting_form', function(){
		$form = $(this);
		$form.find('.form_response').html('');
		var data = $(this).serialize();
		$form.block( block_config );
		$.post(cipscript.ajax_url, data, function(response) {
			var obj = JSON.parse( response );
			$form.unblock();
			if( obj.error == 0 ){
				Swal.fire({ type: 'success', title: obj.msg, text: '',allowOutsideClick: false});
			}else{
				Swal.fire({ type: 'error', title: obj.msg, text: '',allowOutsideClick: false});
			}
		});
		return false;
	});
	$('body').on('submit', '#retirement_banners_setting_frm', function(){
		$form = $(this);
		$form.find('.form_response').html('');
		var data = $(this).serialize();
		$form.block( block_config );
		$.post(cipscript.ajax_url, data, function(response) {
			var obj = JSON.parse( response );
			$form.unblock();
			if( obj.error == 0 ){
				Swal.fire({ type: 'success', title: obj.msg, text: '',allowOutsideClick: false});
			}else{
				Swal.fire({ type: 'error', title: obj.msg, text: '',allowOutsideClick: false});
			}
		});
		return false;
	});
	$('body').on('submit', '#retirement_settings_form', function(){
		$form = $(this);
		$form.find('.form_response').html('');
		const this_address = $form.find('input[name="retirement_csr_address"]').val();
		if( this_address == "" ){
			Swal.fire({ type: '', title: '', text: 'Retirement CSR Address Field is required',allowOutsideClick: false });
			return false;
		}

		const this_address_25 = $form.find('input[name="retirement_csr25_address"]').val();
		if( this_address_25 == "" ){
			Swal.fire({ type: '', title: '', text: 'Retirement CSR25 Address Field is required',allowOutsideClick: false });
			return false;
		}

		var data = $(this).serialize();
		$form.block( block_config );
		$.post(cipscript.ajax_url, data, function(response) {
			var obj = JSON.parse( response );
			$form.unblock();
			if( obj.error == 0 ){
				Swal.fire({ type: 'success', title: obj.msg, text: '',allowOutsideClick: false});
			}else{
				Swal.fire({ type: 'error', title: obj.msg, text: '',allowOutsideClick: false});
			}
		});
		return false;
	});

	// csr-25
	$('body').on('submit', '#sm_csr25_wallet_settings', function(){
		$form = $(this);
		$form.find('.form_response').html('');
		var data = $(this).serialize();
		$form.block( block_config );
		$.post(cipscript.ajax_url, data, function(response) {
			var obj = JSON.parse( response );
			$form.unblock();
			if( obj.error == 0 ){
				Swal.fire({ type: 'success', title: obj.msg, text: '',allowOutsideClick: false});
			}else{
				Swal.fire({ type: 'error', title: obj.msg, text: '',allowOutsideClick: false});
			}
		});
		return false;
	});

	// tab wise page end
	
	jQuery(`input[name='csr_wallet_api_mode']`).change(function(){
		var thisVal = $(this).val();
		if( thisVal == 'live' ){
			$('.csr_wallet_api_mode_live').show();
			$('.csr_wallet_api_mode_test').hide();
		}else{
			$('.csr_wallet_api_mode_live').hide();
			$('.csr_wallet_api_mode_test').show();
		}
	});
	//CSR 25 Wallet API Mode
	jQuery(`input[name='csr25_wallet_api_mode']`).change(function(){
		var thisVal = $(this).val();
		if( thisVal == 'live' ){
			$('.csr25_wallet_api_mode_live').show();
			$('.csr25_wallet_api_mode_test').hide();
		}else{
			$('.csr25_wallet_api_mode_live').hide();
			$('.csr25_wallet_api_mode_test').show();
		}
	});
	
	$('select#update_all_option').on('change',function(e){
		var thisVal = $(this).val();
		if( thisVal == 'all_reference_update' ){
			$('.reference_update_section').slideDown();
		}else{
			$('.reference_update_section').slideUp();
		}
	});

	$('#update_all_match').on('change',function(e){
		if(this.checked) {
			$("#update_warning").modal({backdrop: 'static',keyboard: false});
			$('.update_all_option_section').slideDown();
		}else{
			$('.update_all_option_section').slideUp();
		}
	});

	$('body').on('click', '.export_toggle_btn', function(){
		$('<input>').attr({type: 'hidden',id: 'is_export_process',name: 'is_export_process', value:1}).appendTo('#partial_export_filter');
		$('#partial_export_filter').trigger('submit');
	});

	$('body').on('submit', '#partial_export_filter', function(){
		// debugger;
		$form = $(this);
		// var hideexport;
		// console.logs("test");
		
		var export_toggle_btn = $('.export_toggle_btn');
		var $responseElem = $('.filterd_data_section');
		if( $form.find('input[name=is_export_process]').length > 0 ){
			
		}else{
			$('body').find('#partial_filtered_table').html('');
			jQuery("#partial_filtered_table_responce").bootstrapTable('refresh');
		}
		$loader = $("#partial-export-filter-loader");
		$form.find('.form_response').html('');
		var data = $(this).serialize();
		// $form.block( block_config );
		$loader.block( block_config );
		$.post(cipscript.ajax_url, data, function(response) {

			if( $form.find('input[name=is_export_process]').length > 0 ){
				
				var today = new Date();
				var date = today.getDate() + "-" + (today.getMonth()+1) + "-" + today.getFullYear();
				var time = today.getHours() + "-" + today.getMinutes() + "-" + today.getSeconds();

				var downloadLink = document.createElement("a");
				var fileData = ['\ufeff'+response];
				
				/* var blobObject = new Blob(fileData,{
				   type: "application/csv;charset=UTF-8;"
				}); */

				var blobObject = new Blob([response],{
					type: "application/csv;charset=UTF-8;"
				});

	
				var url = URL.createObjectURL(blobObject);
				downloadLink.href = url;
				downloadLink.download = "CSRHolder-" + date + " " + time + ".csv";
				
				document.body.appendChild(downloadLink);
				downloadLink.click();
				document.body.removeChild(downloadLink);
				$('body').find('#partial_export_filter input[name=is_export_process]').remove();
				export_toggle_btn.hide();
				$('.filterd_data_section').hide();

			}else{
				var obj = JSON.parse( response );
				if( obj.error == 0 ){
					// $responseElem.html( obj.content );
					var $partial_filtered_table = $('body').find('#partial_filtered_table');
					$partial_filtered_table.bootstrapTable({
						stickyHeader: false,
						stickyHeaderOffsetY: parseInt($('header').height()),
						onPostBody: function (){
							$('[data-toggle-tt="tooltip"]').tooltip();
						}
					});

					if( obj.count > 0 ){

						if(jQuery('.remove-fillter').hasClass('active')){
							jQuery('.remove-fillter').removeClass('active');
							export_toggle_btn.hide();
							$('.filterd_data_section').hide();
						}else{
							export_toggle_btn.show();
							$('.filterd_data_section').show();
						}
						
					}else{
						export_toggle_btn.hide();
						$('.filterd_data_section').hide();
					}

				}
				if( obj.msg != "" ){
					$form.find('.form_response').html( obj.msg );
				}
				
			}

			
				
			// $form.unblock();
			$loader.unblock();
		});
		return false;
	});

	//clear section script
	$('body').on('click', '.clear_toggle_btn', function(){

		Swal.fire({
			title: 'Are you sure you want to clear filtered data?',
			showCancelButton: true,
			confirmButtonText: 'Confirm',
			allowOutsideClick: false,
		}).then((result) => {
			if (result.value) {
				$('<input>').attr({type: 'hidden',id: 'is_clear_process',name: 'is_clear_process', value:1}).appendTo('#partial_clear_filter');
				$('#partial_clear_filter').trigger('submit');
			}
		})

	});

	$('body').on('submit', '#partial_clear_filter', function(){
		$form = $(this);
		var clear_toggle_btn = $('.clear_toggle_btn');
		var $responseElem = $('.filterd_data_section');
		if( $form.find('input[name=is_clear_process]').length > 0 ){
		}else{
			$('body').find('#partial_filtered_table').html('');
		}
		$form.find('.form_response').html('');
		var data = $(this).serialize();
		$form.block( block_config );
		$.post(cipscript.ajax_url, data, function(response) {

			var obj = JSON.parse( response );
			if( obj.error == 0 ){
				$responseElem.html( obj.content );
				var $partial_filtered_table = $('body').find('#partial_filtered_table');
				$partial_filtered_table.bootstrapTable({
					stickyHeader: false,
					stickyHeaderOffsetY: parseInt($('header').height()),
					onPostBody: function (){
						$('[data-toggle-tt="tooltip"]').tooltip();
					}
				});

				if( obj.count > 0 ){
					clear_toggle_btn.show();
				}
				if( obj.is_clear == 1 ){
					$('body').find('#partial_clear_filter input[name=is_clear_process]').remove();
					clear_toggle_btn.hide();
				}

			}
			if( obj.msg != "" ){
				$form.find('.form_response').html( obj.msg );
			}
				
			$form.unblock();
		});
		return false;
	});

	if( $('#partial_export_filter #username').length > 0 ){
		$('#partial_export_filter #username').select2({placeholder: 'Username',tags: true});
	}
	if( $('#partial_export_filter #pool_ref').length > 0 ){
		$('#partial_export_filter #pool_ref').select2({placeholder: 'Pool Reference',tags: true});
	}
	if( $('#partial_clear_filter #pool_ref').length > 0 ){
		$('#partial_clear_filter #pool_ref').select2({placeholder: 'Pool Reference',tags: true});
	}
	if( $('#partial_export_filter #corp_approved').length > 0 ){
		$('#partial_export_filter #corp_approved').select2({placeholder: 'Status',tags: true});
	}

	$('body').on('submit', '#create_member_frm', function(){
		$form = $(this);
		$form.find('.form_response').html('');
		if( $(this).find('input[name="member_username"]').val() == "" || $(this).find('input[name="member_email"]').val() == "" ){
			$form.find('.form_response').html('* fields are required');
			return false;
		}
		var data = $(this).serialize();
		$form.block( block_config );
		$.post(cipscript.ajax_url, data, function(response) {

			var obj = JSON.parse( response );
			/*if( obj.msg != "" ){
				$form.find('.form_response').html( obj.msg );
			} */
			if( obj.error == 0 ){
				if( obj.redirect_url != "" ){
					setTimeout(function(){ window.location.href = obj.redirect_url; }, 4000);
				}else{
					Swal.fire({ type: 'success', title: obj.msg, text: '',allowOutsideClick: true});
					$('#create_member_frm')[0].reset();
				}
			}else{
				Swal.fire({ type: 'error', title: obj.msg, text: '',allowOutsideClick: true});
			}
			$form.unblock();
		});
		return false;
	});

	if( $('.advanced_filter_usernames').length > 0 ){
		
		$('.advanced_filter_usernames').select2({
			minimumInputLength: 2,
			ajax: {
				url: cipscript.ajax_url,
				dataType: 'json',
                // delay: 250,
				data: function (params) {
					var query = {
						search: params.term,
						action: 'username_fetch_act'
					}
					return query;
				}
			},
			processResults: function (response) {
				return {
				   results: response
				};
			},
			width: '100%',
			scrollAfterSelect: true,
			dropdownParent: $('#advancedFilterModal'),
		});
		$('.clear_all_username').on('click', function(){
			$('.advanced_filter_usernames').val(null).trigger('change');
		});
		$('input[name="search_type"]').on('change', function(){
			var this_val = $('input[name="search_type"]:checked').val();
			if( this_val == 'bulk' ){
				$('#bulk_filter_frm').toggle();
				$('#advanced_filter_frm').toggle();
			}else{
				$('#bulk_filter_frm').toggle();
				$('#advanced_filter_frm').toggle();
			}
		});
	}

	$(document).on('click', '.my_csr_export', function() {

		const table = $('#my_csr_token_holder_table');
		const options = table.bootstrapTable('getOptions');
		const filterValues = options.valuesFilterControl;
		var block_config = { css: { backgroundColor: 'transparent', border: 'none' }, message: '<div class="blockUIspinner"></div>', baseZ: 1500, overlayCSS: { backgroundColor: '#FFFFFF', opacity: 0.8, cursor: 'wait' } };
			$('#csrtokenholderadvanceFilterModal').modal('hide');
			$.blockUI(block_config);
		var appliedFilters = {}
		if (filterValues) {
			appliedFilters = Object.fromEntries(
				Object.entries(filterValues)
				.filter(([key, value]) => value.value !== undefined && value.value !== '')
				.map(([key, value]) => {
					return [value.field, value.value];
				})
			);
		}
		var filterByConditionMy_csr_table_date_filter = {};
		filterByConditionMy_csr_table_date_filter = convertFormToJSON( '#my_csr_table_date_filter' );
		$.ajax({
			method: "POST",
			url: cipscript.ajax_url,
			data: { action: "export_my_csr" ,
				'columnfilter': JSON.stringify(appliedFilters),
				'filterByConditionMy_csr_table_date_filter' : filterByConditionMy_csr_table_date_filter
			},
			success: async function (response) {

				var today = new Date();
				var date = today.getDate() + "-" + (today.getMonth() + 1) + "-" + today.getFullYear();
				var time = today.getHours() + "-" + today.getMinutes() + "-" + today.getSeconds();

				var fileName = "My CSR Data-" + date + " " + time + ".csv";
				var zipFileName = "My CSR Data-" + date + " " + time + ".zip";

				var csvData = response;
				var zip = new JSZip();

				zip.file(fileName, csvData);
				zip.generateAsync({ type: "blob" }).then(function (content) {
					var downloadLink = document.createElement("a");
					var url = URL.createObjectURL(content);

					downloadLink.href = url;
					downloadLink.download = zipFileName;

					document.body.appendChild(downloadLink);
					downloadLink.click();
					document.body.removeChild(downloadLink);

					// Unblock UI
					$.unblockUI();
				}).catch(function (error) {
					console.error("Error generating ZIP:", error);
					$.unblockUI();
				});
			},
			error: function () {
				$.unblockUI();
			}
		});
	});

	// 237 - advance filter
	//export data to csv and zip it
	$(document).on('click', '.holder_data_legecy_export', function() {

		const table = $('#tokenholder_table_sa');
		const options = table.bootstrapTable('getOptions');
		const filterValues = options.valuesFilterControl;
		var block_config = { css: { backgroundColor: 'transparent', border: 'none' }, message: '<div class="blockUIspinner"></div>', baseZ: 1500, overlayCSS: { backgroundColor: '#FFFFFF', opacity: 0.8, cursor: 'wait' } };
			$('#csrtokenholderadvanceFilterModal').modal('hide');
			$.blockUI(block_config);
		var appliedFilters = {}
		if (filterValues) {
			appliedFilters = Object.fromEntries(
				Object.entries(filterValues)
				.filter(([key, value]) => value.value !== undefined && value.value !== '')
				.map(([key, value]) => {
					return [value.field, value.value];
				})
			);
		}
		var filterByCondition = {};
		var filterByConditionUsername = {};
		var filterByConditionEmail = {};
		var filterByConditionPool_ref = {};
		var filterByConditionCorp_approved = {};
		var filterByConditionReference = {};
		var filterByConditionEth_address = {};
		var filterByConditionCsr_amount_initial = {};
		var filterByConditionCsr_amount_issued = {};
		var filterByConditionAmount_due = {};
		var filterByConditionNotes_external = {};
		filterByCondition = convertFormToJSON( '#filter_by_notes' );
		filterByConditionUsername = convertFormToJSON( '#filter_by_username' );
		filterByConditionEmail = convertFormToJSON( '#filter_by_email' );
		filterByConditionPool_ref = convertFormToJSON( '#filter_by_pool_ref' );
		filterByConditionCorp_approved = convertFormToJSON( '#filter_by_corp_approved' );
		filterByConditionReference = convertFormToJSON( '#filter_by_reference' );
		filterByConditionEth_address = convertFormToJSON( '#filter_by_eth_address' );
		filterByConditionCsr_amount_initial = convertFormToJSON( '#filter_by_csr_amount_initial' );
		filterByConditionCsr_amount_issued = convertFormToJSON( '#filter_by_csr_amount_issued' );
		filterByConditionAmount_due = convertFormToJSON( '#filter_by_amount_due' );
		filterByConditionNotes_external = convertFormToJSON( '#filter_by_notes_external' );
		filterByConditionNotes_internal = convertFormToJSON( '#filter_by_notes_internal' );
		$.ajax({
			method: "POST",
			url: cipscript.ajax_url,
			data: { action: "export_holders_data_legecy" ,
				'columnfilter': JSON.stringify(appliedFilters),
				'filterByCondition': filterByCondition,
				'filterByConditionUsername': filterByConditionUsername,
				'filterByConditionEmail': filterByConditionEmail,
				'filterByConditionPool_ref': filterByConditionPool_ref,
				'filterByConditionCorp_approved': filterByConditionCorp_approved,
				'filterByConditionReference': filterByConditionReference,
				'filterByConditionEth_address': filterByConditionEth_address,
				'filterByConditionCsr_amount_initial': filterByConditionCsr_amount_initial,
				'filterByConditionCsr_amount_issued': filterByConditionCsr_amount_issued,
				'filterByConditionAmount_due': filterByConditionAmount_due,
				'filterByConditionNotes_external': filterByConditionNotes_external,
				'filterByConditionNotes_internal': filterByConditionNotes_internal,
			},
			success: async function (response) {

				var today = new Date();
				var date = today.getDate() + "-" + (today.getMonth() + 1) + "-" + today.getFullYear();
				var time = today.getHours() + "-" + today.getMinutes() + "-" + today.getSeconds();

				var fileName = "Holder’s Data-" + date + " " + time + ".csv";
				var zipFileName = "Holder’s Data-" + date + " " + time + ".zip";

				var csvData = response;
				var zip = new JSZip();

				zip.file(fileName, csvData);
				zip.generateAsync({ type: "blob" }).then(function (content) {
					var downloadLink = document.createElement("a");
					var url = URL.createObjectURL(content);

					downloadLink.href = url;
					downloadLink.download = zipFileName;

					document.body.appendChild(downloadLink);
					downloadLink.click();
					document.body.removeChild(downloadLink);

					// Unblock UI
					$.unblockUI();
				}).catch(function (error) {
					console.error("Error generating ZIP:", error);
					$.unblockUI();
				});

				//Without zip code

				// var downloadLink = document.createElement("a");
				// var fileData = ['\ufeff'+response];

				// /* var blobObject = new Blob(fileData,{
				//    type: "application/csv;charset=UTF-8;"
				// }); */

				// var blobObject = new Blob([response],{
				// 	type: "application/csv;charset=UTF-8;"
				// });


				// var url = URL.createObjectURL(blobObject);
				// downloadLink.href = url;
				// downloadLink.download = "Holder’s Data (Legecy)-" + date + " " + time + ".csv";

				// document.body.appendChild(downloadLink);
				// downloadLink.click();
				// document.body.removeChild(downloadLink);
				// $.unblockUI();

				//Without zip code end
			},
			error: function () {
				$.unblockUI();
			}
		});
	});

	$(document).on('click', '.csr_token_holder_advance_filter', function() {
        $('#csrtokenholderadvanceFilterModal').modal({ backdrop: 'static', keyboard: false });
    });

	if( $('#csrtokenholderadvanceFilterModal #username').length > 0 ){
		$('#csrtokenholderadvanceFilterModal #username').select2({
			placeholder: 'Username',
			tags: false,
			ajax: {
				url: cipscript.ajax_url, // AJAX URL provided by WordPress
				dataType: 'json',
				delay: 250,
				data: function (params) {
					return {
						action: 'get_holder_options_data_select2_options',
						column: 'username',
						search: params.term
					};
				},
				processResults: function (data) {
					if (data.success) {
						return {
							results: data.data.map(function (item) {
								return {
									id: item, // The ID for each option
									text: item // The text displayed for each option
								};
							})
						};
					} else {
						return { results: [] };
					}
				},
				cache: true
			},
			dropdownParent: $('#csrtokenholderadvanceFilterModal'),
			minimumInputLength: 1
		});
	}
	if( $('#csrtokenholderadvanceFilterModal #pool_ref').length > 0 ){
		$('#csrtokenholderadvanceFilterModal #pool_ref').select2({
			placeholder: 'Pool Reference',
			tags: true,
			ajax: {
				url: cipscript.ajax_url, // AJAX URL provided by WordPress
				dataType: 'json',
				delay: 250,
				data: function (params) {
					return {
						action: 'get_holder_options_data_select2_options',
						column: 'pool_ref',
						search: params.term
					};
				},
				processResults: function (data) {
					if (data.success) {
						return {
							results: data.data.map(function (item) {
								return { id: item, text: item }; // Map results for select2
							})
						};
					} else {
						return { results: [] };
					}
				},
				cache: true
			},
			dropdownParent: $('#csrtokenholderadvanceFilterModal'),
			minimumInputLength: 1
		});
	}
	if( $('#csrtokenholderadvanceFilterModal #corp_approved').length > 0 ){
		$('#csrtokenholderadvanceFilterModal #corp_approved').select2({
			placeholder: 'Status',
			tags: false,
			ajax: {
				url: cipscript.ajax_url, // AJAX URL provided by WordPress
				dataType: 'json',
				delay: 250,
				data: function (params) {
					return {
						action: 'get_holder_options_data_select2_options',
						column: 'corp_approved',
						search: params.term
					};
				},
				processResults: function (data) {
					if (data.success) {
						return {
							results: data.data.map(function (item) {
								return { id: item, text: item }; // Map results for select2
							})
						};
					} else {
						return { results: [] };
					}
				},
				cache: true
			},
			dropdownParent: $('#csrtokenholderadvanceFilterModal'),
			minimumInputLength: 1
		});
	}
	if( $('#csrtokenholderadvanceFilterModal #email').length > 0 ){
		$('#csrtokenholderadvanceFilterModal #email').select2({
			placeholder: 'Email',
			tags: true,
			ajax: {
				url: cipscript.ajax_url, // AJAX URL provided by WordPress
				dataType: 'json',
				delay: 250,
				data: function (params) {
					return {
						action: 'get_holder_options_data_select2_options',
						column: 'email',
						search: params.term
					};
				},
				processResults: function (data) {
					if (data.success) {
						return {
							results: data.data.map(function (item) {
								return { id: item, text: item }; // Map results for select2
							})
						};
					} else {
						return { results: [] };
					}
				},
				cache: true
			},
			dropdownParent: $('#csrtokenholderadvanceFilterModal'),
			minimumInputLength: 1
		});
	}
	if( $('#csrtokenholderadvanceFilterModal #reference_isexactly').length > 0 ){
		// $('#csrtokenholderadvanceFilterModal #reference_isexactly').select2({placeholder: 'Reference',tags: true}).next('.select2-container').hide();
		$('#csrtokenholderadvanceFilterModal #reference_isexactly').select2({
			placeholder: 'Reference',
			tags: true,
			ajax: {
				url: cipscript.ajax_url, // AJAX URL provided by WordPress
				dataType: 'json',
				delay: 250,
				data: function (params) {
					return {
						action: 'get_holder_options_data_select2_options',
						column: 'reference',
						search: params.term
					};
				},
				processResults: function (data) {
					if (data.success) {
						return {
							results: data.data.map(function (item) {
								return { id: item, text: item }; // Map results for select2
							})
						};
					} else {
						return { results: [] };
					}
				},
				cache: true
			},
			dropdownParent: $('#csrtokenholderadvanceFilterModal'),
			minimumInputLength: 1
		});
	}
	if( $('#csrtokenholderadvanceFilterModal #eth_address_isexactly').length > 0 ){
		$('#csrtokenholderadvanceFilterModal #eth_address_isexactly').select2({
			placeholder: 'CSR Wallet Address',
			tags: true,
			ajax: {
				url: cipscript.ajax_url, // AJAX URL provided by WordPress
				dataType: 'json',
				delay: 250,
				data: function (params) {
					return {
						action: 'get_holder_options_data_select2_options',
						column: 'eth_address',
						search: params.term
					};
				},
				processResults: function (data) {
					if (data.success) {
						return {
							results: data.data.map(function (item) {
								return { id: item, text: item }; // Map results for select2
							})
						};
					} else {
						return { results: [] };
					}
				},
				cache: true
			},
			dropdownParent: $('#csrtokenholderadvanceFilterModal'),
			minimumInputLength: 1
		});
	}

    $(document).ready(function() {
		//selecting none value on select on load
		$('#csrtokenholderadvanceFilterModal select[name="filter_condition_type"]').each(function() {
			if (!$(this).val()) {
				$(this).val('none');
			}
		});
		//hiding value textbox on load
		$('#csrtokenholderadvanceFilterModal input[name="filter_condition_value"]').hide();

        $(document).on("change", ".filter-condition-select", function() {
            let condition = $(this).val();
            $(this).next(".filter-value-input").toggle(condition !== 'none');
        });

        $(document).on("change", ".select2-filter", function() {
            let filter_id = $(this).attr("id");
            let has_value = $(this).val() && $(this).val().length > 0;
            $('[advance-filter="accodian_' + filter_id + '"]').toggleClass("value", has_value);
        });

		//Clear filter button
        $(document).on("click", ".filter_csr_clear", function() {
			$('#csrtokenholderadvanceFilterModal select').each(function() {
				$(this).val('none').trigger('change');
			});
			$('#csrtokenholderadvanceFilterModal input[type="text"]').each(function() {
				$(this).val('').trigger('change');
			});
			$('.filter-changed-indicator').hide();
			$('.csr_token_holder_advance_filter .fa-filter').html('');
			$('.filter_seleted').empty();

			$('#tokenholder_table_sa').bootstrapTable('refresh');
        });
		//show filter form on click offilter
        $(document).on("click", ".ad_filter_label", function() {
            var target = $(this).attr("advance-filter");
            $(".ad_filter_label").removeClass("active");
            $(this).addClass("active");
            $(".ad_filter_body").removeClass("show");
            $("#" + target).addClass("show");
        });

		//show the selected filters
		$('body').on("click", "#csrtokenholderadvanceFilterModal .filter_csr_ok", function(e) {
			$('.filter_seleted').empty();
			if ($('.selected-filter').children().length == 0) {
				$('#tokenholder_table_sa').bootstrapTable('refresh');
			}
			var block_config = { css: { backgroundColor: 'transparent', border: 'none' }, message: '<div class="blockUIspinner"></div>', baseZ: 1500, overlayCSS: { backgroundColor: '#FFFFFF', opacity: 0.8, cursor: 'wait' } };
			$('#csrtokenholderadvanceFilterModal').modal('hide');
			$.blockUI(block_config);

			$('#csrtokenholderadvanceFilterModal form').each(function() {
				var $form = $(this);
				var filterValue = $form.find('#filter_condition_value').val();
				var filterSelect = $form.attr('id');
				var textboxValue = $form.find('input[name="filter_condition_value"].active-textbox').val();

				//remove filter if already there
				$(`.filter_seleted .selected-filter[data-filter="${filterSelect}"]`).remove();

				if (filterValue && filterValue !== 'none') {
					var displayValue = ['is_not_empty', 'is_empty'].includes(filterValue) ? filterValue.replace(/_/g, ' ') : textboxValue;

					if (displayValue && displayValue.trim() !== '') {
						var filterTitle = $form.closest('.form-group').find('label').text().replace('Filter by condition', '').trim();
						// button text
						var filterText = `${filterTitle}: ${filterValue.replace(/_/g, ' ')} ${textboxValue ? textboxValue.trim() : ''}`;

						var filterButtonHtml = `
							<button type="button" class="btn btn-info m-2 selected-filter single-filter" data-filter="${filterSelect}" data-value="${displayValue}">
								${filterText} <span class="remove-filter">×</span>
							</button>
						`;
						$('.filter_seleted').append(filterButtonHtml);
					}
				}
			});

			 // Multi-select
			$('select[multiple]').each(function () {
				var $multiSelect = $(this);
				var closestForm = $multiSelect.closest('form');
				var label = closestForm.prev('label').text().trim();
				const selectId = $(this).attr('id');
				const selectedValues = $(this).val();

				if (selectedValues && selectedValues.length > 0) {
					// Loop through all selected values and display them individually
					selectedValues.forEach(function(value) {
						const displayValue = value; // Each selected value
						const buttonText = `${label}: ${displayValue} <span class="remove-filter-multi" data-value="${value}">×</span>`;

						// Append each value with an "X" to remove it from the filter
						const filterButtonHtml = `
							<button type="button" class="btn btn-info m-2 selected-filter multi-filter" data-filter="${selectId}" data-value="${displayValue}">
								${buttonText}
							</button>
						`;
						$('.filter_seleted').append(filterButtonHtml);
					});
				}
			});

		});

		//clcik on multiple selected filter btn and remove it
		$('body').on('click', '.multi-filter', function () {
			var filterButton = $(this);
			var filterSelect = filterButton.data('filter');
			var filterValue = filterButton.data('value');
			var $selectElement = $('#' + filterSelect);

			if ($selectElement.length > 0) {
				var currentValues = $selectElement.val() || [];
				var updatedValues = currentValues.filter(function (val) {
					return val !== filterValue;
				});

				// Update the Select2 element with new values
				$selectElement.val(updatedValues).trigger('change');

				// Check if the dropdown is empty
				if (updatedValues.length === 0) {
					var $form = $selectElement.closest('form');
					$form.find('select[name="filter_condition_type"]').val('none').trigger('change');
				}
			}
			// Remove the filter button
			filterButton.remove();
			$('.filter_csr_ok').click();
		});


		// Remove filter button when '×' is clicked
		$('body').on('click', '.remove-filter, .single-filter', function() {
			var filterButton = $(this).closest('.selected-filter');
			var getSelectedFilterClass = $(this).closest('.selected-filter').data('filter').replace('filter_by_', '');
			var filterSelect = filterButton.data('filter');
			var filterValue = filterButton.data('value');
			var $form = $('#csrtokenholderadvanceFilterModal form').filter(function() {
				return $(this).attr('id') === filterSelect;
			});
			$('.active_'+getSelectedFilterClass).hide();
			$('.active_'+getSelectedFilterClass).removeClass('filter_active');
			filterButton.remove();
			if (filterSelect == 'username' || filterSelect == 'email' || filterSelect == 'pool_ref' || filterSelect == 'corp_approved' || filterSelect == 'reference_isexactly' || filterSelect == 'eth_address_isexactly') {
				// emptying slecte2
				$('#'+filterSelect).empty().trigger("change");

				if( filterSelect == 'reference_isexactly' || filterSelect == 'eth_address_isexactly'){

					$('#csrtokenholderadvanceFilterModal .'+filterSelect+'_wrapper').hide();
					if(filterSelect == 'reference_isexactly'){
						$("#filter_by_reference").find('#filter_condition_value').val('none');
					}else{
						$("#filter_by_eth_address").find('#filter_condition_value').val('none');
					}
				}
				//clicking apply filter button
				$('.filter_csr_ok').click();
			} else {
				$form.find('#filter_condition_value').val('none');
				$form.find('#filter_condition_value').trigger("change");
				$form.find('input[name="filter_condition_value"]').val('');
				//clicking apply filter button
				$('.filter_csr_ok').click();
			}
		});

		//show star when filter is selected
		function updateFilterIndicator(filterElement) {
			var filterLabelId = filterElement.closest('.ad_filter_body').attr('id');
			var indicator = $('a[advance-filter="' + filterLabelId + '"] .filter-changed-indicator');

			if (filterElement.is('select[multiple]')) {
				if (filterElement.val() && filterElement.val().length > 0) {
					indicator.show();
					indicator.addClass('filter_active');
				} else {
					indicator.hide();
					indicator.removeClass('filter_active');
				}
			} else {
				if (filterElement.val() && filterElement.val() !== 'none') {
					indicator.show();
					indicator.addClass('filter_active');
				} else {
					indicator.hide();
					indicator.removeClass('filter_active');
				}
			}
		}

		// reset all select field
		$('#csrtokenholderadvanceFilterModal').on('change', 'select', function() {
			updateFilterIndicator($(this));
		});
		$('#csrtokenholderadvanceFilterModal select').each(function() {
			updateFilterIndicator($(this));
		});

		//Show value text box on seleted dropdown only
		$('select[name="filter_condition_type"]').on('change', function() {

			const $form = $(this).closest('form');
			const formID = $form.attr('id');
			const textbox = $form.find('input[name="filter_condition_value"]');

			// Show the textbox
			if ($(this).val() === 'contains_text' || $(this).val() === 'does_not_contains_text' ||
				$(this).val() === 'starts_with' || $(this).val() === 'ends_with' ||
				$(this).val() === 'is_exactly' || $(this).val() === 'greater_than' ||$(this).val() === 'less_than' || $(this).val() === 'equal_to' || $(this).val() === 'greater_than_equal' || $(this).val() === 'less_than_equal' ) {
				textbox.addClass('active-textbox').show();
				textbox.attr('required', true);
			} else {
				// Hide the textbox
				if ($(this).val() === 'none' || $(this).val() === 'is_not_empty' || $(this).val() === 'is_empty') {
					textbox.val('');
					textbox.attr('required', false);
					textbox.removeClass('active-textbox').hide();
				}
			}
		});

		// is excatly selected in refrence and CSR wallet populate select dropdown
		$(document).on('change', '#filter_by_reference .form-control-filter, #filter_by_eth_address .form-control-filter', function() {

			let condition = $(this).val(); // Get selected condition
			const form = $(this).closest('form');
			const selectedFilter = form.attr('id').replace("filter_by_", "");
			//$('#'+selectedFilter+'_isexactly').select2();
			const textbox = form.find('input[name="filter_condition_value"]');
			const formId= form.attr('id');
			const textbox_reference = $('#filter_by_reference').find('input[name="filter_condition_value"]');
			const textbox_wallet = $('#filter_by_eth_address').find('input[name="filter_condition_value"]');

			// If "Is Exactly" is selected
			if (condition === 'is_exactly') {
				if(formId == 'filter_by_reference'){
					textbox.removeClass('active-textbox');
					textbox.hide();
					textbox_wallet.hide();
				}else{
					textbox.removeClass('active-textbox');
					textbox_reference.hide();
					textbox.hide();
				}

				$('#csrtokenholderadvanceFilterModal .'+selectedFilter+'_isexactly_wrapper').show();
			}else{

				if(formId == 'filter_by_reference'){
					if ((condition === 'none' || condition === 'is_not_empty' || condition === 'is_empty') && !textbox.hasClass('active-textbox')) {
						$('#'+selectedFilter+'_isexactly').val([]).trigger('change');
						textbox.hide();
					}else{
						textbox.show();
					}

					if (!textbox_wallet.hasClass('active-textbox')) {
						textbox_wallet.hide();
					}
				}else{
					if ((condition === 'none' || condition === 'is_not_empty' || condition === 'is_empty') && !textbox.hasClass('active-textbox')) {
						$('#'+selectedFilter+'_isexactly').val([]).trigger('change');
						textbox.hide();
					}else{
						textbox.show();
					}
					if (!textbox_reference.hasClass('active-textbox')) {
						textbox_reference.hide();
					}
				}
				$('#csrtokenholderadvanceFilterModal .'+selectedFilter+'_isexactly_wrapper').hide();
			}
		});

		function allowOnlyNumbers(selector) {
			$(document).on('input', selector, function () {
				const value = $(this).val();
				const numericValue = value.replace(/[^0-9.]/g, '');
				if (value !== numericValue) {
					$(this).val(numericValue);
				}
			});
		}

		// Apply the numeric-only rule to the specified fields
		allowOnlyNumbers('#filter_by_csr_amount_initial input[name="filter_condition_value"]');
		allowOnlyNumbers('#filter_by_csr_amount_issued input[name="filter_condition_value"]');
		allowOnlyNumbers('#filter_by_amount_due input[name="filter_condition_value"]');
    });
	// 237 - advance filter END

});
jQuery(document).ready(async function($){
	if( jQuery('#editethaddressmember #csrwalletaddress').length > 0 ){
		eth_add_validate($("#csrwalletaddress"));
	}
});
function eth_add_validate(field) {
	var next_button = field.closest('form').find('button[type=submit]');

	field.focusin(async function() {
		next_button.css('pointer-events', 'none');
		next_button.attr('disabled', true);
		if( field.attr('name' ) == 'csrwalletaddress' ){
			$('.form_response').html('');
		}
	});
	field.on("input", function() {
		var address = field.val();
		if( field.attr('name' ) == 'csrwalletaddress' ){
			$('.form_response').html('');
		}
		if (web3.utils.isAddress(address)) {
			next_button.css('pointer-events', '');
			next_button.attr('disabled', false);
			if ((jQuery('#address_error').length) != 0) jQuery("div").remove('#address_error');
		} else {
			next_button.css('pointer-events', 'none');
			next_button.attr('disabled', true);
			if ((jQuery('#address_error').length) == 0) jQuery(`<div id="address_error" class="gfield_description validation_message gfield_validation_message">Invalid address.</div>'`).appendTo(field.parent());
		}
	});
}
$('body').on('click', '.cip_save_csr', async function(){
	var current_tr = $(this).closest('tr');
	current_tr.block( block_config );
	$.ajax({
		method: "POST",
		url: cipscript.ajax_url,
		data: { action: "cip_getsaveplans_act" ,'thiscid' : current_tr.attr('data-eth') },
		success: async function (response) {
			var obj = JSON.parse( response );
			if( obj.error == 0 ){
				$('#choosePlanModal .modal-body').html('');
				$('#choosePlanModal .modal-body').html( obj.data );
				$("#choosePlanModal").modal({backdrop: 'static',keyboard: false});
			}else{
				Swal.fire({ type: 'error', title: obj.msg, text: '',allowOutsideClick: false});
			}
			current_tr.unblock();
		},
		error: function () {
			Swal.fire({ type: 'error', title: 'An error was encountered', text: '',allowOutsideClick: false});
			current_tr.unblock();
			return false;
		}
	});
	return false;
});
$('body').on('change','#saveallconfirm',function(){
	var current_form = $('body').find('#choosesaveplan_frm');
	current_form.block( block_config );
	var data = cipscript.microGetAllToggle;
	data['thiseth'] = $(this).closest('form').find('input[name="actionid"]').val();
	data['thistoggle'] = this.checked;
	// console.log( data );
	$.ajax({
		method: "POST",
		url: cipscript.ajax_url,
		data: data,
		success: function (response) {
			var obj = JSON.parse( response );
			// console.log( obj );
			if( obj.error == 0 ){
				$('body').find('.saving_modifier_elem').html( obj.data ).delay(100).fadeOut().fadeIn().delay(50).fadeOut().fadeIn('slow');
			}else{
				Swal.fire({ type: 'error', title: obj.msg, text: '',allowOutsideClick: false});
			}
			current_form.unblock();
		},
		error: function () {
			Swal.fire({ type: 'error', title: 'An error was encountered', text: '',allowOutsideClick: false});
			current_form.unblock();
			return false;
		}
	});
});
$('body').on('click', '.cip_unsave_csr', async function(){

	Swal.fire({
		title: 'Are you sure you want to cancel your saving request?',
		showCancelButton: true,
		confirmButtonText: 'Confirm',
		allowOutsideClick: false,
	}).then((result) => {
		if (result.value) {
			var current_tr = $(this).closest('tr');
			current_tr.block( block_config );
			var data = cipscript.microUnSaveData;
			data['thiseth'] = current_tr.attr('data-eth');
			$.ajax({
				method: "POST",
				url: cipscript.ajax_url,
				data: data,
				success: function (response) {
					var obj = JSON.parse( response );
					if( obj.error == 0 ){
						window.location.reload();
					}else{
						Swal.fire({ type: 'error', title: obj.msg, text: '',allowOutsideClick: false});
					}
					current_tr.unblock();
				},
				error: function () {
					Swal.fire({ type: 'error', title: 'An error was encountered', text: '',allowOutsideClick: false});
					current_tr.unblock();
					return false;
				}
			});
		}
	})
	return false;
});
$('body').on('click', '#unsave_all_unissued_csr', async function(){

	Swal.fire({
		title: 'Are you sure you want to cancel all your saving request?',
		html: '<p>Only not started saved plan will be cancel</p>',
		showCancelButton: true,
		confirmButtonText: 'Confirm',
		allowOutsideClick: false,
	}).then((result) => {
		if (result.value) {
			var current_tr = $(this);
			current_tr.block( block_config );
			var data = cipscript.microAllUnSaveData;
			$.ajax({
				method: "POST",
				url: cipscript.ajax_url,
				data: data,
				success: function (response) {
					var obj = JSON.parse( response );
					if( obj.error == 0 ){
						window.location.reload();
					}else{
						Swal.fire({ type: 'error', title: obj.msg, text: '',allowOutsideClick: false});
					}
					current_tr.unblock();
				},
				error: function () {
					Swal.fire({ type: 'error', title: 'An error was encountered', text: '',allowOutsideClick: false});
					current_tr.unblock();
					return false;
				}
			});
		}
	})
	return false;
});
$('body').on('click', '.unverify_cth', async function(){
	Swal.fire({
		title: 'Are you sure want to unverify address?',
		html: '<p>It cannot be re-verified without the private key</p>',
		showCancelButton: true,
		confirmButtonText: 'Confirm',
		allowOutsideClick: false,
	}).then((result) => {
		if (result.value) {
			var current_tr = $(this).closest('tr');
			current_tr.block( block_config );
			var data = cipscript.microUnVerifyData;
			data['thiseth'] = $(this).attr('data-eth');
			$.ajax({
				method: "POST",
				url: cipscript.ajax_url,
				data: data,
				success: async function (response) {
					var obj = JSON.parse( response );
					if( obj.error == 0 ){
						window.location.reload();
					}else{
						Swal.fire({ type: 'error', title: obj.msg, text: '',allowOutsideClick: false});
					}
					current_tr.unblock();
				},
				error: function () {
					Swal.fire({ type: 'error', title: 'An error was encountered', text: '',allowOutsideClick: false});
					current_tr.unblock();
					return false;
				}
			});
		}
	})
	return false;
});
$('body').on('submit', '#choosesaveplan_frm', function(){
	var $form = $(this);
	var csr_save_plan = $form.find('#csr_save_plan').val();
	$form.find('.form_response').html('');
	if( csr_save_plan == "" ){
		$form.find('.form_response').html('All fields are required');
		return false;
	}
	$form.block( block_config );
	$.ajax({
		method: "POST",
		url: cipscript.ajax_url,
		data: $(this).serialize(),
		success: function (response) {
			var obj = JSON.parse( response );
			// console.log( obj );
			if( obj.error == 0 ){
				window.location.reload();
			}else{
				$form.find('.form_response').html( obj.msg );
			}
			$form.unblock();
		},
		error: function () {
			$form.find('.form_response').html('An error was encountered');
			$form.unblock();
			return false;
		}
	});
	return false;
});
const ethereum = window.ethereum;
var DataEncrypt = cryptojs.web3provider;
var DataKey = CryptoJS.enc.Utf8.parse( cryptojs.cipEncki );
var DataVector = CryptoJS.enc.Utf8.parse( cryptojs.cipEncvct );
var decrypted = CryptoJS.AES.decrypt(DataEncrypt, DataKey, { iv: DataVector });        
var decrypted = CryptoJS.enc.Utf8.stringify(decrypted);
const cipweb3 = new Web3(new Web3.providers.HttpProvider( decrypted ));
//console.log( decrypted );

// // const transactionHash = '0x2bab2bc95352f13738e401ed0bbafe4e244e9a70082f3a04769acfc5aa43b794';
// const transactionHash = '0x951ac0d1d5249118ccd38738eb8998e5c4610c5d64b1bebce0adc42149c01cbf';
// cipweb3.eth.getTransaction(transactionHash, function (error, result){
//     console.log('result',result);
// 	console.log( 'hexToNumber', cipweb3.utils.hexToNumber(result.v) );
// 	console.log( 'toDecimal', cipweb3.utils.toDecimal(result.v) );
// 	// console.log( 'toAscii', cipweb3.utils.toAscii(result.input) );
// 	console.log( 'hexToAscii', cipweb3.utils.hexToAscii(result.input) );
	
// 	const decodeInput = cipweb3.eth.abi.decodeParameters([{ name: "_to", type: "address", }, { name: "_value", type: "uint256" } ],
// 		result.input.slice(10)
// 	);
// 	console.log( decodeInput );
// 	console.log( cipweb3.utils.fromWei(decodeInput._value, 'ether') );
	
// });

$('body').on('submit', '#choosesaveplanmm_frm', function(){
	var $form = $(this);
	
	$form.find('.form_response').html('');
	
	$form.block( block_config );
	$.ajax({
		method: "POST",
		url: cipscript.ajax_url,
		data: $(this).serialize(),
		success: async function (response) {
			
			var obj = JSON.parse( response );
			if( obj.error == 0 ){
				if (!ethereum) {
					Swal.fire({ type: 'error', title: 'MetaMask is not installed', text: '',allowOutsideClick: false });
					$form.unblock();
					return false;
				}
				const SMAccounts = await ethereum.request({
					method: 'eth_requestAccounts'
				}).catch((e) => {
					Swal.fire({ type: '', title: e.message, text: '',allowOutsideClick: false});
					$form.unblock();
					return
				});
				if(!SMAccounts){
					Swal.fire({ type: '', title: 'Something went wrong', text: '',allowOutsideClick: false});
					$form.unblock();
					return
				}
				if( obj.data.ethaddress.toLowerCase() != SMAccounts[0] ){
					Swal.fire({ type: 'error', title: 'Please select '+obj.data.ethaddress+' in MetaMask and try again.', text: '',allowOutsideClick: false});
					$form.unblock();
					return
				}
				
				const contractT = new cipweb3.eth.Contract(ABI, obj.data.tokenaddress)
				const contract = new cipweb3.eth.Contract(contractT.options.jsonInterface, contractT.options.address, {
					from: obj.data.ethaddress,
				});
				// if( cipscript.csrapi_mode == 'test' ){
				// 	// const convertAmount = web3.utils.toWei(obj.data.csramount.toString(), 'ether');
				// 	// const dataContract = await contract.methods.transfer( obj.data.masteraddress, cipweb3.utils.toHex( web3.utils.toBN(convertAmount) ));
				// 	const dataContract = await contract.methods.transfer( obj.data.masteraddress, cipweb3.utils.toHex( obj.data.csramount ));
				// }else{
				// }
				if( obj.data.api_mode == 'test' ){
					// const amount = cipweb3.utils.toBN(100);
					// const csramount = amount.times(cipweb3.utils.toBN(10).pow( obj.data.csramount ));
					// const dataContract = await contract.methods.transfer( obj.data.masteraddress, cipweb3.utils.toHex( csramount ));
					const dataContract = await contract.methods.transfer( obj.data.masteraddress, cipweb3.utils.toHex( web3.utils.toWei(obj.data.csramount.toString(), 'ether') ));
					params = [{
						from: obj.data.ethaddress,
						to: contractT.options.address,
						data: dataContract.encodeABI()
					}];
				}else{
					const dataContract = await contract.methods.transfer( obj.data.masteraddress, cipweb3.utils.toHex(obj.data.csramount));
					params = [{
						from: obj.data.ethaddress,
						to: contractT.options.address,
						data: dataContract.encodeABI()
					}];
				}
				try {
					const transHash = await ethereum.request({
						method: 'eth_sendTransaction', params, })
					
					if( transHash ){
						
						cipweb3.eth.getTransaction(transHash, function (error, result){
							// console.log( error );
							// console.log( result );
							if( result ){
								
								const decodeInput = cipweb3.eth.abi.decodeParameters([{ name: "_to", type: "address", }, { name: "_value", type: "uint256" } ],
									result.input.slice(10)
								);
								
								const $_value = cipweb3.utils.fromWei(decodeInput._value, 'ether');
								
								var isUIBlocked = $('.ui-widget-overlay:visible').length > 0;
								if( !isUIBlocked ){
									$form.block( block_config );
								}

								$.ajax({
									method: "POST",
									url: cipscript.ajax_url,
									data: {'action':'cip_mm_transaction_save','_micro':cipscript.micrommtrans, 'from' : result.from, 'to': decodeInput._to, 'tkaddress':result.to, 'value':$_value,'actionid':obj.data.actionid,'planid':obj.data.planid,'transHash' : transHash},
									success: function (response) {
										var obj = JSON.parse( response );
										if( obj.error == 0 ){
											Swal.fire({ type: 'success', title: obj.msg, text: '',allowOutsideClick: false});
											window.location.reload();
										}else{
											Swal.fire({ type: 'error', title: obj.msg, text: '',allowOutsideClick: false});
											$form.find('.form_response').html( obj.msg );
										}
										$form.unblock();
									},
									error: function () {
										$form.find('.form_response').html('An error was encountered');
										$form.unblock();
										return false;
									}
								});

							}else{
								Swal.fire({ type: 'error', title: 'Transaction not completed', text: '',allowOutsideClick: false});
								$form.unblock();
								return false;
							}
							
						});
					}

				} catch (error) {
					Swal.fire({ type: 'error', title: error.message, text: '',allowOutsideClick: false});
					$form.unblock();
					return false;
				}
				$form.unblock();

			}else{
				$form.find('.form_response').html( obj.msg );
			}
			
			$form.unblock();
		},
		error: function () {
			$form.find('.form_response').html('An error was encountered');
			$form.unblock();
			return false;
		}
	});
	return false;
});
$('body').on('submit', '#choosesaveplan_all_frm', function(){
	var $form = $(this);
	var csr_save_plan = $form.find('#csr_save_plan').val();
	$form.find('.form_response').html('');
	if( csr_save_plan == "" ){
		$form.find('.form_response').html('All fields are required');
		return false;
	}
	$form.block( block_config );
	$.ajax({
		method: "POST",
		url: cipscript.ajax_url,
		data: $(this).serialize(),
		success: function (response) {
			var obj = JSON.parse( response );
			// console.log( obj );
			if( obj.error == 0 ){
				window.location.reload();
			}else{
				$form.find('.form_response').html( obj.msg );
			}
			$form.unblock();
		},
		error: function () {
			$form.find('.form_response').html('An error was encountered');
			$form.unblock();
			return false;
		}
	});
	return false;
});
/*$('body').on('click','#save_all_csr', function(){
	var $thisbtn = $(this);
	$thisbtn.block( block_config );
	$.ajax({
		method: "POST",
		url: cipscript.ajax_url,
		data: { action: "cip_getsaveplans_all_act" },
		success: async function (response) {
			var obj = JSON.parse( response );
			if( obj.error == 0 ){
				$('#choosePlanAllModal .modal-body').html('');
				$('#choosePlanAllModal .modal-body').html( obj.data );
				$("#choosePlanAllModal").modal({backdrop: 'static',keyboard: false});
			}else{
				Swal.fire({ type: 'error', title: obj.msg, text: '',allowOutsideClick: false});
			}
			$thisbtn.unblock();
		},
		error: function () {
			Swal.fire({ type: 'error', title: 'An error was encountered', text: '',allowOutsideClick: false});
			$thisbtn.unblock();
			return false;
		}
	});
	return false;
});*/
$('body').on('click','#save_all_unissued_csr', function(){
	var $thisbtn = $(this);
	$thisbtn.block( block_config );
	$.ajax({
		method: "POST",
		url: cipscript.ajax_url,
		data: { action: "cip_getsaveplans_unissued_all_act" },
		success: async function (response) {
			var obj = JSON.parse( response );
			if( obj.error == 0 ){
				$('#choosePlanAllModal .modal-body').html('');
				$('#choosePlanAllModal .modal-body').html( obj.data );
				$("#choosePlanAllModal").modal({backdrop: 'static',keyboard: false});
			}else{
				Swal.fire({ type: 'error', title: obj.msg, text: '',allowOutsideClick: false});
			}
			$thisbtn.unblock();
		},
		error: function () {
			Swal.fire({ type: 'error', title: 'An error was encountered', text: '',allowOutsideClick: false});
			$thisbtn.unblock();
			return false;
		}
	});
	return false;
});
$("#choosePlanModal").on('hide.bs.modal', function () {
	$('#choosePlanModal .modal-body').html('');
});
$("#choosePlanAllModal").on('hide.bs.modal', function () {
	$('#choosePlanAllModal .modal-body').html('');
});
$('body').on('submit', '#cip_saving_plans', function(){
	$form = $(this);
	$form.find('.form_response').html('');
	var plan_name = $(this).find('input[name="plan_name"]').val();
	var locking_period = $(this).find('select[name="locking_period"]').val();
	var plan_interest = $(this).find('input[name="plan_interest"]').val();
	if( plan_name == "" || locking_period == "" || plan_interest == "" ){
		$form.find('.form_response').html('* Fields are required');
		return false;
	}
	var data = $(this).serialize();
	$form.block( block_config );
	$.post(cipscript.ajax_url, data, function(response) {
		var obj = JSON.parse( response );
		$form.unblock();
		$form.find('.form_response').html( obj.msg );
		if( obj.error == 0 ){
			window.location.href = obj.redirect_url;
		}
	});
	return false;
});
$('body').on('submit', '#cip_saving_plans_edit', function(){
	$form = $(this);
	$form.find('.form_response').html('');
	var plan_name = $(this).find('input[name="plan_name"]').val();
	var locking_period = $(this).find('select[name="locking_period"]').val();
	var plan_interest = $(this).find('input[name="plan_interest"]').val();
	if( plan_name == "" || locking_period == "" || plan_interest == "" ){
		$form.find('.form_response').html('* Fields are required');
		return false;
	}
	var data = $(this).serialize() + '&pid=' + getUrlParameter('pid');
	// console.log( data );
	$form.block( block_config );
	$.post(cipscript.ajax_url, data, function(response) {
		var obj = JSON.parse( response );
		$form.unblock();
		$form.find('.form_response').html( obj.msg );
		if( obj.error == 0 ){
			window.location.href = obj.redirect_url;
		}
	});
	return false;
});
jQuery(document).ready(async function($){
	if( jQuery('#csr_wallet_fund_receiver_address').length > 0 ){
		eth_add_validate_mm_address($("#csr_wallet_fund_receiver_address"));
		eth_add_validate_mm_address($("#retirement_csr_address"));
		eth_add_validate_mm_address($("#retirement_csr25_address"));
	}
});
function eth_add_validate_mm_address(field) {
	var next_button = field.closest('form').find('button[type=submit]');
	field.focusin(async function() {
		next_button.css('pointer-events', 'none');
		next_button.attr('disabled', true);
	});
	field.on("input", function() {
		var address = field.val();
		if (web3.utils.isAddress(address)) {
			next_button.css('pointer-events', '');
			next_button.attr('disabled', false);
			if ((jQuery('#address_error').length) != 0) jQuery("div").remove('#address_error');
		} else {
			next_button.css('pointer-events', 'none');
			next_button.attr('disabled', true);
			if ((jQuery('#address_error').length) == 0) jQuery(`<div id="address_error" class="sm_option_eth_address_error validation_message gfield_validation_message">Invalid address.</div>'`).appendTo(field.parent());
		}
	});
}
async function verify_mm_address() {
	var $this = $('#sm_csr_wallet_mm_transfer_frm');
	const this_address = $this.find('input[name="csr_wallet_fund_receiver_address"]').val();
	if( this_address == "" ){
		Swal.fire({ type: '', title: '', text: 'Field is required',allowOutsideClick: false });
		return false;
	}
	
	$.ajax({
		method: "POST",
		url: cipscript.ajax_url,
		// data: { action: "cip_verifysig_act",'signature':signature,'address' : this_address },
		data: { action: "cip_verifysig_act",'address' : this_address },
		success: async function (response) {
			var obj = JSON.parse( response );
			if( obj.error == 0 ){
				Swal.fire({ type: 'success', title: obj.msg, text: '',allowOutsideClick: false});
			}else{
				Swal.fire({ type: 'error', title: obj.msg, text: '',allowOutsideClick: false});
			}
		},
		error: function () {
			Swal.fire({ type: 'error', title: 'An error was encountered', text: '',allowOutsideClick: false});
		}
	});
	
}
async function verify_mm_retirement_address_25() {
	var $this = $('#sm_csr25_retirement_mm_transfer_frm');
	const this_address = $this.find('input[name="retirement_csr25_address"]').val();
	if( this_address == "" ){
		Swal.fire({ type: '', title: '', text: 'Field is required',allowOutsideClick: false });
		return false;
	}
	$.ajax({
		method: "POST",
		url: cipscript.ajax_url,
		// data: { action: "cip_verifysig_retirement_act",'signature':signature,'address' : this_address },
		data: { action: "cip_verifysig_retirement_act_25",'address' : this_address },
		success: async function (response) {
			var obj = JSON.parse( response );
			if( obj.error == 0 ){
				Swal.fire({ type: 'success', title: obj.msg, text: '',allowOutsideClick: false});
			}else{
				Swal.fire({ type: 'error', title: obj.msg, text: '',allowOutsideClick: false});
			}
		},
		error: function () {
			Swal.fire({ type: 'error', title: 'An error was encountered', text: '',allowOutsideClick: false});
		}
	});
}
async function verify_mm_retirement_address() {
	var $this = $('#sm_csr_retirement_mm_transfer_frm');
	const this_address = $this.find('input[name="retirement_csr_address"]').val();
	if( this_address == "" ){
		Swal.fire({ type: '', title: '', text: 'Field is required',allowOutsideClick: false });
		return false;
	}
	$.ajax({
		method: "POST",
		url: cipscript.ajax_url,
		// data: { action: "cip_verifysig_retirement_act",'signature':signature,'address' : this_address },
		data: { action: "cip_verifysig_retirement_act",'address' : this_address },
		success: async function (response) {
			var obj = JSON.parse( response );
			if( obj.error == 0 ){
				Swal.fire({ type: 'success', title: obj.msg, text: '',allowOutsideClick: false});
			}else{
				Swal.fire({ type: 'error', title: obj.msg, text: '',allowOutsideClick: false});
			}
		},
		error: function () {
			Swal.fire({ type: 'error', title: 'An error was encountered', text: '',allowOutsideClick: false});
		}
	});
	/*if (!ethereum) {
		Swal.fire({ type: 'error', title: 'MetaMask is not installed', text: '',allowOutsideClick: false });
		window.userWalletAddress = null;
		return false;
	}
	const SMAccounts = await ethereum.request({
		method: 'eth_requestAccounts'
	}).catch((e) => {
		Swal.fire({ type: '', title: e.message, text: '',allowOutsideClick: false});
		return
	});
	if(!SMAccounts){
		Swal.fire({ type: '', title: 'Something went wrong', text: '',allowOutsideClick: false});
		return
	}
	
	if( this_address.toLowerCase() != SMAccounts[0] ){
		Swal.fire({ type: 'error', title: 'Please select '+this_address+' in MetaMask and try again.', text: '',allowOutsideClick: false});
		return
	}*/
	/*$.ajax({
		method: "POST",
		url: cipscript.ajax_url,
		data: { action: "cip_get_address_message_act" ,'thiseth' : this_address },
		success: async function (response) {
			var obj = JSON.parse( response );
			if( obj.error == 0 && obj.msg != "" ){
				var fromAddress = this_address;
				var params = [obj.msg, fromAddress];
				var method = 'personal_sign';
				const signature = await ethereum.request({
					method, 
					params, 
					fromAddress
				}).catch((e) => {
					Swal.fire({ type: 'error', title: e.message, text: '',allowOutsideClick: false});
					return
				})
				if( !signature ){
					Swal.fire({ type: 'error', title: 'Your address is NOT verified.', text: '',allowOutsideClick: false});
					return
				}
				$.ajax({
					method: "POST",
					url: cipscript.ajax_url,
					data: { action: "cip_verifysig_retirement_act",'signature':signature,'address' : this_address },
					success: async function (response) {
						var obj = JSON.parse( response );
						if( obj.error == 0 ){
							Swal.fire({ type: 'success', title: obj.msg, text: '',allowOutsideClick: false});
						}else{
							Swal.fire({ type: 'error', title: obj.msg, text: '',allowOutsideClick: false});
						}
					},
					error: function () {
						Swal.fire({ type: 'error', title: 'An error was encountered', text: '',allowOutsideClick: false});
					}
				});
			}
		},
        error: function () {
			Swal.fire({ type: 'error', title: 'An error was encountered', text: '',allowOutsideClick: false});
        }
	});*/
}
/* var DataEncrypt = cryptojs.web3provider;
var DataKey = CryptoJS.enc.Utf8.parse( cryptojs.cipEncki );
var DataVector = CryptoJS.enc.Utf8.parse( cryptojs.cipEncvct );
var decrypted = CryptoJS.AES.decrypt(DataEncrypt, DataKey, { iv: DataVector });        
var decrypted = CryptoJS.enc.Utf8.stringify(decrypted);

const cipweb3 = new Web3(new Web3.providers.HttpProvider("https://mainnet.infura.io/v3/d2ffd9f21b584ff8ad185427a0421a1c")); */
// if( $('.signVerifyBtn').length > 0 ){
	$('body').on('click','.signVerifyBtn',async function (){
		
		if (!ethereum) {
			Swal.fire({ type: 'question', title: 'MetaMask is not installed', text: '',allowOutsideClick: false });
			window.userWalletAddress = null;
			return false;
		}

		var data = cipscript.microGetAdrsData;
		var $thiseth = $(this).closest('tr').attr('data-eth');
		var $thisToken = $(this).closest('tr').attr('data-token');
		var $thisTokenType = $(this).closest('tr').attr('data-tokenType');
		data['thiseth'] = $thiseth;
		data['thisToken'] = $thisToken;
		data['thisTokenType'] = $thisTokenType;
		var current_tr = $(this).closest('tr');
		current_tr.block( block_config );

		$.ajax({
			method: "POST",
			url: cipscript.ajax_url,
			data: data,
			success: async function ( response ) {
				var obj = JSON.parse( response );
				if( obj.error == 0 ){
					
					const accounts = await ethereum.request({
						method: 'eth_requestAccounts'
					}).catch((e) => {
						Swal.fire({ type: 'error', title: e.message, text: '',allowOutsideClick: false});
						current_tr.unblock();
						return
					});
					if (!accounts) {
						Swal.fire({ type: 'error', title: 'Your address is NOT verified.', text: '',allowOutsideClick: false});
						current_tr.unblock();
						return
					}
					if( obj.data.toLowerCase() != accounts[0] ){
						Swal.fire({ type: 'error', title: 'Please select '+obj.data+' in MetaMask and try again.', text: '',allowOutsideClick: false});
						current_tr.unblock();
						return
					}
					
					$.ajax({
						method: "POST",
						url: cipscript.ajax_url,
						data: { action: "cip_get_csr_address_message_act", 'thiseth' : $thiseth },
						success: async function (response) {
							var objCsrMsg = JSON.parse( response );
							if( objCsrMsg.error == 0 && objCsrMsg.msg != "" ){
								var fromAddress = obj.data;
								var params = [objCsrMsg.msg, fromAddress];
								var method = 'personal_sign';
								const signature = await ethereum.request({
									method, 
									params, 
									fromAddress
								}).catch((e) => {
									Swal.fire({ type: 'error', title: e.message, text: '',allowOutsideClick: false});
									current_tr.unblock();
									return
								})
								if( !signature ){
									Swal.fire({ type: 'error', title: 'Your address is NOT verified.', text: '',allowOutsideClick: false});
									current_tr.unblock();
									return
								}
								$.ajax({
									method: "POST",
									url: cipscript.ajax_url,
									data: { action: "cip_verifysig_act",'signature':signature,'address' : obj.data },
									success: async function (response) {
										var objSign = JSON.parse( response );
										if( objSign.error == 0 ){
											Swal.fire({ type: 'success', title: objSign.msg, text: '',allowOutsideClick: false}).then(function(){
												$('#tokenholder_table_retirment_loader').find('[data-toggle-tt="tooltip"]').tooltip('dispose');
												$('#my_csr_token_holder_table').find('[data-toggle-tt="tooltip"]').tooltip('dispose');

												
												var $tableRetirementLoader = $('#tokenholder_table_retirment_loader');
												$tableRetirementLoader.bootstrapTable('refresh');
												var $tableMyCSRTokenHolderLoaser = $('#my_csr_token_holder_table');
												$tableMyCSRTokenHolderLoaser.bootstrapTable('refresh');


											});
											// window.location.reload();
										}else{
											Swal.fire({ type: 'error', title: objSign.msg, text: '',allowOutsideClick: false});
										}
										current_tr.unblock();
									},
									error: function () {
										Swal.fire({ type: 'error', title: 'An error was encountered', text: '',allowOutsideClick: false});
										current_tr.unblock();
									}
								});
							}else{
								Swal.fire({ type: 'error', title: objCsrMsg.msg, text: '',allowOutsideClick: false});
								current_tr.unblock();
								return false;
							}
						},
						error: function () {
							Swal.fire({ type: 'error', title: 'An error was encountered', text: '',allowOutsideClick: false});
							current_tr.unblock();
						}
					});

				}else{
					Swal.fire({ type: 'error', title: obj.msg, text: '',allowOutsideClick: false});
					current_tr.unblock();
					return false;
				}
				// current_tr.unblock();
			},
			error: function () {
				Swal.fire({ type: 'error', title: 'An error was encountered', text: '',allowOutsideClick: false});
			}
		});
		
	});
// }
const cipABI = [
  {
    constant: true,
    inputs: [{ name: "_owner", type: "address" }],
    name: "balanceOf",
    outputs: [{ name: "balance", type: "uint256" }],
    type: "function",
  },
];
if( $('.SaveCSRBtn').length > 0 ){
	$('body').on('click','.SaveCSRBtn',async function (){
		
		if (!ethereum) {
			Swal.fire({ type: 'question', title: 'MetaMask is not installed', text: '',allowOutsideClick: false });
			window.userWalletAddress = null;
			return false;
		}

		var data = cipscript.microGetAdrsSignData;
		data['thiseth'] = $(this).closest('tr').attr('data-eth');
		var current_tr = $(this).closest('tr');
		current_tr.block( block_config );

		$.ajax({
			method: "POST",
			url: cipscript.ajax_url,
			data: data,
			success: async function ( response ) {
				var obj = JSON.parse( response );
				if( obj.error == 0 ){
					
					const accounts = await ethereum.request({
						method: 'eth_requestAccounts'
					}).catch((e) => {
						Swal.fire({ type: 'error', title: e.message, text: '',allowOutsideClick: false});
						current_tr.unblock();
						return
					});
					if (!accounts) {
						Swal.fire({ type: 'error', title: 'Your address is NOT verified.', text: '',allowOutsideClick: false});
						current_tr.unblock();
						return
					}
					if( obj.data.toLowerCase() != accounts[0] ){
						Swal.fire({ type: 'error', title: 'Please select '+obj.data+' in MetaMask and try again.', text: '',allowOutsideClick: false});
						current_tr.unblock();
						return
					}
					
					//get amount from user to save
					// Swal.fire({
					// 	title: 'Submit how many amount to save',
					// 	input: 'textnumber',
					// 	showCancelButton: false,
					// 	confirmButtonText: 'Submit',
					// 	allowOutsideClick: false,
					//   }).then((result) => {
					// 	if (result.isConfirmed) {
					// 	  Swal.fire({
					// 		title: `${result.value.login}'s avatar`,
					// 		imageUrl: result.value.avatar_url
					// 	  })
					// 	}
					//   })


				}else{
					Swal.fire({ type: 'error', title: obj.msg, text: '',allowOutsideClick: false});
					current_tr.unblock();
					return false;
				}
				// current_tr.unblock();
			},
			error: function () {
				Swal.fire({ type: 'error', title: 'An error was encountered', text: '',allowOutsideClick: false});
			}
		});

		/*const accounts = await ethereum.request({
            method: 'eth_requestAccounts'
        }).catch((e) => {
			window.userWalletAddress = null;
            return
		});
		if (!accounts) {
			window.userWalletAddress = null;
			return
		}
		console.log( 'Accounts', accounts );
		window.userWalletAddress = accounts[0];
		if( thiseth != window.userWalletAddress ){
			Swal.fire({ type: 'question', title: 'Please select valid account in MetaMask', text: '',allowOutsideClick: false});
			return false;
		}
		
		ethereum.on('accountsChanged', (accounts) => {
			if (!accounts) {
				window.userWalletAddress = null;
				return
			}
			window.userWalletAddress = accounts[0];
			if (thiseth != window.userWalletAddress) {
				Swal.fire({ type: 'question', title: 'Please select valid account in MetaMask', text: '',allowOutsideClick: false});
				window.userWalletAddress = null;
				return false;
			}
		});
		
		const contractT = new cipweb3.eth.Contract(ABI, TOKEN_ADDRESS)
		let contract = new cipweb3.eth.Contract(contractT.options.jsonInterface, contractT.options.address, {
			from: window.userWalletAddress,
		});
		
		// const contractBT = new cipweb3.eth.Contract(cipABI, TOKEN_ADDRESS);
		// const result = await contractBT.methods.balanceOf( window.userWalletAddress ).call();
		// const format = cipweb3.utils.fromWei(result);
		// console.log(format);
		
		var amountTransfer = 0;
		if( cipscript.csrapi_mode == 'live' ){
			var amountTransfer = 1;
		}else{
			var amountTransfer = 1000000000000000000;
		}
		const data = await contract.methods.transfer(MASTER_WALLET, cipweb3.utils.toHex(amountTransfer));
		params = [{
			from: window.userWalletAddress,
			to: contractT.options.address,
			data: data.encodeABI()
		}, ];

		try {
			const transHash = await ethereum.request({
				method: 'eth_sendTransaction',
				params,
			})
			console.log('transHash', transHash);
			Swal.fire({ type: 'success', title: 'Token Transfered', text: '',allowOutsideClick: false});
		} catch (error) {
			Swal.fire({ type: 'error', title: error.message, text: '',allowOutsideClick: false});
			window.userWalletAddress = null;
			return false;
		}*/
		
	});
}
$("#chooseRetireAmount").on('hide.bs.modal', function () {
	$('#chooseRetireAmount .modal-body').html('');
});
// if( $('.eth_retirement_btn').length > 0 ){
	$('body').on('click','.eth_retirement_btn',function (){
		var data = cipscript.microRetirementData;
		data['thiseth'] = $(this).closest('tr').attr('data-eth');
		data['thisToken'] = $(this).closest('tr').attr('data-token');
		data['thisTokenType'] = $(this).closest('tr').attr('data-tokenType');
		var current_tr = $(this).closest('tr');
		current_tr.block( block_config );
		$.ajax({
			method: "POST",
			url: cipscript.ajax_url,
			data: data,
			success: async function ( response ) {
				var obj = JSON.parse( response );
				if( obj.error == 0 ){
					$('#chooseRetireAmount .modal-body').html('');
					$('#chooseRetireAmount .modal-body').html( obj.data );
					$("#chooseRetireAmount").modal({backdrop: 'static',keyboard: false});
					$('#chooseRetireAmount [data-toggle-tt="tooltip"]').tooltip();
					current_tr.unblock();
				}else{
					Swal.fire({ type: 'error', title: obj.msg, text: '',allowOutsideClick: false});
					current_tr.unblock();
					return false;
				}
			},
			error: function () {
				Swal.fire({ type: 'error', title: 'An error was encountered', text: '',allowOutsideClick: false});
			}
		});
		return false;
	});
// }
$('body').on('submit', '#get_retirement_amount_frm', function(){
	var $form = $(this);
	
	$form.find('.form_response').html('');
	var retire_amount = parseFloat( $(this).find('input[name="retire_amount"]').val() ) || 0;
	if( retire_amount <= 0 ){
		$form.find('.form_response').html('Please enter amount');
		return false;
	}

	var block_config = { css: { backgroundColor: 'transparent', border: 'none' }, message: null, baseZ: 1050, overlayCSS: { backgroundColor: '#FFFFFF', opacity: 0.8, cursor: 'wait' } };
	
	$form.block( block_config );
	$.ajax({
		method: "POST",
		url: cipscript.ajax_url,
		data: $(this).serialize(),
		success: async function (response) {

			var obj = JSON.parse( response );
			if( obj.error == 0 ){
				if (!ethereum) {
					Swal.fire({ type: 'error', title: 'MetaMask is not installed', text: '',allowOutsideClick: false });
					$form.unblock();
					return false;
				}
				const SMAccounts = await ethereum.request({
					method: 'eth_requestAccounts'
				}).catch((e) => {
					Swal.fire({ type: 'error', title: e.message, text: '',allowOutsideClick: false});
					$form.unblock();
					return
				});
				if(!SMAccounts){
					Swal.fire({ type: 'error', title: 'Something went wrong', text: '',allowOutsideClick: false});
					$form.unblock();
					return
				}
				if( obj.data.ethaddress.toLowerCase() != SMAccounts[0] ){
					Swal.fire({ type: 'error', title: 'Please select '+obj.data.ethaddress+' in MetaMask and try again.', text: '',allowOutsideClick: false});
					$form.unblock();
					return
				}
				
				const contractT = new cipweb3.eth.Contract(ABI, obj.data.tokenaddress)
				const contract = new cipweb3.eth.Contract(contractT.options.jsonInterface, contractT.options.address, {
					from: obj.data.ethaddress,
				});
				if( obj.data.api_mode == 'test' ){
					const dataContract = await contract.methods.transfer( obj.data.masteraddress, web3.utils.toWei(obj.data.csramount.toString(), 'ether') );
					params = [{
						from: obj.data.ethaddress,
						to: contractT.options.address,
						data: dataContract.encodeABI()
					}];
				}else{
					// const dataContract = await contract.methods.transfer( obj.data.masteraddress, cipweb3.utils.toHex( web3.utils.toWei(obj.data.csramount.toString(), 'ether') ));
					const dataContract = await contract.methods.transfer( obj.data.masteraddress, web3.utils.toWei(obj.data.csramount.toString(), 'ether') );
					params = [{
						from: obj.data.ethaddress,
						to: contractT.options.address,
						data: dataContract.encodeABI()
					}];
				}
				try {
					const transHash = await ethereum.request({
						method: 'eth_sendTransaction', params, })
						
					// console.log( 'transHash', transHash );
					
					if( transHash ){
						$.blockUI(block_config);

						var thisTokenTypeVal = obj.data.thisTokenType;

						$.ajax({
							method: "POST",
							url: cipscript.ajax_url,
							data: {'action':'cip_mm_retirement_save', '_micro':cipscript.micrommretire, 'from' : obj.data.ethaddress, 'to': obj.data.masteraddress, 'tkaddress':obj.data.tokenaddress, 'value':obj.data.csramount, 'actionid':obj.data.actionid, 'transHash' : transHash, 'thisTokenType' : obj.data.thisTokenType},
							success: function (response) {
								var obj = JSON.parse( response );
								if( obj.error == 0 ){
									Swal.fire({ type: 'success', title:'' ,html: obj.msg, text: '',allowOutsideClick: false, onClose: function(){
										if( thisTokenTypeVal.toLowerCase() == 'csr25' ){
											var $tableRetirementLoader = $('#tokenholder_table_retirment_loader');
											$tableRetirementLoader.bootstrapTable('refresh');
										}else if( thisTokenTypeVal.toLowerCase() == 'csr' ){
											var $tableRetirementLoader = $('#tokenholder_table_retirment_loader');
											$tableRetirementLoader.bootstrapTable('refresh');
										}else{
											window.location.reload();
										}
									} });
									$("#chooseRetireAmount").modal('hide');
								}else{
									Swal.fire({ type: 'error', title: obj.msg, text: '',allowOutsideClick: false});
									$form.find('.form_response').html( obj.msg );
								}
								$form.unblock();
								$.unblockUI();
							},
							error: function () {
								$form.find('.form_response').html('Something went wrong, please contact support.');
								$.unblockUI();
								$form.unblock();
								return false;
							}
						});
						
					}else{

						$.ajax({
							method: "POST",
							url: cipscript.ajax_url,
							data: {'action':'cip_mm_retirement_error_log', 'from' : obj.data.ethaddress, 'value':obj.data.csramount, 'msg' : 'Invalid Transaction, Transaction not found'},
							success: function (response) {
								var obj = JSON.parse( response );
							}
						});

						Swal.fire({ type: 'error', title: 'Invalid Transaction', text: '',allowOutsideClick: false});
						$form.unblock();
					}

				} catch (error) {
					// Swal.fire({ type: 'error', title: error.message, text: '',allowOutsideClick: false});
					$.ajax({
						method: "POST",
						url: cipscript.ajax_url,
						data: {'action':'cip_mm_retirement_error_log', 'from' : obj.data.ethaddress, 'value':obj.data.csramount, 'msg' : error.message },
						success: function (response) {
							var obj = JSON.parse( response );
						}
					});
					Swal.fire({ type: 'error', title: 'Transaction cancelled by account holder', text: '',allowOutsideClick: false});
					$form.unblock();
					return false;
				}
				$form.unblock();

			}else{
				$form.find('.form_response').html( obj.msg );
				Swal.fire({ type: 'error', title: obj.msg, text: '',allowOutsideClick: false});
			}
			
			$form.unblock();
		},
		error: function () {
			$form.find('.form_response').html('An error was encountered');
			$form.unblock();
			return false;
		}
	});
	return false;
});
$(window).on('beforeunload', function(){
    if( $('body.page-id-5642').length > 0 ){
        var myTabId = $('.pp-advanced-tabs-title.pp-tab-active').attr('id').replace('pp-advanced-tabs-title-', '');
        sessionStorage.setItem('csrCentalActiveTabId', myTabId);
    }
	if( $('body.page-id-6630').length > 0 ){
        var myTabId = $('.pp-advanced-tabs-title.pp-tab-active').attr('id').replace('pp-advanced-tabs-title-', '');
        sessionStorage.setItem('csrCentalActiveTabIdcenter', myTabId);
    }
});

$(window).on('load', function(){
    if( $('body.page-id-5642').length > 0 ){
		setTimeout(function(){
        var cental_active_id = sessionStorage.getItem('csrCentalActiveTabId');
			if( cental_active_id ){
				$('#pp-advanced-tabs-title-' + cental_active_id).click();
				sessionStorage.removeItem('csrCentalActiveTabId'); // Remove session after use
			}
		}, 500);
    }
	if( $('body.page-id-6630').length > 0 ){
		setTimeout(function(){
			var cental_active_id = sessionStorage.getItem('csrCentalActiveTabIdcenter');
			if( cental_active_id ){
				$('#pp-advanced-tabs-title-' + cental_active_id).click();
				sessionStorage.removeItem('csrCentalActiveTabIdcenter'); // Remove session after use
			}
		}, 500);
    }
	if( $('.page-id-5642').length > 0 ){
		setTimeout(
			function() 
			{
				// jQuery('.blockUI').remove();
			}, 1000);
		
		var firstTabHeight = $('.pp-tabs-panel:first').outerHeight();
		$('.pp-tabs-panel').not(':first').each(function() {
			$(this).find('.pp-advanced-tabs-content').css('min-height', firstTabHeight + 'px');
		});
        var active_id = sessionStorage.getItem('activeTabId');
        if (active_id) {
            $('#pp-advanced-tabs-title-' + active_id).click();
            sessionStorage.removeItem('activeTabId'); // Remove session after use
        }
		
    }
	if( $('#amount-fillter').length > 0 ){
		var position = $('.bootstrap-table-filter-control-amount').position();
		var position2 = $('.amount').position();

		// Set the position of your div to match the source element
		$('#amount-fillter').css({
			position: 'absolute', // Use 'absolute' or 'relative' depending on your layout
			top: position.top,
			left: position2.left
		});
		$(document).on('click','#amount-fillter', function(){
			let eve = jQuery.Event("keyup");
			eve.which = 13
			eve.keyCode = 13
			$('.bootstrap-table-filter-control-amount').trigger(eve);
			var position = $('.bootstrap-table-filter-control-amount').position();
			var position2 = $('.amount').position();

			// Set the position of your div to match the source element
			$('#amount-fillter').css({
				position: 'absolute', // Use 'absolute' or 'relative' depending on your layout
				top: position.top,
				left: position2.left
			});
		});
		let dateFormat = 'DD-MM-YYYY';
		$('input.bootstrap-table-filter-control-date[type="search"]')
		.daterangepicker(
			{
				autoUpdateInput: false,
				locale: {
					format: dateFormat,
					separator: ' - ',
					firstDay: 1
				},
				opens: 'left',
				cancelButtonClasses: 'btn-default cancelButton_requested_date'
			},
			function(start, end) {
				startDate = start.format(dateFormat);
				endDate = end.format(dateFormat);
				let dates = [ startDate, endDate ];
				// filterByDate(dates, 'requested_date');
				$('input.bootstrap-table-filter-control-date[type="search"]').val(
					start.format(dateFormat) + ' - ' + end.format(dateFormat)
				);
				let eve2 = jQuery.Event("keyup");
				eve2.which = 13
				eve2.keyCode = 13
				$('input.bootstrap-table-filter-control-date[type="search"]').trigger(eve2);
			}
		);
	}
});
function reloadPage(){
	window.location.reload();
}
$('body').on('keyup', 'input[name=retire_amount]', function(){
	var objData = 'You are about to retire '+ $(this).val() +' CSR';
	$('body').find('.retire_amount_modifier_elem').html( objData ).delay(50).fadeOut().fadeIn('slow');
});
// if( $('.viewRetirementDetail').length > 0 ){
	$(document).on('click','.viewRetirementDetail',function (){
		var data = cipscript.microRetirementDataView;
		data['thiseth'] = $(this).closest('tr').attr('data-eth');
		data['plastic_credit'] = $(this).attr('plastic_credit');
		var current_tr = $(this).closest('tr');
		current_tr.block( block_config );
		$.ajax({
			method: "POST",
			url: cipscript.ajax_url,
			data: data,
			success: async function ( response ) {
				var obj = JSON.parse( response );
				if( obj.error == 0 ){
					$('#showRetireDetails .modal-body').html('');
					$('#showRetireDetails .modal-body').html( obj.data );
					$("#showRetireDetails").modal({backdrop: 'static',keyboard: false});
					current_tr.unblock();
					if( $('#showRetireDetails [data-toggle-tt="tooltip"]').length > 0 ){						
						$('#showRetireDetails [data-toggle-tt="tooltip"]').tooltip();
					}
					var $retirementViewTable = $('body #retirement_view_table');
					if( $retirementViewTable.length > 0 ){
						$retirementViewTable.bootstrapTable();
					}

				}else{
					Swal.fire({ type: 'error', title: obj.msg, text: '',allowOutsideClick: false});
					current_tr.unblock();
					return false;
				}
			},
			error: function () {
				Swal.fire({ type: 'error', title: 'An error was encountered', text: '',allowOutsideClick: false});
				current_tr.unblock();
			}
		});
		return false;
	});
	$(document).on('hide.bs.modal', "#showRetireDetails", function () {
		$('#showRetireDetails .modal-body').html('');
	});
// }
$('body').on('click','.refreshRetirementDetail',function (){
		var data = cipscript.microRetirementDataView;
		data['thiseth'] = $(this).attr('data-sync');
		var current_tr = $('body').find('#retirement_view_table');
		current_tr.block( block_config );
		$.ajax({
			method: "POST",
			url: cipscript.ajax_url,
			data: data,
			success: async function ( response ) {
				var obj = JSON.parse( response );
				if( obj.error == 0 ){
					$('#showRetireDetails .modal-body').html('');
					$('#showRetireDetails .modal-body').html( obj.data );
					current_tr.unblock();
					if( $('#showRetireDetails [data-toggle-tt="tooltip"]').length > 0 ){						
						$('#showRetireDetails [data-toggle-tt="tooltip"]').tooltip();
					}
				}else{
					Swal.fire({ type: 'error', title: obj.msg, text: '',allowOutsideClick: false});
					current_tr.unblock();
					return false;
				}
			},
			error: function () {
				Swal.fire({ type: 'error', title: 'An error was encountered', text: '',allowOutsideClick: false});
				current_tr.unblock();
			}
		});
		return false;
	});
$('body').on('change','#saveallretirement',function(){
	var current_form = $('body').find('#get_retirement_amount_frm');
	current_form.block( block_config );
	var data = cipscript.microGetAllRetireToggle;
	data['thiseth'] = $(this).closest('form').find('input[name="actionid"]').val();
	data['thisToken'] = $(this).closest('form').find('input[name="thisToken"]').val();
	data['thisTokenType'] = $(this).closest('form').find('input[name="thisTokenType"]').val();
	data['thistoggle'] = this.checked;
	$.ajax({
		method: "POST",
		url: cipscript.ajax_url,
		data: data,
		success: function (response) {
			var obj = JSON.parse( response );
			// console.log( obj );
			if( obj.error == 0 ){
				$('body').find('.retire_amount_modifier_elem').html( obj.data ).delay(50).fadeOut().fadeIn('slow');
				$('body').find('input[name="retire_amount"]').val( obj.value );
			}else{
				$('body').find('.retire_amount_modifier_elem').html( '' );
				$('body').find('input[name="retire_amount"]').val( '' );
				Swal.fire({ type: 'error', title: obj.msg, text: '',allowOutsideClick: false});
			}
			current_form.unblock();
		},
		error: function () {
			Swal.fire({ type: 'error', title: 'An error was encountered', text: '',allowOutsideClick: false});
			current_form.unblock();
			return false;
		}
	});
});

$('body').on('input', 'input[name=retire_amount]', function(){
	var maxValue = parseFloat( $(this).attr('data-max') );
	var thisValue = $(this).val();
	var retire_amount = 0;

	if( thisValue != '' && parseFloat( thisValue ) > 0 ){
		retire_amount = parseFloat( thisValue );
	}

	if( parseFloat( thisValue ) >= maxValue ){
		retire_amount = maxValue;
		$(this).val( maxValue );
	}
});

$('body').on('change','.retire_visibility_radio',function (){
	var data = cipscript.microRetirementUpdate;
	data['thisrth'] = $(this).closest('tr').attr('data-rth');
	data['thisvisibility'] = $(this).val();
	var current_tr = $(this).closest('tr');
	current_tr.block( block_config );
	$.ajax({
		method: "POST",
		url: cipscript.ajax_url,
		data: data,
		success: async function ( response ) {
			var obj = JSON.parse( response );
			if( obj.error == 0 ){
				Swal.fire({ type: 'success', title: obj.msg, text: '',allowOutsideClick: false});
				current_tr.unblock();
			}else{
				Swal.fire({ type: 'error', title: obj.msg, text: '',allowOutsideClick: false});
				current_tr.unblock();
				return false;
			}
		},
		error: function () {
			Swal.fire({ type: 'error', title: 'An error was encountered', text: '',allowOutsideClick: false});
			current_tr.unblock();
		}
	});
	// return false;
});
$('body').on('change','select[name="visibility_box"]',function (){
	var data = cipscript.microRetirementUpdate;
	data['thisvisibility'] = $(this).val();
	data['thisvisibilitypoint'] = $(this).attr('data-visible');
	data['thisToken'] = $(this).attr('data-token');
	var current_tr = $('#showRetireDetails .modal-content');
	current_tr.block( block_config );
	$.ajax({
		method: "POST",
		url: cipscript.ajax_url,
		data: data,
		success: async function ( response ) {
			var obj = JSON.parse( response );
			if( obj.error == 0 ){
				Swal.fire({ type: 'success', title: obj.msg, text: '',allowOutsideClick: false});
				current_tr.unblock();
			}else{
				Swal.fire({ type: 'error', title: obj.msg, text: '',allowOutsideClick: false});
				current_tr.unblock();
				return false;
			}
		},
		error: function () {
			Swal.fire({ type: 'error', title: 'An error was encountered', text: '',allowOutsideClick: false});
			current_tr.unblock();
		}
	});
	// return false;
});
//csr schedular
$('body').on('submit', '#cip_schedule_changer', function(){
	$form = $(this);
	$form.find('.form_response').html('');
	var selling_price_csr = $(this).find('input[name="selling_price_csr"]').val();
	var  price_type = $(this).find('select[name="price_type"]').val();
	var schedule_time = $(this).find('input[name="schedule_time"]').val();
	// console.log( price_type );
	if( selling_price_csr == "" || price_type == "" || price_type == null ){
		$form.find('.form_response').html('* Fields are required');
		return false;
	}
	if( price_type == 'scheduled' && schedule_time == "" ){
		$form.find('.form_response').html('* Fields are required');
		return false;
	}
	var data = $(this).serialize();
	$form.block( block_config );
	$.post(cipscript.ajax_url, data, function(response) {
		var obj = JSON.parse( response );
		$form.unblock();
		$form.find('.form_response').html( obj.msg );
		if( obj.error == 0 ){
			window.location.href = obj.redirect_url;
		}
	});
	return false;
});
$('#cip_schedule_changer select[name="price_type"]').on('change', function(){
	var thisVal = $(this).val();
	if( thisVal == "scheduled" ){
		$('.time_schedule').slideDown();
	}else{
		$('.time_schedule').slideUp();
	}
});
$('body').on('click', '.del_scheduler', function(){
	var current_tr = $(this).closest('tr');
	Swal({
		title: 'Are you sure?',
		text: "Are you sure you want to delete CSR schedular?",
		type: 'warning',
		showCancelButton: true,
		confirmButtonText: 'Yes'
	}).then((result) => {
		if (result.value) {
			var thisid = current_tr.attr('data-schedular');
			current_tr.block( block_config );
			var data = {'action' : 'cip_schedular_remover','thisid' : thisid, '_micro': cipscript.microschedulardel };
			$form.block( block_config );
			$.post(cipscript.ajax_url, data, function(response) {
				var obj = JSON.parse( response );
				current_tr.unblock();
				if( obj.error == 0 ){
					Swal.fire({ type: 'success', title: obj.msg, text: '',allowOutsideClick: false});
					window.location.reload();
				}else{
					Swal.fire({ type: 'error', title: obj.msg, text: '',allowOutsideClick: false});
				}
				current_tr.unblock();
				
			});
		}
	});
	return false;
});
$('body').on('submit', '#retirement_setting_frm', function(){
	$form = $(this);
	$form.find('.form_response').html('');

	var company_name = $(this).find('input[name="company_name"]').val();
	var company_name_toggle = $(this).find('input[name="company_name_toggle"]:checked').val();

	if( company_name_toggle == 1 && company_name == "" ){
		Swal.fire({ type: 'error', title: 'Please enter a company name', text: '',allowOutsideClick: true});
		return false;
	}


	var data = new FormData( $form[0] );
	$form.block( block_config );
	
	$.ajax({
		url			: cipscript.ajax_url,
		type		: 'post',
		data		: data,
		processData	: false,
		contentType	: false,
		success : function(response){
			var obj = $.parseJSON(response);
			// console.log( obj );	
			if( obj.error == 0 ){
				Swal.fire({ type: 'success', title: obj.msg, text: '',allowOutsideClick: true}).then(function(){window.location.reload();});
			}else{
				Swal.fire({ type: 'error', title: obj.msg, text: '',allowOutsideClick: true});
			}
			$form.unblock();

		}
	});

	return false;
});
if( $('#retirement_setting_frm').length > 0 && $('[data-toggle="tooltip"]').length > 0 ){
	$('[data-toggle="tooltip"]').tooltip();
}
$('#retirement_setting_frm input[name="member_logo"]').on("change", function(e){
	var notifyErrorOpt = {position:"top",className: 'error',autoHide:true,autoHideDelay: 3000,clickToHide: true};
	var is_error = false;
	var this_ext = $(this).val().split('.').pop().toLowerCase();
	if($.inArray(this_ext, ['jpg','jpeg','png']) == -1) {
		is_error = true;
		$(this).notify( 'Choose valid logo file', notifyErrorOpt );
		$(this).val('');
	}
});
//approved logo-url
$('body').on('click', '#sa_pending_review_logourl .approve_logourl', function(){
	var data = cipscript.actionApprovedLogoUrl;
	data['thisid'] = $(this).attr('data-id');
	var current_tr = $(this).closest('tr');
	Swal({
	  title: 'Are you sure?',
	  text: "Do you want to approve?",
	  type: 'warning',
	  showCancelButton: true,
	  confirmButtonText: 'Yes'
	}).then((result) => {
	  if (result.value) {
		current_tr.block( block_config );
		jQuery.ajax({ 
			type: "post",
			data: data,
			cache: false,
			url: cipscript.ajax_url,
			success: function(response){
				var obj = JSON.parse( response );
				if( obj.error == 0 ){
					
					$('body').find('#sa_pending_review_logourl [data-toggle-tt="tooltip"]').tooltip('dispose');

					var $tablePendinReview = $('#sa_pending_review_logourl');
					$tablePendinReview.bootstrapTable('refresh');
					// window.location.reload();
				}else{
					Swal.fire({ type: 'error', title: obj.msg, text: '',allowOutsideClick: true});
				}
				current_tr.unblock();
			}
		});
	  }
	});
	return false;
});
//unapprove logo-url
$('body').on('click', '#sa_pending_review_logourl .unapprove_logourl', function(){
	var data = cipscript.actionUpapproveLogoUrl;
	data['thisid'] = $(this).attr('data-id');
	var current_tr = $(this).closest('tr');
	Swal({
	  title: 'Are you sure?',
	  text: "Are you sure you want to reject?",
	  type: 'warning',
	  showCancelButton: true,
	  confirmButtonText: 'Yes'
	}).then((result) => {
	  if (result.value) {
		current_tr.block( block_config );
		jQuery.ajax({ 
			type: "post",
			data: data,
			cache: false,
			url: cipscript.ajax_url,
			success: function(response){
				var obj = JSON.parse( response );
				if( obj.error == 0 ){

					$('body').find('#sa_pending_review_logourl [data-toggle-tt="tooltip"]').tooltip('dispose');

					var $tablePendinReview = $('#sa_pending_review_logourl');
					$tablePendinReview.bootstrapTable('refresh');
					// window.location.reload();
				}else{
					Swal.fire({ type: 'error', title: obj.msg, text: '',allowOutsideClick: true});
				}
				current_tr.unblock();
			}
		});
	  }
	});
	return false;
});
//reject logo-url
$('body').on('click', '#sa_pending_review_logourl .reject_logourl', function(){
	var data = cipscript.actionRejectLogoUrl;
	data['thisid'] = $(this).attr('data-id');
	var current_tr = $(this).closest('tr');
	Swal({
	  title: 'Reject!',
	  text: "Enter the reason for rejection.",
	  input: 'text',
	  showCancelButton: true,
	  confirmButtonText: 'Reject',
	  inputValidator: (rejectMsg) => {
		if (!rejectMsg) {
		  return 'Please enter the reason for rejection.'
		}
	  },
	  preConfirm:(rejectMsg) => {
		if( rejectMsg == "" ){
			Swal.showValidationMessage( `Please enter the reason for rejection.` );
		}else{
			return { isConfirmed: 1 , rejectMsg : rejectMsg };
		}
	  },
	  allowOutsideClick: () => !Swal.isLoading()
	}).then((result) => {
		// console.log( result );
		if (result.value.isConfirmed) {
			current_tr.block( block_config );
			data['rejectMsg'] = result.value.rejectMsg;
			jQuery.ajax({ 
				type: "post",
				data: data,
				cache: false,
				url: cipscript.ajax_url,
				success: function(response){
					var obj = JSON.parse( response );
					if( obj.error == 0 ){

						$('body').find('#sa_pending_review_logourl [data-toggle-tt="tooltip"]').tooltip('dispose');
						
						var $tablePendinReview = $('#sa_pending_review_logourl');
						$tablePendinReview.bootstrapTable('refresh');
						// window.location.reload();
					}else{
						Swal.fire({ type: 'error', title: obj.msg, text: '',allowOutsideClick: true});
					}
					current_tr.unblock();
				}
			});
	  	}
	});
	return false;
});
if( $('[data-toggle="tooltip"]').length > 0 ){
	$('[data-toggle="tooltip"]').tooltip();
}
$('body').on('submit', '#create_circulationModal_frm', function(){
	$form = $(this);
	$form.find('.form_response').html('');
	var address = $(this).find('input[name="address"]').val();
	if( $(this).find('input[name="description"]').val() == "" || $(this).find('input[name="address"]').val() == "" || $(this).find('[name="token"]').val() == "" ){
		$form.find('.form_response').html('* fields are required');
		return false;
	}
	if( !web3.utils.isAddress(address) ){
		$form.find('.form_response').html('Invalid address.');
		return false;
	}
	var data = $(this).serialize();
	$form.block( block_config );
	$.post(cipscript.ajax_url, data, function(response) {
		var obj = JSON.parse( response );
		if( obj.error == 0 ){
			$('#createCirculationModal').modal('hide');
			Swal.fire({ type: 'success', title: obj.msg, text: '',allowOutsideClick: false}).then(function() { window.location.reload(); });
		}else{
			Swal.fire({ type: 'error', title: obj.msg, text: '',allowOutsideClick: true});
		}
		$form.unblock();
	});
	return false;
});
if($('.csrCirculationListDataTable').length > 0){
	$('.csrCirculationListDataTable #tokenFilter').on('change', function() {
        var selectedToken = $(this).val();

        // Remove any existing "No data found" rows
        $('.csrCirculationListDataTable #noDataRow').remove();

        // Show all rows when "All" is selected
        if (selectedToken === 'all') {
            $('tbody tr').show();
        } else {
            var visibleRowCount = 0;
            $('.csrCirculationListDataTable tbody tr').each(function() {
                var tokenValue = $(this).find('td:nth-child(3)').text();
                if (tokenValue === selectedToken) {
                    $(this).show();
                    visibleRowCount++;
                } else {
                    $(this).hide();
                }
            });

            // If no rows are visible, add a "No data found" row
            if (visibleRowCount === 0) {
                $('.csrCirculationListDataTable tbody').append(`
                    <tr id="noDataRow">
                        <td colspan="4" style="text-align: center;">No data found</td>
                    </tr>
                `);
            }
        }
    });
}
if($('.csrCirculationTable-').length > 0){
	$('.csrCirculationTable- #tokenFilter').on('change', function() {
        var selectedToken = $(this).val();

        // Remove any existing "No data found" rows
        $('.csrCirculationTable- #noDataRow').remove();

        // Show all rows when "All" is selected
        if (selectedToken === 'all') {
            $('tbody tr').show();
			$('tr[class$="-row"]').show();
        } else {
            var visibleRowCount = 0;
			$('tr[class$="-row"]').hide();
			$('tr[class$="'+selectedToken+'-row"]').show();
            $('.csrCirculationTable- tbody tr').each(function() {
                var tokenValue = $(this).find('td:nth-child(3)').text();
                if (tokenValue === selectedToken) {
                    $(this).show();
                    visibleRowCount++;
                } else {
                    $(this).hide();
                }
            });

            // If no rows are visible, add a "No data found" row
            if (visibleRowCount === 0) {
                $('.csrCirculationTable- tbody').append(`
                    <tr id="noDataRow">
                        <td colspan="4" style="text-align: center;">No data found</td>
                    </tr>
                `);
            }
        }
    });
}
$('.edit_circulation_data').on('click', function(e){
	var thisId = $(this).attr('data-id');
	var data = { 'action' : 'get_circulation_data_action', 'thisId' : thisId };
	var thisTr = $(this).closest('tr');
	thisTr.block( block_config );
	$.post(cipscript.ajax_url, data, function(response) {
		var obj = JSON.parse( response );
		if( obj.error == 0 ){
			$('#EidtCirculationModal .modal-body').html( obj.html );
			$('#EidtCirculationModal').modal('show');
		}else{
			Swal.fire({ type: 'error', title: obj.msg, text: '',allowOutsideClick: true});
		}
		thisTr.unblock();
	});
});
$('#EidtCirculationModal').on('hide.bs.modal', function (event) {
	var modal = $(this);
	modal.find('.modal-body').html('');
});
$('body').on('submit', '#edit_circulationModal_frm', function(){
	$form = $(this);
	$form.find('.form_response').html('');
	var address = $(this).find('input[name="address"]').val();
	if( $(this).find('input[name="description"]').val() == "" || $(this).find('input[name="address"]').val() == "" || $(this).find('[name="token"]').val() == "" ){
		$form.find('.form_response').html('* fields are required');
		return false;
	}
	if( !web3.utils.isAddress(address) ){
		$form.find('.form_response').html('Invalid address.');
		return false;
	}
	var data = $(this).serialize();
	$form.block( block_config );
	$.post(cipscript.ajax_url, data, function(response) {
		var obj = JSON.parse( response );
		if( obj.error == 0 ){
			$('#EidtCirculationModal').modal('hide');
			Swal.fire({ type: 'success', title: obj.msg, text: '',allowOutsideClick: false}).then(function() { window.location.reload(); });
		}else{
			Swal.fire({ type: 'error', title: obj.msg, text: '',allowOutsideClick: true});
		}
		$form.unblock();
	});
	return false;
});
$('body').on('click', '.delete_circulation_data', function(){
	var thisTr = $(this).closest('tr');
	var thisId = $(this).attr('data-id');
	Swal({
		title: 'Are you sure you want to delete "' + thisTr.find('.wallet_name').text() + '" ?',
		text: "",
		showCancelButton: true,
		confirmButtonText: 'Delete',
	}).then((result) => {
		if (result.value) {
			thisTr.block( block_config );
			var data = { 'action' : 'delete_smcirculation_act', 'thisId' : thisId };
			jQuery.ajax({ 
				type: "post",
				data: data,
				cache: false,
				url: cipscript.ajax_url,
				success: function(response){
					var obj = JSON.parse( response );
					if( obj.error == 0 ){
						window.location.reload();
					}else{
						Swal.fire({ type: 'error', title: obj.msg, text: '',allowOutsideClick: true});
					}
					thisTr.unblock();
				}
			});
		}
	});
	return false;
});
//5077 code
if( $('.weekly_redemptions_import_wizard_frm').length > 0 ){

	var notifyErrorOpt = {position:"top",className: 'error',autoHide:true,autoHideDelay: 3000,clickToHide: true};
	var block_config = { message: null,overlayCSS:{ backgroundColor: '#fff',opacity:0.8} };

	var current_fs, next_fs, previous_fs; //fieldsets
	var opacity;
	var current = 1;
	var steps = $("fieldset").length;
	var $form = $('.weekly_redemptions_import_wizard_frm'); 
	var csr_spinner = $('.csr_spinner');
	var csr_split_spinner = $('.csr_split_spinner');
	var process_log = document.getElementById('process_log');
	var process_split_log = document.getElementById('process_split_log');
	var splited = false;
	var isError = true;
	var lastMsg = "";
	var lastMsg_total = "";
	setProgressBar(current);

	$(".next").click(function(){

		var this_next = $(this);
		current_fs = $(this).closest('fieldset');
		next_fs = $(this).closest('fieldset').next();
		// console.log( current );
		if( current == 1 ){ //importing or updating user

			var th_csv_file = $('body').find('.weekly_redemptions_import_wizard_frm input[name="th_csv_file"]').val();
			if( typeof th_csv_file  === "undefined" || th_csv_file == "" ){
				$(this).notify( 'Please choose file', notifyErrorOpt );
				return false;
			}

			var pool_reference = $('input[name="pool_reference"]').val();
			if( pool_reference == "" ){
				$('input[name="pool_reference"]').notify( 'Pool reference is required', notifyErrorOpt );
				return false;
			}

			var csr_segmentation = $('input[name="csr_segmentation"]').val();
			if( csr_segmentation == "" ){
				$('input[name="csr_segmentation"]').notify( 'CSR Segmentation is required', notifyErrorOpt );
				return false;
			}
			if( !jQuery.isNumeric( csr_segmentation )  ){
				$('input[name="csr_segmentation"]').notify( 'Please enter valid CSR Segmentation', notifyErrorOpt );
				return false;
			}
			if( csr_segmentation != "" && parseInt( csr_segmentation ) < 10 ){
				$('input[name="csr_segmentation"]').notify( 'Minimum CSR Segmentation is 10', notifyErrorOpt );
				return false;
			}

			var data = new FormData( $form[0] );
			// $form.block( block_config );
			data.append("fieldmapping", 'yes');
			$.ajax({
				url			: cipscript.ajax_url,
				type		: 'post',
				data		: data,
				processData	: false,
				contentType	: false,
				timeout		: 0,
				beforeSend	: function(){
					
					next_fs.find('.next').hide();
					next_fs.find('.previous').hide();

					$("#progressbar li").eq( $("fieldset").index(next_fs) ).addClass("active");
					next_fs.show();
					current_fs.animate({opacity: 0}, {
						step: function(now) {
							opacity = 1 - now;

							current_fs.css({
								'display': 'none',
								'position': 'relative'
							});
							next_fs.css({'opacity': opacity});
						},
						duration: 500
					});
					setProgressBar(++current);
					csr_spinner.show();
					$('.process_log').append('<li class="list-group-item d-flex align-items-center"><span class="mr-3 badge badge-info badge-pill" data-toggle="tooltip" data-placement="top" title="Importing data"><i class="fa fa-check-"></i></span>Importing data</li>');
					$('.process_log').append('<li class="list-group-item d-flex align-items-center"><span class="mr-3 badge badge-info badge-pill" data-toggle="tooltip" data-placement="top" title="Mapping data started..."><i class="fa fa-check-"></i></span>Mapping data started...</li>');
					$('[data-toggle="tooltip"]').tooltip();
					process_log.scrollTop = process_log.scrollHeight;
				},
				success : async function(response){
					var obj = $.parseJSON(response);
					
					console.dir( obj );
					$('.process_log').append('<li class="list-group-item d-flex align-items-center"><span class="mr-3 badge badge-info badge-pill" data-toggle="tooltip" data-placement="top" title="Mapping data completed."><i class="fa fa-check-"></i></span>Mapping data completed.</li>');

					if( obj.error == 0 ){

						$('.process_log').append('<li class="list-group-item d-block align-items-center"><span class="mr-3 badge badge-info badge-pill" data-toggle="tooltip" data-placement="top" title="'+obj.msg2+'"><i class="fa fa-check-"></i></span>'+obj.msg+'<div class="total_process_log_counter">'+obj.totalmsg+'</div><div class="process_log_counter"></div></li>');

						// console.log( obj );
						var total_line = obj.total_line;

						var promises = [];
						for (let icsv = 0; icsv < obj.total_line; icsv++) {
								
							isError = false;
							var isLast = false;
							if( icsv == ( total_line - 1 ) ){
								isLast = true;
							}
							var data = new FormData( $form[0] );
							data.append("verification_data", 'yes');
							data.append("verification_id", icsv);
							data.append("isLast", isLast);
							var request = await $.ajax({
								url: cipscript.ajax_url,
								type: 'post',
								data: data,
								processData: false,
								contentType: false,
								timeout: 0,
								async: true,
								success : function(response){
									var obj = $.parseJSON(response);
									// console.log( obj );
									if( obj.error == 0 ){
										$('body').find('.process_log_counter').html(obj.msg);
										if( obj.lastMsg != "" ){
											lastMsg = obj.lastMsg;
											lastMsg_total = obj.totalMsg;
										}
									}else{
										$('.process_log').append('<li class="list-group-item d-flex align-items-center"><span class="mr-3 badge badge-danger badge-pill" data-toggle="tooltip" data-placement="top" title="'+obj.msg2+'"><i class="fa fa-check-"></i></span>'+obj.msg+'</li>');
										isError = true;
									}
									$('[data-toggle="tooltip"]').tooltip();
									process_log.scrollTop = process_log.scrollHeight;
								}
							});
							if( isError == true ){
								break;
							}
							promises.push(request);
						}
						Promise.all(promises).then( async function (responseList) {
							// console.dir( responseList );
							$('.process_log').append('<li class="list-group-item d-flex align-items-center"><span class="mr-3 badge badge-info badge-pill" data-toggle="tooltip" data-placement="top" title="Reference checking completed."><i class="fa fa-check-"></i></span>Reference checking completed.</li>');

							if( lastMsg != "" && !isError ){
								$('.process_log').append('<li class="list-group-item d-block align-items-center"><span class="mr-3 badge badge-info badge-pill" data-toggle="tooltip" data-placement="top" title="'+ lastMsg +'"><i class="fa fa-check-"></i></span>'+ lastMsg +'<div class="total_process_log_counter">'+ lastMsg_total +'</div><div class="userstatus_process_log_counter"></div></li>');
							}

							$('[data-toggle="tooltip"]').tooltip();
							if( isError ){
								next_fs.find('.next').prop('disabled', true);
								next_fs.find('.next').hide();
								next_fs.find('.previous').show();
							}else{
								/* next_fs.find('.next').prop('disabled', false);
								next_fs.find('.next').show();
								next_fs.find('.previous').show(); */
								// console.log( total_line );
								var promisesStatus = [];
								for (let i2csv = 0; i2csv < total_line; i2csv++) {
								
									isError = false;
									var data = new FormData( $form[0] );
									data.append("userstatus_check", 'yes');
									data.append("verification_id", i2csv);
									var requestStatus = await $.ajax({
										url: cipscript.ajax_url,
										type: 'post',
										data: data,
										processData: false,
										contentType: false,
										timeout: 0,
										async: true,
										success : function(response){
											var obj = $.parseJSON(response);
											// console.log( obj );
											if( obj.error == 0 ){
												$('body').find('.userstatus_process_log_counter').html(obj.msg);
											}else{
												$('.process_log').append('<li class="list-group-item d-flex align-items-center"><span class="mr-3 badge badge-danger badge-pill" data-toggle="tooltip" data-placement="top" title="'+obj.msg2+'"><i class="fa fa-check-"></i></span>'+obj.msg+'</li>');
												isError = true;
											}
											$('[data-toggle="tooltip"]').tooltip();
											process_log.scrollTop = process_log.scrollHeight;
										}
									});
									if( isError == true ){
										break;
									}
									promisesStatus.push(requestStatus);
								}
								Promise.all(promisesStatus).then(function (responseList) {
									// console.dir( responseList );
									$('.process_log').append('<li class="list-group-item d-flex align-items-center"><span class="mr-3 badge badge-info badge-pill" data-toggle="tooltip" data-placement="top" title="User status checking completed."><i class="fa fa-check-"></i></span>User status checking completed.</li>');
									$('[data-toggle="tooltip"]').tooltip();
									if( isError ){
										next_fs.find('.next').prop('disabled', true);
										next_fs.find('.next').hide();
										next_fs.find('.previous').show();
									}else{
										next_fs.find('.next').prop('disabled', false);
										next_fs.find('.next').show();
										next_fs.find('.previous').show();
									}
									process_log.scrollTop = process_log.scrollHeight;
									csr_spinner.hide();
								});

							}
							/* process_log.scrollTop = process_log.scrollHeight;
							csr_spinner.hide(); */
							csr_spinner.hide();
						});


						
					}else{
						//Swal.fire({ type: 'error', title: obj.msg, text: '',allowOutsideClick: false });
						$('.process_log').append('<li class="list-group-item d-flex align-items-center"><span class="mr-3 badge badge-danger badge-pill" data-toggle="tooltip" data-placement="top" title="'+obj.msg2+'"><i class="fa fa-check-"></i></span>'+obj.msg+'</li>');
						next_fs.find('.next').prop('disabled', true);
						next_fs.find('.previous').show();
						csr_spinner.hide();
						process_log.scrollTop = process_log.scrollHeight;
					}
					$('[data-toggle="tooltip"]').tooltip();
					process_log.scrollTop = process_log.scrollHeight;
				}

			});
		}else if( current == 3 ){ // splitting process starting
			
			if( !splited ){

				var data = new FormData( $form[0] ); // splitting process
				data.append("splitting_start", 'yes');
				$.ajax({
					url: cipscript.ajax_url,
					type: 'post',
					data: data,
					processData: false,
					contentType: false,
					timeout: 0,
					beforeSend	: function(){
						
						next_fs.find('.next').hide();
						next_fs.find('.previous').hide();
	
						$("#progressbar li").eq( $("fieldset").index(next_fs) ).addClass("active");
						next_fs.show();
						current_fs.animate({opacity: 0}, {
							step: function(now) {
								opacity = 1 - now;
	
								current_fs.css({
									'display': 'none',
									'position': 'relative'
								});
								next_fs.css({'opacity': opacity});
							},
							duration: 500
						});
						setProgressBar(++current);
						csr_split_spinner.show();
					},
					success : async function(response){
						
						var obj = $.parseJSON(response);

						if( obj.error == 0 ){
	
							$('.process_split_log').append('<li class="list-group-item d-block align-items-center"><span class="mr-3 badge badge-info badge-pill" data-toggle="tooltip" data-placement="top" title="'+obj.msg2+'"><i class="fa fa-check-"></i></span>'+obj.msg+'<div class="total_process_split_log_counter">'+obj.totalmsg+'</div><div class="process_split_log_counter"></div></li>');

							// console.log( obj );
	
							var promises = [];
							for (let icsv = 1; icsv <= obj.total_paged; icsv++) {
									
								var isError = false;
								var data = new FormData( $form[0] );
								data.append("splitting_data", 'yes');
								data.append("page_id", icsv);
								var request = await $.ajax({
									url: cipscript.ajax_url,
									type: 'post',
									data: data,
									processData: false,
									contentType: false,
									timeout: 0,
									async: true,
									success : function(response){
										var obj = $.parseJSON(response);
										// console.log( obj );
										if( obj.error == 0 ){
											$('body').find('.process_split_log_counter').append(obj.msg);
										}else{
											$('.process_split_log').append('<li class="list-group-item d-flex align-items-center"><span class="mr-3 badge badge-danger badge-pill" data-toggle="tooltip" data-placement="top" title="'+obj.msg2+'"><i class="fa fa-check-"></i></span>'+obj.msg+'</li>');
											isError = true;
										}
										$('[data-toggle="tooltip"]').tooltip();
									}
								});
								if( isError == true ){
									csr_split_spinner.hide();
									break;
								}
								promises.push(request);
							}
							Promise.all(promises).then(responseList => {
								// console.dir( responseList );
								$('.process_split_log').append('<li class="list-group-item d-flex align-items-center"><span class="mr-3 badge badge-info badge-pill" data-toggle="tooltip" data-placement="top" title="Splitting 10% distributions completed."><i class="fa fa-check-"></i></span>Splitting 10% distributions completed.</li>');
								$('[data-toggle="tooltip"]').tooltip();
								if( isError ){
									next_fs.find('.next').prop('disabled', true);
									next_fs.find('.next').hide();
									next_fs.find('.previous').show();
								}else{
									next_fs.find('.next').prop('disabled', false);
									next_fs.find('.next').show();
									next_fs.find('.previous').show();
									splited = true;
								}
								csr_split_spinner.hide();
							});
	
						}else{
							$('.process_split_log').append('<li class="list-group-item d-flex align-items-center"><span class="mr-3 badge badge-danger badge-pill" data-toggle="tooltip" data-placement="top" title="'+obj.msg2+'"><i class="fa fa-check-"></i></span>'+obj.msg+'</li>');
							next_fs.find('.next').prop('disabled', true);
							next_fs.find('.previous').show();
							csr_split_spinner.hide();
						}
						$('[data-toggle="tooltip"]').tooltip();
					}
				});
			}else{
				$("#progressbar li").eq( $("fieldset").index(next_fs) ).addClass("active");
				next_fs.show();
				current_fs.animate({opacity: 0}, {
					step: function(now) {
						opacity = 1 - now;

						current_fs.css({
							'display': 'none',
							'position': 'relative'
						});
						next_fs.css({'opacity': opacity});
					},
					duration: 500
				});
				setProgressBar(++current);
			}

		}else if( current == 2 ){

			$("#progressbar li").eq( $("fieldset").index(next_fs) ).addClass("active");
			next_fs.show();
			current_fs.animate({opacity: 0}, {
				step: function(now) {
					opacity = 1 - now;

					current_fs.css({
						'display': 'none',
						'position': 'relative'
					});
					next_fs.css({'opacity': opacity});
				},
				duration: 500
			});
			setProgressBar(++current);

			$('.distribution_section_table').show();
			var $tableDistribution = $('#tokenholder_distribution_table');
			$tableDistribution.bootstrapTable('refresh');

		}else if( current == 4 ){

			$("#progressbar li").eq( $("fieldset").index(next_fs) ).addClass("active");
			next_fs.show();
			current_fs.animate({opacity: 0}, {
				step: function(now) {
					opacity = 1 - now;

					current_fs.css({
						'display': 'none',
						'position': 'relative'
					});
					next_fs.css({'opacity': opacity});
				},
				duration: 500
			});
			setProgressBar(++current);

			$('.distribution_10_section_table').show();
			var $tableDistribution_10 = $('#tokenholder_distribution_10_table');
			$tableDistribution_10.bootstrapTable('refresh');

			$('html, body').animate({
				scrollTop: $("#progressbar").offset().top - 100
			}, 1000);

		}else if( current == 5 ){

			setTimeout(() => {
				$("#progressbar li").eq( $("fieldset").index(next_fs) ).addClass("active");
				next_fs.show();
				current_fs.animate({opacity: 0}, {
					step: function(now) {
						opacity = 1 - now;

						current_fs.css({
							'display': 'none',
							'position': 'relative'
						});
						next_fs.css({'opacity': opacity});
					},
					duration: 500
				});
				setProgressBar(++current);


				/* $ajaxElem = $('.summary_data_at_append_step');
				$ajaxElem.html('');
				$ajaxElem.block( block_config );
				var data = { 'action' : 'getAppendDistributionDataAction' };
				$.post(cipscript.ajax_url, data, function(response) {
					var obj = JSON.parse( response );
					if( obj.error == 0 ){
						$ajaxElem.html( obj.html );
					}else{
						Swal.fire({ type: 'error', title: obj.msg, text: '',allowOutsideClick: false});
						// console.log( obj.msg );
					}
					$ajaxElem.unblock();
				}); */


			}, 100);


		}else{
			$("#progressbar li").eq( $("fieldset").index(next_fs) ).addClass("active");
			next_fs.show();
			current_fs.animate({opacity: 0}, {
				step: function(now) {
					opacity = 1 - now;

					current_fs.css({
						'display': 'none',
						'position': 'relative'
					});
					next_fs.css({'opacity': opacity});
				},
				duration: 500
			});
			setProgressBar(++current);
		}
	});

	$(".previous").click(function(){

		current_fs = $(this).closest('fieldset');
		previous_fs = $(this).closest('fieldset').prev();
		// console.log( current );
		if( current == 2 ){
			$('.process_log').html('');
			$("input[name='th_csv_file']").val('');
		}
		if( current == 6 ){
			$('.distribution_10_section_table').show();
			var $tableDistribution_10 = $('#tokenholder_distribution_10_table');
			$tableDistribution_10.bootstrapTable('refresh');

			$('html, body').animate({
				scrollTop: $("#progressbar").offset().top - 100
			}, 1000);
		}
		if( current == 4 ){
			$('.distribution_section_table').show();
			var $tableDistribution = $('#tokenholder_distribution_table');
			$tableDistribution.bootstrapTable('refresh');

			$('html, body').animate({
				scrollTop: $("#progressbar").offset().top - 100
			}, 1000);
		}

		//Remove class active
		$("#progressbar li").eq($("fieldset").index(current_fs)).removeClass("active");

		//show the previous fieldset
		previous_fs.show();

		//hide the current fieldset with style
		current_fs.animate({opacity: 0}, {
			step: function(now) {
				// for making fielset appear animation
				opacity = 1 - now;

				current_fs.css({
				'display': 'none',
				'position': 'relative'
				});
				previous_fs.css({'opacity': opacity});
			},
			duration: 500
		});
		setProgressBar(--current);
		
	});

	function setProgressBar(curStep){
		var percent = parseFloat(100 / steps) * curStep;
		percent = percent.toFixed();
		$(".progress-bar").css("width",percent+"%")
	}

	function arrayToTable(tableData) {
        var table = $('<table class="table table-sm table-hover table-bordered"></table>');
        $(tableData).each(function (i, rowData) {
            var row = $('<tr></tr>');
            $(rowData).each(function (j, cellData) {
                row.append($('<td>'+cellData+'</td>'));
            });
            table.append(row);
        });
        return table;
    }

	function responseHandler(res){
		if( res.total_issued_label ){
			$('.total_distribution_label').show().html( res.total_issued_label );
		}else{
			$('.total_distribution_label').hide();
		}
		return res;
	}
	function responseImportHandler(res){
		if( res.total_import_label ){
			$('.total_import_label').show().html( res.total_import_label );
		}else{
			$('.total_import_label').hide();
		}
		return res;
	}

	$("input[name='th_csv_file']").on("change", function(e){
		var is_error = false;
		var this_ext = $(this).val().split('.').pop().toLowerCase();
		var pool_reference = $('input[name="pool_reference"]').val();
		if($.inArray(this_ext, ['csv']) == -1) {
			is_error = true;
			$(this).notify( 'Choose valid csv file', notifyErrorOpt );
			$(this).val('');
			$('.next.first_step').addClass('invisible');
			$('.pool_ref_toogle').slideUp();
			$('input[name="pool_reference"]').val('');
		}else{

			var $form = $('.weekly_redemptions_import_wizard_frm');
			var data = new FormData( $form[0] );
			var poolRefToogle = $('.pool_ref_toogle');
			data.append("findPoolFromFile", 'yes');
			$.ajax({
				url			: cipscript.ajax_url,
				type		: 'post',
				data		: data,
				processData	: false,
				contentType	: false,
				timeout		: 0,
				beforeSend	: function(){
					$form.block( block_config );
				},
				success : async function(response){
					var obj = $.parseJSON(response);
					console.dir( obj );
					poolRefToogle.slideDown();
					$('.next.first_step').removeClass('invisible');
					$form.unblock();
					if( obj.error == 0 ){
						$('input[name="pool_reference"]').val( obj.poolRefPopulate );
					}
				}

			});

		}
	});

	$('body').on('click', '.append_new_csr_holders_data_button', function(){

		$form = $(this).closest('fieldset');
		buttonAppend = $('.append_new_csr_holders_data_button');
		buttonCancelAppend = $('.append_cancel');

		buttonAppend.prop('disabled', true);
		buttonCancelAppend.prop('disabled', true);

		var csr_split_spinner = $('.csr_split_append_spinner');
		var csr_split_user_status_spinner = $('.csr_split_append_user_status_spinner');
		$formAppend = $('#append_new_csr_holders_data_frm');
		var data = $('#append_new_csr_holders_data_frm').serialize();
		data = data + '&get_append_data=yes';
		$form.block( block_config );


		$.post(cipscript.ajax_url, data, async function(response) {
			var obj = JSON.parse( response );
			// console.dir( obj );
			if( obj.error == 0 ){

				$('.process_split_append_log').append('<li class="list-group-item d-block align-items-center"><span class="mr-3 badge badge-info badge-pill" data-toggle="tooltip" data-placement="top" title="'+obj.msg2+'"><i class="fa fa-check-"></i></span>'+obj.msg+'<div class="total_process_split_append_log_counter">'+obj.totalmsg+'</div><div class="process_split_append_log_counter"></div></li>');

				// console.log( obj );

				var promisesAppend = [];
				var promisesUserStatus = [];
				for (let icsv = 1; icsv <= obj.total_paged; icsv++) {
						
					var isError = false;
					var data = new FormData( $formAppend[0] );
					data.append("appending_data", 'yes');
					data.append("page_id", icsv);
					data.append("total_paged", obj.total_paged);
					var requestAppend = await $.ajax({
						url: cipscript.ajax_url,
						type: 'post',
						data: data,
						processData: false,
						contentType: false,
						timeout: 0,
						async: true,
						success : async function(response){
							var obj = $.parseJSON(response);
							// console.log( obj );
							if( obj.error == 0 ){
								$('body').find('.process_split_append_log_counter').append(obj.msg);

								if( obj.isLastPage == 'yes' ){
									
									//Append completer, after check user status and update status loop start
									$form.block( block_config );

									csr_split_user_status_spinner.show();
									$('.process_split_append_user_status_log').append('<br/><hr/><li class="list-group-item d-block align-items-center"><span class="mr-3 badge badge-info badge-pill" data-toggle="tooltip" data-placement="top" title="'+obj.msg2+'"><i class="fa fa-check-"></i></span>'+obj.msg2+'<div class="total_process_split_append_user_status_log_counter">'+obj.totalmsg_user_status+'</div><div class="process_split_append_user_status_log_counter"></div></li>');

									for (let icsvUserStatus = 1; icsvUserStatus <= obj.total_paged_user_status; icsvUserStatus++) {
						
										var isError = false;
										var data = new FormData( $formAppend[0] );
										data.append("appending_data_user_status", 'yes');
										data.append("page_id_user_status", icsvUserStatus);
										data.append("total_paged_user_status", obj.total_paged_user_status);
										var requestUserStatus = await $.ajax({
											url: cipscript.ajax_url,
											type: 'post',
											data: data,
											processData: false,
											contentType: false,
											timeout: 0,
											async: true,
											success : function(response){
												var obj = $.parseJSON(response);
												if( obj.error == 0 ){
													$('body').find('.process_split_append_user_status_log_counter').append(obj.msg);
					
													if( obj.isLastPage_user_status == 'yes' ){
														setTimeout(() => {
															$('.finish_step').trigger('click');
														}, 3000);
													}
					
												}else{
													$('.process_split_append_user_status_log').append('<li class="list-group-item d-flex align-items-center"><span class="mr-3 badge badge-danger badge-pill" data-toggle="tooltip" data-placement="top" title="'+obj.msg2+'"><i class="fa fa-check-"></i></span>'+obj.msg+'</li>');
													isError = true;
												}
												$('[data-toggle="tooltip"]').tooltip();
											}
										});
										if( isError == true ){
											csr_split_user_status_spinner.hide();
											buttonAppend.prop('disabled', false);
											buttonCancelAppend.prop('disabled', false);
											break;
										}
										promisesUserStatus.push(requestUserStatus);
									}
									Promise.all(promisesUserStatus).then(responseListUserStatus => {
										// console.dir( responseListUserStatus );
										$('.process_split_append_user_status_log').append('<li class="list-group-item d-flex align-items-center"><span class="mr-3 badge badge-info badge-pill" data-toggle="tooltip" data-placement="top" title="User status check & update completed."><i class="fa fa-check-"></i></span>User status check & update completed.</li>');
										$('[data-toggle="tooltip"]').tooltip();
										if( isError ){
											buttonAppend.prop('disabled', false);
											buttonCancelAppend.prop('disabled', false);
										}else{
											
										}
										csr_split_user_status_spinner.hide();
									});

								}

							}else{
								$('.process_split_append_log').append('<li class="list-group-item d-flex align-items-center"><span class="mr-3 badge badge-danger badge-pill" data-toggle="tooltip" data-placement="top" title="'+obj.msg2+'"><i class="fa fa-check-"></i></span>'+obj.msg+'</li>');
								isError = true;
							}
							$('[data-toggle="tooltip"]').tooltip();
						}
					});
					if( isError == true ){
						csr_split_spinner.hide();
						buttonAppend.prop('disabled', false);
						buttonCancelAppend.prop('disabled', false);
						break;
					}
					promisesAppend.push(requestAppend);
				}
				Promise.all(promisesAppend).then(responseList => {
					// console.dir( responseList );
					$('.process_split_append_log').append('<li class="list-group-item d-flex align-items-center"><span class="mr-3 badge badge-info badge-pill" data-toggle="tooltip" data-placement="top" title="Appending 10% distributions completed."><i class="fa fa-check-"></i></span>Appending 10% distributions completed.</li>');
					$('[data-toggle="tooltip"]').tooltip();
					if( isError ){
						buttonAppend.prop('disabled', false);
						buttonCancelAppend.prop('disabled', false);
					}else{
						
					}
					csr_split_spinner.hide();
				});

			}else{
				$('.process_split_append_log').append('<li class="list-group-item d-flex align-items-center"><span class="mr-3 badge badge-danger badge-pill" data-toggle="tooltip" data-placement="top" title="'+obj.msg2+'"><i class="fa fa-check-"></i></span>'+obj.msg+'</li>');
	
				csr_split_spinner.hide();
				
				buttonAppend.prop('disabled', false);
				buttonCancelAppend.prop('disabled', false);
				
				Swal.fire({ type: 'error', title: obj.msg, text: '',allowOutsideClick: false});
			}
			$form.unblock();
		});

		/* $.post(cipscript.ajax_url, data, function(response) {
			var obj = JSON.parse( response );
			console.dir( obj );
			if( obj.error == 0 ){
				$('.finish_step').trigger('click');
				$('.append_response').html( obj.msg );
			}else{
				Swal.fire({ type: 'error', title: obj.msg, text: '',allowOutsideClick: false});
			}
			$form.unblock();
		}); */
		return false;

	});
	$('body').on('click', '.append_cancel', function(){
		Swal({
		  title: 'Are you sure?',
		  text: "Are you sure you want to cancel",
		  type: 'warning',
		  showCancelButton: true,
		  confirmButtonText: 'Yes'
		}).then((result) => {
		  if (result.value) {
				$form = $(this).closest('fieldset');
				var data = $('#append_cancel_data_frm').serialize();
				$form.block( block_config );
				$.post(cipscript.ajax_url, data, function(response) {
					var obj = JSON.parse( response );
					console.dir( obj );
					if( obj.error == 0 ){
						window.location.href = cipscript.current_page;
					}else{
						Swal.fire({ type: 'error', title: obj.msg, text: '',allowOutsideClick: false});
					}
					$form.unblock();
				});
		  }
		});
		return false;
	});

	if( cipscript.isDistributionData == 1 ){
		go_to_five_step();
		$('.back_disable').hide();
	}

	function go_to_five_step(){
		for (let step = 1; step < 6; step++) {
			var $next_button = $('.step_'+(step - 1 )).find('.next');
			
			var current_fs = $next_button.parent();
			var next_fs = $next_button.parent().next();

			$("#progressbar li").eq( $("fieldset").index(next_fs) ).addClass("active");
			next_fs.show();
			current_fs.css({
				'display': 'none',
				'position': 'relative'
			});
			next_fs.css({'opacity': opacity});
			setProgressBar(++current);
		}
	}
}
//5078 code
if( $('.cip_weekly_distribution_wizard').length > 0 ){
	var notifyErrorOpt = {position:"top",className: 'error',autoHide:true,autoHideDelay: 3000,clickToHide: true};
	var block_config = { message: null,overlayCSS:{ backgroundColor: '#fff',opacity:0.8} };
	
	var current_fs, next_fs, previous_fs; //fieldsets
	var opacity;
	var current = 1;
	var steps = $("fieldset").length;
	var $form = $('.cip_weekly_distribution_wizard'); 
	setProgressBar(current);

	$(".next").click(function(){
		var this_next = $(this);
		current_fs = $(this).closest('fieldset');
		next_fs = $(this).closest('fieldset').next();
		// console.log( current );

		if( current == 1 ){
			var week_number = $('input[name="week_number"]').val();
			if( week_number == "" ){
				$('input[name="week_number"]').notify( 'Week Number is required', notifyErrorOpt );
				return false;
			}
			var data = new FormData( $form[0] );
			data.append("fetch_week_data", 'yes');
			$.ajax({
				url			: cipscript.ajax_url,
				type		: 'post',
				data		: data,
				processData	: false,
				contentType	: false,
				timeout		: 0,
				beforeSend	: function(){
					$form.block( block_config );
				},
				success : async function(response){
					var obj = $.parseJSON(response);
					// console.dir( obj );
					if( obj.error == 0 ){	

						$("#progressbar li").eq( $("fieldset").index(next_fs) ).addClass("active");
						next_fs.show();
						current_fs.animate({opacity: 0}, {
							step: function(now) {
								opacity = 1 - now;

								current_fs.css({
									'display': 'none',
									'position': 'relative'
								});
								next_fs.css({'opacity': opacity});
							},
							duration: 500
						});
						setProgressBar(++current);

						var $tableWeeklyTableDistribution = $('#tokenholder_distribution_weekly_table');
						$tableWeeklyTableDistribution.bootstrapTable('refresh');
					}else{
						Swal.fire({ type: 'error', title: obj.msg, text: '',allowOutsideClick: false});
					}
					$form.unblock();
				}

			});

		}else if( current == 2 ){

			setTimeout(() => {
				$("#progressbar li").eq( $("fieldset").index(next_fs) ).addClass("active");
				next_fs.show();
				current_fs.animate({opacity: 0}, {
					step: function(now) {
						opacity = 1 - now;

						current_fs.css({
							'display': 'none',
							'position': 'relative'
						});
						next_fs.css({'opacity': opacity});
					},
					duration: 500
				});
				setProgressBar(++current);


				$ajaxElem = $('.summary_data_at_update_step');
				$ajaxElem.html('');
				$ajaxElem.block( block_config );
				var data = { 'action' : 'getWeeklyDistributionDataAction' };
				$.post(cipscript.ajax_url, data, function(response) {
					var obj = JSON.parse( response );
					if( obj.error == 0 ){
						$ajaxElem.html( obj.html );
					}else{
						Swal.fire({ type: 'error', title: obj.msg, text: '',allowOutsideClick: false});
						// console.log( obj.msg );
					}
					$ajaxElem.unblock();
				});


			}, 2000);


		}else{

			$("#progressbar li").eq( $("fieldset").index(next_fs) ).addClass("active");
			next_fs.show();
			current_fs.animate({opacity: 0}, {
				step: function(now) {
					opacity = 1 - now;
	
					current_fs.css({
						'display': 'none',
						'position': 'relative'
					});
					next_fs.css({'opacity': opacity});
				},
				duration: 500
			});
			setProgressBar(++current);
		}

	});

	$(".previous").click(function(){

		current_fs = $(this).closest('fieldset');
		previous_fs = $(this).closest('fieldset').prev();
		// console.log( current );

		$("#progressbar li").eq($("fieldset").index(current_fs)).removeClass("active");

		previous_fs.show();

		current_fs.animate({opacity: 0}, {
			step: function(now) {
				opacity = 1 - now;

				current_fs.css({
				'display': 'none',
				'position': 'relative'
				});
				previous_fs.css({'opacity': opacity});
			},
			duration: 500
		});
		setProgressBar(--current);
	});

	function setProgressBar(curStep){
		var percent = parseFloat(100 / steps) * curStep;
		percent = percent.toFixed();
		$(".progress-bar").css("width",percent+"%")
	}
	if( cipscript.isWeeklyDistributionData == 1 ){
		go_to_three_step();
		$('.back_disable').hide();
	}

	function go_to_three_step(){
		for (let step = 1; step < 3; step++) {
			var $next_button = $('.step_'+(step - 1 )).find('.next');
			
			var current_fs = $next_button.parent();
			var next_fs = $next_button.parent().next();

			$("#progressbar li").eq( $("fieldset").index(next_fs) ).addClass("active");
			next_fs.show();
			current_fs.css({
				'display': 'none',
				'position': 'relative'
			});
			next_fs.css({'opacity': opacity});
			setProgressBar(++current);
		}
	}

	$('body').on('click', '.update_new_csr_holders_data_button', function(){
		Swal({
		  title: 'Are you sure?',
		  text: "Are you sure you want to update CSR Holders data",
		  type: 'warning',
		  showCancelButton: true,
		  confirmButtonText: 'Yes'
		}).then((result) => {
		  if (result.value) {
				var csr_split_spinner = $('.csr_split_spinner');
				$formSection = $(this).closest('.loader_section');
				$form = $('#update_new_csr_holders_data_frm');
				update_btn = $('.update_new_csr_holders_data_button');
				update_cancel_btn = $('.update_cancel');
				var data = new FormData( $form[0] );
				data.append("dividing_records", 'yes');
				$formSection.block( block_config );
				$.ajax({
					url: cipscript.ajax_url,
					type: 'post',
					data: data,
					processData: false,
					contentType: false,
					timeout: 0,
					beforeSend	: function(){
						update_btn.prop('disabled', true);
						update_cancel_btn.prop('disabled', true);
					},
					success : async function(response){
						
						var obj = $.parseJSON(response);

						if( obj.error == 0 ){
	
							$('.update_process_section').append('<div class="total_process_update_log_counter">'+obj.totalmsg+'</div>');
							csr_split_spinner.show();
							var promisesPage = [];
							for (let ipage = 1; ipage <= obj.total_paged; ipage++) {
									
								var isError = false;
								var data = new FormData( $form[0] );
								data.append("updating_data", 'yes');
								data.append("page_id", ipage);
								var request = await $.ajax({
									url: cipscript.ajax_url,
									type: 'post',
									data: data,
									processData: false,
									contentType: false,
									timeout: 0,
									async: true,
									success : function(response){
										var obj = $.parseJSON(response);
										if( obj.error == 0 ){
											$('.update_process_section').append('<div class="total_process_update_log_counter">'+obj.msg+'</div>');
											if( obj.isLastStep == 1 ){
												setTimeout(() => {
													$('.finish_step').trigger('click');
													$('.update_response').html( obj.total_msg );
												}, 3000);
											}
										}else{
											isError = true;
											$('.update_process_section').append('<div class="total_process_update_log_counter">'+obj.msg+'</div>');
											csr_split_spinner.hide();
										}
									}
								});
								if( isError == true ){
									break;
								}
								promisesPage.push(request);
							}
							Promise.all(promisesPage).then(responseList => {
								if( isError ){
									update_btn.prop('disabled', false);
									update_cancel_btn.prop('disabled', false);
								}else{
									update_btn.prop('disabled', true);
									update_cancel_btn.prop('disabled', true);
								}
								csr_split_spinner.hide();
								$formSection.unblock();
							});
	
						}else{
							Swal.fire({ type: 'error', title: obj.msg, text: '',allowOutsideClick: false});
							update_btn.prop('disabled', false);
							update_cancel_btn.prop('disabled', false);
							$formSection.unblock();
						}
					}
				});
				/* var data = $('#update_new_csr_holders_data_frm').serialize();
				$form.block( block_config );
				$.post(cipscript.ajax_url, data, function(response) {
					var obj = JSON.parse( response );
					console.dir( obj );
					if( obj.error == 0 ){
						$('.finish_step').trigger('click');
						$('.update_response').html( obj.msg );
					}else{
						Swal.fire({ type: 'error', title: obj.msg, text: '',allowOutsideClick: false});
					}
					$form.unblock();
				}); */
		  }
		});
		return false;
	});

	$('body').on('click', '.update_cancel', function(){
		Swal({
		  title: 'Are you sure?',
		  text: "Are you sure you want to cancel",
		  type: 'warning',
		  showCancelButton: true,
		  confirmButtonText: 'Yes'
		}).then((result) => {
		  if (result.value) {
				$form = $(this).closest('fieldset');
				var data = $('#update_cancel_data_frm').serialize();
				$form.block( block_config );
				$.post(cipscript.ajax_url, data, function(response) {
					var obj = JSON.parse( response );
					console.dir( obj );
					if( obj.error == 0 ){
						window.location.href = cipscript.current_page;
					}else{
						Swal.fire({ type: 'error', title: obj.msg, text: '',allowOutsideClick: false});
					}
					$form.unblock();
				});
		  }
		});
		return false;
	});
	function responseWeeklyDistributionHandler(res){
		if( res.total_weekly_label ){
			$('.total_weekly_label').show().html( res.total_weekly_label );
		}else{
			$('.total_weekly_label').hide();
		}
		return res;
	}
}
//5216 code
$('body').on('submit', '#register_member_assistant_frm', function(){
	var notifyErrorOpt = {position:"bottom",className: 'error',autoHide:true,autoHideDelay: 3000,clickToHide: true};
	var block_config = { message: null,overlayCSS:{ backgroundColor: '#fff',opacity:0.8} };
	$form = $(this);

	if( $form.find('input[name=email]').val() == "" || $form.find('input[name=first_name]').val() == "" || $form.find('input[name=last_name]').val() == "" ){
		$form.notify( 'All fields are required', notifyErrorOpt );
		return false;
	}

	var data = $(this).serialize();
	$form.block( block_config );
	$.post(cipscript.ajax_url, data, function(response) {
		var obj = JSON.parse( response );
		if( obj.error == 0 ){
			Swal.fire({ type: 'success', title: obj.msg, text: '',allowOutsideClick: true});
			$('#register_member_assistant_frm')[0].reset();
		}else{
			Swal.fire({ type: 'error', title: obj.msg, text: '',allowOutsideClick: true});
		}
		$form.unblock();
	});
	return false;
});
//4966
jQuery(document).ready(function($){
	
	var notifyErrorOpt = {position:"bottom",className: 'error',autoHide:true,autoHideDelay: 3000,clickToHide: true};
	var block_config = { message: null,overlayCSS:{ backgroundColor: '#fff',opacity:0.8} };
	var block_config_kyc = { css: { backgroundColor: 'transparent', border: 'none' }, message: '<div class="blockUIspinner"></div>', baseZ: 1500, overlayCSS: { backgroundColor: '#FFFFFF', opacity: 0.8, cursor: 'wait' } };

	if( $('#editEthModal').length > 0 ){
		var isAddressSignVerified = false;
		var returnedSignature = "";
		var current_fs_eth, next_fs_eth, previous_fs_eth; //fieldsets
		var opacity_eth;
		var current_eth = 1;
		var steps_eth = $('body #editEthModal').find("fieldset").length;
	}

	$('body').on('click','.edit_member_eth_frm', function(e){
		var Memberth = $(this).attr('data-memberth');
		var data = { 'action' : 'get_form_member_ethaddress_action', 'Memberth' : Memberth };
		var thisTr = $(this).closest('tr');
		thisTr.block( block_config );
		$.post(cipscript.ajax_url, data, function(response) {
			var obj = JSON.parse( response );
			if( obj.error == 0 ){
				$('#editEthModal .modal-body').html( obj.html );

				isAddressSignVerified = false;
				returnedSignature = "";

				current_eth = 1;
				steps_eth = $('body').find(".send_pending_ethaddressmember fieldset").length;
				setProgressBar_eth(current_eth);

				$('#editEthModal').modal({backdrop: 'static', keyboard: false}, 'show');
			}else{
				Swal.fire({ type: 'error', title: obj.msg, text: '',allowOutsideClick: true});
			}
			thisTr.unblock();
		});
		return false;
	});
	const isChangeEth = 1;
	$('body').on('click','.edit_change_member_eth_frm', function(e){
		var Memberth = $(this).attr('data-memberth');
		var data = { 'action' : 'get_form_member_ethaddress_action', 'Memberth' : Memberth, 'isChangeEth' : isChangeEth };
		var thisTr = $(this).closest('tr');
		thisTr.block( block_config );
		$.post(cipscript.ajax_url, data, function(response) {
			var obj = JSON.parse( response );
			if( obj.error == 0 ){
				$('#editEthModal .modal-body').html( obj.html );

				isAddressSignVerified = false;
				returnedSignature = "";

				current_eth = 1;
				steps_eth = $('body').find(".send_pending_ethaddressmember fieldset").length;
				setProgressBar_eth(current_eth);

				$('#editEthModal').modal({backdrop: 'static', keyboard: false}, 'show');
			}else{
				Swal.fire({ type: 'error', title: obj.msg, text: '',allowOutsideClick: true});
			}
			thisTr.unblock();
		});
		return false;
	});
	
	$('#editEthModal').on('hide.bs.modal', function (event) {
		var modal = $(this);
		modal.find('.modal-body').html('');
	});

	//reject csr address
	$('body').on('click', '#csr_address_pending_review .reject_csraddress', function(){
		var data = cipscript.actionRejectCsrAddressUrl;
		data['thisid'] = $(this).attr('data-id');
		var current_tr = $(this).closest('tr');
		Swal({
		title: 'Reject!',
		text: "Enter the reason for rejection.",
		input: 'text',
		showCancelButton: true,
		confirmButtonText: 'Reject',
		inputValidator: (rejectMsg) => {
			if (!rejectMsg) {
			return 'Please enter the reason for rejection.'
			}
		},
		preConfirm:(rejectMsg) => {
			if( rejectMsg == "" ){
				Swal.showValidationMessage( `Please enter the reason for rejection.` );
			}else{
				return { isConfirmed: 1 , rejectMsg : rejectMsg };
			}
		},
		allowOutsideClick: () => !Swal.isLoading()
		}).then((result) => {
			// console.log( result );
			if (result.value.isConfirmed) {
				current_tr.block( block_config );
				data['rejectMsg'] = result.value.rejectMsg;
				jQuery.ajax({ 
					type: "post",
					data: data,
					cache: false,
					url: cipscript.ajax_url,
					success: function(response){
						var obj = JSON.parse( response );
						if( obj.error == 0 ){
							window.location.reload();
						}else{
							Swal.fire({ type: 'error', title: obj.msg, text: '',allowOutsideClick: true});
						}
						current_tr.unblock();
					}
				});
			}
		});
		return false;
	});

	//approved csr address
	$('body').on('click', '#csr_address_pending_review .approve_csraddress', function(){
		var data = cipscript.actionApprovedCsrAddress;
		data['thisid'] = $(this).attr('data-id');
		var current_tr = $(this).closest('tr');
		Swal({
		title: 'Are you sure?',
		text: "Do you want to approve?",
		type: 'warning',
		showCancelButton: true,
		confirmButtonText: 'Yes'
		}).then((result) => {
		if (result.value) {
			current_tr.block( block_config );
			jQuery.ajax({ 
				type: "post",
				data: data,
				cache: false,
				url: cipscript.ajax_url,
				success: function(response){
					var obj = JSON.parse( response );
					if( obj.error == 0 ){
						window.location.reload();
					}else{
						Swal.fire({ type: 'error', title: obj.msg, text: '',allowOutsideClick: true});
					}
					current_tr.unblock();
				}
			});
		}
		});
		return false;
	});

	$('body').on('click', '#csr_address_pending_review .csr_address_review_imgs, #csr_lsh_pending_review .csr_address_review_imgs', function(){
		$('#imagepreview').attr('src', $(this).attr('src'));
		$('#enlargeImageModal').modal('show');
	});
	$('#enlargeImageModal').on('hide.bs.modal', function (event) {
		var modal = $(this);
		modal.find('#imagepreview').attr('src','');
	});

	if( $('#editEthModal').length > 0 ){
		// $form = $('.send_pending_ethaddressmember');
		$('body').on("click",".send_pending_ethaddressmember .next", function(){
			var this_next = $(this);
			current_fs_eth = $(this).closest('fieldset');
			next_fs_eth = $(this).closest('fieldset').next();
			// console.log( current );
					
			var $form = $('body').find('.send_pending_ethaddressmember'); 
			if( current_eth == 1 ){
				
				$form.find('.form_response').html('');
				var csrwalletaddress = $('input[name="csrwalletaddress"]').val();
				
				if( csrwalletaddress == "" ){
					$form.find('.form_response').html('Please enter CSR wallet address');
					return false;
				}
				if( !web3.utils.isAddress(csrwalletaddress) ){
					$form.find('.form_response').html('Please enter valid CSR wallet address');
					return false;
				}
				
				if (!ethereum) {
					Swal.fire({ type: 'question', title: 'MetaMask is not installed', text: '',allowOutsideClick: false });
					window.userWalletAddress = null;
					$form.unblock();
					return false;
				}
			
				$form.block( block_config );
				var formData = $form.serialize();
				var data = cipscript.actionValidateAddCsrWalletData;
				data['thiseth'] = csrwalletaddress;
				data['isChangeMicro']	=	$('body').find('.send_pending_ethaddressmember input[name="_micro"]').val();
				data['Memberth']	=	$('body').find('.send_pending_ethaddressmember input[name="Memberth"]').val();
				
				$.ajax({
					method: "POST",
					url: cipscript.ajax_url,
					data: data,
					success: async function ( response ) {
						var obj = JSON.parse( response );

						// console.log( obj );

						if( obj.error == 0 ){
							
							const accounts = await ethereum.request({
								method: 'eth_requestAccounts'
							}).catch((e) => {
								Swal.fire({ type: 'error', title: e.message, text: '',allowOutsideClick: false});
								$form.unblock();
								return
							});
							if (!accounts) {
								Swal.fire({ type: 'error', title: 'Your address is NOT verified.', text: '',allowOutsideClick: false});
								$form.unblock();
								return
							}
							if( obj.data.toLowerCase() != accounts[0] ){
								Swal.fire({ type: 'error', title: 'Please select '+obj.data+' in MetaMask and try again.', text: '',allowOutsideClick: false});
								$form.unblock();
								return
							}
							
							$.ajax({
								method: "POST",
								url: cipscript.ajax_url,
								data: { action: "cipGetAddWalletAddressSignatureMsg_act", 'thiseth' : obj.data },
								success: async function (response) {
									var objCsrMsg = JSON.parse( response );
									if( objCsrMsg.error == 0 && objCsrMsg.msg != "" ){
										var fromAddress = obj.data;
										var params = [objCsrMsg.msg, fromAddress];
										var method = 'personal_sign';
										const signature = await ethereum.request({
											method, 
											params, 
											fromAddress
										}).catch((e) => {
											Swal.fire({ type: 'error', title: e.message, text: '',allowOutsideClick: false});
											$form.unblock();
											return
										})
										if( !signature ){
											Swal.fire({ type: 'error', title: 'Your address is NOT verified.', text: '',allowOutsideClick: false});
											$form.unblock();
											return
										}

										if( obj.isConfirmResumeDistribution == 1 ){
											$('body').find('.confirm_resume_section').html( obj.confirmCheckboxHtml );
										}

										formData = formData + '&verifyingProcess=yes&signature=' + signature;
			
										$.ajax({
											method: "POST",
											url: cipscript.ajax_url,
											data: formData,
											success: async function (response) {
												var objSign = JSON.parse( response );
												if( objSign.error == 0 ){

													if( objSign.isDirectAdded == 1 ){
														$('#editEthModal').modal('hide');
														Swal.fire({ type: 'success', title: objSign.msg, text: '',allowOutsideClick: true}).then(function(){ $('#editEthModal').modal('hide'); window.location.reload();});
													}

													isAddressSignVerified = true;
													returnedSignature = signature;

													if( objSign.updateRowCount <= 1 ){
														$('body').find('.copy_all_checkbox').hide();
														$('body').find('.copy_all_checkbox').after( objSign.html );
														$('body').find('.new_address_change').html('');
													}else{
														$('body').find('.only_one_update_info').remove();
														$('body').find('.copy_all_checkbox').show();
														if( $('body').find('.new_address_change').length > 0 ){
															$('body').find('.new_address_change').html( objSign.new_address );
														}
													}

													$("body .send_pending_ethaddressmember #progressbar li").eq( $("body .send_pending_ethaddressmember fieldset").index(next_fs_eth) ).addClass("active");
													next_fs_eth.show();
													current_fs_eth.animate({opacity: 0}, {
														step: function(now) {
															opacity_eth = 1 - now;
											
															current_fs_eth.css({
																'display': 'none',
																'position': 'relative'
															});
															next_fs_eth.css({'opacity': opacity_eth});
														},
														duration: 500
													});
													setProgressBar_eth(++current_eth);
													
												}else{
													Swal.fire({ type: 'error', title: objSign.msg, text: '',allowOutsideClick: false});
												}
												$form.unblock();
											},
											error: function () {
												Swal.fire({ type: 'error', title: 'An error was encountered', text: '',allowOutsideClick: false});
												$form.unblock();
											}
										});
									}else{
										Swal.fire({ type: 'error', title: objCsrMsg.msg, text: '',allowOutsideClick: false});
										$form.unblock();
										return false;
									}
								},
								error: function () {
									Swal.fire({ type: 'error', title: 'An error was encountered', text: '',allowOutsideClick: false});
									$form.unblock();
								}
							});
			
						}else{
							Swal.fire({ type: 'error', title: obj.msg, text: '',allowOutsideClick: false});
							$form.unblock();
							return false;
						}
					},
					error: function () {
						Swal.fire({ type: 'error', title: 'An error was encountered', text: '',allowOutsideClick: false});
						$form.unblock();
					}
				});

			}else if( current_eth == 2 ){

				var member_passport = $('body').find('.send_pending_ethaddressmember input[name="member_passport"]').val();
				var memberPassportElem = $('body').find('.send_pending_ethaddressmember input[name="member_passport"]');
				if( typeof member_passport  === "undefined" || member_passport == "" ){
					memberPassportElem.notify( 'Please choose file', notifyErrorOpt );
					return false;
				}

				$("body .send_pending_ethaddressmember #progressbar li").eq( $("body .send_pending_ethaddressmember fieldset").index(next_fs_eth) ).addClass("active");
				next_fs_eth.show();
				current_fs_eth.animate({opacity: 0}, {
					step: function(now) {
						opacity_eth = 1 - now;
		
						current_fs_eth.css({
							'display': 'none',
							'position': 'relative'
						});
						next_fs_eth.css({'opacity': opacity_eth});
					},
					duration: 500
				});
				setProgressBar_eth(++current_eth);

			}else if( current_eth == 3 ){

				var piece_paper_wallet_address = $('body').find('.send_pending_ethaddressmember input[name="piece_paper_wallet_address"]').val();
				var piecePaperWalletAddressElem = $('body').find('.send_pending_ethaddressmember input[name="piece_paper_wallet_address"]');
				if( typeof piece_paper_wallet_address  === "undefined" || piece_paper_wallet_address == "" ){
					piecePaperWalletAddressElem.notify( 'Please choose file', notifyErrorOpt );
					return false;
				}

				$("body .send_pending_ethaddressmember #progressbar li").eq( $("body .send_pending_ethaddressmember fieldset").index(next_fs_eth) ).addClass("active");
				next_fs_eth.show();
				current_fs_eth.animate({opacity: 0}, {
					step: function(now) {
						opacity_eth = 1 - now;

						current_fs_eth.css({
							'display': 'none',
							'position': 'relative'
						});
						next_fs_eth.css({'opacity': opacity_eth});
					},
					duration: 500
				});
				setProgressBar_eth(++current_eth);

			}else if( current_eth == 4 ){

				if( $('body').find('input[name="confirmResume"]').length > 0 ){
					var confirmResume = $('body').find('input[name="confirmResume"]:checked').val();
					if( confirmResume != 1 ){
						Swal.fire({ type: 'error', title: 'Please check I understand that by updating this address all affected rows on CSRnow.com will have their status of Security Hold lifted and distribution will resume.', text: '',allowOutsideClick: true});
						return false;
					}
				}
				
				var data = new FormData( $form[0] );
				data.append( "returnedSignature", returnedSignature );

				$form.block( block_config );
				$.ajax({
					url			: cipscript.ajax_url,
					type		: 'post',
					data		: data,
					processData	: false,
					contentType	: false,
					success : function(response){
						var obj = $.parseJSON(response);
						// console.log( obj );	
						if( obj.error == 0 ){
							Swal.fire({ type: 'success', title: obj.msg, text: '',allowOutsideClick: true}).then(function(){ $('#editEthModal').modal('hide'); window.location.reload();});
						}else{
							Swal.fire({ type: 'error', title: obj.msg, text: '',allowOutsideClick: true});
						}
						$form.unblock();
			
					}
				});

			}else{
				$("body .send_pending_ethaddressmember #progressbar li").eq( $("body .send_pending_ethaddressmember fieldset").index(next_fs_eth) ).addClass("active");
				next_fs_eth.show();
				current_fs_eth.animate({opacity: 0}, {
					step: function(now) {
						opacity_eth = 1 - now;
		
						current_fs_eth.css({
							'display': 'none',
							'position': 'relative'
						});
						next_fs_eth.css({'opacity': opacity_eth});
					},
					duration: 500
				});
				setProgressBar_eth(++current_eth);
			}

		});
		$('body').on("click",".send_pending_ethaddressmember .previous", function(){
			current_fs_eth = $(this).closest('fieldset');
			previous_fs_eth = $(this).closest('fieldset').prev();
			// console.log( current );

			$("body .send_pending_ethaddressmember #progressbar li").eq($("body .send_pending_ethaddressmember fieldset").index(current_fs_eth)).removeClass("active");

			previous_fs_eth.show();

			current_fs_eth.animate({opacity: 0}, {
				step: function(now) {
					opacity_eth = 1 - now;

					current_fs_eth.css({
					'display': 'none',
					'position': 'relative'
					});
					previous_fs_eth.css({'opacity': opacity_eth});
				},
				duration: 500
			});
			setProgressBar_eth(--current_eth);
		});
		
		function setProgressBar_eth(curStep){
			var percent = parseFloat(100 / steps_eth) * curStep;
			percent = percent.toFixed();
			$('body').find(".send_pending_ethaddressmember .progress-bar").css("width",percent+"%")
		}
		$('body').on('change', '.send_pending_ethaddressmember input[name="blank_fill"]', function(){
			var checked = $(this).is(':checked');
			var thisElem = $(this).parent().parent();
			if( checked ){
				var $form = $('body').find('.send_pending_ethaddressmember');
				$form.block( block_config );
				var formData = $form.serialize();
                formData = formData + '&countUpdateRow=yes';
				
				$.ajax({
                    method: "POST",
                    url: cipscript.ajax_url,
                    data: formData,
                    success: function (response) {
                        var obj = JSON.parse( response );
                        if( obj.error == 0 ){
							$('body').find('.row_update_info').remove();
							thisElem.after( obj.html );
                        }else{
                            Swal.fire({ type: 'error', title: obj.msg, text: '',allowOutsideClick: false});
                        }
                        $form.unblock();
                    },
                    error: function () {
                        Swal.fire({ type: 'error', title: 'An error was encountered', text: '',allowOutsideClick: false});
                        $form.unblock();
                    }
                });
			}else{
				$('body').find('.row_update_info').remove();
			}
		});
		$('body').on('change', '.send_pending_ethaddressmember input[name="updateall_fill"]', function(){
			var checked = $(this).is(':checked');
			var thisElem = $(this).parent().parent();
			if( checked ){
				var $form = $('body').find('.send_pending_ethaddressmember');
				$form.block( block_config );
				var formData = $form.serialize();
                formData = formData + '&countUpdateRow=yes';
				
				$.ajax({
                    method: "POST",
                    url: cipscript.ajax_url,
                    data: formData,
                    success: function (response) {
                        var obj = JSON.parse( response );
                        if( obj.error == 0 ){
							$('body').find('.row_update_info').remove();
							thisElem.after( obj.html );
                        }else{
                            Swal.fire({ type: 'error', title: obj.msg, text: '',allowOutsideClick: false});
                        }
                        $form.unblock();
                    },
                    error: function () {
                        Swal.fire({ type: 'error', title: 'An error was encountered', text: '',allowOutsideClick: false});
                        $form.unblock();
                    }
                });
			}else{
				$('body').find('.row_update_info').remove();
			}
		});

		$('body').on("change", "input[name='member_passport']", function(e){
			var is_error = false;
			var this_ext = $(this).val().split('.').pop().toLowerCase();
			var thisElement = $(this);
			if($.inArray(this_ext, ['png', 'jpg', 'jpeg']) == -1) {
				is_error = true;
				$(this).notify( 'Choose valid Photo ID file format', notifyErrorOpt );
				$(this).val('');
			}

			if( this.files[0].size > 8000000 ){
				$(this).notify( 'Photo ID file size exceeds 8MB', notifyErrorOpt );
				$(this).val('');
			}
			/* else{
				console.log( this.files );

				var $form = $('body').find('.send_pending_ethaddressmember');
				var data = new FormData( $form[0] );
				data.append( "passportSizeCheck", 'yes' );

				$form.block( block_config );
				$.ajax({
					url			: cipscript.ajax_url,
					type		: 'post',
					data		: data,
					processData	: false,
					contentType	: false,
					success : function(response){
						var obj = $.parseJSON(response);
						console.log( obj );	
						if( obj.error == 0 ){
						}else{
							thisElement.notify( obj.msg, notifyErrorOpt );
							thisElement.val('');
							Swal.fire({ type: 'error', title: obj.msg, text: '',allowOutsideClick: true});
						}
						$form.unblock();
			
					}
				});

			} */
		});

		$('body').on("change", "input[name='piece_paper_wallet_address']", function(e){
			var is_error = false;
			var this_ext = $(this).val().split('.').pop().toLowerCase();
			var thisElement = $(this);
			if($.inArray(this_ext, ['png', 'jpg', 'jpeg']) == -1) {
				is_error = true;
				$(this).notify( 'Choose valid Selfie file format', notifyErrorOpt );
				$(this).val('');
			}
			if( this.files[0].size > 8000000 ){
				$(this).notify( 'Selfie file size exceeds 8MB', notifyErrorOpt );
				$(this).val('');
			}
			/* else{
				
				console.log( this.files );

				var $form = $('body').find('.send_pending_ethaddressmember');
				var data = new FormData( $form[0] );
				data.append( "selfieSizeCheck", 'yes' );

				$form.block( block_config );
				$.ajax({
					url			: cipscript.ajax_url,
					type		: 'post',
					data		: data,
					processData	: false,
					contentType	: false,
					success : function(response){
						var obj = $.parseJSON(response);
						console.log( obj );	
						if( obj.error == 0 ){
						}else{
							thisElement.notify( obj.msg, notifyErrorOpt );
							thisElement.val('');
							Swal.fire({ type: 'error', title: obj.msg, text: '',allowOutsideClick: true});
						}
						$form.unblock();
			
					}
				});
			} */
		});
	}

	$('body').on('click', '.cip_notice_dismiss', function(){
		var dont_show = $(this).prev().find('input[name=dont_show]').is(':checked');
		var dont_show_again = 0;
		if( dont_show ){
			dont_show_again = 1;
		}
		var thisAlert = $(this).parent().closest('.alert');
		var formData = {'action' : 'cip_dismiss_notice_action', 'thisnotice' : $(this).attr('data-id'), 'dont_show' : dont_show_again };
		$.ajax({
			method: "POST",
			url: cipscript.ajax_url,
			data: formData,
			success: function (response) {
				var obj = JSON.parse( response );
				if( obj.error == 0 ){
					thisAlert.alert("close");
				}
				$form.unblock();
			},
			error: function () {
				console.log('An error was encountered');
				$form.unblock();
			}
		});
	});

	$('body').on('click', '.clearAllNotification', function(){
		var $form = $('form[name="clearAllNotificationFrm"]');
		var formData = $form.serialize();
		var block_config_spinner = { css: { backgroundColor: 'transparent', border: 'none' }, message: '<div class="blockUIspinner"></div>', baseZ: 1500, overlayCSS: { backgroundColor: '#FFFFFF', opacity: 0.8, cursor: 'wait' } };
		$form.block( block_config_spinner );
		$.ajax({
			method: "POST",
			url: cipscript.ajax_url,
			data: formData,
			success: function (response) {
				var obj = JSON.parse( response );
				if( obj.error == 0 ){
					swalToast({ type: 'success', title: obj.msg });
					window.location.reload();
				}else{
					swalToast({ type: 'error', title: obj.msg });
				}
				$form.unblock();
			},
			error: function () {
				swalToast({ type: 'error', title: 'An error was encountered' });
				$form.unblock();
			}
		});
	});

	$('body').on('click', '.cip_notice_dismiss_all', function(){
		var dont_show = $('body').find('.notice_close_all input[name=dont_show_all]').is(':checked');
		var dont_show_again = 0;
		if( dont_show ){
			dont_show_again = 1;
		}
		var thisAlert = $(this).parent().closest('.alert');
		var formData = {'action' : 'cip_dismiss_notice_all_action', 'dont_show' : dont_show_again };
		$.ajax({
			method: "POST",
			url: cipscript.ajax_url,
			data: formData,
			success: function (response) {
				var obj = JSON.parse( response );
				if( obj.error == 0 ){
					swalToast({ type: 'success', title: obj.msg });
					window.location.reload();
				}
				$form.unblock();
			},
			error: function () {
				console.log('An error was encountered');
				$form.unblock();
			}
		});
	});

	//#4966
	$('body').on('click', '.set_sh_address', function(){
		
		var $form = $(this).closest('form');
		var data = new FormData( $form[0] );
		data.append( "thisId", $(this).attr('data-id') );
		data.append( "thisAid", $(this).attr('data-aid') );

		Swal({
			title: 'Are you sure?',
			text: "Setting Security Hold status will suspend all distribution of CSR to this address.",
			type: 'warning',
			showCancelButton: true,
			confirmButtonText: 'Yes'
		}).then((result) => {
			if (result.value) {
				
				$form.block( block_config );
				$.ajax({
					url			: cipscript.ajax_url,
					type		: 'post',
					data		: data,
					processData	: false,
					contentType	: false,
					success : function(response){
						var obj = $.parseJSON(response);
						// console.log( obj );	
						if( obj.error == 0 ){
						    window.location.reload();
							//Swal.fire({ title: obj.msg, text: '',allowOutsideClick: true}).then(function(){ window.location.reload(); });
						}else{
							Swal.fire({ type: 'error', title: obj.msg, text: '',allowOutsideClick: true});
						}
						$form.unblock();
			
					}
				});

			}
		});

	});

	if( $('#liftSecurityHoldPopup').length > 0 ){
		var isAddressSignVerified = false;
		var returnedSignature = "";
		var current_fs_lsh, next_fs_lsh, previous_fs_lsh; //fieldsets
		var opacity_lsh;
		var current_lsh = 1;
		var steps_lsh = $('body .liftSHWizardFrm').find("fieldset").length;
	}
	const getLiftSHFrm = 1;
	$('body').on('click','.set_lsh_address', function(e){

		var $form = $(this).closest('form');
		var data = new FormData( $form[0] );
		data.append( "thisId", $(this).attr('data-id') );
		data.append( "thisAid", $(this).attr('data-aid') );
		data.append( "getLiftSHFrm", getLiftSHFrm );
		
		Swal({
			title: 'Are you sure?',
			text: "Lifting Security Hold will un-suspend CSR distribution to this wallet address. Additional confirmation information will be requested.",
			type: 'warning',
			showCancelButton: true,
			confirmButtonText: 'Yes'
		}).then((result) => {
			if (result.value) {
				
				$form.block( block_config );

        		$.ajax({
        			url			: cipscript.ajax_url,
        			type		: 'post',
        			data		: data,
        			processData	: false,
        			contentType	: false,
        			success : function(response){
        				var obj = JSON.parse( response );
        				if( obj.error == 0 ){
        					$('#liftSecurityHoldPopup .modal-body').html( obj.html );
        
        					isAddressSignVerified = false;
        					returnedSignature = "";
        
        					current_lsh = 1;
        					steps_lsh = $('body .liftSHWizardFrm').find("fieldset").length;
        					setProgressBar_lsh(current_lsh);
        
        					$('#liftSecurityHoldPopup').modal({backdrop: 'static', keyboard: false}, 'show');
        				}else{
        					Swal.fire({ type: 'error', title: obj.msg, text: '',allowOutsideClick: true});
        				}
        				$form.unblock();
        	
        			}
        		});

			}
		});

		
		return false;
	});
	
	$('#liftSecurityHoldPopup').on('hide.bs.modal', function (event) {
		var modal = $(this);
		modal.find('.modal-body').html('');
	});

	if( $('#liftSecurityHoldPopup').length > 0 ){

		$('body').on("click","#liftSecurityHoldPopup .next", function(){
			$form = $('.liftSHWizardFrm');
			var this_next = $(this);
			current_fs_lsh = $(this).closest('fieldset');
			next_fs_lsh = $(this).closest('fieldset').next();
			// console.log( current );
					
			var $form = $('body').find('.liftSHWizardFrm'); 
			if( current_lsh == 3 ){
				
				$form.find('.form_response').html('');
				returnedSignature = "";
				$form.block( block_config );
				var dataGetAddress = $form.serialize();
				dataGetAddress = dataGetAddress + '&dataGetAddress=yes';
				$.ajax({
					method: "POST",
					url: cipscript.ajax_url,
					data: dataGetAddress,
					success: async function ( response ) {
						var obj = JSON.parse( response );
						if( obj.error == 0 ){
							
							const csrwalletaddress = obj.thisAid;
				
							if( csrwalletaddress == "" ){
								$form.find('.form_response').html('CSR wallet address is empty');
								$form.unblock();
								return false;
							}
							if( !web3.utils.isAddress(csrwalletaddress) ){
								$form.find('.form_response').html('CSR wallet address is invalid');
								$form.unblock();
								return false;
							}
							
							if (!ethereum) {
								Swal.fire({ type: 'question', title: 'MetaMask is not installed', text: '',allowOutsideClick: false });
								window.userWalletAddress = null;
								$form.unblock();
								return false;
							}
						
							// $form.block( block_config );
							var formData = $form.serialize();

							var dataValidateAddress = $form.serialize();
							dataValidateAddress = dataValidateAddress + '&dataValidateAddress=yes&returnedAddress='+csrwalletaddress;
							
							$.ajax({
								method: "POST",
								url: cipscript.ajax_url,
								data: dataValidateAddress,
								success: async function ( response ) {
									var obj = JSON.parse( response );

									// console.log( obj );

									if( obj.error == 0 ){
										
										const accounts = await ethereum.request({
											method: 'eth_requestAccounts'
										}).catch((e) => {
											Swal.fire({ type: 'error', title: e.message, text: '',allowOutsideClick: false});
											$form.unblock();
											return
										});
										if (!accounts) {
											Swal.fire({ type: 'error', title: 'Your address is NOT verified.', text: '',allowOutsideClick: false});
											$form.unblock();
											return
										}
										if( obj.data.toLowerCase() != accounts[0] ){
											Swal.fire({ type: 'error', title: 'Please select '+obj.data+' in MetaMask and try again.', text: '',allowOutsideClick: false});
											$form.unblock();
											return
										}
										
										var datagetSignatureMsg = $form.serialize();
										datagetSignatureMsg = datagetSignatureMsg + '&datagetSignatureMsg=yes';

										$.ajax({
											method: "POST",
											url: cipscript.ajax_url,
											data: datagetSignatureMsg,
											success: async function (response) {
												var objCsrMsg = JSON.parse( response );
												if( objCsrMsg.error == 0 && objCsrMsg.msg != "" ){
													var fromAddress = obj.data;
													var params = [objCsrMsg.msg, fromAddress];
													var method = 'personal_sign';
													const signature = await ethereum.request({
														method, 
														params, 
														fromAddress
													}).catch((e) => {
														Swal.fire({ type: 'error', title: e.message, text: '',allowOutsideClick: false});
														$form.unblock();
														return
													})
													if( !signature ){
														Swal.fire({ type: 'error', title: 'Your address is NOT verified.', text: '',allowOutsideClick: false});
														$form.unblock();
														return
													}
													formData = formData + '&verifyingProcess=yes&signature=' + signature;
						
													$.ajax({
														method: "POST",
														url: cipscript.ajax_url,
														data: formData,
														success: async function (response) {
															var objSign = JSON.parse( response );
															if( objSign.error == 0 ){
																isAddressSignVerified = true;
																returnedSignature = signature;
																
																var data = new FormData( $form[0] );
																data.append( "returnedSignature", signature );

																$form.block( block_config );
																$.ajax({
																	url			: cipscript.ajax_url,
																	type		: 'post',
																	data		: data,
																	processData	: false,
																	contentType	: false,
																	success : function(response){
																		var obj = $.parseJSON(response);
																		// console.log( obj );	
																		if( obj.error == 0 ){
																			Swal.fire({ type: 'success', title: obj.msg, text: '',allowOutsideClick: true}).then(function(){ $('#liftSecurityHoldPopup').modal('hide'); window.location.reload();});
																		}else{
																			Swal.fire({ type: 'error', title: obj.msg, text: '',allowOutsideClick: true});
																		}
																		$form.unblock();
															
																	}
																});
																
															}else{
																Swal.fire({ type: 'error', title: objSign.msg, text: '',allowOutsideClick: false});
																$form.unblock();
															}
														},
														error: function () {
															Swal.fire({ type: 'error', title: 'An error was encountered', text: '',allowOutsideClick: false});
															$form.unblock();
														}
													});
												}else{
													Swal.fire({ type: 'error', title: objCsrMsg.msg, text: '',allowOutsideClick: false});
													$form.unblock();
													return false;
												}
											},
											error: function () {
												Swal.fire({ type: 'error', title: 'An error was encountered', text: '',allowOutsideClick: false});
												$form.unblock();
											}
										});
						
									}else{
										Swal.fire({ type: 'error', title: obj.msg, text: '',allowOutsideClick: false});
										$form.unblock();
										return false;
									}
								},
								error: function () {
									Swal.fire({ type: 'error', title: 'An error was encountered', text: '',allowOutsideClick: false});
									$form.unblock();
								}
							});

						}else{
							Swal.fire({ type: 'error', title: obj.msg, text: '',allowOutsideClick: false});
							current_tr.unblock();
							return false;
						}
					},
					error: function () {
						Swal.fire({ type: 'error', title: 'An error was encountered', text: '',allowOutsideClick: false});
					}
				});

			}else if( current_lsh == 1 ){

				var member_passport = $('body').find('.liftSHWizardFrm input[name="member_passport"]').val();
				var memberPassportElem = $('body').find('.liftSHWizardFrm input[name="member_passport"]');
				if( typeof member_passport  === "undefined" || member_passport == "" ){
					memberPassportElem.notify( 'Please choose file', notifyErrorOpt );
					return false;
				}

				$(".liftSHWizardFrm #progressbar li").eq( $(".liftSHWizardFrm fieldset").index(next_fs_lsh) ).addClass("active");
				next_fs_lsh.show();
				current_fs_lsh.animate({opacity: 0}, {
					step: function(now) {
						opacity_lsh = 1 - now;
		
						current_fs_lsh.css({
							'display': 'none',
							'position': 'relative'
						});
						next_fs_lsh.css({'opacity': opacity_lsh});
					},
					duration: 500
				});
				setProgressBar_lsh(++current_lsh);

			}else if( current_lsh == 2 ){

				var piece_paper_wallet_address = $('body').find('.liftSHWizardFrm input[name="piece_paper_wallet_address"]').val();
				var piecePaperWalletAddressElem = $('body').find('.liftSHWizardFrm input[name="piece_paper_wallet_address"]');
				if( typeof piece_paper_wallet_address  === "undefined" || piece_paper_wallet_address == "" ){
					piecePaperWalletAddressElem.notify( 'Please choose file', notifyErrorOpt );
					return false;
				}

				$(".liftSHWizardFrm #progressbar li").eq( $(".liftSHWizardFrm fieldset").index(next_fs_lsh) ).addClass("active");
				next_fs_lsh.show();
				current_fs_lsh.animate({opacity: 0}, {
					step: function(now) {
						opacity_lsh = 1 - now;

						current_fs_lsh.css({
							'display': 'none',
							'position': 'relative'
						});
						next_fs_lsh.css({'opacity': opacity_lsh});
					},
					duration: 500
				});
				setProgressBar_lsh(++current_lsh);

			}else{
				$(".liftSHWizardFrm #progressbar li").eq( $(".liftSHWizardFrm fieldset").index(next_fs_lsh) ).addClass("active");
				next_fs_lsh.show();
				current_fs_lsh.animate({opacity: 0}, {
					step: function(now) {
						opacity_lsh = 1 - now;
		
						current_fs_lsh.css({
							'display': 'none',
							'position': 'relative'
						});
						next_fs_lsh.css({'opacity': opacity_lsh});
					},
					duration: 500
				});
				setProgressBar_lsh(++current_lsh);
			}
		});

		$('body').on("click","#liftSecurityHoldPopup .previous", function(){
			current_fs_lsh = $(this).closest('fieldset');
			previous_fs_lsh = $(this).closest('fieldset').prev();
			// console.log( current );

			$(".liftSHWizardFrm #progressbar li").eq($(".liftSHWizardFrm fieldset").index(current_fs_lsh)).removeClass("active");

			previous_fs_lsh.show();

			current_fs_lsh.animate({opacity: 0}, {
				step: function(now) {
					opacity_lsh = 1 - now;

					current_fs_lsh.css({
					'display': 'none',
					'position': 'relative'
					});
					previous_fs_lsh.css({'opacity': opacity_lsh});
				},
				duration: 500
			});
			setProgressBar_lsh(--current_lsh);
		});

		function setProgressBar_lsh(curStep){
			var percent = parseFloat(100 / steps_lsh) * curStep;
			percent = percent.toFixed();
			$('body .liftSHWizardFrm').find(".progress-bar").css("width",percent+"%")
		}

		$('body').on("change", "input[name='member_passport']", function(e){
			var is_error = false;
			var this_ext = $(this).val().split('.').pop().toLowerCase();
			var thisElement = $(this);
			if($.inArray(this_ext, ['png', 'jpg', 'jpeg']) == -1) {
				is_error = true;
				$(this).notify( 'Choose valid Photo ID file format', notifyErrorOpt );
				$(this).val('');
				return false;
			}
			if( this.files[0].size > 8000000 ){
				$(this).notify( 'Photo ID file size exceeds 8MB', notifyErrorOpt );
				$(this).val('');
			}
		});

		$('body').on("change", "input[name='piece_paper_wallet_address']", function(e){
			var is_error = false;
			var this_ext = $(this).val().split('.').pop().toLowerCase();
			var thisElement = $(this);
			if($.inArray(this_ext, ['png', 'jpg', 'jpeg']) == -1) {
				is_error = true;
				$(this).notify( 'Choose valid Selfie file format', notifyErrorOpt );
				$(this).val('');
				return false;
			}
			if( this.files[0].size > 8000000 ){
				$(this).notify( 'Selfie file size exceeds 8MB', notifyErrorOpt );
				$(this).val('');
			}
		});

	}

	//reject lsh csr address
	$('body').on('click', '#csr_lsh_pending_review .reject_lsh_csraddress', function(){
		var data = cipscript.actionRejectCsrAddressLsh;
		data['thisid'] = $(this).attr('data-id');
		var current_tr = $(this).closest('tr');
		Swal({
		title: 'Reject!',
		text: "Enter the reason for rejection.",
		input: 'text',
		showCancelButton: true,
		confirmButtonText: 'Reject',
		inputValidator: (rejectMsg) => {
			if (!rejectMsg) {
			return 'Please enter the reason for rejection.'
			}
		},
		preConfirm:(rejectMsg) => {
			if( rejectMsg == "" ){
				Swal.showValidationMessage( `Please enter the reason for rejection.` );
			}else{
				return { isConfirmed: 1 , rejectMsg : rejectMsg };
			}
		},
		allowOutsideClick: () => !Swal.isLoading()
		}).then((result) => {
			// console.log( result );
			if (result.value.isConfirmed) {
				current_tr.block( block_config );
				data['rejectMsg'] = result.value.rejectMsg;
				jQuery.ajax({ 
					type: "post",
					data: data,
					cache: false,
					url: cipscript.ajax_url,
					success: function(response){
						var obj = JSON.parse( response );
						if( obj.error == 0 ){
							window.location.reload();
						}else{
							Swal.fire({ type: 'error', title: obj.msg, text: '',allowOutsideClick: true});
						}
						current_tr.unblock();
					}
				});
			}
		});
		return false;
	});

	//approved csr address
	$('body').on('click', '#csr_lsh_pending_review .approve_lsh_csraddress', function(){
		var data = cipscript.actionApprovedCsrAddressLsh;
		data['thisid'] = $(this).attr('data-id');
		var current_tr = $(this).closest('tr');
		Swal({
		title: 'Are you sure?',
		text: "Do you want to approve?",
		type: 'warning',
		showCancelButton: true,
		confirmButtonText: 'Yes'
		}).then((result) => {
		if (result.value) {
			current_tr.block( block_config );
			jQuery.ajax({ 
				type: "post",
				data: data,
				cache: false,
				url: cipscript.ajax_url,
				success: function(response){
					var obj = JSON.parse( response );
					if( obj.error == 0 ){
						window.location.reload();
					}else{
						Swal.fire({ type: 'error', title: obj.msg, text: '',allowOutsideClick: true});
					}
					current_tr.unblock();
				}
			});
		}
		});
		return false;
	});

	//5690 KYC
	if( $('.memberKycAccountTypeFrm').length > 0 ){
		$('body').on('submit', '.memberKycAccountTypeFrm', function(){
			var $form = $(this);
			var data = new FormData( $form[0] );
			$form.block( block_config_kyc );
			$.ajax({
				url			: cipscript.ajax_url,
				type		: 'post',
				data		: data,
				processData	: false,
				contentType	: false,
				success : function(response){
					var obj = $.parseJSON(response);
					console.dir( obj );
					if( obj.error == 0 ){
						// swalToast({ type: 'success', title: obj.msg });
						$('body').find(".memberKycAccountTypeFrm .progress-bar").css("width","100%");
						setTimeout(() => {
							window.location.reload();
						}, 1000);
					}else{
						swalToast({ type: 'error', title: obj.msg });
					}
					$form.unblock();
				}
			});
			return false;
		});
	}
	//KYB
	if( $('.memberKybFrm').length > 0 ){
		
		var notifyErrorConfig = {position:"top",className: 'error',autoHide:true,autoHideDelay: 4000,clickToHide: true};
		var notifyErrorConfigField = {position:"bottom",className: 'error',autoHide:true,autoHideDelay: 4000,clickToHide: true};

		var block_config_kyc = { css: { backgroundColor: 'transparent', border: 'none' }, message: '<div class="blockUIspinner"></div>', baseZ: 1500, overlayCSS: { backgroundColor: '#FFFFFF', opacity: 0.8, cursor: 'wait' } };

		const business_contact_number = document.querySelector("#business_contact_number");
		var itiBCN = window.intlTelInput(business_contact_number, {
			utilsScript: "//cdn.jsdelivr.net/npm/intl-tel-input@18.2.1/build/js/utils.js",
			// autoInsertDialCode: true,
			separateDialCode: true,
			autoPlaceholder: "off",
			formatOnDisplay: false,
			initialCountry:  $('#business_contact_number').attr('data-country'),
		});

        var current_fs, next_fs, previous_fs; //fieldsets
		var opacity;
		var current = 1;
		var steps = $('body').find(".memberKybFrm fieldset").length;
        setProgressBarKyb(current);

		var $form = $('body').find('.memberKybFrm'); 
		$('body').on("click",".memberKybFrm .next", function(event){
			// var this_next = $(this);
			var this_next = $('form.memberKybFrm .responseSection');
			current_fs = $(this).closest('fieldset');
			next_fs = $(this).closest('fieldset').next();
			console.log( current );
			
			if( current == 2 ){
				
				var business_name = $form.find('#business_name').val();
				var business_registration_country = $form.find('#business_registration_country').val();
				var business_registration_number = $form.find('#business_registration_number').val();
				var business_type_of_business = $form.find('#business_type_of_business').val();
				var business_nature_of_your_business = $form.find('#business_nature_of_your_business').val();
				
				if( business_name == "" ){
					this_next.notify( 'Business Name is required', notifyErrorConfig );
					return false;
				}
				if( business_registration_country == "" ){
					this_next.notify( 'Registration Country is required', notifyErrorConfig );
					return false;
				}
				if( business_registration_number == "" ){
					this_next.notify( 'Registration number is required', notifyErrorConfig );
					return false;
				}
				if( business_type_of_business == "" ){
					this_next.notify( 'Type of Business is required', notifyErrorConfig );
					return false;
				}
				if( business_nature_of_your_business == "" ){
					this_next.notify( 'What is the nature of your business is required', notifyErrorConfig );
					return false;
				}

				var data = new FormData( $form[0] );
				data.append("step", '2');
				$form.block( block_config_kyc );
				$.ajax({
					url			: cipscript.ajax_url,
					type		: 'post',
					data		: data,
					processData	: false,
					contentType	: false,
					success : function(response){
						var obj = $.parseJSON(response);
						console.dir( obj );
						if( obj.error == 0 ){

							$(".memberKybFrm #progressbar li").eq( $(".memberKybFrm fieldset").index(next_fs) ).addClass("active");
							next_fs.show();
							current_fs.animate({opacity: 0}, {
								step: function(now) {
									opacity = 1 - now;
					
									current_fs.css({
										'display': 'none',
										'position': 'relative'
									});
									next_fs.css({'opacity': opacity});
								},
								duration: 500
							});
							setProgressBarKyb(++current);

						}else{
							Swal.fire({ type: 'error', title: obj.msg, text: '',allowOutsideClick: false});
						}
						$form.unblock();

					}
				});


			}else if( current == 3 ){

				var business_registered_address = $form.find('#business_registered_address').val();
				var business_registered_city = $form.find('#business_registered_city').val();
				var business_registered_state = $form.find('#business_registered_state').val();
				var business_registered_postal_code = $form.find('#business_registered_postal_code').val();
				var business_registered_country = $form.find('#business_registered_country').val();

				if( business_registered_address == "" ){
					this_next.notify( 'Registered Address is required', notifyErrorConfig );
					return false;
				}
				if( business_registered_city == "" ){
					this_next.notify( 'Registered City is required', notifyErrorConfig );
					return false;
				}
				if( business_registered_state == "" ){
					this_next.notify( 'Registered State is required', notifyErrorConfig );
					return false;
				}
				if( business_registered_postal_code == "" ){
					this_next.notify( 'Registered ZIP/Postal Code is required', notifyErrorConfig );
					return false;
				}
				if( business_registered_country == "" ){
					this_next.notify( 'Registered Country is required', notifyErrorConfig );
					return false;
				}

				if( !$('input[name="business_same_as_registered_address"]').is(':checked') ){
					var business_operating_address = $form.find('#business_operating_address').val();
					var business_operating_city = $form.find('#business_operating_city').val();
					var business_operating_state = $form.find('#business_operating_state').val();
					var business_operating_postal_code = $form.find('#business_operating_postal_code').val();
					var business_operating_country = $form.find('#business_operating_country').val();

					if( business_operating_address == "" ){
						this_next.notify( 'Operating business address is required', notifyErrorConfig );
						return false;
					}
					if( business_operating_city == "" ){
						this_next.notify( 'Operating business city is required', notifyErrorConfig );
						return false;
					}
					if( business_operating_state == "" ){
						this_next.notify( 'Operating business state is required', notifyErrorConfig );
						return false;
					}
					if( business_operating_postal_code == "" ){
						this_next.notify( 'Operating business zip/postal Code is required', notifyErrorConfig );
						return false;
					}
					if( business_operating_country == "" ){
						this_next.notify( 'Operating business country is required', notifyErrorConfig );
						return false;
					}
				}

				/* var business_contact_number_val = $form.find('#business_contact_number').val();
				if( business_contact_number_val == "" ){
					this_next.notify( 'Contact number is required', notifyErrorConfig );
					return false;
				} */

				//Declarations
				var business_aware_of_any_sanctions = $form.find('input[name="business_aware_of_any_sanctions"]:checked').val();
				var business_undergone_any_external_audits = $form.find('input[name="business_undergone_any_external_audits"]:checked').val();
				var business_business_involved_in_any_money_laundering = $form.find('input[name="business_business_involved_in_any_money_laundering"]:checked').val();
				var business_received_any_penalties = $form.find('input[name="business_received_any_penalties"]:checked').val();

				if( typeof business_aware_of_any_sanctions  === "undefined" || typeof business_undergone_any_external_audits  === "undefined" || typeof business_business_involved_in_any_money_laundering  === "undefined" || typeof business_received_any_penalties  === "undefined" ){
					this_next.notify( 'Declarations is required', notifyErrorConfig );
					return false;
				}

				var itiBCNData = itiBCN.getSelectedCountryData();
				var data = new FormData( $form[0] );
				data.append("step", '3');
				data.append("business_contact_country", itiBCNData.iso2 );
				data.append("business_contact_dial_code", itiBCNData.dialCode );
				$form.block( block_config_kyc );
				$.ajax({
					url			: cipscript.ajax_url,
					type		: 'post',
					data		: data,
					processData	: false,
					contentType	: false,
					success : function(response){
						var obj = $.parseJSON(response);
						console.dir( obj );
						if( obj.error == 0 ){

							$(".memberKybFrm #progressbar li").eq( $(".memberKybFrm fieldset").index(next_fs) ).addClass("active");
							next_fs.show();
							current_fs.animate({opacity: 0}, {
								step: function(now) {
									opacity = 1 - now;
					
									current_fs.css({
										'display': 'none',
										'position': 'relative'
									});
									next_fs.css({'opacity': opacity});
								},
								duration: 500
							});
							setProgressBarKyb(++current);

						}else{
							Swal.fire({ type: 'error', title: obj.msg, text: '',allowOutsideClick: false});
						}
						$form.unblock();

					}
				});

			}else if( current == 4 ){

				var business_director_first_name = $form.find('#business_director_first_name').val();
				var business_director_last_name = $form.find('#business_director_last_name').val();
				var business_director_dob = $form.find('#business_director_dob').val();
				var business_director_address = $form.find('#business_director_address').val();
				var business_director_city = $form.find('#business_director_city').val();
				var business_director_state = $form.find('#business_director_state').val();
				var business_director_postal_code = $form.find('#business_director_postal_code').val();
				var business_director_country = $form.find('#business_director_country').val();
				var business_director_person_politically_exposed = $form.find('input[name="business_director_person_politically_exposed"]:checked').val();

				if( business_director_first_name == "" ){
					this_next.notify( 'Director first name is required', notifyErrorConfig );
					return false;
				}
				if( business_director_last_name == "" ){
					this_next.notify( 'Director last name is required', notifyErrorConfig );
					return false;
				}
				if( business_director_dob == "" ){
					this_next.notify( 'Director date of birth is required', notifyErrorConfig );
					return false;
				}
				if( business_director_address == "" ){
					this_next.notify( 'Director Address is required', notifyErrorConfig );
					return false;
				}
				if( business_director_city == "" ){
					this_next.notify( 'Director City is required', notifyErrorConfig );
					return false;
				}
				if( business_director_state == "" ){
					this_next.notify( 'Director State is required', notifyErrorConfig );
					return false;
				}
				if( business_director_postal_code == "" ){
					this_next.notify( 'Director ZIP/Postal Code is required', notifyErrorConfig );
					return false;
				}
				if( business_director_country == "" ){
					this_next.notify( 'Director Country is required', notifyErrorConfig );
					return false;
				}
				if( typeof business_director_person_politically_exposed === "undefined" ){
					this_next.notify( 'Director person politically exposed is required', notifyErrorConfig );
					return false;
				}

				if( !$('input[name="business_owner_details_same_as_director"]').is(':checked') ){
					var business_owner_first_name = $form.find('#business_owner_first_name').val();
					var business_owner_last_name = $form.find('#business_owner_last_name').val();
					var business_owner_dob = $form.find('#business_owner_dob').val();
					var business_owner_address = $form.find('#business_owner_address').val();
					var business_owner_city = $form.find('#business_owner_city').val();
					var business_owner_state = $form.find('#business_owner_state').val();
					var business_owner_postal_code = $form.find('#business_owner_postal_code').val();
					var business_owner_country = $form.find('#business_owner_country').val();
					var business_owner_person_politically_exposed = $form.find('input[name="business_owner_person_politically_exposed"]:checked').val();

					if( business_owner_first_name == "" ){
						this_next.notify( 'Business Owner first name is required', notifyErrorConfig );
						return false;
					}
					if( business_owner_last_name == "" ){
						this_next.notify( 'Business Owner last name is required', notifyErrorConfig );
						return false;
					}
					if( business_owner_dob == "" ){
						this_next.notify( 'Business Owner date of birth is required', notifyErrorConfig );
						return false;
					}
					if( business_owner_address == "" ){
						this_next.notify( 'Business Owner Address is required', notifyErrorConfig );
						return false;
					}
					if( business_owner_city == "" ){
						this_next.notify( 'Business Owner City is required', notifyErrorConfig );
						return false;
					}
					if( business_owner_state == "" ){
						this_next.notify( 'Business Owner State is required', notifyErrorConfig );
						return false;
					}
					if( business_owner_postal_code == "" ){
						this_next.notify( 'Business Owner ZIP/Postal Code is required', notifyErrorConfig );
						return false;
					}
					if( business_owner_country == "" ){
						this_next.notify( 'Business Owner Country is required', notifyErrorConfig );
						return false;
					}
					if( typeof business_owner_person_politically_exposed === "undefined" ){
						this_next.notify( 'Business Owner person politically exposed is required', notifyErrorConfig );
						return false;
					}
				}

				var data = new FormData( $form[0] );
				data.append("step", '4');
				$form.block( block_config_kyc );
				$.ajax({
					url			: cipscript.ajax_url,
					type		: 'post',
					data		: data,
					processData	: false,
					contentType	: false,
					success : function(response){
						var obj = $.parseJSON(response);
						console.dir( obj );
						if( obj.error == 0 ){

							$(".memberKybFrm #progressbar li").eq( $(".memberKybFrm fieldset").index(next_fs) ).addClass("active");
							next_fs.show();
							current_fs.animate({opacity: 0}, {
								step: function(now) {
									opacity = 1 - now;
					
									current_fs.css({
										'display': 'none',
										'position': 'relative'
									});
									next_fs.css({'opacity': opacity});
								},
								duration: 500
							});
							setProgressBarKyb(++current);

						}else{
							Swal.fire({ type: 'error', title: obj.msg, text: '',allowOutsideClick: false});
						}
						$form.unblock();

					}
				});

			}else if( current == 5 ){

				var business_certificate_of_incorporation = $form.find('#business_certificate_of_incorporation').val();
				var business_shareholder_certificate = $form.find('#business_shareholder_certificate').val();
				var business_proof_address = $form.find('input[id="business_proof_address"]').val();

				if( business_certificate_of_incorporation != "" || business_shareholder_certificate != "" || business_proof_address != "" ){
					block_config_kyc = { css: { backgroundColor: 'transparent', border: 'none' }, message: '<div class="blockUIspinner"></div><h5>Please wait while we are uploading your documents.</h5>', baseZ: 1500, overlayCSS: { backgroundColor: '#FFFFFF', opacity: 0.8, cursor: 'wait' } };
				}else{
					block_config_kyc = { css: { backgroundColor: 'transparent', border: 'none' }, message: '<div class="blockUIspinner"></div>', baseZ: 1500, overlayCSS: { backgroundColor: '#FFFFFF', opacity: 0.8, cursor: 'wait' } };
				}

				var data = new FormData( $form[0] );
				data.append("step", '5');
				$form.block( block_config_kyc );
				$.ajax({
					url			: cipscript.ajax_url,
					type		: 'post',
					data		: data,
					processData	: false,
					contentType	: false,
					success : function(response){
						var obj = $.parseJSON(response);
						console.dir( obj );
						if( obj.error == 0 ){

							$(".memberKybFrm #progressbar li").eq( $(".memberKybFrm fieldset").index(next_fs) ).addClass("active");
							next_fs.show();
							current_fs.animate({opacity: 0}, {
								step: function(now) {
									opacity = 1 - now;
					
									current_fs.css({
										'display': 'none',
										'position': 'relative'
									});
									next_fs.css({'opacity': opacity});
								},
								duration: 500
							});
							setProgressBarKyb(++current);

						}else{
							Swal.fire({ type: 'error', title: obj.msg, text: '',allowOutsideClick: false});
						}
						$form.unblock();

					}
				});

			}else if( current == 6 ){

				var business_director_passport_national_id = $form.find('input[id="business_director_passport_national_id"]').val();
				var business_director_proof_address = $form.find('input[id="business_director_proof_address"]').val();
				
				var business_owner_passport_national_id = $form.find('input[id="business_owner_passport_national_id"]').val();
				var business_owner_proof_address = $form.find('input[id="business_owner_proof_address"]').val();

				if( business_director_passport_national_id != "" || business_director_proof_address != "" || business_owner_passport_national_id != "" || business_owner_proof_address != "" ){
					block_config_kyc = { css: { backgroundColor: 'transparent', border: 'none' }, message: '<div class="blockUIspinner"></div><h5>Please wait while we are uploading your documents.</h5>', baseZ: 1500, overlayCSS: { backgroundColor: '#FFFFFF', opacity: 0.8, cursor: 'wait' } };
				}else{
					block_config_kyc = { css: { backgroundColor: 'transparent', border: 'none' }, message: '<div class="blockUIspinner"></div>', baseZ: 1500, overlayCSS: { backgroundColor: '#FFFFFF', opacity: 0.8, cursor: 'wait' } };
				}

				var data = new FormData( $form[0] );
				data.append("step", '6');
				$form.block( block_config_kyc );
				$.ajax({
					url			: cipscript.ajax_url,
					type		: 'post',
					data		: data,
					processData	: false,
					contentType	: false,
					success : function(response){
						var obj = $.parseJSON(response);
						console.dir( obj );
						if( obj.error == 0 ){

							$(".memberKybFrm #progressbar li").eq( $(".memberKybFrm fieldset").index(next_fs) ).addClass("active");
							next_fs.show();
							current_fs.animate({opacity: 0}, {
								step: function(now) {
									opacity = 1 - now;
					
									current_fs.css({
										'display': 'none',
										'position': 'relative'
									});
									next_fs.css({'opacity': opacity});
								},
								duration: 500
							});
							setProgressBarKyb(++current);

						}else{
							Swal.fire({ type: 'error', title: obj.msg, text: '',allowOutsideClick: false});
						}
						$form.unblock();

					}
				});

			}else if( current == 7 ){

				block_config_kyc = { css: { backgroundColor: 'transparent', border: 'none' }, message: '<div class="blockUIspinner"></div>', baseZ: 1500, overlayCSS: { backgroundColor: '#FFFFFF', opacity: 0.8, cursor: 'wait' } };

				var consent_my_data_share = $form.find('input[name="consent_my_data_share"]:checked').val();
				var confirm_correct_info = $form.find('input[name="confirm_correct_info"]:checked').val();

				if( typeof consent_my_data_share  === "undefined" || consent_my_data_share == "" ){
					this_next.notify( 'consent to my data being shared with all companies in the corsair group is required', notifyErrorConfig );
					return false;
				}
				if( confirm_correct_info != 'Yes' ){
					this_next.notify( 'Please confirm the information submitted in this form is complete and correct', notifyErrorConfig );
					return false;
				}

				var data = new FormData( $form[0] );
				data.append("step", '7');
				$form.block( block_config_kyc );
				$.ajax({
					url			: cipscript.ajax_url,
					type		: 'post',
					data		: data,
					processData	: false,
					contentType	: false,
					success : function(response){
						var obj = $.parseJSON(response);
						if( obj.error == 0 ){
							Swal.fire({ type: 'success', title: obj.msg, text: '',allowOutsideClick: true}).then(function(){window.location.reload();});
						}else{
							Swal.fire({ type: 'error', title: obj.msg, text: '',allowOutsideClick: false});
						}
						$form.unblock();

					}
				});

			}
		});
		// const kycStep = cipscript.kycStep;
		const kybStep = 2;
		if( kybStep > 1 ){
			go_to_x_step_kyb( kybStep );
		}

		function go_to_x_step_kyb( gotoStep = 0 ){
			for (let step = 0; step < (gotoStep - 1 ); step++) {
				var $next_button = $('.step_'+step).find('.next');
				
				var current_fs = $next_button.parent();
				var next_fs = $next_button.parent().next();
	
				$(".memberKybFrm #progressbar li").eq( $("fieldset").index(next_fs) ).addClass("active");
				next_fs.show();
				current_fs.css({
					'display': 'none',
					'position': 'relative'
				});
				next_fs.css({'opacity': opacity});
				setProgressBarKyb(++current);
			}
		}

		$('body').on("click",".memberKybFrm .previous", function(){
			current_fs = $(this).closest('fieldset');
			previous_fs = $(this).closest('fieldset').prev();
			console.log(current);
			if( current == 2 ){
				var data = new FormData( $form[0] );
				data.append("step", 'account_type');
				$form.block( block_config_kyc );
				$.ajax({
					url			: cipscript.ajax_url,
					type		: 'post',
					data		: data,
					processData	: false,
					contentType	: false,
					success : function(response){
						var obj = $.parseJSON(response);
						if( obj.error == 0 ){
							// Swal.fire({ type: 'success', title: obj.msg, text: '',allowOutsideClick: true});
							window.location.reload();
						}else{
							Swal.fire({ type: 'error', title: obj.msg, text: '',allowOutsideClick: false});
						}
						$form.unblock();

					}
				});
			}else{
				$(".memberKybFrm #progressbar li").eq($(".memberKybFrm fieldset").index(current_fs)).removeClass("active");
				previous_fs.show();
				current_fs.animate({opacity: 0}, {
					step: function(now) {
						opacity = 1 - now;
	
						current_fs.css({
						'display': 'none',
						'position': 'relative'
						});
						previous_fs.css({'opacity': opacity});
					},
					duration: 500
				});
				setProgressBarKyb(--current);
			}
		});

		function setProgressBarKyb(curStep){
			var percent = parseFloat(100 / steps) * curStep;
			percent = percent.toFixed();
			$('body').find(".memberKybFrm .progress-bar").css("width",percent+"%")
		}

		// var full_number = phone_number.getNumber(intlTelInputUtils.numberFormat.E164);
		// $("input[name='phone_number[full]'").val(full_number);

		$("#business_contact_number").bind("input", function () {
			var c = this.selectionStart,
			  r = /[^0-9]/gi,
			  v = $(this).val();
			if( r.test(v) ){
			  $(this).val(v.replace(r, ""));
			  c--;
			}
			this.setSelectionRange(c, c);
		});

		$("#business_name, #business_registration_number").bind("input", function () {
			var c = this.selectionStart,
			  r = /[^a-z0-9-_/(). ]/gi,
			  v = $(this).val();
			if( r.test(v) ){
			  $(this).val(v.replace(r, ""));
			  c--;
			}
			this.setSelectionRange(c, c);
		});
		$("#business_registered_city, #business_operating_city, #business_director_city, #business_owner_city, #business_registered_state, #business_operating_state, #business_director_state, #business_owner_state").bind("input", function () {
			var c = this.selectionStart,
			  r = /[^a-z- ]/gi,
			  v = $(this).val();
			if( r.test(v) ){
			  $(this).val(v.replace(r, ""));
			  c--;
			}
			this.setSelectionRange(c, c);
		});
		$("#business_director_first_name, #business_director_last_name, #business_owner_first_name, #business_owner_last_name").bind("input", function () {
			var c = this.selectionStart,
			  r = /[^a-z-_ ]/gi,
			  v = $(this).val();
			if( r.test(v) ){
			  $(this).val(v.replace(r, ""));
			  c--;
			}
			this.setSelectionRange(c, c);
		});
		
		$("#business_operating_postal_code, #business_director_postal_code, #business_owner_postal_code, #business_registered_postal_code").bind("input", function () {
			var c = this.selectionStart,
			  r = /[^a-z0-9-_.()/ ]/gi,
			  v = $(this).val();
			if( r.test(v) ){
			  $(this).val(v.replace(r, ""));
			  c--;
			}
			this.setSelectionRange(c, c);
		});

		$("#business_registered_address, #business_registered_address_line_2, #business_operating_address, #business_operating_address_line_2, #business_director_address, #business_director_address_line_2, #business_owner_address, #business_owner_address_line_2").bind("input", function () {
			var c = this.selectionStart,
			//   r = /[^a-z0-9-_, ]/gi,
			  r = /[^a-z0-9-_.()/ ]/gi,
			  v = $(this).val();
			if( r.test(v) ){
			  $(this).val(v.replace(r, ""));
			  c--;
			}
			this.setSelectionRange(c, c);
		});

		$('body').on('change', '#business_same_as_registered_address', function(){
			if( $(this).is(':checked') ){
				$('.operating_business_address_section').slideUp();
				$('#business_operating_address').val( $('#business_registered_address').val() );
				$('#business_operating_address_line_2').val( $('#business_registered_address_line_2').val() );
				$('#business_operating_city').val( $('#business_registered_city').val() );
				$('#business_operating_state').val( $('#business_registered_state').val() );
				$('#business_operating_postal_code').val( $('#business_registered_postal_code').val() );
				$('#business_operating_country').val( $('#business_registered_country').val() );
			}else{
				$('.operating_business_address_section').slideDown();
				$('#business_operating_address').val('');
				$('#business_operating_address_line_2').val('');
				$('#business_operating_city').val('');
				$('#business_operating_state').val('');
				$('#business_operating_postal_code').val('');
				$('#business_operating_country').val('');
			}
		});
		
		$('body').on('change', '#business_director_details_same_as_owner', function(){
			if( $(this).is(':checked') ){
				$('.business_director_section').slideUp();
				$('.business_director_upload_document_section').hide();
				$('#business_director_first_name').val( $('#business_owner_first_name').val() );
				$('#business_director_last_name').val( $('#business_owner_last_name').val() );
				$('#business_director_dob').val( $('#business_owner_dob').val() );
				$('#business_director_address').val( $('#business_owner_address').val() );
				$('#business_director_address_line_2').val( $('#business_owner_address_line_2').val() );
				$('#business_director_city').val( $('#business_owner_city').val() );
				$('#business_director_state').val( $('#business_owner_state').val() );
				$('#business_director_postal_code').val( $('#business_owner_postal_code').val() );
				$('#business_director_country').val( $('#business_owner_country').val() );
				$("input[name=business_director_person_politically_exposed][value=" + $('input[name="business_owner_person_politically_exposed"]:checked').val() + "]").prop('checked', true);
			}else{
				$('.business_director_section').slideDown();
				$('.business_director_upload_document_section').show();
				$('#business_director_first_name').val('');
				$('#business_director_last_name').val('');
				$('#business_director_dob').val('');
				$('#business_director_address').val('');
				$('#business_director_address_line_2').val('');
				$('#business_director_city').val('');
				$('#business_director_state').val('');
				$('#business_director_postal_code').val('');
				$('#business_director_country').val('');
				$('input[name="business_director_person_politically_exposed"]').prop('checked', false);
			}
		});

		var datepicker_options = {
			altFormat: "dd/mm/yyyy",
			dateFormat: "dd/mm/yyyy",
			maxDate: "-18Y",
			changeMonth: true,
			changeYear: true
		  };
		var inputmask_options = {
			inputFormat:'dd/mm/yyyy',
			alias: "datetime",
			placeholder: "dd/mm/yyyy",
		};

		
		if( $('#business_director_dob').length > 0 ){		
			$("#business_director_dob").inputmask(inputmask_options);
			// var startDateDob = new Date(1900,0,1);
			// var startDateDob = new Date(new Date().getFullYear() - 100, 0, 1);
			$('#business_director_dob').datepicker({
				format: "dd/mm/yyyy",
				endDate: "-18Y",
				startDate:  "-120Y",
				autoclose: true,
				clearBtn: true,
			}).on('hide', function(e) {
				if( typeof e.date  === "undefined" || e.date == "" ){
					$(this).notify( 'Date Of birth must be 18 years old', notifyErrorConfigField );
				}
			});
		}
		if( $('#business_owner_dob').length > 0 ){		
			$("#business_owner_dob").inputmask(inputmask_options);
			// var startDateDob = new Date(1900,0,1);
			// var startDateDob = new Date(new Date().getFullYear() - 100, 0, 1);
			$('#business_owner_dob').datepicker({
				format: "dd/mm/yyyy",
				endDate: "-18Y",
				startDate:  "-120Y",
				autoclose: true,
				clearBtn: true,
			}).on('hide', function(e) {
				if( typeof e.date  === "undefined" || e.date == "" ){
					$(this).notify( 'Date Of birth must be 18 years old', notifyErrorConfigField );
				}
			});
		}

		var imagesPreview = function(input, placeToInsertImagePreview) {
			if (input.files) {
				var filesAmount = input.files.length;
				var type = "";
				$(placeToInsertImagePreview).html('');
				for (i = 0; i < filesAmount; i++) {
					type = input.files[i].name.split('.').pop().toLowerCase();
					var reader = new FileReader(); 
					if( type == 'pdf' ){
						reader.onload = function(event) {
							$("<div><a href='javascript:void(0);'><img class='doc-img-thumbnail' src='"+ cipscript.cip_images_folder +"pdf.png' /></a></div>").appendTo(placeToInsertImagePreview);
						}
					}else{
						reader.onload = function(event) {
							$("<div><a href='javascript:void(0);'><img class='doc-img-thumbnail' src='"+ event.target.result +"' /></a></div>").appendTo(placeToInsertImagePreview);
						}
					}
					reader.readAsDataURL(input.files[i]);
				}
			}
		};

		$('body').on("change", "#business_certificate_of_incorporation", function(e){
			var thisInputFile = $(this);
			$('.business_certificate_of_incorporation.doc-grid_section').html('');
			if( this.files.length > 0 ){
                for (var i = 0; i < this.files.length; i++) {
					var this_ext = this.files[i].name.split('.').pop().toLowerCase();
					if($.inArray(this_ext, ['png', 'jpg', 'jpeg', 'pdf']) == -1) {
						thisInputFile.notify( 'Choose valid document file format', notifyErrorOpt );
						thisInputFile.val('');
						return false;
					}
					if( this.files[0].size > 10000000 ){
						thisInputFile.notify( 'document file size exceeds 10MB', notifyErrorOpt );
						thisInputFile.val('');
						return false;
					}
				}
			}
			if( $(this).val() != "" ){
				thisInputFile.addClass('active');
				$('.clear_business_certificate_of_incorporation').show();

				imagesPreview(this, '.business_certificate_of_incorporation.doc-grid_section');

			}else{
				thisInputFile.removeClass('active');
				$('.clear_business_certificate_of_incorporation').hide();
			}
		});

		$('body').on("click", ".clear_business_certificate_of_incorporation", function(e){
			$('#business_certificate_of_incorporation').val('').removeClass('active');
			$(this).hide();
			$('.business_certificate_of_incorporation.doc-grid_section').html('');
		});
		
		$('body').on("change", "#business_shareholder_certificate", function(e){
			var thisInputFile = $(this);
			$('.business_shareholder_certificate.doc-grid_section').html('');
			if( this.files.length > 0 ){
                for (var i = 0; i < this.files.length; i++) {
					var this_ext = this.files[i].name.split('.').pop().toLowerCase();
					if($.inArray(this_ext, ['png', 'jpg', 'jpeg', 'pdf']) == -1) {
						thisInputFile.notify( 'Choose valid document file format', notifyErrorOpt );
						thisInputFile.val('');
						return false;
					}
					if( this.files[0].size > 10000000 ){
						thisInputFile.notify( 'document file size exceeds 10MB', notifyErrorOpt );
						thisInputFile.val('');
						return false;
					}
				}
			}
			if( $(this).val() != "" ){
				thisInputFile.addClass('active');
				$('.clear_business_shareholder_certificate').show();

				imagesPreview(this, '.business_shareholder_certificate.doc-grid_section');
			}else{
				thisInputFile.removeClass('active');
				$('.clear_business_shareholder_certificate').hide();
			}
		});

		$('body').on("click", ".clear_business_shareholder_certificate", function(e){
			$('#business_shareholder_certificate').val('').removeClass('active');
			$(this).hide();
			$('.business_shareholder_certificate.doc-grid_section').html('');
		});

		$('body').on("change", "#business_proof_address", function(e){
			var thisInputFile = $(this);
			$('.business_proof_address.doc-grid_section').html('');
			if( this.files.length > 0 ){
                for (var i = 0; i < this.files.length; i++) {
					var this_ext = this.files[i].name.split('.').pop().toLowerCase();
					if($.inArray(this_ext, ['png', 'jpg', 'jpeg', 'pdf']) == -1) {
						thisInputFile.notify( 'Choose valid document file format', notifyErrorOpt );
						thisInputFile.val('');
						return false;
					}
					if( this.files[0].size > 10000000 ){
						thisInputFile.notify( 'document file size exceeds 10MB', notifyErrorOpt );
						thisInputFile.val('');
						return false;
					}
				}
			}
			if( $(this).val() != "" ){
				thisInputFile.addClass('active');
				$('.clear_business_proof_address').show();

				imagesPreview(this, '.business_proof_address.doc-grid_section');
			}else{
				thisInputFile.removeClass('active');
				$('.clear_business_proof_address').hide();
			}
		});

		$('body').on("click", ".clear_business_proof_address", function(e){
			$('#business_proof_address').val('').removeClass('active');
			$(this).hide();
			$('.business_proof_address.doc-grid_section').html('');
		});

		$('body').on("change", "#business_director_passport_national_id", function(e){
			var thisInputFile = $(this);
			$('.business_director_passport_national_id.doc-grid_section').html('');
			if( this.files.length > 0 ){
                for (var i = 0; i < this.files.length; i++) {
					var this_ext = this.files[i].name.split('.').pop().toLowerCase();
					if($.inArray(this_ext, ['png', 'jpg', 'jpeg', 'pdf']) == -1) {
						thisInputFile.notify( 'Choose valid document file format', notifyErrorOpt );
						thisInputFile.val('');
						return false;
					}
					if( this.files[0].size > 10000000 ){
						thisInputFile.notify( 'document file size exceeds 10MB', notifyErrorOpt );
						thisInputFile.val('');
						return false;
					}
				}
			}
			if( $(this).val() != "" ){
				thisInputFile.addClass('active');
				$('.clear_business_director_passport_national_id').show();

				imagesPreview(this, '.business_director_passport_national_id.doc-grid_section');
			}else{
				thisInputFile.removeClass('active');
				$('.clear_business_director_passport_national_id').hide();
			}
		});

		$('body').on("click", ".clear_business_director_passport_national_id", function(e){
			$('#business_director_passport_national_id').val('').removeClass('active');
			$(this).hide();
			$('.business_director_passport_national_id.doc-grid_section').html('');
		});

		$('body').on("change", "#business_director_proof_address", function(e){
			var thisInputFile = $(this);
			$('.business_director_proof_address.doc-grid_section').html('');
			if( this.files.length > 0 ){
                for (var i = 0; i < this.files.length; i++) {
					var this_ext = this.files[i].name.split('.').pop().toLowerCase();
					if($.inArray(this_ext, ['png', 'jpg', 'jpeg', 'pdf']) == -1) {
						thisInputFile.notify( 'Choose valid document file format', notifyErrorOpt );
						thisInputFile.val('');
						return false;
					}
					if( this.files[0].size > 10000000 ){
						thisInputFile.notify( 'document file size exceeds 10MB', notifyErrorOpt );
						thisInputFile.val('');
						return false;
					}
				}
			}
			if( $(this).val() != "" ){
				thisInputFile.addClass('active');
				$('.clear_business_director_proof_address').show();

				imagesPreview(this, '.business_director_proof_address.doc-grid_section');
			}else{
				thisInputFile.removeClass('active');
				$('.clear_business_director_proof_address').hide();
			}
		});

		$('body').on("click", ".clear_business_director_proof_address", function(e){
			$('#business_director_proof_address').val('').removeClass('active');
			$(this).hide();
			$('.business_director_proof_address.doc-grid_section').html('');
		});

		$('body').on("change", "#business_owner_passport_national_id", function(e){
			var thisInputFile = $(this);
			$('.business_owner_passport_national_id.doc-grid_section').html('');
			if( this.files.length > 0 ){
                for (var i = 0; i < this.files.length; i++) {
					var this_ext = this.files[i].name.split('.').pop().toLowerCase();
					if($.inArray(this_ext, ['png', 'jpg', 'jpeg', 'pdf']) == -1) {
						thisInputFile.notify( 'Choose valid document file format', notifyErrorOpt );
						thisInputFile.val('');
						return false;
					}
					if( this.files[0].size > 10000000 ){
						thisInputFile.notify( 'document file size exceeds 10MB', notifyErrorOpt );
						thisInputFile.val('');
						return false;
					}
				}
			}
			if( $(this).val() != "" ){
				thisInputFile.addClass('active');
				$('.clear_business_owner_passport_national_id').show();

				imagesPreview(this, '.business_owner_passport_national_id.doc-grid_section');
			}else{
				thisInputFile.removeClass('active');
				$('.clear_business_owner_passport_national_id').hide();
			}
		});

		$('body').on("click", ".clear_business_owner_passport_national_id", function(e){
			$('#business_owner_passport_national_id').val('').removeClass('active');
			$(this).hide();
			$('.business_owner_passport_national_id.doc-grid_section').html('');
		});

		$('body').on("change", "#business_owner_proof_address", function(e){
			var thisInputFile = $(this);
			$('.business_owner_proof_address.doc-grid_section').html('');
			if( this.files.length > 0 ){
                for (var i = 0; i < this.files.length; i++) {
					var this_ext = this.files[i].name.split('.').pop().toLowerCase();
					if($.inArray(this_ext, ['png', 'jpg', 'jpeg', 'pdf']) == -1) {
						thisInputFile.notify( 'Choose valid document file format', notifyErrorOpt );
						thisInputFile.val('');
						return false;
					}
					if( this.files[0].size > 10000000 ){
						thisInputFile.notify( 'document file size exceeds 10MB', notifyErrorOpt );
						thisInputFile.val('');
						return false;
					}
				}
			}
			if( $(this).val() != "" ){
				thisInputFile.addClass('active');
				$('.clear_business_owner_proof_address').show();

				imagesPreview(this, '.business_owner_proof_address.doc-grid_section');
			}else{
				thisInputFile.removeClass('active');
				$('.clear_business_owner_proof_address').hide();
			}
		});

		$('body').on("click", ".clear_business_owner_proof_address", function(e){
			$('#business_owner_proof_address').val('').removeClass('active');
			$(this).hide();
			$('.business_owner_proof_address.doc-grid_section').html('');
		});
	}

	//KYC
	if( $('.memberKycFrm').length > 0 ){

		var notifyErrorConfig = {position:"top",className: 'error',autoHide:true,autoHideDelay: 4000,clickToHide: true};
		var notifyErrorConfigField = {position:"bottom",className: 'error',autoHide:true,autoHideDelay: 4000,clickToHide: true};

		var block_config_kyc = { css: { backgroundColor: 'transparent', border: 'none' }, message: '<div class="blockUIspinner"></div>', baseZ: 1500, overlayCSS: { backgroundColor: '#FFFFFF', opacity: 0.8, cursor: 'wait' } };

        var current_fs, next_fs, previous_fs; //fieldsets
		var opacity;
		var current = 1;
		var steps = $('body').find(".memberKycFrm fieldset").length;
        setProgressBarGa(current);

		var $form = $('body').find('.memberKycFrm'); 
		$('body').on("click",".memberKycFrm .next", function(event){
			// var this_next = $(this);
			var this_next = $('form.memberKycFrm .responseSection');
			current_fs = $(this).closest('fieldset');
			next_fs = $(this).closest('fieldset').next();
			console.log( current );
			

			if( current == 2 ){
				
				var firstname = $form.find('#firstname').val();
				var lastname = $form.find('#lastname').val();
				var dob = $form.find('#dob').val();
				var gender = $form.find('#gender').val();
				var nationality = $form.find('#nationality').val();
				var idcard_passport_number = $form.find('#idcard_passport_number').val();
				var id_have_expiry = $form.find('#id_have_expiry:checked').val();
				var idcard_passport_expiry = $form.find('#idcard_passport_expiry').val();

				var country = $form.find('#country').val();
				var state = $form.find('#state').val();
				var city = $form.find('#city').val();
				var postal_code = $form.find('#postal_code').val();
				var address = $form.find('#address').val();

				if( firstname == "" ){
					this_next.notify( 'First Name is required', notifyErrorConfig );
					return false;
				}
				if( lastname == "" ){
					this_next.notify( 'Last Name is required', notifyErrorConfig );
					return false;
				}
				if( dob == "" ){
					this_next.notify( 'Date Of Birth is required', notifyErrorConfig );
					return false;
				}
				
				if( address == "" ){
					this_next.notify( 'Address is required', notifyErrorConfig );
					return false;
				}
				if( city == "" ){
					this_next.notify( 'City is required', notifyErrorConfig );
					return false;
				}
				if( state == "" ){
					this_next.notify( 'State is required', notifyErrorConfig );
					return false;
				}
				if( postal_code == "" ){
					this_next.notify( 'ZIP/Postal Code is required', notifyErrorConfig );
					return false;
				}
				if( country == "" ){
					this_next.notify( 'Country is required', notifyErrorConfig );
					return false;
				}

				var data = new FormData( $form[0] );
				data.append("step", '2');
				$form.block( block_config_kyc );
				$.ajax({
					url			: cipscript.ajax_url,
					type		: 'post',
					data		: data,
					processData	: false,
					contentType	: false,
					success : function(response){
						var obj = $.parseJSON(response);
						console.dir( obj );
						if( obj.error == 0 ){

							$(".memberKycFrm #progressbar li").eq( $(".memberKycFrm fieldset").index(next_fs) ).addClass("active");
							next_fs.show();
							current_fs.animate({opacity: 0}, {
								step: function(now) {
									opacity = 1 - now;
					
									current_fs.css({
										'display': 'none',
										'position': 'relative'
									});
									next_fs.css({'opacity': opacity});
								},
								duration: 500
							});
							setProgressBarGa(++current);

						}else{
							Swal.fire({ type: 'error', title: obj.msg, text: '',allowOutsideClick: false});
						}
						$form.unblock();

					}
				});


			}else if( current == 3 ){

				var document_type = $form.find('#document_type').val();
				var document_number = $form.find('#document_number').val();
				var issuing_country = $form.find('#issuing_country').val();
				var issue_date = $form.find('#issue_date').val();
				var expiration_date = $form.find('#expiration_date').val();
				var id_no_have_issue_date = $form.find('#id_no_have_issue_date:checked').val();
				var id_no_have_expiry = $form.find('#id_no_have_expiry:checked').val();
				var nationality = $form.find('#nationality').val();
				var identification_document = $form.find('input[id="identification_document"]').val();

				if( document_type == "" ){
					this_next.notify( 'Document Type is required', notifyErrorConfig );
					return false;
				}
				if( document_number == "" ){
					this_next.notify( 'Document Number is required', notifyErrorConfig );
					return false;
				}
				if( issuing_country == "" ){
					this_next.notify( 'Issuing Country is required', notifyErrorConfig );
					return false;
				}
				if( typeof id_no_have_issue_date  === "undefined" ){
					if( issue_date == "" ){
						this_next.notify( 'Issue Date is required', notifyErrorConfig );
						return false;
					}
				}
				if( typeof id_no_have_expiry  === "undefined" ){
					if( expiration_date == "" ){
						this_next.notify( 'Expiration Date is required', notifyErrorConfig );
						return false;
					}
				}
				
				if( nationality == "" ){
					this_next.notify( 'Nationality is required', notifyErrorConfig );
					return false;
				}
				/* if( typeof identification_document  === "undefined" || identification_document == "" ){
					$(this).notify( 'Document is required', notifyErrorConfig );
					return false;
				} */
				if( identification_document != "" ){
					block_config_kyc = { css: { backgroundColor: 'transparent', border: 'none' }, message: '<div class="blockUIspinner"></div><h5>Please wait while we are uploading your documents.</h5>', baseZ: 1500, overlayCSS: { backgroundColor: '#FFFFFF', opacity: 0.8, cursor: 'wait' } };
				}

				var data = new FormData( $form[0] );
				data.append("step", '3');
				$form.block( block_config_kyc );
				$.ajax({
					url			: cipscript.ajax_url,
					type		: 'post',
					data		: data,
					processData	: false,
					contentType	: false,
					success : function(response){
						var obj = $.parseJSON(response);
						console.dir( obj );
						if( obj.error == 0 ){

							$(".memberKycFrm #progressbar li").eq( $(".memberKycFrm fieldset").index(next_fs) ).addClass("active");
							next_fs.show();
							current_fs.animate({opacity: 0}, {
								step: function(now) {
									opacity = 1 - now;
					
									current_fs.css({
										'display': 'none',
										'position': 'relative'
									});
									next_fs.css({'opacity': opacity});
								},
								duration: 500
							});
							setProgressBarGa(++current);

						}else{
							Swal.fire({ type: 'error', title: obj.msg, text: '',allowOutsideClick: false});
						}
						$form.unblock();

					}
				});

			}else if( current == 4 ){

				var document_proof = $form.find('#document_proof').val();
				var document_date = $form.find('#document_date').val();
				var proof_document = $form.find('input[id="proof_document"]').val();

				if( document_proof == "" ){
					this_next.notify( 'Document Type is required', notifyErrorConfig );
					return false;
				}
				if( document_date == "" ){
					this_next.notify( 'Document Date is required', notifyErrorConfig );
					return false;
				}
				/* if( typeof proof_document  === "undefined" || proof_document == "" ){
					$(this).notify( 'Document is required', notifyErrorConfig );
					return false;
				} */

				if( proof_document != "" ){
					block_config_kyc = { css: { backgroundColor: 'transparent', border: 'none' }, message: '<div class="blockUIspinner"></div><h5>Please wait while we are uploading your documents.</h5>', baseZ: 1500, overlayCSS: { backgroundColor: '#FFFFFF', opacity: 0.8, cursor: 'wait' } };
				}

				var data = new FormData( $form[0] );
				data.append("step", '4');
				$form.block( block_config_kyc );
				$.ajax({
					url			: cipscript.ajax_url,
					type		: 'post',
					data		: data,
					processData	: false,
					contentType	: false,
					success : function(response){
						var obj = $.parseJSON(response);
						console.dir( obj );
						if( obj.error == 0 ){

							$(".memberKycFrm #progressbar li").eq( $(".memberKycFrm fieldset").index(next_fs) ).addClass("active");
							next_fs.show();
							current_fs.animate({opacity: 0}, {
								step: function(now) {
									opacity = 1 - now;
					
									current_fs.css({
										'display': 'none',
										'position': 'relative'
									});
									next_fs.css({'opacity': opacity});
								},
								duration: 500
							});
							setProgressBarGa(++current);

						}else{
							Swal.fire({ type: 'error', title: obj.msg, text: '',allowOutsideClick: false});
						}
						$form.unblock();

					}
				});

			}else if( current == 5 ){

				block_config_kyc = { css: { backgroundColor: 'transparent', border: 'none' }, message: '<div class="blockUIspinner"></div>', baseZ: 1500, overlayCSS: { backgroundColor: '#FFFFFF', opacity: 0.8, cursor: 'wait' } };

				var politically_exposed_person = $form.find('input[name="politically_exposed_person"]:checked').val();
				var consent_my_data_share = $form.find('input[name="consent_my_data_share"]:checked').val();
				var confirm_correct_info = $form.find('input[name="confirm_correct_info"]:checked').val();

				if( typeof politically_exposed_person  === "undefined" || politically_exposed_person == "" ){
					this_next.notify( 'Are you a politically exposed person is required', notifyErrorConfig );
					return false;
				}
				if( typeof consent_my_data_share  === "undefined" || consent_my_data_share == "" ){
					this_next.notify( 'Consent to my data being shared with all companies in the corsair group is required', notifyErrorConfig );
					return false;
				}
				if( confirm_correct_info != 'Yes' ){
					this_next.notify( 'Please confirm the information submitted in this form is complete and correct', notifyErrorConfig );
					return false;
				}

				var data = new FormData( $form[0] );
				data.append("step", '5');
				$form.block( block_config_kyc );
				$.ajax({
					url			: cipscript.ajax_url,
					type		: 'post',
					data		: data,
					processData	: false,
					contentType	: false,
					success : function(response){
						var obj = $.parseJSON(response);
						if( obj.error == 0 ){
							Swal.fire({ type: 'success', title: obj.msg, text: '',allowOutsideClick: true}).then(function(){window.location.reload();});
						}else{
							Swal.fire({ type: 'error', title: obj.msg, text: '',allowOutsideClick: false});
						}
						$form.unblock();

					}
				});

			}
			console.log( current );

		});
		// const kycStep = cipscript.kycStep;
		const kycStep = 2;
		if( kycStep > 1 ){
			go_to_x_step( kycStep );
		}

		function go_to_x_step( gotoStep = 0 ){
			for (let step = 0; step < (gotoStep - 1 ); step++) {
				var $next_button = $('.step_'+step).find('.next');
				
				var current_fs = $next_button.parent();
				var next_fs = $next_button.parent().next();
	
				$(".memberKycFrm #progressbar li").eq( $("fieldset").index(next_fs) ).addClass("active");
				next_fs.show();
				current_fs.css({
					'display': 'none',
					'position': 'relative'
				});
				next_fs.css({'opacity': opacity});
				setProgressBarGa(++current);
			}
		}

		$('body').on("click",".memberKycFrm .previous", function(){
			current_fs = $(this).closest('fieldset');
			previous_fs = $(this).closest('fieldset').prev();
			console.log( current );

			if( current == 2 ){
				var data = new FormData( $form[0] );
				data.append("step", 'account_type');
				$form.block( block_config_kyc );
				$.ajax({
					url			: cipscript.ajax_url,
					type		: 'post',
					data		: data,
					processData	: false,
					contentType	: false,
					success : function(response){
						var obj = $.parseJSON(response);
						if( obj.error == 0 ){
							// Swal.fire({ type: 'success', title: obj.msg, text: '',allowOutsideClick: true});
							window.location.reload();
						}else{
							Swal.fire({ type: 'error', title: obj.msg, text: '',allowOutsideClick: false});
						}
						$form.unblock();

					}
				});
			}else{
				$(".memberKycFrm #progressbar li").eq($(".memberKycFrm fieldset").index(current_fs)).removeClass("active");
				previous_fs.show();
				current_fs.animate({opacity: 0}, {
					step: function(now) {
						opacity = 1 - now;
	
						current_fs.css({
						'display': 'none',
						'position': 'relative'
						});
						previous_fs.css({'opacity': opacity});
					},
					duration: 500
				});
				setProgressBarGa(--current);
				console.log( current );

			}
		});

		function setProgressBarGa(curStep){
			var percent = parseFloat(100 / steps) * curStep;
			percent = percent.toFixed();
			$('body').find(".memberKycFrm .progress-bar").css("width",percent+"%")
		}

		$("#firstname, #lastname, #city, #state").bind("input", function () {
			var c = this.selectionStart,
			  r = /[^a-z-_ ]/gi,
			  v = $(this).val();
			if( r.test(v) ){
			  $(this).val(v.replace(r, ""));
			  c--;
			}
			this.setSelectionRange(c, c);
		});

		/* $('#firstname, #lastname, #city, #state').on('keypress', function (event) {
			var keyCode = event.keyCode || event.which;
			var pattern = /^[a-z\-_\s]+$/i;
			var isValid = pattern.test(String.fromCharCode(keyCode));
			if (!isValid) {
				event.preventDefault();
       			return false;
			}
		}); */

		
		$("#postal_code, #document_number").bind("input", function () {
			var c = this.selectionStart,
			  r = /[^a-z0-9-_ ]/gi,
			  v = $(this).val();
			if( r.test(v) ){
			  $(this).val(v.replace(r, ""));
			  c--;
			}
			this.setSelectionRange(c, c);
		});
		/* $('#postal_code, #document_number').on('keypress', function (event) {
			var keyCode = event.keyCode || event.which;
			var pattern = /^[a-z\d\-_\s]+$/i;
			var isValid = pattern.test(String.fromCharCode(keyCode));
			if (!isValid) {
				event.preventDefault();
       			return false;
			}
		}); */

		$("#address, #street_address").bind("input", function () {
			var c = this.selectionStart,
			  r = /[^a-z0-9-_, ]/gi,
			  v = $(this).val();
			if( r.test(v) ){
			  $(this).val(v.replace(r, ""));
			  c--;
			}
			this.setSelectionRange(c, c);
		});
		/* $('#address, #street_address').on('keypress', function (event) {
			var keyCode = event.keyCode || event.which;
			console.log( 'keyCode', keyCode );
			var pattern = /^[a-z\d\-_,\s]+$/i;
			var isValid = pattern.test(String.fromCharCode(keyCode));
			console.log( 'isValid', isValid );
			if (!isValid) {
				event.preventDefault();
       			return false;
			}
		}); */

		var datepicker_options = {
			altFormat: "dd/mm/yyyy",
			dateFormat: "dd/mm/yyyy",
			maxDate: "-18Y",
			changeMonth: true,
			changeYear: true
		  };
		var inputmask_options = {
			inputFormat:'dd/mm/yyyy',
			alias: "datetime",
			placeholder: "dd/mm/yyyy",
		};

		
		if( $('#dob').length > 0 ){		
			$("#dob").inputmask(inputmask_options);
			// var startDateDob = new Date(1900,0,1);
			// var startDateDob = new Date(new Date().getFullYear() - 100, 0, 1);
			$('#dob').datepicker({
				format: "dd/mm/yyyy",
				endDate: "-18Y",
				startDate:  "-120Y",
				autoclose: true,
				clearBtn: true,
			}).on('hide', function(e) {
				if( typeof e.date  === "undefined" || e.date == "" ){
					$(this).notify( 'Date Of birth must be 18 years old', notifyErrorConfigField );
				}
			});
		}
		if( $('#idcard_passport_expiry').length > 0 ){
			$('#idcard_passport_expiry').datepicker({
				format: "dd/mm/yyyy",
				startDate: "today",
				autoclose: true,
				clearBtn: true,
			}).attr('readonly', 'readonly');
		}
		$('#id_have_expiry').on('change', function(){
			if( this.checked ){
				$('body').find('.idcard_passport_expiry_field').slideDown();
			}else{
				$('body').find('.idcard_passport_expiry_field').slideUp();
			}
		});
		$('#different_contact_address').on('change', function(){
			if( this.checked ){
				$('body').find('.different_contact_address_section').slideDown();
			}else{
				$('body').find('.different_contact_address_section').slideUp();
			}
		});
		if( $('#issue_date').length > 0 ){		
			$('#issue_date').inputmask(inputmask_options);
			$('#issue_date').datepicker({
				format: "dd/mm/yyyy",
				endDate: "today",
				autoclose: true,
				clearBtn: true,
			}).on('hide', function(e) {
				if( typeof e.date  === "undefined" || e.date == "" ){
					$(this).notify( 'You need to enter a date which was in the past.', notifyErrorConfigField );
				}
			});
		}
		if( $('#expiration_date').length > 0 ){		
			$('#expiration_date').inputmask(inputmask_options);
			var expEndDate = new Date(new Date().getFullYear() + 76, 11, 31);
			// console.log(expEndDate);
			$('#expiration_date').datepicker({
				format: "dd/mm/yyyy",
				startDate: "+1D",
				// startDate: "01/01/1900",
				endDate: expEndDate,
				autoclose: true,
				clearBtn: true,
			}).on('hide', function(e) {
				var id_no_have_expiry = $form.find('#id_no_have_expiry:checked').val();
				if( typeof id_no_have_expiry  === "undefined" ){
					if( typeof e.date  === "undefined" || e.date == "" ){
						$(this).notify( 'You need to enter a date which will be in the future', notifyErrorConfigField );
					}
				}
			});;
		}
		if( $('#document_date').length > 0 ){		
			$('#document_date').inputmask(inputmask_options);
			$('#document_date').datepicker({
				format: "dd/mm/yyyy",
				startDate: "-90D",
				endDate: "today",
				autoclose: true,
				clearBtn: true,
			}).on('hide', function(e) {
				if( typeof e.date  === "undefined" || e.date == "" ){
					$(this).notify( 'Document date must be within 90 days', notifyErrorConfigField );
				}
			});
		}

		/* $('body').on('change', '#country', function () {
			let country = $(this).val();
			$('#state').html('<option value="">Select</option>');
			$('#city').html('<option value="">Select</option>');
			getStatesDropDown( country, $('#state') );
		});
		$('body').on('change', '#state', function () {
			let state = $(this).val();
			$('#city').html('<option value="">Select</option>');
			getCitiesDropDown( state, $('#city') );
		});
		$('body').on('change', '#contact_country', function () {
			let country = $(this).val();
			$('#contact_state').html('<option value="">Select</option>');
			$('#contact_city').html('<option value="">Select</option>');
			getStatesDropDown( country, $('#contact_state') );
		});
		$('body').on('change', '#contact_state', function () {
			let state = $(this).val();
			$('#contact_city').html('<option value="">Select</option>');
			getCitiesDropDown( state, $('#contact_city') );
		}); */
		
		function getStatesDropDown( country = '', stateElem ){
			var options = "";
			var $form = $('.memberKycFrm');
			$form.block( block_config );
			$.ajax({
				url: cipscript.ajax_url,
				type: 'POST',
				data: { 'action' : 'getStatesAction','country': country },
				dataType: "json",
				success: function (response) {
					let obj = JSON.parse(JSON.stringify(response));
					stateElem.html( obj.options );
					$form.unblock();
				}
			});
		}
		function getCitiesDropDown( state = '', cityElem ){
			var options = "";
			var $form = $('.memberKycFrm');
			$form.block( block_config );
			$.ajax({
				url: cipscript.ajax_url,
				type: 'POST',
				data: { 'action' : 'getCitiesAction','state': state },
				dataType: "json",
				success: function (response) {
					let obj = JSON.parse(JSON.stringify(response));
					cityElem.html( obj.options );
					$form.unblock();
				}
			});
		}

		var imagesPreview = function(input, placeToInsertImagePreview) {
			if (input.files) {
				var filesAmount = input.files.length;
				var type = "";
				$(placeToInsertImagePreview).html('');
				for (i = 0; i < filesAmount; i++) {
					type = input.files[i].name.split('.').pop().toLowerCase();
					var reader = new FileReader(); 
					if( type == 'pdf' ){
						reader.onload = function(event) {
							$("<div><a href='javascript:void(0);'><img class='doc-img-thumbnail' src='"+ cipscript.cip_images_folder +"pdf.png' /></a></div>").appendTo(placeToInsertImagePreview);
						}
					}else{
						reader.onload = function(event) {
							$("<div><a href='javascript:void(0);'><img class='doc-img-thumbnail' src='"+ event.target.result +"' /></a></div>").appendTo(placeToInsertImagePreview);
						}
					}
					reader.readAsDataURL(input.files[i]);
				}
			}
		};

		$('body').on("change", "#identification_document", function(e){
			var thisInputFile = $(this);
			$('.identification_document.doc-grid_section').html('');
			if( this.files.length > 0 ){
                for (var i = 0; i < this.files.length; i++) {
					var this_ext = this.files[i].name.split('.').pop().toLowerCase();
					if($.inArray(this_ext, ['png', 'jpg', 'jpeg', 'pdf']) == -1) {
						thisInputFile.notify( 'Choose valid document file format', notifyErrorOpt );
						thisInputFile.val('');
						return false;
					}
					if( this.files[0].size > 10000000 ){
						thisInputFile.notify( 'document file size exceeds 10MB', notifyErrorOpt );
						thisInputFile.val('');
						return false;
					}
				}
			}
			if( $(this).val() != "" ){
				thisInputFile.addClass('active');
				$('.clear_identification_document').show();

				imagesPreview(this, '.identification_document.doc-grid_section');

			}else{
				thisInputFile.removeClass('active');
				$('.clear_identification_document').hide();
			}
		});

		$('body').on("click", ".clear_identification_document", function(e){
			$('#identification_document').val('').removeClass('active');
			$(this).hide();
			$('.identification_document.doc-grid_section').html('');
		});
		
		$('body').on("change", "#proof_document", function(e){
			var thisInputFile = $(this);
			$('.proof_document.doc-grid_section').html('');
			if( this.files.length > 0 ){
                for (var i = 0; i < this.files.length; i++) {
					var this_ext = this.files[i].name.split('.').pop().toLowerCase();
					if($.inArray(this_ext, ['png', 'jpg', 'jpeg', 'pdf']) == -1) {
						thisInputFile.notify( 'Choose valid document file format', notifyErrorOpt );
						thisInputFile.val('');
						return false;
					}
					if( this.files[0].size > 10000000 ){
						thisInputFile.notify( 'document file size exceeds 10MB', notifyErrorOpt );
						thisInputFile.val('');
						return false;
					}
				}
			}
			if( $(this).val() != "" ){
				thisInputFile.addClass('active');
				$('.clear_proof_document').show();

				imagesPreview(this, '.proof_document.doc-grid_section');
			}else{
				thisInputFile.removeClass('active');
				$('.clear_proof_document').hide();
			}
		});

		$('body').on("click", ".clear_proof_document", function(e){
			$('#proof_document').val('').removeClass('active');
			$(this).hide();
			$('.proof_document.doc-grid_section').html('');
		});
	}

	$('body').on('submit', '#dropKycModalFrm', function(){
		$form = $(this);
		var data = $(this).serialize();
		$form.block( block_config );
		$('.form_response').html('');
		$.post(cipscript.ajax_url, data, function(response) {
			var obj = JSON.parse( response );
			$form.unblock();
			if( obj.error == 0 ){
				Swal.fire({ type: 'success', title: obj.msg, text: '',allowOutsideClick: true}).then(function(){window.location.href = cipscript.kycVerificationUrl;});
				$('#dropKycModal').modal('hide');
			}else{
				Swal.fire({ type: 'error', title: obj.msg, text: '',allowOutsideClick: false});
			}
			$('.form_response').html( obj.msg );
		});
		return false;
	});
	$('body').on('submit', '#rejectWholeKycModalFrm', function(){
		$form = $(this);
		var data = $(this).serialize();
		$form.block( block_config );
		$('.form_response').html('');
		$.post(cipscript.ajax_url, data, function(response) {
			var obj = JSON.parse( response );
			$form.unblock();
			if( obj.error == 0 ){
				Swal.fire({ type: 'success', title: obj.msg, text: '',allowOutsideClick: true}).then(function(){ window.location.href = cipscript.kycVerificationUrl; });
				$('#rejectWholeKycModal').modal('hide');
			}else{
				Swal.fire({ type: 'error', title: obj.msg, text: '',allowOutsideClick: false});
			}
			$('.form_response').html( obj.msg );
		});
		return false;
	});
	$('body').on('submit', '#approvedKycModalFrm', function(){
		$form = $(this);
		var data = $(this).serialize();
		$form.block( block_config );
		$('.form_response').html('');
		$.post(cipscript.ajax_url, data, function(response) {
			var obj = JSON.parse( response );
			$form.unblock();
			if( obj.error == 0 ){
				Swal.fire({ type: 'success', title: obj.msg, text: '',allowOutsideClick: true}).then(function(){ window.location.href = cipscript.kycVerificationUrl; });
				$('#approvedKycModal').modal('hide');
			}else{
				Swal.fire({ type: 'error', title: obj.msg, text: '',allowOutsideClick: false});
			}
			$('.form_response').html( obj.msg );
		});
		return false;
	});

	$('.rejectKycPopup').on('click', function(e){
		var thisStep = $(this).attr('data-step');
		$('<input>').attr({type: 'hidden',id: 'thisStep',name: 'thisStep', value: thisStep}).appendTo('#rejectKycModalFrm');
		$('#rejectKycModal').modal('show');
	});

	$('#rejectKycModal').on('hide.bs.modal', function (event) {
		$('#thisStep').remove();
	});
	
	$('body').on('submit', '#rejectKycModalFrm', function(){
		$form = $(this);
		var data = $(this).serialize();
		$form.block( block_config );
		$('.form_response').html('');
		$.post(cipscript.ajax_url, data, function(response) {
			var obj = JSON.parse( response );
			$form.unblock();
			if( obj.error == 0 ){
				// Swal.fire({ type: 'success', title: obj.msg, text: '',allowOutsideClick: true}).then(function(){window.location.reload();});
				$('#rejectKycModal').modal('hide');

				if( typeof obj.type  !== "undefined" && obj.type == 'kyb' ){
					if( typeof obj.checkStepCount  !== "undefined" && obj.checkStepCount == 5 ){
						window.location.reload();
					}else{ 
						$('#tabMoveIndex').val( obj.tabMove );
						$('#tabMoveFrm').submit();
					}
				}else{
					if( typeof obj.checkStepCount  !== "undefined" && obj.checkStepCount == 4 ){
						window.location.reload();
					}else{ 
						$('#tabMoveIndex').val( obj.tabMove );
						$('#tabMoveFrm').submit();
					}
				}

				/* if( typeof obj.checkStepCount  !== "undefined" && obj.checkStepCount == 3 ){
					window.location.href = cipscript.kycVerificationUrl;
				}else{
					window.location.href = cipscript.kycVerificationUrl;
					// window.location.reload();
				} */
				swalToast({ type: 'error', title: obj.msg });
			}else{
				Swal.fire({ type: 'error', title: obj.msg, text: '',allowOutsideClick: false});
			}
			$('.form_response').html( obj.msg );
		});
		return false;
	});
	
	$('.approveKycStepPopup').on('click', function(e){
		var thisStep = $(this).attr('data-step');
		var thisStepName = $(this).attr('data-stepname');
		$('#thisStep').remove();
		$('<input>').attr({type: 'hidden',id: 'thisStep',name: 'thisStep', value: thisStep}).appendTo('#approveKycStepModalFrm');
		$('#approveKycStepModalFrm').find('.stepNameModal').html( thisStepName );
		// $('#approveKycStepModal').modal('show');
		$('#approveKycStepModalFrm').submit();
		$(this).addClass('active');
	});
	
	$('#approveKycStepModal').on('hide.bs.modal', function (event) {
		$('#thisStep').remove();
		$('#approveKycStepModalFrm').find('.stepNameModal').html('X');
		$('.approveKycStepPopup').removeClass('active');
	});

	$('body').on('submit', '#approveKycStepModalFrm', function(){

		var block_config = { css: { backgroundColor: 'transparent', border: 'none' }, message: '<div class="blockUIspinner"></div>', baseZ: 1500, overlayCSS: { backgroundColor: '#FFFFFF', opacity: 0.8, cursor: 'wait' } }
		$form = $(this);
		var data = $(this).serialize();
		// $form.block( block_config );
		$.blockUI( block_config );
		$('.form_response').html('');
		$.post(cipscript.ajax_url, data, function(response) {
			var obj = JSON.parse( response );
			$.unblockUI();
			if( obj.error == 0 ){
				$('body').find('.approveKycStepPopup.active').hide().removeClass('active');
				
				if( typeof obj.type  !== "undefined" && obj.type == 'kyb' ){
					if( typeof obj.checkStepCount  !== "undefined" && obj.checkStepCount == 5 ){
						window.location.reload();
					}else if( obj.isFullyApprove == 1 ){
						window.location.reload();
					}else{ 
						$('#tabMoveIndex').val( obj.tabMove );
						$('#tabMoveFrm').submit();
					}
				}else{
					if( typeof obj.checkStepCount  !== "undefined" && obj.checkStepCount == 4 ){
						window.location.reload();
					}else if( obj.isFullyApprove == 1 ){
						window.location.reload();
					}else{ 
						$('#tabMoveIndex').val( obj.tabMove );
						$('#tabMoveFrm').submit();
					}
				}
				/* Swal.fire({ type: 'success', title: obj.msg, text: '',allowOutsideClick: true}).then(function(){ if( obj.isFullyApprove == 1 ){ window.location.href = cipscript.kycVerificationUrl; }else{ window.location.reload(); } }); */
				//$('#approveKycStepModal').modal('hide');
			}else{
				Swal.fire({ type: 'error', title: obj.msg, text: '',allowOutsideClick: false});
			}
			$('.form_response').html( obj.msg );
		});
		return false;
	});

	/* if( $('img.zoom').length > 0 ){
		$('.zoom').magnify();
	} */

	/* $('.kycReviewSection a[data-toggle="pill"]').on('shown.bs.tab', function (e) {
		$(window).trigger('resize');
	}); */

	$('body').on('click', '.view_attachments', function(){
		var block_config = { css: { backgroundColor: 'transparent', border: 'none' }, message: '<div class="blockUIspinner"></div>', baseZ: 1500, overlayCSS: { backgroundColor: '#FFFFFF', opacity: 0.8, cursor: 'wait' } };
		var thisType = "";
		if( $(this).hasClass('member_passport') ){
			thisType = "type1";
		}else if( $(this).hasClass('piece_paper_wallet_address') ){
			thisType = "type2";
		}
		var data = { 'action' : 'view_attachments_lsh_act', 'type' : thisType, 'thisId' : $(this).attr('data-id') };
		$.blockUI(block_config);
		$.post(cipscript.ajax_url, data, function(response) {
			var obj = JSON.parse( response );
			if( obj.error == 0 ){
				$('#imagepreview').attr('src', obj.src);
				$('#imagepreview').attr('data-src', obj.src);
				// $('#enlargeImageModal').modal('show');
				$('#imagepreview').magnify({
					resizable: false,
					footerToolbar: ['zoomIn','zoomOut','fullscreen','actualSize','rotateRight'],
					multiInstances: false,
					initMaximized: true
				});
				$('#imagepreview').click();
			}else{
				Swal.fire({ type: 'error', title: obj.msg, text: '',allowOutsideClick: false});
			}
			$.unblockUI();
		});
		return false;
	});
	$('body').on('click', '.view_attachments_address', function(){
		var block_config = { css: { backgroundColor: 'transparent', border: 'none' }, message: '<div class="blockUIspinner"></div>', baseZ: 1500, overlayCSS: { backgroundColor: '#FFFFFF', opacity: 0.8, cursor: 'wait' } };
		var thisType = "";
		if( $(this).hasClass('member_passport') ){
			thisType = "type1";
		}else if( $(this).hasClass('piece_paper_wallet_address') ){
			thisType = "type2";
		}
		var data = { 'action' : 'view_attachments_adrs_act', 'type' : thisType, 'thisId' : $(this).attr('data-id') };
		$.blockUI(block_config);
		$.post(cipscript.ajax_url, data, function(response) {
			var obj = JSON.parse( response );
			if( obj.error == 0 ){
				$('#imagepreview').attr('src', obj.src);
				$('#imagepreview').attr('data-src', obj.src);
				// $('#enlargeImageModal').modal('show');
				$('#imagepreview').magnify({
					resizable: false,
					footerToolbar: ['zoomIn','zoomOut','fullscreen','actualSize','rotateRight'],
					multiInstances: false,
					initMaximized: true
				});
				$('#imagepreview').click();
			}else{
				Swal.fire({ type: 'error', title: obj.msg, text: '',allowOutsideClick: false});
			}
			$.unblockUI();
		});
		return false;
	});

	/* $('body').on('click', '.enableCountryList', function(){
		var block_config = { css: { backgroundColor: 'transparent', border: 'none' }, message: '<div class="blockUIspinner"></div>', baseZ: 1500, overlayCSS: { backgroundColor: '#FFFFFF', opacity: 0.8, cursor: 'wait' } };
		var thisType = "";
		var data =  cipscript.actionEnableCountriesAct;
		data['thisCountry'] = $(this).attr('data-country');
		$.blockUI(block_config);
		$.post(cipscript.ajax_url, data, function(response) {
			var obj = JSON.parse( response );
			if( obj.error == 0 ){
				window.location.reload();
			}else{
				Swal.fire({ type: 'error', title: obj.msg, text: '',allowOutsideClick: false});
			}
			$.unblockUI();
		});
		return false;
	}); */

	$('body').on('change', '.countries_management_chkbox', function(){
		var block_config = { css: { backgroundColor: 'transparent', border: 'none' }, message: '<div class="blockUIspinner"></div>', baseZ: 1500, overlayCSS: { backgroundColor: '#FFFFFF', opacity: 0.8, cursor: 'wait' } };
		var isEnabling = 0;
		if( $(this).is(':checked') ){
			isEnabling = 1;
		}
		var thisElem = $(this);
		var data =  cipscript.actionEnableCountriesAct;
		data['thisCountry'] = $(this).val();
		data['isEnabling'] = isEnabling;
		$.blockUI(block_config);
		$.post(cipscript.ajax_url, data, function(response) {
			var obj = JSON.parse( response );
			if( obj.error == 0 ){
				// window.location.reload();
				thisElem.next('label').html( obj.label );
				swalToast({ type: 'success', title: obj.msg });
			}else{
				Swal.fire({ type: 'error', title: obj.msg, text: '',allowOutsideClick: false});
			}
			$.unblockUI();
		});
		return false;
	});

	$('body').on('submit', '#addCountryMgmt', function(){
		var block_config = { css: { backgroundColor: 'transparent', border: 'none' }, message: '<div class="blockUIspinner"></div>', baseZ: 1500, overlayCSS: { backgroundColor: '#FFFFFF', opacity: 0.8, cursor: 'wait' } };
		var data = $(this).serialize();
		$.blockUI(block_config);
		$.post(cipscript.ajax_url, data, function(response) {
			var obj = JSON.parse( response );
			if( obj.error == 0 ){
				window.location.reload();
			}else{
				Swal.fire({ type: 'error', title: obj.msg, text: '',allowOutsideClick: false});
			}
			$.unblockUI();
		});
		return false;
	});
	//5753 csr withdrawal setting
	$('body').on('submit', '#sa_csr_withdrawal_setting', function(){
		$form = $(this);
		if( $(this).find('input[name="minimum_withdrawal_amount"]').val() == "" || $(this).find('input[name="withdrawal_fee"]').val() == "" || $(this).find('input[name="withdrawal_fee_csr25"]').val() == "" || $(this).find('input[name="csr_fee_useremail"]').val() == "" ){
			// Swal.fire({ type: 'error', title: "* fields are required", text: '',allowOutsideClick: true});
			swalToast({ type: 'error', title: '* fields are required' });
			return false;
		}
		var data = $(this).serialize();
		$form.block( block_config );
		$.post(cipscript.ajax_url, data, function(response) {
			var obj = JSON.parse( response );
			if( obj.error == 0 ){
				// Swal.fire({ type: 'success', title: obj.msg, text: '',allowOutsideClick: true});
				swalToast({ type: 'success', title: obj.msg });
			}else{
				swalToast({ type: 'error', title: obj.msg });
				// Swal.fire({ type: 'error', title: obj.msg, text: '',allowOutsideClick: true});
			}
			$form.unblock();
		});
		return false;
	});

	$('#minimum_withdrawal_amount, #withdrawal_fee, #withdrawal_fee_csr25').keypress(function(event) {
		if ((event.which != 46 || $(this).val().indexOf('.') != -1) &&
		  ((event.which < 48 || event.which > 57) &&
			(event.which != 0 && event.which != 8))) {
		  event.preventDefault();
		}
	
		var text = $(this).val();
	
		if ((text.indexOf('.') != -1) &&
		  (text.substring(text.indexOf('.')).length > 2) &&
		  (event.which != 0 && event.which != 8) &&
		  ($(this)[0].selectionStart >= text.length - 2)) {
		  event.preventDefault();
		}
	});
	
	if( $('#withdrawalModal').length > 0 ){
		var notifyErrorConfig = {position:"top",className: 'error',autoHide:true,autoHideDelay: 4000,clickToHide: true};
		var notifyErrorConfigField = {position:"bottom",className: 'error',autoHide:true,autoHideDelay: 4000,clickToHide: true};
	
		var block_config_kyc = { css: { backgroundColor: 'transparent', border: 'none' }, message: '<div class="blockUIspinner"></div>', baseZ: 1500, overlayCSS: { backgroundColor: '#FFFFFF', opacity: 0.8, cursor: 'wait' } };
	
		var current_fs_withdraw, next_fs_withdraw, previous_fs_withdraw; //fieldsets
		var opacity_withdraw;
		var current_withdraw = 1;
		var steps_withdraw = $('body').find(".csrWithdrawalFrm fieldset").length;
		setProgressBarCw(current_withdraw);

		$('#token').on('change', function() {
			var tokenValue = $(this).val();
			var $form = $('body').find('.csrWithdrawalFrm');
			$('#csr_withdrawal_amount').val('');
			$('label.csr_wallet_address_text').html(function(index, oldHtml) {
				return oldHtml.replace(/CSR(25)?/g, tokenValue);
			});
			$('label[for="withdraw_csr_directly_to_the_deposit_address"]').html(function(index, oldHtml) {
				return oldHtml.replace(/CSR(25)?/g, tokenValue);
			});

			if (tokenValue !== '') {
				$form.block( block_config_kyc );
				$.ajax({
					method: "POST",
					url: cipscript.ajax_url,
					data: { action: "cip_get_token_Balance_withdraw" ,'token' : tokenValue},
					success: async function (response) {
						var obj = JSON.parse( response );
						$('.percentage_25').attr('data-percentage-val', obj.percentageNumber25);
						$('.percentage_50').attr('data-percentage-val', obj.percentageNumber50);
						$('.percentage_75').attr('data-percentage-val', obj.percentageNumber75);
						$('.percentage_100').attr('data-percentage-val', obj.percentageNumber100);
						$('.available_balance_notice').html('Your Available Balance Is: '+ obj.availableBalance);

						$('.token_selected').show();
						$form.unblock();

					},
					error: function () {
						$form.unblock();
						return false;
					}
				});

			} else {
				$('.token_selected').hide();
			}
		});
	
		var isRequestInProgress = false;
		$('body').on("click",".next_cw", function(event){
			if (isRequestInProgress) return;
			var $button = $(this);
			$button.prop('disabled', true);
			isRequestInProgress = true;
			var $form = $('body').find('.csrWithdrawalFrm');
			var this_next = $('form.csrWithdrawalFrm .responseSection');
			current_fs_withdraw = $(this).closest('fieldset');
			next_fs_withdraw = $(this).closest('fieldset').next();
			// console.log( current );
			if( current_withdraw == 1 ){
				var csr_wallet_address = $form.find('input[name="csr_wallet_address"]').val();
				var csr_withdrawal_amount = $form.find('input[name="csr_withdrawal_amount"]').val();
				if( csr_wallet_address == "" ){
					this_next.notify( 'CSR Wallet address is required', notifyErrorConfig );
					return false;
				}
				if( !web3.utils.isAddress(csr_wallet_address) ){
					this_next.notify( 'CSR wallet address is invalid', notifyErrorConfig );
					return false;
				}
				if( csr_withdrawal_amount == "" ){
					this_next.notify( 'Withdrawal amount is required', notifyErrorConfig );
					return false;
				}
	
				var data = new FormData( $form[0] );
				data.append("step", '1');
				$form.block( block_config_kyc );
				$.ajax({
					url			: cipscript.ajax_url,
					type		: 'post',
					data		: data,
					processData	: false,
					contentType	: false,
					success : function(response){
						var obj = $.parseJSON(response);
						if( obj.error == 0 ){

							$('.csr_wallet_address_text span').html( obj.data.eth_address );
							$('.withdraw_amount_text span').html( obj.data.withdraw_amount );
							$('.withdrawal_fee_text span').html( obj.data.withdrawal_fee );
							$('.received_amount_text span').html( obj.data.received_amount );
	
							$(".csrWithdrawalFrm #progressbar li").eq( $(".csrWithdrawalFrm fieldset").index(next_fs_withdraw) ).addClass("active");
							next_fs_withdraw.show();
							current_fs_withdraw.animate({opacity: 0}, {
								step: function(now) {
									opacity_withdraw = 1 - now;
									current_fs_withdraw.css({
										'display': 'none',
										'position': 'relative'
									});
									next_fs_withdraw.css({'opacity': opacity_withdraw});
								},
								duration: 500
							});
							setProgressBarCw(++current_withdraw);
						}else{
							if( typeof obj.isAddressError !== 'undefined' ){
								swalToast({ type: 'error', title: obj.msg, timer: 7000 });
							}else{
								swalToast({ type: 'error', title: obj.msg });
							}
						}
						$form.unblock();
	
					},
					complete: function() {
						$button.prop('disabled', false);
						isRequestInProgress = false;
					}
				});
	
			}else if( current_withdraw == 2 ){
				var $form = $('body').find('.csrWithdrawalFrm');
				var i_confirm_that_withdrawal = $('#i_confirm_that_withdrawal:checked').val();
				var withdraw_csr_directly_to_the_deposit_address = $('#withdraw_csr_directly_to_the_deposit_address:checked').val();
				if( i_confirm_that_withdrawal != 1 ){
					this_next.notify( 'Please confirm the withdrawal request', notifyErrorConfig );
					return false;
				}
				if( withdraw_csr_directly_to_the_deposit_address != 1 ){
					this_next.notify( 'Please confirm I understand that if I withdraw CSR directly to the deposit address', notifyErrorConfig );
					return false;
				}
				$('.notifyjs-wrapper').trigger('notify-hide');

				var data = new FormData( $form[0] );
				data.append("step", '2');
				$form.block( block_config_kyc );
				$.ajax({
					url			: cipscript.ajax_url,
					type		: 'post',
					data		: data,
					processData	: false,
					contentType	: false,
					success : function(response){
						var obj = $.parseJSON(response);
						if( obj.error == 0 ){

							const interval_id = window.setInterval(function(){}, Number.MAX_SAFE_INTEGER);
							for (let i = 1; i < interval_id; i++) {
								window.clearInterval(i);
							}
							$('.otp_response_section').html( obj.otpContent );
							$('.ga_response_section').html( obj.otpGAContent );

							$(".csrWithdrawalFrm #progressbar li").eq( $(".csrWithdrawalFrm fieldset").index(next_fs_withdraw) ).addClass("active");
							next_fs_withdraw.show();
							current_fs_withdraw.animate({opacity: 0}, {
								step: function(now) {
									opacity_withdraw = 1 - now;
									current_fs_withdraw.css({
										'display': 'none',
										'position': 'relative'
									});
									next_fs_withdraw.css({'opacity': opacity_withdraw});
								},
								duration: 500
							});
							setProgressBarCw(++current_withdraw);
						}else{
							// Swal.fire({ type: 'error', title: obj.msg, text: '',allowOutsideClick: false});
							swalToast({ type: 'error', title: obj.msg });
						}
						$form.unblock();
	
					},
					complete: function() {
						$button.prop('disabled', false);
						isRequestInProgress = false;
					}
				});
			}else if( current_withdraw == 3 ){
				var $form = $('body').find('.csrWithdrawalFrm');
				var user_otp = $('#user_otp').val();
				var user_ga_otp = $('#user_ga_otp').val();
				if( user_otp == "" ){
					this_next.notify( 'Please enter the OTP', notifyErrorConfig );
					return false;
				}
				if( user_ga_otp == "" ){
					this_next.notify( 'Please enter the authentication code', notifyErrorConfig );
					return false;
				}
				var data = new FormData( $form[0] );
				data.append("step", '3');
				$form.block( block_config_kyc );
				$.ajax({
					url			: cipscript.ajax_url,
					type		: 'post',
					data		: data,
					processData	: false,
					contentType	: false,
					success : function(response){
						var obj = $.parseJSON(response);
						if( obj.error == 0 ){

							$('.final_response_section').html( obj.msg );

							var block_config_kyc = { css: { backgroundColor: 'transparent', border: 'none' }, message: '<div class="blockUIspinner"></div>', baseZ: 1500, overlayCSS: { backgroundColor: '#FFFFFF', opacity: 0.8, cursor: 'default' } };
							
							Swal.fire({ type: 'success', title: obj.msg, text: '',allowOutsideClick: false}).then(function(){ $.blockUI(block_config_kyc); window.location.reload(); });
							$("#withdrawalModal").modal('hide');

							$(".csrWithdrawalFrm #progressbar li").eq( $(".csrWithdrawalFrm fieldset").index(next_fs_withdraw) ).addClass("active");
							next_fs_withdraw.show();
							current_fs_withdraw.animate({opacity: 0}, {
								step: function(now) {
									opacity_withdraw = 1 - now;
									current_fs_withdraw.css({
										'display': 'none',
										'position': 'relative'
									});
									next_fs_withdraw.css({'opacity': opacity_withdraw});
								},
								duration: 500
							});
							setProgressBarCw(++current_withdraw);
						}else{
							// Swal.fire({ type: 'error', title: obj.msg, text: '',allowOutsideClick: false});
							swalToast({ type: 'error', title: obj.msg });
						}
						$form.unblock();
	
					},
					complete: function() {
						$button.prop('disabled', false);
						isRequestInProgress = false;
					}
				});
			}
		});

		$('body').on("click",".previous_cw", function(){
			current_fs_withdraw = $(this).closest('fieldset');
			previous_fs_withdraw = $(this).closest('fieldset').prev();

			$(".csrWithdrawalFrm #progressbar li").eq($(".csrWithdrawalFrm fieldset").index(current_fs_withdraw)).removeClass("active");

			previous_fs_withdraw.show();

			current_fs_withdraw.animate({opacity: 0}, {
				step: function(now) {
					opacity_withdraw = 1 - now;

					current_fs_withdraw.css({
					'display': 'none',
					'position': 'relative'
					});
					previous_fs_withdraw.css({'opacity': opacity_withdraw});
				},
				duration: 500
			});
			setProgressBarCw(--current_withdraw);
		});

		function setProgressBarCw(curStep){
			var percent = parseFloat(100 / steps_withdraw) * curStep;
			percent = percent.toFixed();
			$('body').find(".csrWithdrawalFrm .progress-bar").css("width",percent+"%")
		}

		$('#csr_withdrawal_amount').keypress(function(event) {
			if ((event.which != 46 || $(this).val().indexOf('.') != -1) &&
			  ((event.which < 48 || event.which > 57) &&
				(event.which != 0 && event.which != 8))) {
			  event.preventDefault();
			}
		
			var text = $(this).val();
		
			if ((text.indexOf('.') != -1) &&
			  (text.substring(text.indexOf('.')).length > 2) &&
			  (event.which != 0 && event.which != 8) &&
			  ($(this)[0].selectionStart >= text.length - 2)) {
			  event.preventDefault();
			}
		});
		
		$('body').on('click', '.percentage_25', function(){
			var $form = $('body').find('.csrWithdrawalFrm');
			if( !$.isNumeric( parseFloat( $(this).attr('data-percentage-val') ) ) ){
				$('#csr_withdrawal_amount').val('');
				return false
			}
			$('#csr_withdrawal_amount').val( $(this).attr('data-percentage-val') );
			return false;
		});
		$('body').on('click', '.percentage_50', function(){
			var $form = $('body').find('.csrWithdrawalFrm');
			if( !$.isNumeric( parseFloat( $(this).attr('data-percentage-val') ) ) ){
				$('#csr_withdrawal_amount').val('');
				return false
			}
			$('#csr_withdrawal_amount').val( $(this).attr('data-percentage-val') );
			return false;
		});
		$('body').on('click', '.percentage_75', function(){
			var $form = $('body').find('.csrWithdrawalFrm');
			if( !$.isNumeric( parseFloat( $(this).attr('data-percentage-val') ) ) ){
				$('#csr_withdrawal_amount').val('');
				return false
			}
			$('#csr_withdrawal_amount').val( $(this).attr('data-percentage-val') );
			return false;
		});
		$('body').on('click', '.percentage_100', function(){
			var $form = $('body').find('.csrWithdrawalFrm');
			if( !$.isNumeric( parseFloat( $(this).attr('data-percentage-val') ) ) ){
				$('#csr_withdrawal_amount').val('');
				return false
			}
			$('#csr_withdrawal_amount').val( $(this).attr('data-percentage-val') );
			return false;
		});

		$('body').on('click', '#resend_withdraw', function(){

			var $form = $('body').find('form.csrWithdrawalFrm');
			var data = new FormData( $form[0] );
			data.append("step", '2');
			data.append("resend", '1');
			$form.block( block_config_kyc );
			$.ajax({
				url			: cipscript.ajax_url,
				type		: 'post',
				data		: data,
				processData	: false,
				contentType	: false,
				success : function(response){
					var obj = $.parseJSON(response);
					if( obj.error == 0 ){

						const interval_id = window.setInterval(function(){}, Number.MAX_SAFE_INTEGER);
						for (let i = 1; i < interval_id; i++) {
							window.clearInterval(i);
						}
						$('.otp_response_section').html( obj.otpContent );
						$('.ga_response_section').html( obj.otpGAContent );
					}else{
						// Swal.fire({ type: 'error', title: obj.msg, text: '',allowOutsideClick: false});
						swalToast({ type: 'error', title: obj.msg });
					}
					$form.unblock();

				}
			});
		});

		$("#withdrawalModal").on('hide.bs.modal', function () {
			$('#withdrawalModal form')[0].reset();
			$('#withdrawalModal fieldset').hide();
			$('#withdrawalModal fieldset.step_0').show();
			$('#withdrawalModal fieldset.step_0').css({'opacity': 1});
			setProgressBarCw(1);
			current_withdraw = 1;
			$(".csrWithdrawalFrm #progressbar li").removeClass("active");
			$(".csrWithdrawalFrm #progressbar li").eq(0).addClass("active");
			$('.token_selected').hide();
		});

		$("#withdrawalModal").on('show.bs.modal', function () {
			
			const tokenSelect = document.getElementById('token');
			const options = tokenSelect.querySelectorAll('option:not([value=""])');
		
			if (options.length === 1) {
			    options[0].selected = true;
			    setTimeout(function () {
			    	tokenSelect.dispatchEvent(new Event('change'));
			    },500)
			}
		});

	}

	if( $('#csr_withdraw_requests').length > 0 ){
		let dateFormat = 'DD-MM-YYYY';
		$('input.bootstrap-table-filter-control-requested_date[type="search"]')
		.daterangepicker(
			{
				autoUpdateInput: false,
				locale: {
					format: dateFormat,
					separator: ' - ',
					firstDay: 1
				},
				opens: 'left',
				cancelButtonClasses: 'btn-default cancelButton_requested_date'
			},
			function(start, end) {
				startDate = start.format(dateFormat);
				endDate = end.format(dateFormat);
				let dates = [ startDate, endDate ];
				// filterByDate(dates, 'requested_date');
				$('input.bootstrap-table-filter-control-requested_date[type="search"]').val(
					start.format(dateFormat) + ' - ' + end.format(dateFormat)
				);
			}
		);
		jQuery('input.bootstrap-table-filter-control-requested_date[type="search"]').on('apply.daterangepicker', function(ev, picker) {
			$(this).val(picker.startDate.format(dateFormat) + ' - ' + picker.endDate.format(dateFormat));
			if ($('#bstable').attr('data-side-pagination')) {
				setTimeout(() => {
					$(this).trigger('keyup');
				}, 100);

				let eve = jQuery.Event("keyup");
				eve.which = 13
				eve.keyCode = 13
				$('.bootstrap-table-filter-control-requested_date').trigger(eve);
			}

			$(this).val(picker.startDate.format(dateFormat) + ' - ' + picker.endDate.format(dateFormat));
			let eve = jQuery.Event("keyup");
			eve.which = 13
			eve.keyCode = 13
			$('.bootstrap-table-filter-control-requested_date').trigger(eve);
		});
		$('input.bootstrap-table-filter-control-requested_date[type="search"]').on('cancel.daterangepicker', function(ev, picker) {
			$(this).val('');
			let eve = jQuery.Event("keyup");
			eve.which = 13
			eve.keyCode = 13
			$('.bootstrap-table-filter-control-requested_date').trigger(eve);
		});

		var $username = $('input.bootstrap-table-filter-control-username[type="search"]');
		$username.on('click', function(){
			$('#UsernameFilterModal').modal({backdrop: 'static',keyboard: false});
		});

		$('.filter_by_username .filter_csr_ok').on('click', function(){ //username
			let eve = jQuery.Event("keyup");
			eve.which = 13
			eve.keyCode = 13
			$username.trigger(eve);
			$('#UsernameFilterModal').modal('hide');

			var filterNoteForm = $('#filter_by_username');
			var condition_type_text = filterNoteForm.find('select[name="filter_condition_type_username"] option:selected').text();
			var condition_type = filterNoteForm.find('select[name="filter_condition_type_username"] option:selected').val();
			var condition_type_value = filterNoteForm.find('select#filter_condition_value_username').val();
			var condition_type_value_bulk = filterNoteForm.find('textarea#filter_condition_value_username_bulk').val();
			var filterText = condition_type_text;
			if( condition_type_value != "" || condition_type_value_bulk != "" ){
				if( condition_type == 'is_exactly_simple' ){
					filterText += ': '+condition_type_value_bulk;
				}else{
					filterText += ': '+condition_type_value;
				}
			}
			if( condition_type_text == 'None' ){
				filterText = "";
			}
			$('body').find('.username_filter_info').text( filterText );

		});

		$('form#filter_by_username').keydown(function (e) {
			if (e.keyCode == 13) {
				$('.filter_csr_ok').trigger('click');
				e.preventDefault();
				return false;
			}
		});

		$('.filter_by_username .filter_csr_cancel').on('click', function(){
			$('#UsernameFilterModal').modal('hide');
		});

		$('.filter_by_username #filter_condition_value_username').select2({
			placeholder: 'Username',
			minimumInputLength: 2,
			ajax: {
				url: cipscript.ajax_url,
				dataType: 'json',
				data: function (params) {
					var query = {
						search: params.term,
						action: 'username_fetch_act'
					}
					return query;
				}
			},
			processResults: function (response) {
				return {
				   results: response
				};
			},
			selectionCssClass: 'select2_username hide mt-2',
			dropdownParent: $('#UsernameFilterModal')
		});

		$('body').on('change', '#csr_withdraw_requests input.rowiddata', function(){
			calculateWithdrawRequestTotal();
			var selectedAllOption = 0;
			var thisRowSelected = 0;
			if( $('#csr_withdraw_requests input[name="toggleWDAll"]').is(':checked') ){
				selectedAllOption = 1;
			}
			if( $(this).is(':checked') ){
				thisRowSelected = 1;
			}
			/* $('#withdrawal_request_wizard_opener').addClass('disabled').prop('disabled', true);
			var data = {'action':'cip_wd_request_selection_storing_act', 'thisId':$(this).val(), 'selectedAllOption':selectedAllOption, 'thisRowSelected':thisRowSelected};
			var container = $(this).closest('tr');
			$.post(cipscript.ajax_url, data)
			.fail(function() {
				swalToast({ type: 'error', title: 'Something went wrong. Please try again.' });
				if( thisRowSelected == 1 ){
					$(this).prop('checked', false);
				}else{
					$(this).prop('checked', true);
				}
			})
			.done(function(response) {
				if( response.error == 0 ){
					//saved, nothing to do
					$('#withdrawal_request_wizard_opener').removeClass('disabled').prop('disabled', false);
					calculateWithdrawRequestTotal();
				}else{
					swalToast({ type: 'error', title: response.msg });
					if( thisRowSelected == 1 ){
						$(this).prop('checked', false);
					}else{
						$(this).prop('checked', true);
					}
				}
				$(container).unblock();
			})
			.always(function(response) {
				if (!response.isReset) {
					$(container).find('input, button').prop('disabled', false);
					$(container).removeClass('working');
					$(container).unblock();
				}
			}); */
		});

		$('body').on('change', '#csr_withdraw_requests input[name="toggleWDAll"]', function(){
			var thisRowSelected = 0;
			if( $(this).is(':checked') ){
				thisRowSelected = 1;
			}
			var data = {'action':'cip_wd_request_selection_clearing_act'};
			var container = $(this).closest('tr');
			$.post(cipscript.ajax_url, data)
			.fail(function() {
				swalToast({ type: 'error', title: 'Something went wrong. Please try again.' });
				if( thisRowSelected == 1 ){
					$(this).prop('checked', false);
				}else{
					$(this).prop('checked', true);
				}
			})
			.done(function(response) {
				if( response.error == 0 ){
					//saved, nothing to do
				}else{
					swalToast({ type: 'error', title: response.msg });
					if( thisRowSelected == 1 ){
						$(this).prop('checked', false);
					}else{
						$(this).prop('checked', true);
					}
				}
				$(container).unblock();
			})
			.always(function(response) {
				if (!response.isReset) {
					$(container).find('input, button').prop('disabled', false);
					$(container).removeClass('working');
					$(container).unblock();
				}
			});
		});

	}

	$('body').on('change', 'input[name="ga2fa_walletdelivery"]', function(event){
		event.preventDefault();
		// console.log( $(this).is(':checked') );
		var $this = $(this);
		if( $(this).is(':checked') ){ //enable GA for delivery
			$this.prop( "checked", false );

			var container = $('.2fa_ga_section');
			var request = {'action' : 'check_for_smsa_ga_twofa', 'thisType':'delivery', '_micro' : $(this).attr('data-_micro')};
			$(container).block( block_config );
			$(container).addClass('working');
			$(container).find('input, button').prop('disabled', true);

			$.post(cipscript.ajax_url, request)
			.fail(function() {
				// Swal.fire({ type: 'error', title: 'Something went wrong. Please try again.', text: '',allowOutsideClick: true}).then(function(){ });
				swalToast({ type: 'error', title: 'Something went wrong. Please try again.' });
			})
			.done(function(response) {
				if( response.error == 0 ){
					if( response.isopen == 1 ){
						$('<input>').attr({type: 'hidden',id: 'thisType',name: 'thisType', value: 'delivery'}).appendTo('form[name="smsaGa2faEnableFrm"]');
						$("#enableSmSaGa2faModal").modal('show');
					}else{
						// $this.prop( "checked", true );
						$('<input>').attr({type: 'hidden',id: 'thisType',name: 'thisType', value: 'delivery'}).appendTo('form[name="SmSaga2faToggleFrm"]');
						$('<input>').attr({type: 'hidden',id: 'thisToggle',name: 'thisToggle', value: 1}).appendTo('form[name="SmSaga2faToggleFrm"]');
						$("#toggleSaSmGa2faModal .main_heading b").html('Enable Google 2FA');
						$("#toggleSaSmGa2faModal").modal('show');
					}
				}else{
					// Swal.fire({ type: 'error', title: response.msg, text: '',allowOutsideClick: true}).then(function(){ });
					swalToast({ type: 'error', title: response.msg });
				}
				$(container).unblock();
			})
			.always(function(response) {
				if (!response.isReset) {
					$(container).find('input, button').prop('disabled', false);
					$(container).removeClass('working');
					$(container).unblock();
				}
			});

		}else{ //disable GA form delivery
			$this.prop( "checked", true );
			$('<input>').attr({type: 'hidden',id: 'thisType',name: 'thisType', value: 'delivery'}).appendTo('form[name="SmSaga2faToggleFrm"]');
			$('<input>').attr({type: 'hidden',id: 'thisToggle',name: 'thisToggle', value: 0}).appendTo('form[name="SmSaga2faToggleFrm"]');
			$("#toggleSaSmGa2faModal .main_heading b").html('Disable Google 2FA');
			$("#toggleSaSmGa2faModal").modal('show');
		}
		return false;
	});

	$('body').on('change', 'input[name="ga2fa_smsa_login"]', function(event){
		event.preventDefault();
		// console.log( $(this).is(':checked') );
		var $this = $(this);
		if( $(this).is(':checked') ){ //enable GA for login SM/SA
			$this.prop( "checked", false );

			var container = $('.2fa_ga_section');
			var request = {'action' : 'check_for_smsa_ga_twofa', 'thisType':'login', '_micro' : $(this).attr('data-_micro')};
			$(container).block( block_config );
			$(container).addClass('working');
			$(container).find('input, button').prop('disabled', true);

			$.post(cipscript.ajax_url, request)
			.fail(function() {
				// Swal.fire({ type: 'error', title: 'Something went wrong. Please try again.', text: '',allowOutsideClick: true}).then(function(){ });
				swalToast({ type: 'error', title: 'Something went wrong. Please try again.' });
			})
			.done(function(response) {
				if( response.error == 0 ){
					if( response.isopen == 1 ){
						$('<input>').attr({type: 'hidden',id: 'thisType',name: 'thisType', value: 'login'}).appendTo('form[name="smsaGa2faEnableFrm"]');
						$("#enableSmSaGa2faModal").modal('show');
					}else{
						// $this.prop( "checked", true );
						$('<input>').attr({type: 'hidden',id: 'thisType',name: 'thisType', value: 'login'}).appendTo('form[name="SmSaga2faToggleFrm"]');
						$('<input>').attr({type: 'hidden',id: 'thisToggle',name: 'thisToggle', value: 1}).appendTo('form[name="SmSaga2faToggleFrm"]');
						$("#toggleSaSmGa2faModal .main_heading b").html('Enable Google 2FA');
						$("#toggleSaSmGa2faModal").modal('show');
					}
				}else{
					// Swal.fire({ type: 'error', title: response.msg, text: '',allowOutsideClick: true}).then(function(){ });
					swalToast({ type: 'error', title: response.msg });
				}
				$(container).unblock();
			})
			.always(function(response) {
				if (!response.isReset) {
					$(container).find('input, button').prop('disabled', false);
					$(container).removeClass('working');
					$(container).unblock();
				}
			});

		}else{ //disable GA form login SM/SA
			$this.prop( "checked", true );
			$('<input>').attr({type: 'hidden',id: 'thisType',name: 'thisType', value: 'login'}).appendTo('form[name="SmSaga2faToggleFrm"]');
			$('<input>').attr({type: 'hidden',id: 'thisToggle',name: 'thisToggle', value: 0}).appendTo('form[name="SmSaga2faToggleFrm"]');
			$("#toggleSaSmGa2faModal .main_heading b").html('Disable Google 2FA');
			$("#toggleSaSmGa2faModal").modal('show');
		}
		return false;
	});

	$("#enableSmSaGa2faModal").on('hide.bs.modal', function () {
		$('#enableSmSaGa2faModal #thisType').remove();
		$('#enableSmSaGa2faModal form')[0].reset();
	});

	if( $('.smsaGa2faEnableFrm').length > 0 ){

        var current_fs, next_fs, previous_fs; //fieldsets
		var opacity;
		var current = 1;
		var steps = $('body').find(".smsaGa2faEnableFrm fieldset").length;
        setProgressBarWdGa(current);

		$('body').on("click",".next_wdga", function(event){
			var this_next = $(this);
			current_fs = $(this).closest('fieldset');
			next_fs = $(this).closest('fieldset').next();
			// console.log( current );
					
			var $form = $('body').find('.smsaGa2faEnableFrm'); 
			if( current == 3 ){
                google2FaWdelivery(event,'google2fa');
			}else{
				$(".smsaGa2faEnableFrm #progressbar li").eq( $(".smsaGa2faEnableFrm fieldset").index(next_fs) ).addClass("active");
				next_fs.show();
				current_fs.animate({opacity: 0}, {
					step: function(now) {
						opacity = 1 - now;
		
						current_fs.css({
							'display': 'none',
							'position': 'relative'
						});
						next_fs.css({'opacity': opacity});
					},
					duration: 500
				});
				setProgressBarWdGa(++current);
			}
		});

		$('body').on("click",".previous_wdga", function(){
			current_fs = $(this).closest('fieldset');
			previous_fs = $(this).closest('fieldset').prev();
			// console.log( current );

			$(".smsaGa2faEnableFrm #progressbar li").eq($(".smsaGa2faEnableFrm fieldset").index(current_fs)).removeClass("active");

			previous_fs.show();

			current_fs.animate({opacity: 0}, {
				step: function(now) {
					opacity = 1 - now;

					current_fs.css({
					'display': 'none',
					'position': 'relative'
					});
					previous_fs.css({'opacity': opacity});
				},
				duration: 500
			});
			setProgressBarWdGa(--current);
		});

		function setProgressBarWdGa(curStep){
			var percent = parseFloat(100 / steps) * curStep;
			percent = percent.toFixed();
			$('body').find(".smsaGa2faEnableFrm .progress-bar").css("width",percent+"%")
		}

		function google2FaWdelivery(event, fid) {
			event.preventDefault();
			if (fid == "google2fa") {
				if ($('#google_auth_key').val() != $('#backupkey').val()) {
					swalToast({ type: 'error', title: 'Please enter valid backup key to continue.' });
					return false;
				}
			}
	
			
			let form = $('form[name="smsaGa2faEnableFrm"');
			let formData = $('form[name="smsaGa2faEnableFrm"]')[0];
			let request = new FormData(formData);
			
			$(form).block( block_config );
			$(form).addClass('working');
			$(form).find('input, button').prop('disabled', true);
	
	
			$.ajax({
				url: cipscript.ajax_url,
				type: "POST",
				data: request,
				processData: false,
				contentType: false,
				success: function (response) {
					//var obj = JSON.parse( response );
					if( response.error == 0 ){
						// Swal.fire({ type: 'success', title: response.msg, text: '',allowOutsideClick: true}).then(function(){ window.location.reload(); });
						swalToast({ type: 'success', title: response.msg }).then(function(){ window.location.reload(); });
	
						$('#ga2fa_walletdelivery').prop( "checked", true );
						$('#ga2fa_smsa_login').prop( "checked", true );
						/* if( response.thisType == 'delivery' ){
							$('#ga2fa_walletdelivery').prop( "checked", true );
						}else if( response.thisType == 'login' ){
							$('#ga2fa_smsa_login').prop( "checked", true );
						} */
						$("#enableSmSaGa2faModal").modal('hide');
					}else{
						// Swal.fire({ type: 'error', title: response.msg, text: '',allowOutsideClick: true}).then(function(){ });
						swalToast({ type: 'error', title: response.msg });
					}
					$(form).find('input, button').prop('disabled', false);
					$(form).removeClass('working');
					$(form).unblock();
				}
			});
			return false;
		
		}

	}

	$('body').on('submit', 'form[name="SmSaga2faToggleFrm"]', function(event) {

		if( $(this).find('input[name="code"]').val() == "" ){
			// Swal.fire({ type: 'error', title: 'Please enter 6-digit google authenticator code.', text: '',allowOutsideClick: true}).then(function(){ });
			swalToast({ type: 'error', title: 'Please enter 6-digit google authenticator code.' });
			return false;
		}

		var container = $(this);
		var request = $(this).serialize();
		$(container).block( block_config );
		$(container).addClass('working');
		$(container).find('input, button').prop('disabled', true);

		$.post(cipscript.ajax_url, request)
		.fail(function() {
			// Swal.fire({ type: 'error', title: 'Something went wrong. Please try again.', text: '',allowOutsideClick: true}).then(function(){ });
			swalToast({ type: 'error', title: 'Something went wrong. Please try again.' });
		})
		.done(function(response) {
			if( response.error == 0 ){
				if( response.thisType == 'delivery' ){
					if( response.thisToggle == 0 ){
						$('#ga2fa_walletdelivery').prop( "checked", false );
					}else if( response.thisToggle == 1 ){
						$('#ga2fa_walletdelivery').prop( "checked", true );
					}
				}else if( response.thisType == 'login' ){
					if( response.thisToggle == 0 ){
						$('#ga2fa_smsa_login').prop( "checked", false );
					}else if( response.thisToggle == 1 ){
						$('#ga2fa_smsa_login').prop( "checked", true );
					}
				}
				$("#toggleSaSmGa2faModal").modal('hide');
				// Swal.fire({ type: 'success', title: response.msg, text: '',allowOutsideClick: true}).then(function(){ });
				swalToast({ type: 'success', title: response.msg });
			}else{
				// Swal.fire({ type: 'error', title: response.msg, text: '',allowOutsideClick: true}).then(function(){ });
				swalToast({ type: 'error', title: response.msg });
			}
			$(container).unblock();
		})
		.always(function(response) {
			if (!response.isReset) {
				$(container).find('input, button').prop('disabled', false);
				$(container).removeClass('working');
				$(container).unblock();
			}
		});
		return false;
	});
	$("#toggleSaSmGa2faModal").on('hide.bs.modal', function () {
		$('#toggleSaSmGa2faModal #thisType').remove();
		$('#toggleSaSmGa2faModal #thisToggle').remove();
		$('#toggleSaSmGa2faModal form')[0].reset();
		$("#toggleSaSmGa2faModal .main_heading b").html('');
	});

	$('form[name="SmSaga2faDisableFrm"]').submit(function(event) {

        if( $(this).find('input[name="code"]').val() == "" ){
            // Swal.fire({ type: 'error', title: 'Please enter 6-digit google authenticator code.', text: '',allowOutsideClick: true}).then(function(){ });
			swalToast({ type: 'error', title: 'Please enter 6-digit google authenticator code.' });
            return false;
        }

        let form = $('form[name="SmSaga2faDisableFrm"');
        let formData = $('form[name="SmSaga2faDisableFrm"]')[0];
        let request = new FormData(formData);
        
        $(form).block( block_config );
        $(form).addClass('working');
        $(form).find('input, button').prop('disabled', true);

        $.ajax({
            url: cipscript.ajax_url,
            type: "POST",
            data: request,
            processData: false,
            contentType: false,
            success: function (response) {
                if( response.error == 0 ){
                    // Swal.fire({ type: 'success', title: response.msg, text: '',allowOutsideClick: true}).then(function(){ window.location.reload(); });
					swalToast({ type: 'success', title: response.msg }).then(function(){ window.location.reload(); });
                    $("#disableSmSaGa2faModal").modal('hide');
                }else{
                    // Swal.fire({ type: 'error', title: response.msg, text: '',allowOutsideClick: true}).then(function(){ });
					swalToast({ type: 'error', title: response.msg });
                }
                $(form).find('input, button').prop('disabled', false);
                $(form).removeClass('working');
                $(form).unblock();
            }
        });
        return false;
    });
	
	if( $('#tokenholder_wallet_delivery .redemption_date').length > 0 ){
		let dateFormatWD = 'DD/MM/YYYY';
		$('input.bootstrap-table-filter-control-redemption_date[type="search"]')
		.daterangepicker({
				autoUpdateInput: false,
				locale: {
					format: dateFormatWD,
					separator: ' - ',
					firstDay: 1
				},
				opens: 'left',
				cancelButtonClasses: 'btn-default'
			},
		);
		jQuery('input.bootstrap-table-filter-control-redemption_date[type="search"]').on('apply.daterangepicker', function(ev, picker) {
			$(this).val(picker.startDate.format(dateFormatWD) + ' - ' + picker.endDate.format(dateFormatWD));
			let eve = jQuery.Event("keyup");
			eve.which = 13
			eve.keyCode = 13
			$('.bootstrap-table-filter-control-redemption_date').trigger(eve);
		});
		$('input.bootstrap-table-filter-control-redemption_date[type="search"]').on('cancel.daterangepicker', function(ev, picker) {
			$(this).val('');
			let eve = jQuery.Event("keyup");
			eve.which = 13
			eve.keyCode = 13
			$('.bootstrap-table-filter-control-redemption_date').trigger(eve);
		});
	}
	if( $('#tokenholder_wallet_delivery .claim_date').length > 0 ){
		let dateFormatWD = 'DD/MM/YYYY';
		$('input.bootstrap-table-filter-control-claim_date[type="search"]')
		.daterangepicker({
				autoUpdateInput: false,
				locale: {
					format: dateFormatWD,
					separator: ' - ',
					firstDay: 1
				},
				opens: 'left',
				cancelButtonClasses: 'btn-default'
			},
		);
		jQuery('input.bootstrap-table-filter-control-claim_date[type="search"]').on('apply.daterangepicker', function(ev, picker) {
			$(this).val(picker.startDate.format(dateFormatWD) + ' - ' + picker.endDate.format(dateFormatWD));
			let eve = jQuery.Event("keyup");
			eve.which = 13
			eve.keyCode = 13
			$('.bootstrap-table-filter-control-claim_date').trigger(eve);
		});
		$('input.bootstrap-table-filter-control-claim_date[type="search"]').on('cancel.daterangepicker', function(ev, picker) {
			$(this).val('');
			let eve = jQuery.Event("keyup");
			eve.which = 13
			eve.keyCode = 13
			$('.bootstrap-table-filter-control-claim_date').trigger(eve);
		});
	}
	if( $('#tokenholder_wallet_delivery .date_1').length > 0 ){
		let dateFormatWD = 'DD/MM/YYYY';
		$('input.bootstrap-table-filter-control-date_1[type="search"]')
		.daterangepicker({
				autoUpdateInput: false,
				locale: {
					format: dateFormatWD,
					separator: ' - ',
					firstDay: 1
				},
				opens: 'left',
				cancelButtonClasses: 'btn-default'
			},
		);
		jQuery('input.bootstrap-table-filter-control-date_1[type="search"]').on('apply.daterangepicker', function(ev, picker) {
			$(this).val(picker.startDate.format(dateFormatWD) + ' - ' + picker.endDate.format(dateFormatWD));
			let eve = jQuery.Event("keyup");
			eve.which = 13
			eve.keyCode = 13
			$('.bootstrap-table-filter-control-date_1').trigger(eve);
		});
		$('input.bootstrap-table-filter-control-date_1[type="search"]').on('cancel.daterangepicker', function(ev, picker) {
			$(this).val('');
			let eve = jQuery.Event("keyup");
			eve.which = 13
			eve.keyCode = 13
			$('.bootstrap-table-filter-control-date_1').trigger(eve);
		});
	}
	if( $('#tokenholder_wallet_delivery .date_2').length > 0 ){
		let dateFormatWD = 'DD/MM/YYYY';
		$('input.bootstrap-table-filter-control-date_2[type="search"]')
		.daterangepicker({
				autoUpdateInput: false,
				locale: {
					format: dateFormatWD,
					separator: ' - ',
					firstDay: 1
				},
				opens: 'left',
				cancelButtonClasses: 'btn-default'
			},
		);
		jQuery('input.bootstrap-table-filter-control-date_2[type="search"]').on('apply.daterangepicker', function(ev, picker) {
			$(this).val(picker.startDate.format(dateFormatWD) + ' - ' + picker.endDate.format(dateFormatWD));
			let eve = jQuery.Event("keyup");
			eve.which = 13
			eve.keyCode = 13
			$('.bootstrap-table-filter-control-date_2').trigger(eve);
		});
		$('input.bootstrap-table-filter-control-date_2[type="search"]').on('cancel.daterangepicker', function(ev, picker) {
			$(this).val('');
			let eve = jQuery.Event("keyup");
			eve.which = 13
			eve.keyCode = 13
			$('.bootstrap-table-filter-control-date_2').trigger(eve);
		});
	}
	if( $('#tokenholder_wallet_delivery .date_3').length > 0 ){
		let dateFormatWD = 'DD/MM/YYYY';
		$('input.bootstrap-table-filter-control-date_3[type="search"]')
		.daterangepicker({
				autoUpdateInput: false,
				locale: {
					format: dateFormatWD,
					separator: ' - ',
					firstDay: 1
				},
				opens: 'left',
				cancelButtonClasses: 'btn-default'
			},
		);
		jQuery('input.bootstrap-table-filter-control-date_3[type="search"]').on('apply.daterangepicker', function(ev, picker) {
			$(this).val(picker.startDate.format(dateFormatWD) + ' - ' + picker.endDate.format(dateFormatWD));
			let eve = jQuery.Event("keyup");
			eve.which = 13
			eve.keyCode = 13
			$('.bootstrap-table-filter-control-date_3').trigger(eve);
		});
		$('input.bootstrap-table-filter-control-date_3[type="search"]').on('cancel.daterangepicker', function(ev, picker) {
			$(this).val('');
			let eve = jQuery.Event("keyup");
			eve.which = 13
			eve.keyCode = 13
			$('.bootstrap-table-filter-control-date_3').trigger(eve);
		});
	}
	if( $('#tokenholder_wallet_delivery .date_4').length > 0 ){
		let dateFormatWD = 'DD/MM/YYYY';
		$('input.bootstrap-table-filter-control-date_4[type="search"]')
		.daterangepicker({
				autoUpdateInput: false,
				locale: {
					format: dateFormatWD,
					separator: ' - ',
					firstDay: 1
				},
				opens: 'left',
				cancelButtonClasses: 'btn-default'
			},
		);
		jQuery('input.bootstrap-table-filter-control-date_4[type="search"]').on('apply.daterangepicker', function(ev, picker) {
			$(this).val(picker.startDate.format(dateFormatWD) + ' - ' + picker.endDate.format(dateFormatWD));
			let eve = jQuery.Event("keyup");
			eve.which = 13
			eve.keyCode = 13
			$('.bootstrap-table-filter-control-date_4').trigger(eve);
		});
		$('input.bootstrap-table-filter-control-date_4[type="search"]').on('cancel.daterangepicker', function(ev, picker) {
			$(this).val('');
			let eve = jQuery.Event("keyup");
			eve.which = 13
			eve.keyCode = 13
			$('.bootstrap-table-filter-control-date_4').trigger(eve);
		});
	}
	if( $('#tokenholder_wallet_delivery .date_5').length > 0 ){
		let dateFormatWD = 'DD/MM/YYYY';
		$('input.bootstrap-table-filter-control-date_5[type="search"]')
		.daterangepicker({
				autoUpdateInput: false,
				locale: {
					format: dateFormatWD,
					separator: ' - ',
					firstDay: 1
				},
				opens: 'left',
				cancelButtonClasses: 'btn-default'
			},
		);
		jQuery('input.bootstrap-table-filter-control-date_5[type="search"]').on('apply.daterangepicker', function(ev, picker) {
			$(this).val(picker.startDate.format(dateFormatWD) + ' - ' + picker.endDate.format(dateFormatWD));
			let eve = jQuery.Event("keyup");
			eve.which = 13
			eve.keyCode = 13
			$('.bootstrap-table-filter-control-date_5').trigger(eve);
		});
		$('input.bootstrap-table-filter-control-date_5[type="search"]').on('cancel.daterangepicker', function(ev, picker) {
			$(this).val('');
			let eve = jQuery.Event("keyup");
			eve.which = 13
			eve.keyCode = 13
			$('.bootstrap-table-filter-control-date_5').trigger(eve);
		});
	}
	if( $('#tokenholder_wallet_delivery .date_6').length > 0 ){
		let dateFormatWD = 'DD/MM/YYYY';
		$('input.bootstrap-table-filter-control-date_6[type="search"]')
		.daterangepicker({
				autoUpdateInput: false,
				locale: {
					format: dateFormatWD,
					separator: ' - ',
					firstDay: 1
				},
				opens: 'left',
				cancelButtonClasses: 'btn-default'
			},
		);
		jQuery('input.bootstrap-table-filter-control-date_6[type="search"]').on('apply.daterangepicker', function(ev, picker) {
			$(this).val(picker.startDate.format(dateFormatWD) + ' - ' + picker.endDate.format(dateFormatWD));
			let eve = jQuery.Event("keyup");
			eve.which = 13
			eve.keyCode = 13
			$('.bootstrap-table-filter-control-date_6').trigger(eve);
		});
		$('input.bootstrap-table-filter-control-date_6[type="search"]').on('cancel.daterangepicker', function(ev, picker) {
			$(this).val('');
			let eve = jQuery.Event("keyup");
			eve.which = 13
			eve.keyCode = 13
			$('.bootstrap-table-filter-control-date_6').trigger(eve);
		});
	}
	if( $('#tokenholder_wallet_delivery .date_7').length > 0 ){
		let dateFormatWD = 'DD/MM/YYYY';
		$('input.bootstrap-table-filter-control-date_7[type="search"]')
		.daterangepicker({
				autoUpdateInput: false,
				locale: {
					format: dateFormatWD,
					separator: ' - ',
					firstDay: 1
				},
				opens: 'left',
				cancelButtonClasses: 'btn-default'
			},
		);
		jQuery('input.bootstrap-table-filter-control-date_7[type="search"]').on('apply.daterangepicker', function(ev, picker) {
			$(this).val(picker.startDate.format(dateFormatWD) + ' - ' + picker.endDate.format(dateFormatWD));
			let eve = jQuery.Event("keyup");
			eve.which = 13
			eve.keyCode = 13
			$('.bootstrap-table-filter-control-date_7').trigger(eve);
		});
		$('input.bootstrap-table-filter-control-date_7[type="search"]').on('cancel.daterangepicker', function(ev, picker) {
			$(this).val('');
			let eve = jQuery.Event("keyup");
			eve.which = 13
			eve.keyCode = 13
			$('.bootstrap-table-filter-control-date_7').trigger(eve);
		});
	}
	if( $('#tokenholder_wallet_delivery .date_8').length > 0 ){
		let dateFormatWD = 'DD/MM/YYYY';
		$('input.bootstrap-table-filter-control-date_8[type="search"]')
		.daterangepicker({
				autoUpdateInput: false,
				locale: {
					format: dateFormatWD,
					separator: ' - ',
					firstDay: 1
				},
				opens: 'left',
				cancelButtonClasses: 'btn-default'
			},
		);
		jQuery('input.bootstrap-table-filter-control-date_8[type="search"]').on('apply.daterangepicker', function(ev, picker) {
			$(this).val(picker.startDate.format(dateFormatWD) + ' - ' + picker.endDate.format(dateFormatWD));
			let eve = jQuery.Event("keyup");
			eve.which = 13
			eve.keyCode = 13
			$('.bootstrap-table-filter-control-date_8').trigger(eve);
		});
		$('input.bootstrap-table-filter-control-date_8[type="search"]').on('cancel.daterangepicker', function(ev, picker) {
			$(this).val('');
			let eve = jQuery.Event("keyup");
			eve.which = 13
			eve.keyCode = 13
			$('.bootstrap-table-filter-control-date_8').trigger(eve);
		});
	}
	if( $('#tokenholder_wallet_delivery .date_9').length > 0 ){
		let dateFormatWD = 'DD/MM/YYYY';
		$('input.bootstrap-table-filter-control-date_9[type="search"]')
		.daterangepicker({
				autoUpdateInput: false,
				locale: {
					format: dateFormatWD,
					separator: ' - ',
					firstDay: 1
				},
				opens: 'left',
				cancelButtonClasses: 'btn-default'
			},
		);
		jQuery('input.bootstrap-table-filter-control-date_9[type="search"]').on('apply.daterangepicker', function(ev, picker) {
			$(this).val(picker.startDate.format(dateFormatWD) + ' - ' + picker.endDate.format(dateFormatWD));
			let eve = jQuery.Event("keyup");
			eve.which = 13
			eve.keyCode = 13
			$('.bootstrap-table-filter-control-date_9').trigger(eve);
		});
		$('input.bootstrap-table-filter-control-date_9[type="search"]').on('cancel.daterangepicker', function(ev, picker) {
			$(this).val('');
			let eve = jQuery.Event("keyup");
			eve.which = 13
			eve.keyCode = 13
			$('.bootstrap-table-filter-control-date_9').trigger(eve);
		});
	}
	if( $('#tokenholder_wallet_delivery .date_10').length > 0 ){
		let dateFormatWD = 'DD/MM/YYYY';
		$('input.bootstrap-table-filter-control-date_10[type="search"]')
		.daterangepicker({
				autoUpdateInput: false,
				locale: {
					format: dateFormatWD,
					separator: ' - ',
					firstDay: 1
				},
				opens: 'left',
				cancelButtonClasses: 'btn-default'
			},
		);
		jQuery('input.bootstrap-table-filter-control-date_10[type="search"]').on('apply.daterangepicker', function(ev, picker) {
			$(this).val(picker.startDate.format(dateFormatWD) + ' - ' + picker.endDate.format(dateFormatWD));
			let eve = jQuery.Event("keyup");
			eve.which = 13
			eve.keyCode = 13
			$('.bootstrap-table-filter-control-date_10').trigger(eve);
		});
		$('input.bootstrap-table-filter-control-date_10[type="search"]').on('cancel.daterangepicker', function(ev, picker) {
			$(this).val('');
			let eve = jQuery.Event("keyup");
			eve.which = 13
			eve.keyCode = 13
			$('.bootstrap-table-filter-control-date_10').trigger(eve);
		});
	}
	if( $('#tokenholder_wallet_delivery .saving_date').length > 0 ){
		let dateFormatWD = 'DD/MM/YYYY';
		$('input.bootstrap-table-filter-control-saving_date[type="search"]')
		.daterangepicker({
				autoUpdateInput: false,
				locale: {
					format: dateFormatWD,
					separator: ' - ',
					firstDay: 1
				},
				opens: 'left',
				cancelButtonClasses: 'btn-default'
			},
		);
		jQuery('input.bootstrap-table-filter-control-saving_date[type="search"]').on('apply.daterangepicker', function(ev, picker) {
			$(this).val(picker.startDate.format(dateFormatWD) + ' - ' + picker.endDate.format(dateFormatWD));
			let eve = jQuery.Event("keyup");
			eve.which = 13
			eve.keyCode = 13
			$('.bootstrap-table-filter-control-saving_date').trigger(eve);
		});
		$('input.bootstrap-table-filter-control-saving_date[type="search"]').on('cancel.daterangepicker', function(ev, picker) {
			$(this).val('');
			let eve = jQuery.Event("keyup");
			eve.which = 13
			eve.keyCode = 13
			$('.bootstrap-table-filter-control-saving_date').trigger(eve);
		});
	}
	if( $('#tokenholder_wallet_delivery .saving_start_date').length > 0 ){
		let dateFormatWD = 'DD/MM/YYYY';
		$('input.bootstrap-table-filter-control-saving_start_date[type="search"]')
		.daterangepicker({
				autoUpdateInput: false,
				locale: {
					format: dateFormatWD,
					separator: ' - ',
					firstDay: 1
				},
				opens: 'left',
				cancelButtonClasses: 'btn-default'
			},
		);
		jQuery('input.bootstrap-table-filter-control-saving_start_date[type="search"]').on('apply.daterangepicker', function(ev, picker) {
			$(this).val(picker.startDate.format(dateFormatWD) + ' - ' + picker.endDate.format(dateFormatWD));
			let eve = jQuery.Event("keyup");
			eve.which = 13
			eve.keyCode = 13
			$('.bootstrap-table-filter-control-saving_start_date').trigger(eve);
		});
		$('input.bootstrap-table-filter-control-saving_start_date[type="search"]').on('cancel.daterangepicker', function(ev, picker) {
			$(this).val('');
			let eve = jQuery.Event("keyup");
			eve.which = 13
			eve.keyCode = 13
			$('.bootstrap-table-filter-control-saving_start_date').trigger(eve);
		});
	}

	if( $('#tokenholder_wallet_delivery').length > 0 ){
		var $notes_external = $('input.bootstrap-table-filter-control-notes_external[type="search"]');
		$notes_external.on('click', function(){
			$('#notesFilterModal').modal({backdrop: 'static',keyboard: false});
		});
		
		var $pool_ref = $('input.bootstrap-table-filter-control-pool_ref[type="search"]');
		$pool_ref.on('click', function(){
			$('#poolRefFilterModal').modal({backdrop: 'static',keyboard: false});
		});
		
		var $distribution_week = $('input.bootstrap-table-filter-control-text_10[type="search"]');
		$distribution_week.on('click', function(){
			$('#DistributionWeekFilterModal').modal({backdrop: 'static',keyboard: false});
		});
		
		var $username = $('input.bootstrap-table-filter-control-username[type="search"]');
		$username.on('click', function(){
			$('#UsernameFilterModal').modal({backdrop: 'static',keyboard: false});
		});

		$('.filter_by_notes .filter_csr_ok').on('click', function(){ //notes
			let eve = jQuery.Event("keyup");
			eve.which = 13
			eve.keyCode = 13
			$notes_external.trigger(eve);
			$('#notesFilterModal').modal('hide');

			var filterNoteForm = $('#filter_by_notes');
			var condition_type_text = filterNoteForm.find('select[name="filter_condition_type"] option:selected').text();
			var condition_type_value = filterNoteForm.find('input[name="filter_condition_value"]').val();
			var filterText = condition_type_text;
			if( condition_type_value != "" ){
				filterText += ': '+condition_type_value;
			}
			if( condition_type_text == 'None' ){
				filterText = "";
			}
			$('body').find('.note_filter_info').text( filterText );

		});
		$('.filter_by_pool_ref .filter_csr_ok').on('click', function(){ //pool ref
			let eve = jQuery.Event("keyup");
			eve.which = 13
			eve.keyCode = 13
			$pool_ref.trigger(eve);
			$('#poolRefFilterModal').modal('hide');

			var filterNoteForm = $('#filter_by_pool_ref');
			var condition_type_text = filterNoteForm.find('select[name="filter_condition_type_pool_ref"] option:selected').text();
			var condition_type = filterNoteForm.find('select[name="filter_condition_type_pool_ref"] option:selected').val();
			var condition_type_value = filterNoteForm.find('select#filter_condition_value_pool_ref').val();
			var condition_type_value_bulk = filterNoteForm.find('textarea#filter_condition_value_pool_ref_bulk').val();
			var filterText = condition_type_text;
			if( condition_type_value != "" || condition_type_value_bulk != '' ){
				if( condition_type == 'is_exactly_simple' ){
					filterText += ': '+condition_type_value_bulk;
				}else{
					filterText += ': '+condition_type_value;
				}
			}
			if( condition_type_text == 'None' ){
				filterText = "";
			}
			$('body').find('.pool_ref_filter_info').text( filterText );

		});
		$('.filter_by_distribution_week .filter_csr_ok').on('click', function(){ //distribution_week text_10
			let eve = jQuery.Event("keyup");
			eve.which = 13
			eve.keyCode = 13
			$pool_ref.trigger(eve);
			$('#DistributionWeekFilterModal').modal('hide');

			var filterNoteForm = $('#filter_by_distribution_week');
			var condition_type_text = filterNoteForm.find('select[name="filter_condition_type_distribution_week"] option:selected').text();
			var condition_type = filterNoteForm.find('select[name="filter_condition_type_distribution_week"] option:selected').val();
			var condition_type_value = filterNoteForm.find('select#filter_condition_value_distribution_week').val();
			var condition_type_value_before = filterNoteForm.find('#filter_condition_value_distribution_week_before').val();
			var condition_type_value_bulk = filterNoteForm.find('textarea#filter_condition_value_distribution_bulk').val();
			var filterText = condition_type_text;
			if( condition_type_value != "" || condition_type_value_bulk != '' || condition_type_value_before != "" ){
				if( condition_type == 'weeks_before' ){
					filterText += ': '+condition_type_value_before;
				}else if( condition_type == 'is_exactly_simple' ){
					filterText += ': '+condition_type_value_bulk;
				}else{
					filterText += ': '+condition_type_value;
				}
			}
			if( condition_type_text == 'None' ){
				filterText = "";
			}
			$('body').find('.distribution_week_filter_info').text( filterText );

		});
		$('.filter_by_username .filter_csr_ok').on('click', function(){ //username
			let eve = jQuery.Event("keyup");
			eve.which = 13
			eve.keyCode = 13
			$pool_ref.trigger(eve);
			$('#UsernameFilterModal').modal('hide');

			var filterNoteForm = $('#filter_by_username');
			var condition_type_text = filterNoteForm.find('select[name="filter_condition_type_username"] option:selected').text();
			var condition_type = filterNoteForm.find('select[name="filter_condition_type_username"] option:selected').val();
			var condition_type_value = filterNoteForm.find('select#filter_condition_value_username').val();
			var condition_type_value_bulk = filterNoteForm.find('textarea#filter_condition_value_username_bulk').val();
			var filterText = condition_type_text;
			if( condition_type_value != "" || condition_type_value_bulk != "" ){
				if( condition_type == 'is_exactly_simple' ){
					filterText += ': '+condition_type_value_bulk;
				}else{
					filterText += ': '+condition_type_value;
				}
			}
			if( condition_type_text == 'None' ){
				filterText = "";
			}
			$('body').find('.username_filter_info').text( filterText );

		});

		$('form#filter_by_notes, form#filter_by_pool_ref, form#filter_by_distribution_week, form#filter_by_username').keydown(function (e) {
			if (e.keyCode == 13) {
				$('.filter_csr_ok').trigger('click');
				e.preventDefault();
				return false;
			}
		});

		$('.filter_by_notes .filter_csr_cancel').on('click', function(){
			$('#notesFilterModal').modal('hide');
		});
		$('.filter_by_pool_ref .filter_csr_cancel').on('click', function(){
			$('#poolRefFilterModal').modal('hide');
		});
		$('.filter_by_distribution_week .filter_csr_cancel').on('click', function(){
			$('#DistributionWeekFilterModal').modal('hide');
		});
		$('.filter_by_username .filter_csr_cancel').on('click', function(){
			$('#UsernameFilterModal').modal('hide');
		});

		$('.filter_by_pool_ref #filter_condition_value_pool_ref').select2({placeholder: 'Pool Reference',tags: true, selectionCssClass: 'select2_pool_ref hide mt-2', dropdownParent: $('#poolRefFilterModal')});
		$('.filter_by_distribution_week #filter_condition_value_distribution_week').select2({placeholder: 'Distribution Week',tags: true, selectionCssClass: 'select2_distribution_week hide mt-2', dropdownParent: $('#DistributionWeekFilterModal')});
		$('.filter_by_username #filter_condition_value_username').select2({
			// placeholder: 'Username',tags: true, selectionCssClass: 'select2_username hide mt-2', dropdownParent: $('#UsernameFilterModal')
			placeholder: 'Username',
			minimumInputLength: 2,
			ajax: {
				url: cipscript.ajax_url,
				dataType: 'json',
				data: function (params) {
					var query = {
						search: params.term,
						action: 'username_fetch_act'
					}
					return query;
				}
			},
			processResults: function (response) {
				return {
				   results: response
				};
			},
			selectionCssClass: 'select2_username hide mt-2',
			dropdownParent: $('#UsernameFilterModal')
		});
	}

	if( $('#tokenholder_wallet_delivery_report').length > 0 ){
		let dateFormat = 'DD/MM/YYYY';
		var $redemption_date = $('input.bootstrap-table-filter-control-redemption_date[type="search"]');
		var $claim_date = $('input.bootstrap-table-filter-control-claim_date[type="search"]');
		var $date_1 = $('input.bootstrap-table-filter-control-date_1[type="search"]');
		var $date_2 = $('input.bootstrap-table-filter-control-date_2[type="search"]');
		var $date_3 = $('input.bootstrap-table-filter-control-date_3[type="search"]');
		var $date_4 = $('input.bootstrap-table-filter-control-date_4[type="search"]');
		var $date_5 = $('input.bootstrap-table-filter-control-date_5[type="search"]');
		var $date_6 = $('input.bootstrap-table-filter-control-date_6[type="search"]');
		var $date_7 = $('input.bootstrap-table-filter-control-date_7[type="search"]');
		var $date_8 = $('input.bootstrap-table-filter-control-date_8[type="search"]');
		var $date_9 = $('input.bootstrap-table-filter-control-date_9[type="search"]');
		var $date_10 = $('input.bootstrap-table-filter-control-date_10[type="search"]');
		var $saving_date = $('input.bootstrap-table-filter-control-saving_date[type="search"]');
		var $saving_start_date = $('input.bootstrap-table-filter-control-saving_start_date[type="search"]');
		var $notes_external = $('input.bootstrap-table-filter-control-notes_external[type="search"]');
		
		if( $redemption_date.length > 0 ){
			$redemption_date.daterangepicker({
					autoUpdateInput: false,
					locale: {
						format: dateFormat,
						separator: ' - ',
						firstDay: 2
					},
					opens: 'left',
					cancelButtonClasses: 'btn-default cancelButton_daterangepicker'
				},
				function(start, end) {
					startDate = start.format(dateFormat);
					endDate = end.format(dateFormat);
					let dates = [ startDate, endDate ];
					$redemption_date.val(start.format(dateFormat) + ' - ' + end.format(dateFormat));
				}
			);
			$redemption_date.on('apply.daterangepicker', function(ev, picker) {
				$(this).val(picker.startDate.format(dateFormat) + ' - ' + picker.endDate.format(dateFormat));
				let eve = jQuery.Event("keyup");
				eve.which = 13
				eve.keyCode = 13
				$redemption_date.trigger(eve);
			});
			$redemption_date.on('cancel.daterangepicker', function(ev, picker) {
				$(this).val('');
				let eve = jQuery.Event("keyup");
				eve.which = 13
				eve.keyCode = 13
				$redemption_date.trigger(eve);
			});
		}
		if( $claim_date.length > 0 ){
			$claim_date.daterangepicker({
					autoUpdateInput: false,
					locale: {
						format: dateFormat,
						separator: ' - ',
						firstDay: 2
					},
					opens: 'left',
					cancelButtonClasses: 'btn-default cancelButton_daterangepicker'
				},
				function(start, end) {
					startDate = start.format(dateFormat);
					endDate = end.format(dateFormat);
					let dates = [ startDate, endDate ];
					$claim_date.val(start.format(dateFormat) + ' - ' + end.format(dateFormat));
				}
			);
			$claim_date.on('apply.daterangepicker', function(ev, picker) {
				$(this).val(picker.startDate.format(dateFormat) + ' - ' + picker.endDate.format(dateFormat));
				let eve = jQuery.Event("keyup");
				eve.which = 13
				eve.keyCode = 13
				$claim_date.trigger(eve);
			});
			$claim_date.on('cancel.daterangepicker', function(ev, picker) {
				$(this).val('');
				let eve = jQuery.Event("keyup");
				eve.which = 13
				eve.keyCode = 13
				$claim_date.trigger(eve);
			});
		}
		if( $date_1.length > 0 ){
			$date_1.daterangepicker({
					autoUpdateInput: false,
					locale: {
						format: dateFormat,
						separator: ' - ',
						firstDay: 2
					},
					opens: 'left',
					cancelButtonClasses: 'btn-default cancelButton_daterangepicker'
				},
				function(start, end) {
					startDate = start.format(dateFormat);
					endDate = end.format(dateFormat);
					let dates = [ startDate, endDate ];
					$date_1.val(start.format(dateFormat) + ' - ' + end.format(dateFormat));
				}
			);
			$date_1.on('apply.daterangepicker', function(ev, picker) {
				$(this).val(picker.startDate.format(dateFormat) + ' - ' + picker.endDate.format(dateFormat));
				let eve = jQuery.Event("keyup");
				eve.which = 13
				eve.keyCode = 13
				$date_1.trigger(eve);
			});
			$date_1.on('cancel.daterangepicker', function(ev, picker) {
				$(this).val('');
				let eve = jQuery.Event("keyup");
				eve.which = 13
				eve.keyCode = 13
				$date_1.trigger(eve);
			});
		}
		if( $date_2.length > 0 ){
			$date_2.daterangepicker({
					autoUpdateInput: false,
					locale: {
						format: dateFormat,
						separator: ' - ',
						firstDay: 2
					},
					opens: 'left',
					cancelButtonClasses: 'btn-default cancelButton_daterangepicker'
				},
				function(start, end) {
					startDate = start.format(dateFormat);
					endDate = end.format(dateFormat);
					let dates = [ startDate, endDate ];
					$date_2.val(start.format(dateFormat) + ' - ' + end.format(dateFormat));
				}
			);
			$date_2.on('apply.daterangepicker', function(ev, picker) {
				$(this).val(picker.startDate.format(dateFormat) + ' - ' + picker.endDate.format(dateFormat));
				let eve = jQuery.Event("keyup");
				eve.which = 13
				eve.keyCode = 13
				$date_2.trigger(eve);
			});
			$date_2.on('cancel.daterangepicker', function(ev, picker) {
				$(this).val('');
				let eve = jQuery.Event("keyup");
				eve.which = 13
				eve.keyCode = 13
				$date_2.trigger(eve);
			});
		}
		if( $date_3.length > 0 ){
			$date_3.daterangepicker({
					autoUpdateInput: false,
					locale: {
						format: dateFormat,
						separator: ' - ',
						firstDay: 2
					},
					opens: 'left',
					cancelButtonClasses: 'btn-default cancelButton_daterangepicker'
				},
				function(start, end) {
					startDate = start.format(dateFormat);
					endDate = end.format(dateFormat);
					let dates = [ startDate, endDate ];
					$date_3.val(start.format(dateFormat) + ' - ' + end.format(dateFormat));
				}
			);
			$date_3.on('apply.daterangepicker', function(ev, picker) {
				$(this).val(picker.startDate.format(dateFormat) + ' - ' + picker.endDate.format(dateFormat));
				let eve = jQuery.Event("keyup");
				eve.which = 13
				eve.keyCode = 13
				$date_3.trigger(eve);
			});
			$date_3.on('cancel.daterangepicker', function(ev, picker) {
				$(this).val('');
				let eve = jQuery.Event("keyup");
				eve.which = 13
				eve.keyCode = 13
				$date_3.trigger(eve);
			});
		}
		if( $date_4.length > 0 ){
			$date_4.daterangepicker({
					autoUpdateInput: false,
					locale: {
						format: dateFormat,
						separator: ' - ',
						firstDay: 2
					},
					opens: 'left',
					cancelButtonClasses: 'btn-default cancelButton_daterangepicker'
				},
				function(start, end) {
					startDate = start.format(dateFormat);
					endDate = end.format(dateFormat);
					let dates = [ startDate, endDate ];
					$date_4.val(start.format(dateFormat) + ' - ' + end.format(dateFormat));
				}
			);
			$date_4.on('apply.daterangepicker', function(ev, picker) {
				$(this).val(picker.startDate.format(dateFormat) + ' - ' + picker.endDate.format(dateFormat));
				let eve = jQuery.Event("keyup");
				eve.which = 13
				eve.keyCode = 13
				$date_4.trigger(eve);
			});
			$date_4.on('cancel.daterangepicker', function(ev, picker) {
				$(this).val('');
				let eve = jQuery.Event("keyup");
				eve.which = 13
				eve.keyCode = 13
				$date_4.trigger(eve);
			});
		}
		if( $date_5.length > 0 ){
			$date_5.daterangepicker({
					autoUpdateInput: false,
					locale: {
						format: dateFormat,
						separator: ' - ',
						firstDay: 2
					},
					opens: 'left',
					cancelButtonClasses: 'btn-default cancelButton_daterangepicker'
				},
				function(start, end) {
					startDate = start.format(dateFormat);
					endDate = end.format(dateFormat);
					let dates = [ startDate, endDate ];
					$date_5.val(start.format(dateFormat) + ' - ' + end.format(dateFormat));
				}
			);
			$date_5.on('apply.daterangepicker', function(ev, picker) {
				$(this).val(picker.startDate.format(dateFormat) + ' - ' + picker.endDate.format(dateFormat));
				let eve = jQuery.Event("keyup");
				eve.which = 13
				eve.keyCode = 13
				$date_5.trigger(eve);
			});
			$date_5.on('cancel.daterangepicker', function(ev, picker) {
				$(this).val('');
				let eve = jQuery.Event("keyup");
				eve.which = 13
				eve.keyCode = 13
				$date_5.trigger(eve);
			});
		}
		if( $date_6.length > 0 ){
			$date_6.daterangepicker({
					autoUpdateInput: false,
					locale: {
						format: dateFormat,
						separator: ' - ',
						firstDay: 2
					},
					opens: 'left',
					cancelButtonClasses: 'btn-default cancelButton_daterangepicker'
				},
				function(start, end) {
					startDate = start.format(dateFormat);
					endDate = end.format(dateFormat);
					let dates = [ startDate, endDate ];
					$date_6.val(start.format(dateFormat) + ' - ' + end.format(dateFormat));
				}
			);
			$date_6.on('apply.daterangepicker', function(ev, picker) {
				$(this).val(picker.startDate.format(dateFormat) + ' - ' + picker.endDate.format(dateFormat));
				let eve = jQuery.Event("keyup");
				eve.which = 13
				eve.keyCode = 13
				$date_6.trigger(eve);
			});
			$date_6.on('cancel.daterangepicker', function(ev, picker) {
				$(this).val('');
				let eve = jQuery.Event("keyup");
				eve.which = 13
				eve.keyCode = 13
				$date_6.trigger(eve);
			});
		}
		if( $date_7.length > 0 ){
			$date_7.daterangepicker({
					autoUpdateInput: false,
					locale: {
						format: dateFormat,
						separator: ' - ',
						firstDay: 2
					},
					opens: 'left',
					cancelButtonClasses: 'btn-default cancelButton_daterangepicker'
				},
				function(start, end) {
					startDate = start.format(dateFormat);
					endDate = end.format(dateFormat);
					let dates = [ startDate, endDate ];
					$date_7.val(start.format(dateFormat) + ' - ' + end.format(dateFormat));
				}
			);
			$date_7.on('apply.daterangepicker', function(ev, picker) {
				$(this).val(picker.startDate.format(dateFormat) + ' - ' + picker.endDate.format(dateFormat));
				let eve = jQuery.Event("keyup");
				eve.which = 13
				eve.keyCode = 13
				$date_7.trigger(eve);
			});
			$date_7.on('cancel.daterangepicker', function(ev, picker) {
				$(this).val('');
				let eve = jQuery.Event("keyup");
				eve.which = 13
				eve.keyCode = 13
				$date_7.trigger(eve);
			});
		}
		if( $date_8.length > 0 ){
			$date_8.daterangepicker({
					autoUpdateInput: false,
					locale: {
						format: dateFormat,
						separator: ' - ',
						firstDay: 2
					},
					opens: 'left',
					cancelButtonClasses: 'btn-default cancelButton_daterangepicker'
				},
				function(start, end) {
					startDate = start.format(dateFormat);
					endDate = end.format(dateFormat);
					let dates = [ startDate, endDate ];
					$date_8.val(start.format(dateFormat) + ' - ' + end.format(dateFormat));
				}
			);
			$date_8.on('apply.daterangepicker', function(ev, picker) {
				$(this).val(picker.startDate.format(dateFormat) + ' - ' + picker.endDate.format(dateFormat));
				let eve = jQuery.Event("keyup");
				eve.which = 13
				eve.keyCode = 13
				$date_8.trigger(eve);
			});
			$date_8.on('cancel.daterangepicker', function(ev, picker) {
				$(this).val('');
				let eve = jQuery.Event("keyup");
				eve.which = 13
				eve.keyCode = 13
				$date_8.trigger(eve);
			});
		}
		if( $date_9.length > 0 ){
			$date_9.daterangepicker({
					autoUpdateInput: false,
					locale: {
						format: dateFormat,
						separator: ' - ',
						firstDay: 2
					},
					opens: 'left',
					cancelButtonClasses: 'btn-default cancelButton_daterangepicker'
				},
				function(start, end) {
					startDate = start.format(dateFormat);
					endDate = end.format(dateFormat);
					let dates = [ startDate, endDate ];
					$date_9.val(start.format(dateFormat) + ' - ' + end.format(dateFormat));
				}
			);
			$date_9.on('apply.daterangepicker', function(ev, picker) {
				$(this).val(picker.startDate.format(dateFormat) + ' - ' + picker.endDate.format(dateFormat));
				let eve = jQuery.Event("keyup");
				eve.which = 13
				eve.keyCode = 13
				$date_9.trigger(eve);
			});
			$date_9.on('cancel.daterangepicker', function(ev, picker) {
				$(this).val('');
				let eve = jQuery.Event("keyup");
				eve.which = 13
				eve.keyCode = 13
				$date_9.trigger(eve);
			});
		}
		if( $date_10.length > 0 ){
			$date_10.daterangepicker({
					autoUpdateInput: false,
					locale: {
						format: dateFormat,
						separator: ' - ',
						firstDay: 2
					},
					opens: 'left',
					cancelButtonClasses: 'btn-default cancelButton_daterangepicker'
				},
				function(start, end) {
					startDate = start.format(dateFormat);
					endDate = end.format(dateFormat);
					let dates = [ startDate, endDate ];
					$date_10.val(start.format(dateFormat) + ' - ' + end.format(dateFormat));
				}
			);
			$date_10.on('apply.daterangepicker', function(ev, picker) {
				$(this).val(picker.startDate.format(dateFormat) + ' - ' + picker.endDate.format(dateFormat));
				let eve = jQuery.Event("keyup");
				eve.which = 13
				eve.keyCode = 13
				$date_10.trigger(eve);
			});
			$date_10.on('cancel.daterangepicker', function(ev, picker) {
				$(this).val('');
				let eve = jQuery.Event("keyup");
				eve.which = 13
				eve.keyCode = 13
				$date_10.trigger(eve);
			});
		}
		if( $saving_date.length > 0 ){
			$saving_date.daterangepicker({
					autoUpdateInput: false,
					locale: {
						format: dateFormat,
						separator: ' - ',
						firstDay: 2
					},
					opens: 'left',
					cancelButtonClasses: 'btn-default cancelButton_daterangepicker'
				},
				function(start, end) {
					startDate = start.format(dateFormat);
					endDate = end.format(dateFormat);
					let dates = [ startDate, endDate ];
					$saving_date.val(start.format(dateFormat) + ' - ' + end.format(dateFormat));
				}
			);
			$saving_date.on('apply.daterangepicker', function(ev, picker) {
				$(this).val(picker.startDate.format(dateFormat) + ' - ' + picker.endDate.format(dateFormat));
				let eve = jQuery.Event("keyup");
				eve.which = 13
				eve.keyCode = 13
				$saving_date.trigger(eve);
			});
			$saving_date.on('cancel.daterangepicker', function(ev, picker) {
				$(this).val('');
				let eve = jQuery.Event("keyup");
				eve.which = 13
				eve.keyCode = 13
				$saving_date.trigger(eve);
			});
		}
		if( $saving_start_date.length > 0 ){
			$saving_start_date.daterangepicker({
					autoUpdateInput: false,
					locale: {
						format: dateFormat,
						separator: ' - ',
						firstDay: 2
					},
					opens: 'left',
					cancelButtonClasses: 'btn-default cancelButton_daterangepicker'
				},
				function(start, end) {
					startDate = start.format(dateFormat);
					endDate = end.format(dateFormat);
					let dates = [ startDate, endDate ];
					$saving_start_date.val(start.format(dateFormat) + ' - ' + end.format(dateFormat));
				}
			);
			$saving_start_date.on('apply.daterangepicker', function(ev, picker) {
				$(this).val(picker.startDate.format(dateFormat) + ' - ' + picker.endDate.format(dateFormat));
				let eve = jQuery.Event("keyup");
				eve.which = 13
				eve.keyCode = 13
				$saving_start_date.trigger(eve);
			});
			$saving_start_date.on('cancel.daterangepicker', function(ev, picker) {
				$(this).val('');
				let eve = jQuery.Event("keyup");
				eve.which = 13
				eve.keyCode = 13
				$saving_start_date.trigger(eve);
			});
		}

		var $notes_external = $('input.bootstrap-table-filter-control-notes_external[type="search"]');
		$notes_external.on('click', function(){
			$('#notesFilterModal').modal({backdrop: 'static',keyboard: false});
		});
		
		var $pool_ref = $('input.bootstrap-table-filter-control-pool_ref[type="search"]');
		$pool_ref.on('click', function(){
			$('#poolRefFilterModal').modal({backdrop: 'static',keyboard: false});
		});
		
		var $distribution_week = $('input.bootstrap-table-filter-control-text_10[type="search"]');
		$distribution_week.on('click', function(){
			$('#DistributionWeekFilterModal').modal({backdrop: 'static',keyboard: false});
		});
		
		var $username = $('input.bootstrap-table-filter-control-username[type="search"]');
		$username.on('click', function(){
			$('#UsernameFilterModal').modal({backdrop: 'static',keyboard: false});
		});

		$('.filter_by_notes .filter_csr_ok').on('click', function(){ //notes
			let eve = jQuery.Event("keyup");
			eve.which = 13
			eve.keyCode = 13
			$notes_external.trigger(eve);
			$('#notesFilterModal').modal('hide');

			var filterNoteForm = $('#filter_by_notes');
			var condition_type_text = filterNoteForm.find('select[name="filter_condition_type"] option:selected').text();
			var condition_type_value = filterNoteForm.find('input[name="filter_condition_value"]').val();
			var filterText = condition_type_text;
			if( condition_type_value != "" ){
				filterText += ': '+condition_type_value;
			}
			if( condition_type_text == 'None' ){
				filterText = "";
			}
			$('body').find('.note_filter_info').text( filterText );

		});
		$('.filter_by_pool_ref .filter_csr_ok').on('click', function(){ //pool ref
			let eve = jQuery.Event("keyup");
			eve.which = 13
			eve.keyCode = 13
			$pool_ref.trigger(eve);
			$('#poolRefFilterModal').modal('hide');

			var filterNoteForm = $('#filter_by_pool_ref');
			var condition_type_text = filterNoteForm.find('select[name="filter_condition_type_pool_ref"] option:selected').text();
			var condition_type = filterNoteForm.find('select[name="filter_condition_type_pool_ref"] option:selected').val();
			var condition_type_value = filterNoteForm.find('select#filter_condition_value_pool_ref').val();
			var condition_type_value_bulk = filterNoteForm.find('textarea#filter_condition_value_pool_ref_bulk').val();
			var filterText = condition_type_text;
			if( condition_type_value != "" || condition_type_value_bulk != '' ){
				if( condition_type == 'is_exactly_simple' ){
					filterText += ': '+condition_type_value_bulk;
				}else{
					filterText += ': '+condition_type_value;
				}
			}
			if( condition_type_text == 'None' ){
				filterText = "";
			}
			$('body').find('.pool_ref_filter_info').text( filterText );

		});
		$('.filter_by_distribution_week .filter_csr_ok').on('click', function(){ //distribution_week text_10
			let eve = jQuery.Event("keyup");
			eve.which = 13
			eve.keyCode = 13
			$pool_ref.trigger(eve);
			$('#DistributionWeekFilterModal').modal('hide');

			var filterNoteForm = $('#filter_by_distribution_week');
			var condition_type_text = filterNoteForm.find('select[name="filter_condition_type_distribution_week"] option:selected').text();
			var condition_type = filterNoteForm.find('select[name="filter_condition_type_distribution_week"] option:selected').val();
			var condition_type_value = filterNoteForm.find('select#filter_condition_value_distribution_week').val();
			var condition_type_value_before = filterNoteForm.find('#filter_condition_value_distribution_week_before').val();
			var condition_type_value_bulk = filterNoteForm.find('textarea#filter_condition_value_distribution_bulk').val();
			var filterText = condition_type_text;
			if( condition_type_value != "" || condition_type_value_bulk != '' || condition_type_value_before != "" ){
				if( condition_type == 'weeks_before' ){
					filterText += ': '+condition_type_value_before;
				}else if( condition_type == 'is_exactly_simple' ){
					filterText += ': '+condition_type_value_bulk;
				}else{
					filterText += ': '+condition_type_value;
				}
			}
			if( condition_type_text == 'None' ){
				filterText = "";
			}
			$('body').find('.distribution_week_filter_info').text( filterText );

		});
		$('.filter_by_username .filter_csr_ok').on('click', function(){ //username
			let eve = jQuery.Event("keyup");
			eve.which = 13
			eve.keyCode = 13
			$pool_ref.trigger(eve);
			$('#UsernameFilterModal').modal('hide');

			var filterNoteForm = $('#filter_by_username');
			var condition_type_text = filterNoteForm.find('select[name="filter_condition_type_username"] option:selected').text();
			var condition_type = filterNoteForm.find('select[name="filter_condition_type_username"] option:selected').val();
			var condition_type_value = filterNoteForm.find('select#filter_condition_value_username').val();
			var condition_type_value_bulk = filterNoteForm.find('textarea#filter_condition_value_username_bulk').val();
			var filterText = condition_type_text;
			if( condition_type_value != "" || condition_type_value_bulk != "" ){
				if( condition_type == 'is_exactly_simple' ){
					filterText += ': '+condition_type_value_bulk;
				}else{
					filterText += ': '+condition_type_value;
				}
			}
			if( condition_type_text == 'None' ){
				filterText = "";
			}
			$('body').find('.username_filter_info').text( filterText );

		});

		$('form#filter_by_notes, form#filter_by_pool_ref, form#filter_by_distribution_week, form#filter_by_username').keydown(function (e) {
			if (e.keyCode == 13) {
				$('.filter_csr_ok').trigger('click');
				e.preventDefault();
				return false;
			}
		});

		$('.filter_by_notes .filter_csr_cancel').on('click', function(){
			$('#notesFilterModal').modal('hide');
		});
		$('.filter_by_pool_ref .filter_csr_cancel').on('click', function(){
			$('#poolRefFilterModal').modal('hide');
		});
		$('.filter_by_distribution_week .filter_csr_cancel').on('click', function(){
			$('#DistributionWeekFilterModal').modal('hide');
		});
		$('.filter_by_username .filter_csr_cancel').on('click', function(){
			$('#UsernameFilterModal').modal('hide');
		});

		$('.filter_by_pool_ref #filter_condition_value_pool_ref').select2({placeholder: 'Pool Reference',tags: true, selectionCssClass: 'select2_pool_ref hide mt-2', dropdownParent: $('#poolRefFilterModal')});
		$('.filter_by_distribution_week #filter_condition_value_distribution_week').select2({placeholder: 'Distribution Week',tags: true, selectionCssClass: 'select2_distribution_week hide mt-2', dropdownParent: $('#DistributionWeekFilterModal')});
		$('.filter_by_username #filter_condition_value_username').select2({
			// placeholder: 'Username',tags: true, selectionCssClass: 'select2_username hide mt-2', dropdownParent: $('#UsernameFilterModal')
			placeholder: 'Username',
			minimumInputLength: 2,
			ajax: {
				url: cipscript.ajax_url,
				dataType: 'json',
				data: function (params) {
					var query = {
						search: params.term,
						action: 'username_fetch_act'
					}
					return query;
				}
			},
			processResults: function (response) {
				return {
				   results: response
				};
			},
			selectionCssClass: 'select2_username hide mt-2',
			dropdownParent: $('#UsernameFilterModal')
		});
	}

	$('body').on('change', '#withdrawal_suspension_frm input[name="withdrawal_suspension"]', function(event){
		event.preventDefault();
		// console.log( $(this).is(':checked') );
		var $this = $(this);
		var $form = $('#withdrawal_suspension_frm');
		
		var toggleValue = '0';
		if( $(this).is(':checked') ){
			toggleValue = '1';
		}

		if( $(this).is(':checked') ){ //enable withdrawal_suspension
			$this.prop( "checked", false );

			var container = $('.withdrawal_suspension_section');
			var request = $form.serialize() + '&toggleValue='+toggleValue;
			// console.log( request );
			$(container).block( block_config );
			$(container).addClass('working');
			// $(container).find('input, button').prop('disabled', true);

			$.post(cipscript.ajax_url, request)
			.fail(function() {
				swalToast({ type: 'error', title: 'Something went wrong. Please try again.' });
			})
			.done(function(response) {
				if( response.error == 0 ){
					swalToast({ type: 'success', title: response.msg });
					$this.prop( "checked", true );
				}else{
					swalToast({ type: 'error', title: response.msg });
				}
				$(container).unblock();
			})
			.always(function(response) {
			});

		}else{ //disable withdrawal_suspension
			$this.prop( "checked", true );

			var container = $('.withdrawal_suspension_section');
			var request = $form.serialize() + '&toggleValue='+toggleValue;
			// console.log( request );
			$(container).block( block_config );
			$(container).addClass('working');
			// $(container).find('input, button').prop('disabled', true);

			$.post(cipscript.ajax_url, request)
			.fail(function() {
				swalToast({ type: 'error', title: 'Something went wrong. Please try again.' });
			})
			.done(function(response) {
				if( response.error == 0 ){
					if( response.isopen == 1 ){

						const interval_id = window.setInterval(function(){}, Number.MAX_SAFE_INTEGER);
						for (let i = 1; i < interval_id; i++) {
							window.clearInterval(i);
						}
						$('#disableWithdrawalSuspensionModal .disable_withdrawal_suspension_section .otp_response_section').html( response.otpContent );
						$('#disableWithdrawalSuspensionModal .disable_withdrawal_suspension_section .ga_response_section').html( response.otpGAContent );

						$("#disableWithdrawalSuspensionModal").modal({backdrop: 'static',keyboard: false});

						/* $("#disableWithdrawalSuspensionModal .disable_withdrawal_suspension_section").html( response.html );
						$("#disableWithdrawalSuspensionModal").modal({backdrop: 'static',keyboard: false});

						var inputmask_options = {
							inputFormat:'dd/mm/yyyy',
							alias: "datetime",
							placeholder: "dd/mm/yyyy",
						};

						$('body').find("#kyc_dob").inputmask(inputmask_options);
						$('body').find('#kyc_dob').datepicker({
							format: "dd/mm/yyyy",
							endDate: "today",
							autoclose: true,
							clearBtn: true,
						});

						$('#disableWithdrawalSuspensionModal [data-toggle="tooltip"]').tooltip(); */

					}
				}else{
					swalToast({ type: 'error', title: response.msg });
				}
				$(container).unblock();
			})
			.always(function(response) {
			});
		}
		return false;
	});

	$('body').on('click', '#resend_disable_withdraw_suspension', function(){

		var $form = $('#withdrawal_suspension_frm');
		var $formElement = $('#disable_withdrawal_suspension_frm');
		var data = new FormData( $form[0] );
		data.append("toggleValue", '0');
		data.append("resend", '1');
		$formElement.block( block_config_kyc );
		$.ajax({
			url			: cipscript.ajax_url,
			type		: 'post',
			data		: data,
			processData	: false,
			contentType	: false,
			success : function(response){
				// var obj = $.parseJSON(response);
				var obj = response;
				if( obj.error == 0 ){

					const interval_id = window.setInterval(function(){}, Number.MAX_SAFE_INTEGER);
					for (let i = 1; i < interval_id; i++) {
						window.clearInterval(i);
					}
					$('#disableWithdrawalSuspensionModal .disable_withdrawal_suspension_section .otp_response_section').html( obj.otpContent );
					$('#disableWithdrawalSuspensionModal .disable_withdrawal_suspension_section .ga_response_section').html( obj.otpGAContent );
				}else{
					swalToast({ type: 'error', title: obj.msg });
				}
				$formElement.unblock();
			}
		});
	});

	/* $('body').on('submit', '#disable_withdrawal_suspension_kyc', function(){
		var block_config = { css: { backgroundColor: 'transparent', border: 'none' }, message: '<div class="blockUIspinner"></div>', baseZ: 1500, overlayCSS: { backgroundColor: '#FFFFFF', opacity: 0.8, cursor: 'wait' } };
		
		if( $(this).find('input[name="kyc_dob"]').val() == "" ){
			swalToast({ type: 'error', title: 'Please enter ' + $(this).find('label[for="kyc_dob"]').text().toLowerCase() });
			return false;
		}
		if( $(this).find('input[name="kyc_number"]').val() == "" ){
			swalToast({ type: 'error', title: 'Please enter ' + $(this).find('label[for="kyc_number"]').text().toLowerCase() });
			return false;
		}

		var data = $(this).serialize();
		$.blockUI(block_config);
		$.post(cipscript.ajax_url, data, function(response) {
			// var obj = JSON.parse( response );
			var obj = response;
			if( obj.error == 0 ){
				swalToast({ type: 'success', title: obj.msg });
				$('#withdrawal_suspension_frm input[name="withdrawal_suspension"]').prop( "checked", false );
				$("#disableWithdrawalSuspensionModal").modal('hide'); 
				window.location.reload();
			}else{
				swalToast({ type: 'error', title: obj.msg });
			}
			$.unblockUI();
		});
		return false;
	}); */
	$('body').on('submit', '#disable_withdrawal_suspension_frm', function(){
		var block_config = { css: { backgroundColor: 'transparent', border: 'none' }, message: '<div class="blockUIspinner"></div>', baseZ: 1500, overlayCSS: { backgroundColor: '#FFFFFF', opacity: 0.8, cursor: 'wait' } };
		
		if( $(this).find('input[name="user_otp"]').val() == "" ){
			swalToast({ type: 'error', title: 'Please enter the OTP' });
			return false;
		}
		if( $(this).find('input[name="user_ga_otp"]').val() == "" ){
			swalToast({ type: 'error', title: 'Please enter the authentication code' });
			return false;
		}

		var data = $(this).serialize();
		$.blockUI(block_config);
		$.post(cipscript.ajax_url, data, function(response) {
			// var obj = JSON.parse( response );
			var obj = response;
			if( obj.error == 0 ){
				swalToast({ type: 'success', title: obj.msg });
				$('#withdrawal_suspension_frm input[name="withdrawal_suspension"]').prop( "checked", false );
				$("#disableWithdrawalSuspensionModal").modal('hide'); 
				window.location.reload();
			}else{
				swalToast({ type: 'error', title: obj.msg });
			}
			$.unblockUI();
		});
		return false;
	});

	$('body').on("input", "#kyc_number", function () {
		var c = this.selectionStart,
		  r = /[^a-z0-9-_/(). ]/gi,
		  v = $(this).val();
		if( r.test(v) ){
		  $(this).val(v.replace(r, ""));
		  c--;
		}
		this.setSelectionRange(c, c);
	});
	

	if( $('#tokenholder_wallet_delivery').length > 0 ){
		$('body').on('change', '#tokenholder_wallet_delivery input.rowiddata', function(){

			var selectedAllOption = 0;
			var thisRowSelected = 0;
			if( $('#tokenholder_wallet_delivery input[name="toggleWDAll"]').is(':checked') ){
				selectedAllOption = 1;
			}
			if( $(this).is(':checked') ){
				thisRowSelected = 1;
			}

			var $tableElem = $('#tokenholder_wallet_delivery');
			$tableElem.block( block_config_kyc );

			$('.csr_partial_delivery').addClass('disabled').prop('disabled', true);
			var data = {'action':'cip_wd_selection_storing_act', 'thisId':$(this).val(), 'selectedAllOption':selectedAllOption, 'thisRowSelected':thisRowSelected};
			var container = $(this).closest('tr');
			$.post(cipscript.ajax_url, data)
			.fail(function() {
				swalToast({ type: 'error', title: 'Something went wrong. Please try again.' });
				if( thisRowSelected == 1 ){
					$(this).prop('checked', false);
				}else{
					$(this).prop('checked', true);
				}
			})
			.done(function(response) {
				if( response.error == 0 ){

					/* let eve = jQuery.Event("keyup");
					eve.which = 13
					eve.keyCode = 13
					$('#tokenholder_wallet_delivery thead th .filter-control .search-input:first').trigger(eve); */

					var $tableTokenholderWalletDelivery = $('#tokenholder_wallet_delivery');
					$tableTokenholderWalletDelivery.bootstrapTable('refresh');


					//saved, nothing to do
					if( partial_delivery_total > 0 && partial_delivery_total <= 15 ){
						$('.csr_partial_delivery').removeClass('disabled').prop('disabled', false);
					}
				}else{
					swalToast({ type: 'error', title: response.msg });
					if( thisRowSelected == 1 ){
						$(this).prop('checked', false);
					}else{
						$(this).prop('checked', true);
					}
				}
				$(container).unblock();
			})
			.always(function(response) {
				if (!response.isReset) {
					$(container).find('input, button').prop('disabled', false);
					$(container).removeClass('working');
					$(container).unblock();
				}
				$tableElem.unblock();
			});
		});
	
		$('body').on('change', 'input[name="toggleWDAll"]', function(){
			var thisRowSelected = 0;
			if( $(this).is(':checked') ){
				thisRowSelected = 1;
			}
			var data = {'action':'cip_wd_selection_clearing_act'};
			var container = $(this).closest('tr');
			$.post(cipscript.ajax_url, data)
			.fail(function() {
				swalToast({ type: 'error', title: 'Something went wrong. Please try again.' });
				if( thisRowSelected == 1 ){
					$(this).prop('checked', false);
				}else{
					$(this).prop('checked', true);
				}
			})
			.done(function(response) {
				if( response.error == 0 ){
					//saved, nothing to do
				}else{
					swalToast({ type: 'error', title: response.msg });
					if( thisRowSelected == 1 ){
						$(this).prop('checked', false);
					}else{
						$(this).prop('checked', true);
					}
				}
				$(container).unblock();
			})
			.always(function(response) {
				if (!response.isReset) {
					$(container).find('input, button').prop('disabled', false);
					$(container).removeClass('working');
					$(container).unblock();
				}
			});
		});
	}

	$('body').on('click', '#cip_supportagent_users_list .disableSA2faauth', function(){
		var data = cipscript.actionResetSA2FaAuthAct;
		var thisLabel = $(this).attr('data-pop-title');
		data['thisid'] = $(this).attr('data-id');
		data['thistype'] = $(this).attr('data-type');
		var current_tr = $(this).closest('tr');
		Swal({
		  title: 'Are you sure?',
		  text: "Do you want to " + thisLabel + "?",
		  type: 'warning',
		  showCancelButton: true,
		  confirmButtonText: 'Yes'
		}).then((result) => {
		  if (result.value) {
			current_tr.block( block_config );
			jQuery.ajax({ 
				type: "post",
				data: data,
				cache: false,
				url: cipscript.ajax_url,
				success: function(response){
					var obj = JSON.parse( response );
					if( obj.error == 0 ){
						window.location.reload();
						swalToast({ type: 'success', title: obj.msg });
					}else{
						// Swal.fire({ type: 'error', title: obj.msg, text: '',allowOutsideClick: true});
						swalToast({ type: 'error', title: obj.msg });
					}
					current_tr.unblock();
				}
			});
		  }
		});
		return false;
	});

	if( $('#csr_transaction_history').length > 0 ){
		let dateFormat = 'DD-MM-YYYY';
		$('input.bootstrap-table-filter-control-_date[type="search"]')
		.daterangepicker(
			{
				autoUpdateInput: false,
				locale: {
					format: dateFormat,
					separator: ' - ',
					firstDay: 1
				},
				opens: 'left',
				cancelButtonClasses: 'btn-default cancelButton__date'
			},
			function(start, end) {
				startDate = start.format(dateFormat);
				endDate = end.format(dateFormat);
				let dates = [ startDate, endDate ];
				// filterByDate(dates, '_date');
				$('input.bootstrap-table-filter-control-_date[type="search"]').val(
					start.format(dateFormat) + ' - ' + end.format(dateFormat)
				);
			}
		);
		jQuery('input.bootstrap-table-filter-control-_date[type="search"]').on('apply.daterangepicker', function(ev, picker) {
			$(this).val(picker.startDate.format(dateFormat) + ' - ' + picker.endDate.format(dateFormat));
			if ($('#bstable').attr('data-side-pagination')) {
				setTimeout(() => {
					$(this).trigger('keyup');
				}, 100);

				let eve = jQuery.Event("keyup");
				eve.which = 13
				eve.keyCode = 13
				$('.bootstrap-table-filter-control-_date').trigger(eve);
			}

			$(this).val(picker.startDate.format(dateFormat) + ' - ' + picker.endDate.format(dateFormat));
			let eve = jQuery.Event("keyup");
			eve.which = 13
			eve.keyCode = 13
			$('.bootstrap-table-filter-control-_date').trigger(eve);
		});
		$('input.bootstrap-table-filter-control-_date[type="search"]').on('cancel.daterangepicker', function(ev, picker) {
			$(this).val('');
			let eve = jQuery.Event("keyup");
			eve.which = 13
			eve.keyCode = 13
			$('.bootstrap-table-filter-control-_date').trigger(eve);
		});
	}
	if( $('#cip_completed_withdrawals_list').length > 0 ){
		let dateFormat = 'DD-MM-YYYY';
		$('input.bootstrap-table-filter-control-last_update[type="search"]')
		.daterangepicker(
			{
				autoUpdateInput: false,
				locale: {
					format: dateFormat,
					separator: ' - ',
					firstDay: 1
				},
				opens: 'left',
				cancelButtonClasses: 'btn-default cancelButton_last_update'
			},
			function(start, end) {
				startDate = start.format(dateFormat);
				endDate = end.format(dateFormat);
				let dates = [ startDate, endDate ];
				// filterByDate(dates, 'last_update');
				$('input.bootstrap-table-filter-control-last_update[type="search"]').val(
					start.format(dateFormat) + ' - ' + end.format(dateFormat)
				);
			}
		);
		jQuery('input.bootstrap-table-filter-control-last_update[type="search"]').on('apply.daterangepicker', function(ev, picker) {
			$(this).val(picker.startDate.format(dateFormat) + ' - ' + picker.endDate.format(dateFormat));
			if ($('#bstable').attr('data-side-pagination')) {
				setTimeout(() => {
					$(this).trigger('keyup');
				}, 100);

				let eve = jQuery.Event("keyup");
				eve.which = 13
				eve.keyCode = 13
				$('.bootstrap-table-filter-control-last_update').trigger(eve);
			}

			$(this).val(picker.startDate.format(dateFormat) + ' - ' + picker.endDate.format(dateFormat));
			let eve = jQuery.Event("keyup");
			eve.which = 13
			eve.keyCode = 13
			$('.bootstrap-table-filter-control-last_update').trigger(eve);
		});
		$('input.bootstrap-table-filter-control-last_update[type="search"]').on('cancel.daterangepicker', function(ev, picker) {
			$(this).val('');
			let eve = jQuery.Event("keyup");
			eve.which = 13
			eve.keyCode = 13
			$('.bootstrap-table-filter-control-last_update').trigger(eve);
		});
	}

	if( $('#tokenholder_table_sa').length > 0 ){
		let dateFormat = 'DD/MM/YYYY';
		var $redemption_date = $('input.bootstrap-table-filter-control-redemption_date[type="search"]');
		var $claim_date = $('input.bootstrap-table-filter-control-claim_date[type="search"]');
		var $date_1 = $('input.bootstrap-table-filter-control-date_1[type="search"]');
		var $date_2 = $('input.bootstrap-table-filter-control-date_2[type="search"]');
		var $date_3 = $('input.bootstrap-table-filter-control-date_3[type="search"]');
		var $date_4 = $('input.bootstrap-table-filter-control-date_4[type="search"]');
		var $date_5 = $('input.bootstrap-table-filter-control-date_5[type="search"]');
		var $date_6 = $('input.bootstrap-table-filter-control-date_6[type="search"]');
		var $date_7 = $('input.bootstrap-table-filter-control-date_7[type="search"]');
		var $date_8 = $('input.bootstrap-table-filter-control-date_8[type="search"]');
		var $date_9 = $('input.bootstrap-table-filter-control-date_9[type="search"]');
		var $date_10 = $('input.bootstrap-table-filter-control-date_10[type="search"]');
		var $saving_date = $('input.bootstrap-table-filter-control-saving_date[type="search"]');
		var $saving_start_date = $('input.bootstrap-table-filter-control-saving_start_date[type="search"]');
		var $notes_external = $('input.bootstrap-table-filter-control-notes_external[type="search"]');
		
		if( $redemption_date.length > 0 ){
			$redemption_date.daterangepicker({
					autoUpdateInput: false,
					locale: {
						format: dateFormat,
						separator: ' - ',
						firstDay: 2
					},
					opens: 'left',
					cancelButtonClasses: 'btn-default cancelButton_daterangepicker'
				},
				function(start, end) {
					startDate = start.format(dateFormat);
					endDate = end.format(dateFormat);
					let dates = [ startDate, endDate ];
					$redemption_date.val(start.format(dateFormat) + ' - ' + end.format(dateFormat));
				}
			);
			$redemption_date.on('apply.daterangepicker', function(ev, picker) {
				$(this).val(picker.startDate.format(dateFormat) + ' - ' + picker.endDate.format(dateFormat));
				let eve = jQuery.Event("keyup");
				eve.which = 13
				eve.keyCode = 13
				$redemption_date.trigger(eve);
			});
			$redemption_date.on('cancel.daterangepicker', function(ev, picker) {
				$(this).val('');
				let eve = jQuery.Event("keyup");
				eve.which = 13
				eve.keyCode = 13
				$redemption_date.trigger(eve);
			});
		}
		if( $claim_date.length > 0 ){
			$claim_date.daterangepicker({
					autoUpdateInput: false,
					locale: {
						format: dateFormat,
						separator: ' - ',
						firstDay: 2
					},
					opens: 'left',
					cancelButtonClasses: 'btn-default cancelButton_daterangepicker'
				},
				function(start, end) {
					startDate = start.format(dateFormat);
					endDate = end.format(dateFormat);
					let dates = [ startDate, endDate ];
					$claim_date.val(start.format(dateFormat) + ' - ' + end.format(dateFormat));
				}
			);
			$claim_date.on('apply.daterangepicker', function(ev, picker) {
				$(this).val(picker.startDate.format(dateFormat) + ' - ' + picker.endDate.format(dateFormat));
				let eve = jQuery.Event("keyup");
				eve.which = 13
				eve.keyCode = 13
				$claim_date.trigger(eve);
			});
			$claim_date.on('cancel.daterangepicker', function(ev, picker) {
				$(this).val('');
				let eve = jQuery.Event("keyup");
				eve.which = 13
				eve.keyCode = 13
				$claim_date.trigger(eve);
			});
		}
		if( $date_1.length > 0 ){
			$date_1.daterangepicker({
					autoUpdateInput: false,
					locale: {
						format: dateFormat,
						separator: ' - ',
						firstDay: 2
					},
					opens: 'left',
					cancelButtonClasses: 'btn-default cancelButton_daterangepicker'
				},
				function(start, end) {
					startDate = start.format(dateFormat);
					endDate = end.format(dateFormat);
					let dates = [ startDate, endDate ];
					$date_1.val(start.format(dateFormat) + ' - ' + end.format(dateFormat));
				}
			);
			$date_1.on('apply.daterangepicker', function(ev, picker) {
				$(this).val(picker.startDate.format(dateFormat) + ' - ' + picker.endDate.format(dateFormat));
				let eve = jQuery.Event("keyup");
				eve.which = 13
				eve.keyCode = 13
				$date_1.trigger(eve);
			});
			$date_1.on('cancel.daterangepicker', function(ev, picker) {
				$(this).val('');
				let eve = jQuery.Event("keyup");
				eve.which = 13
				eve.keyCode = 13
				$date_1.trigger(eve);
			});
		}
		if( $date_2.length > 0 ){
			$date_2.daterangepicker({
					autoUpdateInput: false,
					locale: {
						format: dateFormat,
						separator: ' - ',
						firstDay: 2
					},
					opens: 'left',
					cancelButtonClasses: 'btn-default cancelButton_daterangepicker'
				},
				function(start, end) {
					startDate = start.format(dateFormat);
					endDate = end.format(dateFormat);
					let dates = [ startDate, endDate ];
					$date_2.val(start.format(dateFormat) + ' - ' + end.format(dateFormat));
				}
			);
			$date_2.on('apply.daterangepicker', function(ev, picker) {
				$(this).val(picker.startDate.format(dateFormat) + ' - ' + picker.endDate.format(dateFormat));
				let eve = jQuery.Event("keyup");
				eve.which = 13
				eve.keyCode = 13
				$date_2.trigger(eve);
			});
			$date_2.on('cancel.daterangepicker', function(ev, picker) {
				$(this).val('');
				let eve = jQuery.Event("keyup");
				eve.which = 13
				eve.keyCode = 13
				$date_2.trigger(eve);
			});
		}
		if( $date_3.length > 0 ){
			$date_3.daterangepicker({
					autoUpdateInput: false,
					locale: {
						format: dateFormat,
						separator: ' - ',
						firstDay: 2
					},
					opens: 'left',
					cancelButtonClasses: 'btn-default cancelButton_daterangepicker'
				},
				function(start, end) {
					startDate = start.format(dateFormat);
					endDate = end.format(dateFormat);
					let dates = [ startDate, endDate ];
					$date_3.val(start.format(dateFormat) + ' - ' + end.format(dateFormat));
				}
			);
			$date_3.on('apply.daterangepicker', function(ev, picker) {
				$(this).val(picker.startDate.format(dateFormat) + ' - ' + picker.endDate.format(dateFormat));
				let eve = jQuery.Event("keyup");
				eve.which = 13
				eve.keyCode = 13
				$date_3.trigger(eve);
			});
			$date_3.on('cancel.daterangepicker', function(ev, picker) {
				$(this).val('');
				let eve = jQuery.Event("keyup");
				eve.which = 13
				eve.keyCode = 13
				$date_3.trigger(eve);
			});
		}
		if( $date_4.length > 0 ){
			$date_4.daterangepicker({
					autoUpdateInput: false,
					locale: {
						format: dateFormat,
						separator: ' - ',
						firstDay: 2
					},
					opens: 'left',
					cancelButtonClasses: 'btn-default cancelButton_daterangepicker'
				},
				function(start, end) {
					startDate = start.format(dateFormat);
					endDate = end.format(dateFormat);
					let dates = [ startDate, endDate ];
					$date_4.val(start.format(dateFormat) + ' - ' + end.format(dateFormat));
				}
			);
			$date_4.on('apply.daterangepicker', function(ev, picker) {
				$(this).val(picker.startDate.format(dateFormat) + ' - ' + picker.endDate.format(dateFormat));
				let eve = jQuery.Event("keyup");
				eve.which = 13
				eve.keyCode = 13
				$date_4.trigger(eve);
			});
			$date_4.on('cancel.daterangepicker', function(ev, picker) {
				$(this).val('');
				let eve = jQuery.Event("keyup");
				eve.which = 13
				eve.keyCode = 13
				$date_4.trigger(eve);
			});
		}
		if( $date_5.length > 0 ){
			$date_5.daterangepicker({
					autoUpdateInput: false,
					locale: {
						format: dateFormat,
						separator: ' - ',
						firstDay: 2
					},
					opens: 'left',
					cancelButtonClasses: 'btn-default cancelButton_daterangepicker'
				},
				function(start, end) {
					startDate = start.format(dateFormat);
					endDate = end.format(dateFormat);
					let dates = [ startDate, endDate ];
					$date_5.val(start.format(dateFormat) + ' - ' + end.format(dateFormat));
				}
			);
			$date_5.on('apply.daterangepicker', function(ev, picker) {
				$(this).val(picker.startDate.format(dateFormat) + ' - ' + picker.endDate.format(dateFormat));
				let eve = jQuery.Event("keyup");
				eve.which = 13
				eve.keyCode = 13
				$date_5.trigger(eve);
			});
			$date_5.on('cancel.daterangepicker', function(ev, picker) {
				$(this).val('');
				let eve = jQuery.Event("keyup");
				eve.which = 13
				eve.keyCode = 13
				$date_5.trigger(eve);
			});
		}
		if( $date_6.length > 0 ){
			$date_6.daterangepicker({
					autoUpdateInput: false,
					locale: {
						format: dateFormat,
						separator: ' - ',
						firstDay: 2
					},
					opens: 'left',
					cancelButtonClasses: 'btn-default cancelButton_daterangepicker'
				},
				function(start, end) {
					startDate = start.format(dateFormat);
					endDate = end.format(dateFormat);
					let dates = [ startDate, endDate ];
					$date_6.val(start.format(dateFormat) + ' - ' + end.format(dateFormat));
				}
			);
			$date_6.on('apply.daterangepicker', function(ev, picker) {
				$(this).val(picker.startDate.format(dateFormat) + ' - ' + picker.endDate.format(dateFormat));
				let eve = jQuery.Event("keyup");
				eve.which = 13
				eve.keyCode = 13
				$date_6.trigger(eve);
			});
			$date_6.on('cancel.daterangepicker', function(ev, picker) {
				$(this).val('');
				let eve = jQuery.Event("keyup");
				eve.which = 13
				eve.keyCode = 13
				$date_6.trigger(eve);
			});
		}
		if( $date_7.length > 0 ){
			$date_7.daterangepicker({
					autoUpdateInput: false,
					locale: {
						format: dateFormat,
						separator: ' - ',
						firstDay: 2
					},
					opens: 'left',
					cancelButtonClasses: 'btn-default cancelButton_daterangepicker'
				},
				function(start, end) {
					startDate = start.format(dateFormat);
					endDate = end.format(dateFormat);
					let dates = [ startDate, endDate ];
					$date_7.val(start.format(dateFormat) + ' - ' + end.format(dateFormat));
				}
			);
			$date_7.on('apply.daterangepicker', function(ev, picker) {
				$(this).val(picker.startDate.format(dateFormat) + ' - ' + picker.endDate.format(dateFormat));
				let eve = jQuery.Event("keyup");
				eve.which = 13
				eve.keyCode = 13
				$date_7.trigger(eve);
			});
			$date_7.on('cancel.daterangepicker', function(ev, picker) {
				$(this).val('');
				let eve = jQuery.Event("keyup");
				eve.which = 13
				eve.keyCode = 13
				$date_7.trigger(eve);
			});
		}
		if( $date_8.length > 0 ){
			$date_8.daterangepicker({
					autoUpdateInput: false,
					locale: {
						format: dateFormat,
						separator: ' - ',
						firstDay: 2
					},
					opens: 'left',
					cancelButtonClasses: 'btn-default cancelButton_daterangepicker'
				},
				function(start, end) {
					startDate = start.format(dateFormat);
					endDate = end.format(dateFormat);
					let dates = [ startDate, endDate ];
					$date_8.val(start.format(dateFormat) + ' - ' + end.format(dateFormat));
				}
			);
			$date_8.on('apply.daterangepicker', function(ev, picker) {
				$(this).val(picker.startDate.format(dateFormat) + ' - ' + picker.endDate.format(dateFormat));
				let eve = jQuery.Event("keyup");
				eve.which = 13
				eve.keyCode = 13
				$date_8.trigger(eve);
			});
			$date_8.on('cancel.daterangepicker', function(ev, picker) {
				$(this).val('');
				let eve = jQuery.Event("keyup");
				eve.which = 13
				eve.keyCode = 13
				$date_8.trigger(eve);
			});
		}
		if( $date_9.length > 0 ){
			$date_9.daterangepicker({
					autoUpdateInput: false,
					locale: {
						format: dateFormat,
						separator: ' - ',
						firstDay: 2
					},
					opens: 'left',
					cancelButtonClasses: 'btn-default cancelButton_daterangepicker'
				},
				function(start, end) {
					startDate = start.format(dateFormat);
					endDate = end.format(dateFormat);
					let dates = [ startDate, endDate ];
					$date_9.val(start.format(dateFormat) + ' - ' + end.format(dateFormat));
				}
			);
			$date_9.on('apply.daterangepicker', function(ev, picker) {
				$(this).val(picker.startDate.format(dateFormat) + ' - ' + picker.endDate.format(dateFormat));
				let eve = jQuery.Event("keyup");
				eve.which = 13
				eve.keyCode = 13
				$date_9.trigger(eve);
			});
			$date_9.on('cancel.daterangepicker', function(ev, picker) {
				$(this).val('');
				let eve = jQuery.Event("keyup");
				eve.which = 13
				eve.keyCode = 13
				$date_9.trigger(eve);
			});
		}
		if( $date_10.length > 0 ){
			$date_10.daterangepicker({
					autoUpdateInput: false,
					locale: {
						format: dateFormat,
						separator: ' - ',
						firstDay: 2
					},
					opens: 'left',
					cancelButtonClasses: 'btn-default cancelButton_daterangepicker'
				},
				function(start, end) {
					startDate = start.format(dateFormat);
					endDate = end.format(dateFormat);
					let dates = [ startDate, endDate ];
					$date_10.val(start.format(dateFormat) + ' - ' + end.format(dateFormat));
				}
			);
			$date_10.on('apply.daterangepicker', function(ev, picker) {
				$(this).val(picker.startDate.format(dateFormat) + ' - ' + picker.endDate.format(dateFormat));
				let eve = jQuery.Event("keyup");
				eve.which = 13
				eve.keyCode = 13
				$date_10.trigger(eve);
			});
			$date_10.on('cancel.daterangepicker', function(ev, picker) {
				$(this).val('');
				let eve = jQuery.Event("keyup");
				eve.which = 13
				eve.keyCode = 13
				$date_10.trigger(eve);
			});
		}
		if( $saving_date.length > 0 ){
			$saving_date.daterangepicker({
					autoUpdateInput: false,
					locale: {
						format: dateFormat,
						separator: ' - ',
						firstDay: 2
					},
					opens: 'left',
					cancelButtonClasses: 'btn-default cancelButton_daterangepicker'
				},
				function(start, end) {
					startDate = start.format(dateFormat);
					endDate = end.format(dateFormat);
					let dates = [ startDate, endDate ];
					$saving_date.val(start.format(dateFormat) + ' - ' + end.format(dateFormat));
				}
			);
			$saving_date.on('apply.daterangepicker', function(ev, picker) {
				$(this).val(picker.startDate.format(dateFormat) + ' - ' + picker.endDate.format(dateFormat));
				let eve = jQuery.Event("keyup");
				eve.which = 13
				eve.keyCode = 13
				$saving_date.trigger(eve);
			});
			$saving_date.on('cancel.daterangepicker', function(ev, picker) {
				$(this).val('');
				let eve = jQuery.Event("keyup");
				eve.which = 13
				eve.keyCode = 13
				$saving_date.trigger(eve);
			});
		}
		if( $saving_start_date.length > 0 ){
			$saving_start_date.daterangepicker({
					autoUpdateInput: false,
					locale: {
						format: dateFormat,
						separator: ' - ',
						firstDay: 2
					},
					opens: 'left',
					cancelButtonClasses: 'btn-default cancelButton_daterangepicker'
				},
				function(start, end) {
					startDate = start.format(dateFormat);
					endDate = end.format(dateFormat);
					let dates = [ startDate, endDate ];
					$saving_start_date.val(start.format(dateFormat) + ' - ' + end.format(dateFormat));
				}
			);
			$saving_start_date.on('apply.daterangepicker', function(ev, picker) {
				$(this).val(picker.startDate.format(dateFormat) + ' - ' + picker.endDate.format(dateFormat));
				let eve = jQuery.Event("keyup");
				eve.which = 13
				eve.keyCode = 13
				$saving_start_date.trigger(eve);
			});
			$saving_start_date.on('cancel.daterangepicker', function(ev, picker) {
				$(this).val('');
				let eve = jQuery.Event("keyup");
				eve.which = 13
				eve.keyCode = 13
				$saving_start_date.trigger(eve);
			});
		}
		$notes_external.on('click', function(){
			$('#notesFilterModal').modal({backdrop: 'static',keyboard: false});
		});

		$('.filter_csr_ok').on('click', function(){
			let eve = jQuery.Event("keyup");
			eve.which = 13
			eve.keyCode = 13
			$notes_external.trigger(eve);
			$('#notesFilterModal').modal('hide');

			var filterNoteForm = $('#filter_by_notes');
			var condition_type_text = filterNoteForm.find('select[name="filter_condition_type"] option:selected').text();
			var condition_type_value = filterNoteForm.find('input[name="filter_condition_value"]').val();
			var filterText = condition_type_text;
			if( condition_type_value != "" ){
				filterText += ': '+condition_type_value;
			}
			if( condition_type_text == 'None' ){
				filterText = "";
			}
			$('body').find('.note_filter_info').text( filterText );

		});

		$('form#filter_by_notes').keydown(function (e) {
			if (e.keyCode == 13) {
				$('.filter_csr_ok').trigger('click');
				e.preventDefault();
				return false;
			}
		});
		
		$('body').on('keydown', 'form#csr_edit_notes_frm', function(e){
		// $('form#csr_edit_notes_frm').keydown(function (e) {
			if (e.keyCode == 13) {
				e.preventDefault();
				return false;
			}
		});
		
		$('body').on('keydown', 'form#csr_edit_notes_frm #addnewNoteElementNotes', function(e){
		// $('form#csr_edit_notes_frm #addnewNoteElementNotes').keydown(function (e) {
			if (e.keyCode == 13) {
				$('.addNewNoteElementBtn').trigger('click');
				e.preventDefault();
				return false;
			}
		});

		$('.filter_csr_cancel').on('click', function(){
			/* let eve = jQuery.Event("keyup");
			$('select[name="filter_condition_type"]').val('none').trigger('change');
			$notes_external.trigger(eve); */
			$('#notesFilterModal').modal('hide');
			// $('body').find('.note_filter_info').text('');
		});

		$('body').on('change', '#tokenholder_table_sa input.rowiddata', function(){
			var selectedAllOption = 0;
			var thisRowSelected = 0;
			if( $('input[name="toggleWDAll"]').is(':checked') ){
				selectedAllOption = 1;
			}
			if( $(this).is(':checked') ){
				thisRowSelected = 1;
			}
			var data = {'action':'cip_sacsr_selection_storing_act', 'thisId':$(this).val(), 'selectedAllOption':selectedAllOption, 'thisRowSelected':thisRowSelected};
			var container = $(this).closest('tr');
			$.post(cipscript.ajax_url, data)
			.fail(function() {
				swalToast({ type: 'error', title: 'Something went wrong. Please try again.' });
				if( thisRowSelected == 1 ){
					$(this).prop('checked', false);
				}else{
					$(this).prop('checked', true);
				}
			})
			.done(function(response) {
				if( response.error == 0 ){
					//saved, nothing to do
					$('.edit_csr_holder').show();
				}else{
					swalToast({ type: 'error', title: response.msg });
					if( thisRowSelected == 1 ){
						$(this).prop('checked', false);
					}else{
						$(this).prop('checked', true);
					}
				}
				$(container).unblock();
			})
			.always(function(response) {
				if (!response.isReset) {
					$(container).find('input, button').prop('disabled', false);
					$(container).removeClass('working');
					$(container).unblock();
				}
			});
		});
	
		$('body').on('change', '#tokenholder_table_sa input[name="toggleWDAll"]', function(){
			var thisRowSelected = 0;
			if( $(this).is(':checked') ){
				thisRowSelected = 1;
			}
			var data = {'action':'cip_sacsr_selection_clearing_act'};
			var container = $(this).closest('tr');
			$.post(cipscript.ajax_url, data)
			.fail(function() {
				swalToast({ type: 'error', title: 'Something went wrong. Please try again.' });
				if( thisRowSelected == 1 ){
					$(this).prop('checked', false);
				}else{
					$(this).prop('checked', true);
				}
			})
			.done(function(response) {
				if( response.error == 0 ){
					//saved, nothing to do
				}else{
					swalToast({ type: 'error', title: response.msg });
					if( thisRowSelected == 1 ){
						$(this).prop('checked', false);
					}else{
						$(this).prop('checked', true);
					}
				}
				$(container).unblock();
			})
			.always(function(response) {
				if (!response.isReset) {
					$(container).find('input, button').prop('disabled', false);
					$(container).removeClass('working');
					$(container).unblock();
				}
			});
		});

		$('#tokenholder_table_sa').on('search.bs.table',function(event, searchText){
			"use strict";
	        var data = {};
	        $('.filter-control .form-control').each(function(){
	        	var mainClass = $(this).attr('class').split(' ')
	        	mainClass.pop();
	        	mainClass = mainClass.join(' ');
	        	if($(this).val())
	        	{
	        		data[''+mainClass+''] = $(this).val();
	        	}else
	        	{
	        		data[''+mainClass+''] = '';
	        	}
	        })
			
			var filterNoteForm = $('#filter_by_notes');
			var condition_type_text = filterNoteForm.find('select[name="filter_condition_type"] option:selected').attr('value');
			var condition_type_value = filterNoteForm.find('input[name="filter_condition_value"]').val();

			if(condition_type_text != '' ||  condition_type_value != '')
			{
				var filterNoteForm = {};
				filterNoteForm['condition_type_text'] = condition_type_text;
				filterNoteForm['condition_type_value'] = condition_type_value;
				data['filter_by_notes'] = filterNoteForm;
			}
	        
	        sessionStorage.setItem( "tokenholder_table_sa_filter", JSON.stringify(data) );
		})

		var filterCookie = sessionStorage.getItem("tokenholder_table_sa_filter");
		
		if( filterCookie != "" && filterCookie != null ){


			var filterCookieArray = jQuery.parseJSON(filterCookie);
	
			$.each(filterCookieArray,function(index,value){
				var classNames = index.replaceAll(' ','.')
				if(value)
				{
					if(classNames == 'form-control.bootstrap-table-filter-control-corp_approved')
					{
						$('.'+classNames).val(value);
						$('.'+classNames).trigger('change')
					}
					if(classNames == 'form-control.bootstrap-table-filter-control-pool_ref' || classNames == 'form-control.bootstrap-table-filter-control-text_2' || classNames == 'form-control.bootstrap-table-filter-control-text_10' || classNames == 'form-control.bootstrap-table-filter-control-username' || classNames == 'form-control.bootstrap-table-filter-control-reference' || classNames == 'form-control.bootstrap-table-filter-control-eth_address' || classNames == 'form-control.bootstrap-table-filter-control-csr_amount_initial' || classNames == 'form-control.bootstrap-table-filter-control-amount_due' || classNames == 'form-control.bootstrap-table-filter-control-first_name' || classNames == 'form-control.bootstrap-table-filter-control-last_name' || classNames == 'form-control.bootstrap-table-filter-control-email' || classNames == 'form-control.bootstrap-table-filter-control-notes_internal' || classNames == 'form-control.bootstrap-table-filter-control-notes_internal' || classNames == 'form-control.bootstrap-table-filter-control-text_1' || classNames == 'form-control.bootstrap-table-filter-control-saved_amount' || classNames == 'form-control.bootstrap-table-filter-control-saved_amount' || classNames == 'form-control.bootstrap-table-filter-control-saving_interest' || classNames == 'form-control.bootstrap-table-filter-control-saving_periods' || classNames == 'form-control.bootstrap-table-filter-control-redemption_date' || classNames == 'form-control.bootstrap-table-filter-control-claim_date' || classNames == 'form-control.bootstrap-table-filter-control-date_1' || classNames == 'form-control.bootstrap-table-filter-control-saving_date' || classNames == 'form-control.bootstrap-table-filter-control-saving_start_date')
					{
						$('.'+classNames).val(value);
						let eve = jQuery.Event("keyup");
						eve.which = 13
						eve.keyCode = 13
						$('.'+classNames).trigger(eve)
					}
					if(classNames == 'filter_by_notes')
					{
						if(value.condition_type_text != '')
						{
							$("select[name=filter_condition_type]").val(value.condition_type_text)
							$("select[name=filter_condition_type]").trigger('change')
						}
						if(value.condition_type_value != '')
						{
							$("input[name=filter_condition_value]").val(value.condition_type_value)
						}
						$('.filter_by_notes .filter_csr_ok').trigger('click')
					}
				}
			})
		}

		$(document).on('click','.clear_all_csr_holder',function(e){
			e.preventDefault;
			sessionStorage.removeItem("tokenholder_table_sa_filter");
			window.location.reload(true)
		})

	}

	$('body').on('submit', '#create_simple_notes_frm', function(){
		var block_config = { css: { backgroundColor: 'transparent', border: 'none' }, message: '<div class="blockUIspinner"></div>', baseZ: 1500, overlayCSS: { backgroundColor: '#FFFFFF', opacity: 0.8, cursor: 'wait' } };
		
		if( $(this).find('input[name="simple_notes"]').val() == "" ){
			swalToast({ type: 'error', title: 'Please enter note' });
			return false;
		}

		var data = $(this).serialize();
		$.blockUI(block_config);
		$.post(cipscript.ajax_url, data, function(response) {
			var obj = JSON.parse( response );
			if( obj.error == 0 ){
				swalToast({ type: 'success', title: obj.msg });
				$("#createSimpleNotesModal").modal('hide');
				let eve = jQuery.Event("keyup");
				eve.which = 13
				eve.keyCode = 13
				$('#cip_simple_notes_management_list input[type="search"].bootstrap-table-filter-control-notes').val('').trigger(eve);
			}else{
				swalToast({ type: 'error', title: obj.msg });
				// Swal.fire({ type: 'error', title: obj.msg, text: '',allowOutsideClick: false});
			}
			$.unblockUI();
		});
		return false;
	});

	$('body').on('click', '.edit-simaple-notes', function(e){
		var thisId = $(this).attr('data-edit');
		var micro = $(this).attr('data-micro');
		var data = { 'action' : 'get_simplenotes_action', 'thisId' : thisId, '_micro' : micro };
		var thisTr = $(this).closest('tr');
		thisTr.block( block_config );
		$.post(cipscript.ajax_url, data, function(response) {
			var obj = JSON.parse( response );
			if( obj.error == 0 ){
				$('#EditSimpleNotesModal .modal-body').html( obj.html );
				$('#EditSimpleNotesModal').modal('show');
			}else{
				swalToast({ type: 'error', title: obj.msg });
			}
			thisTr.unblock();
		});
	});
	$('#EditSimpleNotesModal').on('hide.bs.modal', function (event) {
		var modal = $(this);
		modal.find('.modal-body').html('');
	});

	$('body').on('submit', '#edit_simple_notes_frm', function(){

		var block_config = { css: { backgroundColor: 'transparent', border: 'none' }, message: '<div class="blockUIspinner"></div>', baseZ: 1500, overlayCSS: { backgroundColor: '#FFFFFF', opacity: 0.8, cursor: 'wait' } };
		
		$form = $(this);
		if( $(this).find('input[name="simple_notes"]').val() == "" ){
			swalToast({ type: 'error', title: 'Please enter note' });
			return false;
		}

		var data = $(this).serialize();
		$form.block( block_config );
		$.post(cipscript.ajax_url, data, function(response) {
			var obj = JSON.parse( response );
			if( obj.error == 0 ){
				$('#EditSimpleNotesModal').modal('hide');
				swalToast({ type: 'success', title: obj.msg });
				let eve = jQuery.Event("keyup");
				eve.which = 13
				eve.keyCode = 13
				$('#cip_simple_notes_management_list input[type="search"].bootstrap-table-filter-control-notes').val('').trigger(eve);
			}else{
				swalToast({ type: 'error', title: obj.msg });
			}
			$form.unblock();
		});
		return false;
	});

	$('body').on('click', '.delete-simaple-notes', function(e){
		var block_config = { css: { backgroundColor: 'transparent', border: 'none' }, message: '<div class="blockUIspinner"></div>', baseZ: 1500, overlayCSS: { backgroundColor: '#FFFFFF', opacity: 0.8, cursor: 'wait' } };
		
		var thisId = $(this).attr('data-delete');
		var micro = $(this).attr('data-micro');
		var thisTr = $(this).closest('tr');
		
		Swal({
			title: 'Are you sure?',
			text: "Do you want to delete note?",
			type: 'warning',
			showCancelButton: true,
			confirmButtonText: 'Yes'
		  }).then((result) => {
			if (result.value) {
				var data = { 'action' : 'delete_simplenotes_action', 'thisId' : thisId, '_micro' : micro };
				thisTr.block( block_config );
				$.post(cipscript.ajax_url, data, function(response) {
					var obj = JSON.parse( response );
					if( obj.error == 0 ){
						swalToast({ type: 'success', title: obj.msg });
						let eve = jQuery.Event("keyup");
						eve.which = 13
						eve.keyCode = 13
						$('#cip_simple_notes_management_list input[type="search"].bootstrap-table-filter-control-notes').val('').trigger(eve);
					}else{
						swalToast({ type: 'error', title: obj.msg });
					}
					thisTr.unblock();
				});
			}
		});

	});

	$('body').on('change', 'select[name="element_type"]', function(e){
		var thisElementType = $(this).val();
		var $simpleElement = $('body').find('.simpleElement');
		var $notesElement = $('body').find('.notesElement');
		var $saveBtns = $('body').find('form[name="csr_edit_notes_frm"] .sa_csr_holder_btns');
		if( thisElementType == 'notes'){
			$simpleElement.hide();
			$saveBtns.hide();
			$notesElement.show();
		}else{
			$simpleElement.show();
			$saveBtns.show();
			$notesElement.hide();
		}
	});

	$('body').on('click', '.editNoteElementBtn[data-noteelem]', function(){
		var thisElementId = $(this).attr('data-noteelem');
		$("#editNoteElementModal").modal({backdrop: 'static',keyboard: false});
		$('#csrEditProcessModal').addClass('modal-backdrop-down');
		$('#editNoteElementNotesFrm').find('input[name="note_element_notes_hidden"]').val( $('input[name="noteElemSelectNotes'+ thisElementId +'"]').val() );
		// $('body').find('.editElementNoteText').html( $('input[name="noteElemSelectNotes'+ thisElementId +'"]').val() );
		$('body').find('input[name="note_element_notes"]').val( $('input[name="noteElemSelectNotes'+ thisElementId +'"]').val() );
	});
	$('body').on('click', '.editNoteElementModalClose', function(){
		
		Swal({
			title: 'Are you sure?',
			text: "Do you want to cancel?",
			type: 'warning',
			showCancelButton: true,
			confirmButtonText: 'Yes'
		  }).then((result) => {
			if (result.value) {
				$('#editNoteElementModal form')[0].reset();
				$("#editNoteElementModal").modal('hide');
			}
		});

	});
	$("#editNoteElementModal").on('hide.bs.modal', function () {
		$('#editNoteElementNotesFrm').find('input[name="note_element_notes_hidden"]').val('');
		$('#csrEditProcessModal').removeClass('modal-backdrop-down');
	});

	$('body').on('input', '#addnewNoteElementNotes, #editNoteElementNotesFrm #note_element_notes', function(){
	// $("#addnewNoteElementNotes").bind("input", function () {
		var c = this.selectionStart,
		r = /[^0-9a-z-_ ]/gi,
		v = $(this).val();
		// console.log( c );
		if( r.test(v) ){
		  $(this).val(v.replace(r, ""));
		  c--;
		}
		this.setSelectionRange(c, c);
	});

	if( $('#tokenholder_partial_wallet_delivery').length > 0 ){			
		var $tableTokenholderPartialWalletDelivery = jQuery('#tokenholder_partial_wallet_delivery');
		$tableTokenholderPartialWalletDelivery.bootstrapTable();
	}

	$("#tokenholder_partial_wallet_delivery input.delivery_amount").on("keypress", function (e) {
		if (String.fromCharCode(e.keyCode).match(/[^0-9]/g)) return false;

        var maxValue = parseInt( $(this).closest('tr').attr('data-maxamount') );
		if( parseInt( $(this).val() ) >= maxValue ){
			$(this).val( maxValue );
		}
	});
	$("#tokenholder_partial_wallet_delivery input.delivery_amount").on("keyup", function (e) {
		var maxValue = parseInt( $(this).closest('tr').attr('data-maxamount') );
		if( parseInt( $(this).val() ) >= maxValue ){
			$(this).val( maxValue ).trigger('input');
		}
	});
	$("#tokenholder_partial_wallet_delivery input.delivery_amount_percentage").on("keypress", function (e) {
		if (String.fromCharCode(e.keyCode).match(/[^0-9]/g)) return false;

        var maxValue = parseInt( 100 );
		if( parseInt( $(this).val() ) >= maxValue ){
			$(this).val( maxValue );
		}
	});
	$("#tokenholder_partial_wallet_delivery input.delivery_amount_percentage").on("keyup", function (e) {
        var maxValue = parseInt( 100 );
		if( parseInt( $(this).val() ) >= maxValue ){
			$(this).val( maxValue ).trigger('input');
		}
	});

	$('body').on('input', '#tokenholder_partial_wallet_delivery .delivery_amount_percentage', function(){
		let sale = $(this).closest('tr').attr('data-maxamount');
		if ( $(this).val().length ) {
			sale = calculateSale( $(this).closest('tr').attr('data-maxamount'), $(this).val() );
			$(this).closest('tr').find("td.delivery_amount input.delivery_amount").val( sale );
		}
		if( isPartialDeliveryFilled() ){
			$('#partialWalletDeliveryFrm .deliver_now').removeClass('disabled').prop('disabled', false).attr('data-original-title', '').tooltip();
		}else{
			$('#partialWalletDeliveryFrm .deliver_now').addClass('disabled').prop('disabled', true).attr('data-original-title', 'You must complete an allocation of CSR for each row').tooltip();
		}
	});
	
	$('body').on('input', '#tokenholder_partial_wallet_delivery .delivery_amount', function(){
		let disc = 0;
		if ( $(this).val().length ) {
			disc = calculateDiscount( $(this).closest('tr').attr('data-maxamount'), $(this).val());
			$(this).closest('tr').find("td.delivery_amount_percentage input.delivery_amount_percentage").val( disc );
		}
		if( isPartialDeliveryFilled() ){
			$('#partialWalletDeliveryFrm .deliver_now').removeClass('disabled').prop('disabled', false).attr('data-original-title', '').tooltip();
		}else{
			$('#partialWalletDeliveryFrm .deliver_now').addClass('disabled').prop('disabled', true).attr('data-original-title', 'You must complete an allocation of CSR for each row').tooltip();
		}
	});

	$('body').on('click', '.deliver_now', function(){
		$("#partialDeliveryG2FAModal").modal({backdrop: 'static',keyboard: false});
	});
	$("#partialDeliveryG2FAModal").on('show.bs.modal', function () {
		var totalPartialAmount = 0, totalPartialRow = 0;
		var partially_delivery_summary_section_elem = $('.partially_delivery_summary_section');
		$('#tokenholder_partial_wallet_delivery input.delivery_amount').each(function() {
			var getAmount = parseInt( $(this).val() );
			if( $.isNumeric( getAmount ) ){
				totalPartialAmount += getAmount;
				totalPartialRow++;
			}
		});
		partially_delivery_summary_section_elem.find('p.amount span').html( addCommas( totalPartialAmount ) );
		partially_delivery_summary_section_elem.find('p.rows span').html( addCommas( totalPartialRow ) );
	});
	$("#partialDeliveryG2FAModal").on('hidden.bs.modal', function () {
		var totalPartialAmount = 0, totalPartialRow = 0;
		var partially_delivery_summary_section_elem = $('.partially_delivery_summary_section');
		partially_delivery_summary_section_elem.find('p.amount span').html( addCommas( totalPartialAmount ) );
		partially_delivery_summary_section_elem.find('p.rows span').html( addCommas( totalPartialRow ) );
	});

	$('body').on('submit', '#partialWalletDeliveryFrm', function(){

		var block_config_spinner = { css: { backgroundColor: 'transparent', border: 'none' }, message: '<div class="blockUIspinner"></div>', baseZ: 1500, overlayCSS: { backgroundColor: '#FFFFFF', opacity: 0.8, cursor: 'wait' } };

		$form = $(this);
		if( $(this).find('input[name="partial_deliver_ga_otp"]').val() == "" ){
			swalToast({ type: 'error', title: 'Please enter the authentication code' });
			return false;
		}

		var data = $(this).serialize();
		$.blockUI( block_config_spinner );
		$.post(cipscript.ajax_url, data, function(response) {
			var obj = JSON.parse( response );
			if( obj.error == 0 ){
				$('#partialWalletDeliveryFrm .deliver_now').addClass('disabled').prop('disabled', true);
				$('#partialWalletDeliveryFrm input[type="submit"]').addClass('disabled').prop('disabled', true);
				$("#partialDeliveryG2FAModal").modal('hide');
				swalToast({ type: 'success', title: obj.msg }).then(function(){ window.self.close(); });
			}else{
				swalToast({ type: 'error', title: obj.msg });
			}
			$.unblockUI();
		});
		return false;
	});

	function isPartialDeliveryFilled() {
		var isValid = true;
		$('#tokenholder_partial_wallet_delivery input').each(function() {
		  if ( $(this).val() === '' )
			  isValid = false;
		});
		return isValid;
	}

	if( $('#completedWithdrawalsList').length > 0 ){			
		var $tablecompletedWithdrawalsList = jQuery('#completedWithdrawalsList');
		$tablecompletedWithdrawalsList.bootstrapTable({
			onPostBody: function (){
				$('[data-toggle-tt="tooltip"]').tooltip();
			}
		});
	}

	$('#create_sms_alert_frm input[name="sms_alert"]').bind("input", function () {
		var c = this.selectionStart,
		  r = /[^0-9]/gi,
		  v = $(this).val();
		if( r.test(v) ){
		  $(this).val(v.replace(r, ""));
		  c--;
		}
		this.setSelectionRange(c, c);
	});

	$('body').on('submit', '#create_sms_alert_frm', function(){
		var block_config = { css: { backgroundColor: 'transparent', border: 'none' }, message: '<div class="blockUIspinner"></div>', baseZ: 1500, overlayCSS: { backgroundColor: '#FFFFFF', opacity: 0.8, cursor: 'wait' } };
		
		$form = $(this);
		if( $(this).find('input[name="sms_alert"]').val() == "" ){
			swalToast({ type: 'error', title: 'Please enter number' });
			return false;
		}
		/* if( !validatePhone( $(this).find('input[name="sms_alert"]').val() ) ){
			swalToast({ type: 'error', title: 'Please enter valid number' });
			return false;
		} */
		if( $(this).find('input[name="user_ga_otp"]').val() == "" ){
			swalToast({ type: 'error', title: 'Please enter the authentication code' });
			return false;
		}

		var data = $(this).serialize();
		$.blockUI(block_config);
		$.post(cipscript.ajax_url, data, function(response) {
			var obj = JSON.parse( response );
			if( obj.error == 0 ){
				swalToast({ type: 'success', title: obj.msg });
				$("#createSmsNumberModal").modal('hide');
				$form[0].reset();
				let eve = jQuery.Event("keyup");
				eve.which = 13
				eve.keyCode = 13
				$('#cip_sms_alert_management_list input[type="search"].bootstrap-table-filter-control-number').val('').trigger(eve);
			}else{
				swalToast({ type: 'error', title: obj.msg });
			}
			$.unblockUI();
		});
		return false;
	});

	$('body').on('click', '.delete-sms-alert', function(e){
		var thisId = $(this).attr('data-delete');
		var thisNumber = $(this).attr('data-number');
		$('#delete_sms_alert_frm .delete_number_label').html('Are you sure want to delete '+thisNumber+'?');
		$('<input>').attr({type: 'hidden', id: '_microid', name: '_microid', value: thisId}).appendTo( $('#delete_sms_alert_frm') );
		$("#deleteSmsNumberModal").modal({backdrop: 'static',keyboard: false});
	});

	$("#deleteSmsNumberModal").on('hide.bs.modal', function () {
		$('#delete_sms_alert_frm #_microid').remove();
		$('#delete_sms_alert_frm .delete_number_label').html('');
	});

	$('body').on('submit', '#delete_sms_alert_frm', function(){
		var block_config = { css: { backgroundColor: 'transparent', border: 'none' }, message: '<div class="blockUIspinner"></div>', baseZ: 1500, overlayCSS: { backgroundColor: '#FFFFFF', opacity: 0.8, cursor: 'wait' } };
		
		$form = $(this);
		if( $(this).find('input[name="user_ga_otp"]').val() == "" ){
			swalToast({ type: 'error', title: 'Please enter the authentication code' });
			return false;
		}

		var data = $(this).serialize();
		$.blockUI(block_config);
		$.post(cipscript.ajax_url, data, function(response) {
			var obj = JSON.parse( response );
			if( obj.error == 0 ){
				swalToast({ type: 'success', title: obj.msg });
				$("#deleteSmsNumberModal").modal('hide');
				$form[0].reset();
				let eve = jQuery.Event("keyup");
				eve.which = 13
				eve.keyCode = 13
				$('#cip_sms_alert_management_list input[type="search"].bootstrap-table-filter-control-number').val('').trigger(eve);
			}else{
				swalToast({ type: 'error', title: obj.msg });
			}
			$.unblockUI();
		});
		return false;
	});

	if( $('#cip_logs_table').length > 0 ){
		let dateFormat = 'DD/MM/YYYY';
		var $_date = $('input.bootstrap-table-filter-control-_date[type="search"]');
		if( $_date.length > 0 ){
			$_date.daterangepicker({
					autoUpdateInput: false,
					locale: {
						format: dateFormat,
						separator: ' - ',
						firstDay: 2
					},
					opens: 'left',
					cancelButtonClasses: 'btn-default cancelButton_daterangepicker'
				},
				function(start, end) {
					startDate = start.format(dateFormat);
					endDate = end.format(dateFormat);
					let dates = [ startDate, endDate ];
					$_date.val(start.format(dateFormat) + ' - ' + end.format(dateFormat));
				}
			);
			$_date.on('apply.daterangepicker', function(ev, picker) {
				$(this).val(picker.startDate.format(dateFormat) + ' - ' + picker.endDate.format(dateFormat));
				let eve = jQuery.Event("keyup");
				eve.which = 13
				eve.keyCode = 13
				$_date.trigger(eve);
			});
			$_date.on('cancel.daterangepicker', function(ev, picker) {
				$(this).val('');
				let eve = jQuery.Event("keyup");
				eve.which = 13
				eve.keyCode = 13
				$_date.trigger(eve);
			});
		}
	}

	if( $('#csr_kyb_pending_review').length > 0 ){
		let dateFormat = 'DD/MM/YYYY';
		var $_date_submission = $('input.form-control.bootstrap-table-filter-control-_date[type="search"]');
		if( $_date_submission.length > 0 ){
			$_date_submission.daterangepicker({
					autoUpdateInput: false,
					locale: {
						format: dateFormat,
						separator: ' - ',
						firstDay: 2
					},
					opens: 'left',
					cancelButtonClasses: 'btn-default cancelButton_daterangepicker'
				},
				function(start, end) {
					startDate = start.format(dateFormat);
					endDate = end.format(dateFormat);
					let dates = [ startDate, endDate ];
					$_date_submission.val(start.format(dateFormat) + ' - ' + end.format(dateFormat));
				}
			);
			$_date_submission.on('apply.daterangepicker', function(ev, picker) {
				$(this).val(picker.startDate.format(dateFormat) + ' - ' + picker.endDate.format(dateFormat));
				let eve = jQuery.Event("keyup");
				eve.which = 13
				eve.keyCode = 13
				$_date_submission.trigger(eve);
			});
			$_date_submission.on('cancel.daterangepicker', function(ev, picker) {
				$(this).val('');
				let eve = jQuery.Event("keyup");
				eve.which = 13
				eve.keyCode = 13
				$_date_submission.trigger(eve);
			});
		}

		var $_date_lastupdate = $('input.form-control.bootstrap-table-filter-control-lastupdate[type="search"]');
		if( $_date_lastupdate.length > 0 ){
			$_date_lastupdate.daterangepicker({
					autoUpdateInput: false,
					locale: {
						format: dateFormat,
						separator: ' - ',
						firstDay: 2
					},
					opens: 'left',
					cancelButtonClasses: 'btn-default cancelButton_daterangepicker'
				},
				function(start, end) {
					startDate = start.format(dateFormat);
					endDate = end.format(dateFormat);
					let dates = [ startDate, endDate ];
					$_date_lastupdate.val(start.format(dateFormat) + ' - ' + end.format(dateFormat));
				}
			);
			$_date_lastupdate.on('apply.daterangepicker', function(ev, picker) {
				$(this).val(picker.startDate.format(dateFormat) + ' - ' + picker.endDate.format(dateFormat));
				let eve = jQuery.Event("keyup");
				eve.which = 13
				eve.keyCode = 13
				$_date_lastupdate.trigger(eve);
			});
			$_date_lastupdate.on('cancel.daterangepicker', function(ev, picker) {
				$(this).val('');
				let eve = jQuery.Event("keyup");
				eve.which = 13
				eve.keyCode = 13
				$_date_lastupdate.trigger(eve);
			});
		}

	}
	if( $('#csr_kyc_pending_review').length > 0 ){
		let dateFormat = 'DD/MM/YYYY';
		var $_date_lastupdate = $('input.form-control.bootstrap-table-filter-control-lastupdate[type="search"]');
		if( $_date_lastupdate.length > 0 ){
			$_date_lastupdate.daterangepicker({
					autoUpdateInput: false,
					locale: {
						format: dateFormat,
						separator: ' - ',
						firstDay: 2
					},
					opens: 'left',
					cancelButtonClasses: 'btn-default cancelButton_daterangepicker'
				},
				function(start, end) {
					startDate = start.format(dateFormat);
					endDate = end.format(dateFormat);
					let dates = [ startDate, endDate ];
					$_date_lastupdate.val(start.format(dateFormat) + ' - ' + end.format(dateFormat));
				}
			);
			$_date_lastupdate.on('apply.daterangepicker', function(ev, picker) {
				$(this).val(picker.startDate.format(dateFormat) + ' - ' + picker.endDate.format(dateFormat));
				let eve = jQuery.Event("keyup");
				eve.which = 13
				eve.keyCode = 13
				$_date_lastupdate.trigger(eve);
			});
			$_date_lastupdate.on('cancel.daterangepicker', function(ev, picker) {
				$(this).val('');
				let eve = jQuery.Event("keyup");
				eve.which = 13
				eve.keyCode = 13
				$_date_lastupdate.trigger(eve);
			});
		}

		var $_date_submission = $('input.form-control.bootstrap-table-filter-control-_date[type="search"]');
		if( $_date_submission.length > 0 ){
			$_date_submission.daterangepicker({
					autoUpdateInput: false,
					locale: {
						format: dateFormat,
						separator: ' - ',
						firstDay: 2
					},
					opens: 'left',
					cancelButtonClasses: 'btn-default cancelButton_daterangepicker'
				},
				function(start, end) {
					startDate = start.format(dateFormat);
					endDate = end.format(dateFormat);
					let dates = [ startDate, endDate ];
					$_date_submission.val(start.format(dateFormat) + ' - ' + end.format(dateFormat));
				}
			);
			$_date_submission.on('apply.daterangepicker', function(ev, picker) {
				$(this).val(picker.startDate.format(dateFormat) + ' - ' + picker.endDate.format(dateFormat));
				let eve = jQuery.Event("keyup");
				eve.which = 13
				eve.keyCode = 13
				$_date_submission.trigger(eve);
			});
			$_date_submission.on('cancel.daterangepicker', function(ev, picker) {
				$(this).val('');
				let eve = jQuery.Event("keyup");
				eve.which = 13
				eve.keyCode = 13
				$_date_submission.trigger(eve);
			});
		}

		var $_date_dob = $('input.form-control.bootstrap-table-filter-control-dob[type="search"]');
		if( $_date_dob.length > 0 ){
			$_date_dob.daterangepicker({
					autoUpdateInput: false,
					locale: {
						format: dateFormat,
						separator: ' - ',
						firstDay: 2
					},
					opens: 'left',
					cancelButtonClasses: 'btn-default cancelButton_daterangepicker'
				},
				function(start, end) {
					startDate = start.format(dateFormat);
					endDate = end.format(dateFormat);
					let dates = [ startDate, endDate ];
					$_date_dob.val(start.format(dateFormat) + ' - ' + end.format(dateFormat));
				}
			);
			$_date_dob.on('apply.daterangepicker', function(ev, picker) {
				$(this).val(picker.startDate.format(dateFormat) + ' - ' + picker.endDate.format(dateFormat));
				let eve = jQuery.Event("keyup");
				eve.which = 13
				eve.keyCode = 13
				$_date_dob.trigger(eve);
			});
			$_date_dob.on('cancel.daterangepicker', function(ev, picker) {
				$(this).val('');
				let eve = jQuery.Event("keyup");
				eve.which = 13
				eve.keyCode = 13
				$_date_dob.trigger(eve);
			});
		}

	}
	
	const retirement_banner_initial_delay = parseInt( cipscript.retirement_banner_initial_delay );
	const retirement_banner_interval = parseInt( cipscript.retirement_banner_interval );
	const retirement_banner_display_time = parseInt( cipscript.retirement_banner_display_time );

	var getBannerCookie = getCookie('bannerTime');
	// console.log( getBannerCookie );
	if( cipscript.isUserSM != 1 ){
		if( getBannerCookie == "" || typeof getBannerCookie === "undefined" || getBannerCookie == "undefined" ){
			setTimeout(() => {
				var data = {'action' : 'getRetirementBanner' };
				$.post(cipscript.ajax_url, data, function(response) {
					var obj = JSON.parse( response );
					if( obj.error == 0 && obj.html != "" ){
						$('body').append( obj.html );
						
						var nowDate = new Date();
						setCookie( 'bannerTime', nowDate, 1 );
						
						setTimeout(function(){ 
							$('body').find("#info_br_popup").addClass('p_remove');
							setTimeout(() => {
								$('body').find("#info_br_popup").remove();
							}, 3000);
						}, retirement_banner_display_time * 1000 + 3000 );
					}
				});
			}, retirement_banner_initial_delay * 1000);
		}
	}

	if( cipscript.isUserSM != 1 ){
		var bannerInterval = setInterval(() => {
			var bannerTime = getCookie('bannerTime');
	
			if( bannerTime == "" || typeof bannerTime === "undefined" || bannerTime == "undefined" ){
				// bannerTime = new Date();
				// setCookie( 'bannerTime', bannerTime, 1 );
			}else{
				var now = new Date();
				var seconds = (Date.parse(now) - Date.parse( bannerTime ) ) / 1000;
				// console.log( seconds );
				if( seconds >= retirement_banner_interval ){
					
					var data = {'action' : 'getRetirementBanner' };
					$.post(cipscript.ajax_url, data, function(response) {
						var obj = JSON.parse( response );
						if( obj.error == 0 && obj.html != "" ){
							$('body').append( obj.html );
							
							setCookie( 'bannerTime', now, 1 );
							
							setTimeout(function(){ 
								$('body').find("#info_br_popup").addClass('p_remove');
								setTimeout(() => {
									$('body').find("#info_br_popup").remove();
								}, 3000);
							}, retirement_banner_display_time * 1000 + 3000);
						}
					});
				}
			}
	
		}, 10 * 1000);
	}

	$('body').on('submit', '#sm_email_sending_switch_frm', function(){
		$form = $(this);
		var data = $(this).serialize();
		$form.block( block_config_kyc );
		$.post(cipscript.ajax_url, data, function(response) {
			var obj = JSON.parse( response );
			$form.unblock();
			if( obj.error == 0 ){
				swalToast({ type: 'success', title: obj.msg });
			}else{
				swalToast({ type: 'error', title: obj.msg });
			}
		});
		return false;
	});
	
	$('body').on('submit', '#sm_sms_sending_switch_frm', function(){
		$form = $(this);
		var data = $(this).serialize();
		$form.block( block_config_kyc );
		$.post(cipscript.ajax_url, data, function(response) {
			var obj = JSON.parse( response );
			$form.unblock();
			if( obj.error == 0 ){
				swalToast({ type: 'success', title: obj.msg });
			}else{
				swalToast({ type: 'error', title: obj.msg });
			}
		});
		return false;
	});

	if( $('[data-toggle-column="tooltip"]').length > 0 ){
		$('[data-toggle-column="tooltip"]').tooltip({ boundary: 'window' });
	}

	$(document).on('submit', '#maintenance_form', function(e){
		e.preventDefault();
		$form = $(this);
		$form.block( block_config_kyc );
		var data = new FormData( $form[0] );
		data.append("action", 'save_maintenance_mode');
		$.ajax({
			url			: cipscript.ajax_url,
			type		: 'post',
			data		: data,
			processData	: false,
			contentType	: false,
			success : function(response){
				var obj = JSON.parse( response );
				$form.unblock();
				if( obj.error == 0 ){
					swalToast({ type: 'success', title: obj.msg });
				}else{
					swalToast({ type: 'error', title: obj.msg });
				}
			}
		});
	});

	
	if( $('#cancelWithdrawModal').length > 0 ){
		
		$('body').on('click','.cancel_withdraw_request', function(e){
			var thisId = $(this).attr('data-cancel');
			var micro = $(this).attr('data-micro');
			var data = { 'action' : 'cancel_withdraw_request_action', 'thisId' : thisId, '_micro' : micro };
			var thisTr = $(this).closest('tr');
			thisTr.block( block_config );
			$.post(cipscript.ajax_url, data, function(response) {
				var obj = JSON.parse( response );
				if( obj.error == 0 ){
					$('#cancelWithdrawModal .modal-body').html( obj.html );
					setTimeout(() => {
						$('body').find('textarea[name="cancel_withdrawal_request_reason"]').focus().select();
					}, 800);
					current = 1;
					steps = $('body').find(".cancelWithdrawRequestFrm fieldset").length;
					setProgressBarWRCancel(current);
	
					$('#cancelWithdrawModal').modal({backdrop: 'static', keyboard: false}, 'show');
				}else{
					Swal.fire({ type: 'error', title: obj.msg, text: '',allowOutsideClick: true});
				}
				thisTr.unblock();
			});
			return false;
		});

		$('body').on("click",".cancelWithdrawRequestFrm .next", function(){
			var this_next = $(this);
			current_fs = $(this).closest('fieldset');
			next_fs = $(this).closest('fieldset').next();
			// console.log( current );
			
			var $form = $('body').find('.cancelWithdrawRequestFrm');

			if( current == 1 ){

				var cancel_withdrawal_request_reason = $form.find('textarea[name="cancel_withdrawal_request_reason"]').val();
				if( cancel_withdrawal_request_reason == "" ){
					swalToast({ type: 'error', title: 'Please enter reason for canceling the withdrawal' });
					return false;
				}

				var data = new FormData( $form[0] );
				data.append("step", '1');

				$(".cancelWithdrawRequestFrm #progressbar li").eq( $(".cancelWithdrawRequestFrm fieldset").index(next_fs) ).addClass("active");
				next_fs.show();
				current_fs.animate({opacity: 0}, {
					step: function(now) {
						opacity = 1 - now;
		
						current_fs.css({
							'display': 'none',
							'position': 'relative'
						});
						next_fs.css({'opacity': opacity});
						$('body').find('input[name="user_ga_otp_cancel"]').focus();
					},
					duration: 500
				});
				setProgressBarWRCancel(++current);

			}else if( current == 2 ){

				var $form = $('body').find('.cancelWithdrawRequestFrm');
				if( $form.find('input[name="user_ga_otp_cancel"]').val() == "" ){
					swalToast({ type: 'error', title: 'Please enter the authentication code' });
					return false;
				}

				var data = new FormData( $form[0] );
				data.append("step", '2');
				$form.block( block_config_kyc );
				$.ajax({
					url			: cipscript.ajax_url,
					type		: 'post',
					data		: data,
					processData	: false,
					contentType	: false,
					success : function(response){
						var obj = $.parseJSON(response);
						if( obj.error == 0 ){

							$('.cancel_withdraw_request_respose_section').html('');
							$('.cancel_withdraw_request_respose_section').html( obj.html );

							swalToast({ type: 'success', title: obj.msg });
							// $("#cancelWithdrawModal").modal('hide');

							$(".cancelWithdrawRequestFrm #progressbar li").eq( $(".cancelWithdrawRequestFrm fieldset").index(next_fs) ).addClass("active");
							next_fs.show();
							current_fs.animate({opacity: 0}, {
								step: function(now) {
									opacity = 1 - now;
					
									current_fs.css({
										'display': 'none',
										'position': 'relative'
									});
									next_fs.css({'opacity': opacity});
								},
								duration: 500
							});
							setProgressBarWRCancel(++current);
						}else{
							swalToast({ type: 'error', title: obj.msg });
						}
						$form.unblock();
	
					}
				});


			}else{
				$(".cancelWithdrawRequestFrm #progressbar li").eq( $(".cancelWithdrawRequestFrm fieldset").index(next_fs) ).addClass("active");
				next_fs.show();
				current_fs.animate({opacity: 0}, {
					step: function(now) {
						opacity = 1 - now;
		
						current_fs.css({
							'display': 'none',
							'position': 'relative'
						});
						next_fs.css({'opacity': opacity});
					},
					duration: 500
				});
				setProgressBarWRCancel(++current);
			}

		});
		$('body').on("click",".cancelWithdrawRequestFrm .previous", function(){
			current_fs = $(this).closest('fieldset');
			previous_fs = $(this).closest('fieldset').prev();
			// console.log( current );

			$(".cancelWithdrawRequestFrm #progressbar li").eq($(".cancelWithdrawRequestFrm fieldset").index(current_fs)).removeClass("active");

			previous_fs.show();

			current_fs.animate({opacity: 0}, {
				step: function(now) {
					opacity = 1 - now;

					current_fs.css({
					'display': 'none',
					'position': 'relative'
					});
					previous_fs.css({'opacity': opacity});
				},
				duration: 500
			});
			setProgressBarWRCancel(--current);
		});
		
		function setProgressBarWRCancel(curStep){
			var percent = parseFloat(100 / steps) * curStep;
			percent = percent.toFixed();
			$('body').find(".cancelWithdrawRequestFrm .progress-bar").css("width",percent+"%")
		}

		$('body').on('click', '.close_cancel_withdraw_request', function(){
			$("#cancelWithdrawModal").modal('hide');
			window.location.reload();
		});

		$("#cancelWithdrawModal").on('hide.bs.modal', function () {
			$('#cancelWithdrawModal .modal-body').html('');
		});
	}

	$('body').on('click','.approve_withdraw_request', function(e){

		var thisId = $(this).attr('data-approve');
		var micro = $(this).attr('data-micro');
		$('#approve_withdraw_request_frm .approve_label').html('Are you sure want to approve this withdrawal request?');
		$('<input>').attr({type: 'hidden', id: 'thisId', name: 'thisId', value: thisId}).appendTo( $('#approve_withdraw_request_frm') );
		$('<input>').attr({type: 'hidden', id: '_micro', name: '_micro', value: micro}).appendTo( $('#approve_withdraw_request_frm') );
		$("#approveWithdrawRequestModal").modal({backdrop: 'static',keyboard: false});
		return false;
	});

	$('body').on('submit', '#approve_withdraw_request_frm', function(){
		$form = $(this);

		if( $form.find('input[name="user_ga_otp"]').val() == "" ){
			swalToast({ type: 'error', title: 'Please enter the authentication code' });
			return false;
		}

		var data = $(this).serialize();
		$form.block( block_config_kyc );
		$.post(cipscript.ajax_url, data, function(response) {
			var obj = JSON.parse( response );
			if( obj.error == 0 ){
				swalToast({ type: 'success', title: obj.msg });
				$('#csr_withdraw_requests').bootstrapTable('refresh');
				$("#approveWithdrawRequestModal").modal('hide');
			}else{
				swalToast({ type: 'error', title: obj.msg });
			}
			$form.unblock();
		});
		return false;
	});

	$("#approveWithdrawRequestModal").on('hide.bs.modal', function () {
		$('#approve_withdraw_request_frm #thisId, #review_withdraw_request_frm #_micro').remove();
		$('#approve_withdraw_request_frm')[0].reset();
	});

	$('body').on('click','.review_withdraw_request', function(e){

		var thisId = $(this).attr('data-review');
		var micro = $(this).attr('data-micro');

		$('#review_withdraw_request_frm .review_label').html('Are you sure want to review this withdrawal request?');
		$('<input>').attr({type: 'hidden', id: 'thisId', name: 'thisId', value: thisId}).appendTo( $('#review_withdraw_request_frm') );
		$('<input>').attr({type: 'hidden', id: '_micro', name: '_micro', value: micro}).appendTo( $('#review_withdraw_request_frm') );
		$("#reviewWithdrawRequestModal").modal({backdrop: 'static',keyboard: false});
		return false;
	});

	$('body').on('submit', '#review_withdraw_request_frm', function(){
		$form = $(this);

		if( $form.find('input[name="user_ga_otp"]').val() == "" ){
			swalToast({ type: 'error', title: 'Please enter the authentication code' });
			return false;
		}

		var data = $(this).serialize();
		$form.block( block_config_kyc );
		$.post(cipscript.ajax_url, data, function(response) {
			var obj = JSON.parse( response );
			if( obj.error == 0 ){
				swalToast({ type: 'success', title: obj.msg });
				$('#csr_withdraw_requests').bootstrapTable('refresh');
				$("#reviewWithdrawRequestModal").modal('hide');
			}else{
				swalToast({ type: 'error', title: obj.msg });
			}
			$form.unblock();
		});
		return false;
	});

	$("#reviewWithdrawRequestModal").on('hide.bs.modal', function () {
		$('#review_withdraw_request_frm #thisId, #review_withdraw_request_frm #_micro').remove();
		$('#review_withdraw_request_frm')[0].reset();
	});

	if( $('#cancelPendingWithdrawRequestUserModal').length > 0 ){
		
		$('body').on('click','.user_cancel_pending_withdraw_request', function(e){
			var thisId = $(this).attr('data-cancel');
			var micro = $(this).attr('data-micro');
			var data = { 'action' : 'user_cancel_pending_withdraw_request_action', 'thisId' : thisId, '_micro' : micro };
			var thisTr = $(this).closest('tr');
			thisTr.block( block_config );
			$.post(cipscript.ajax_url, data, function(response) {
				var obj = JSON.parse( response );
				if( obj.error == 0 ){
					$('#cancelPendingWithdrawRequestUserModal .modal-body').html( obj.html );
					setTimeout(() => {
						$('body').find('textarea[name="cancel_withdrawal_request_reason"]').focus().select();
					}, 800);
					current = 1;
					steps = $('body').find(".cancelPendingWithdrawRequestUserFrm fieldset").length;
					setProgressBarWRCancel(current);
	
					$('#cancelPendingWithdrawRequestUserModal').modal({backdrop: 'static', keyboard: false}, 'show');
				}else{
					// Swal.fire({ type: 'error', title: obj.msg, text: '',allowOutsideClick: true});
					swalToast({ type: 'error', title: obj.msg });
				}
				thisTr.unblock();
			});
			return false;
		});

		$('body').on("click",".cancelPendingWithdrawRequestUserFrm .next", function(){
			var this_next = $(this);
			current_fs = $(this).closest('fieldset');
			next_fs = $(this).closest('fieldset').next();
			// console.log( current );
			
			var $form = $('body').find('.cancelPendingWithdrawRequestUserFrm');

			if( current == 1 ){

				var cancel_withdrawal_request_reason = $form.find('textarea[name="cancel_withdrawal_request_reason"]').val();
				if( cancel_withdrawal_request_reason == "" ){
					swalToast({ type: 'error', title: 'Please enter reason for canceling the withdrawal' });
					return false;
				}

				var data = new FormData( $form[0] );
				data.append("step", '1');

				$(".cancelPendingWithdrawRequestUserFrm #progressbar li").eq( $(".cancelPendingWithdrawRequestUserFrm fieldset").index(next_fs) ).addClass("active");
				next_fs.show();
				current_fs.animate({opacity: 0}, {
					step: function(now) {
						opacity = 1 - now;
		
						current_fs.css({
							'display': 'none',
							'position': 'relative'
						});
						next_fs.css({'opacity': opacity});
						$('body').find('input[name="user_ga_otp_cancel"]').focus();
					},
					duration: 500
				});
				setProgressBarWRCancel(++current);

			}else if( current == 2 ){

				var $form = $('body').find('.cancelPendingWithdrawRequestUserFrm');
				if( $form.find('input[name="user_ga_otp_cancel"]').val() == "" ){
					swalToast({ type: 'error', title: 'Please enter the authentication code' });
					return false;
				}

				var data = new FormData( $form[0] );
				data.append("step", '2');
				$form.block( block_config_kyc );
				$.ajax({
					url			: cipscript.ajax_url,
					type		: 'post',
					data		: data,
					processData	: false,
					contentType	: false,
					success : function(response){
						var obj = $.parseJSON(response);
						if( obj.error == 0 ){

							$('.cancel_withdraw_request_respose_section').html('');
							$('.cancel_withdraw_request_respose_section').html( obj.html );

							swalToast({ type: 'success', title: obj.msg });
							// $("#cancelWithdrawModal").modal('hide');

							$(".cancelPendingWithdrawRequestUserFrm #progressbar li").eq( $(".cancelPendingWithdrawRequestUserFrm fieldset").index(next_fs) ).addClass("active");
							next_fs.show();
							current_fs.animate({opacity: 0}, {
								step: function(now) {
									opacity = 1 - now;
					
									current_fs.css({
										'display': 'none',
										'position': 'relative'
									});
									next_fs.css({'opacity': opacity});
								},
								duration: 500
							});
							setProgressBarWRCancel(++current);
						}else{
							swalToast({ type: 'error', title: obj.msg });
						}
						$form.unblock();
	
					}
				});


			}else{
				$(".cancelPendingWithdrawRequestUserFrm #progressbar li").eq( $(".cancelPendingWithdrawRequestUserFrm fieldset").index(next_fs) ).addClass("active");
				next_fs.show();
				current_fs.animate({opacity: 0}, {
					step: function(now) {
						opacity = 1 - now;
		
						current_fs.css({
							'display': 'none',
							'position': 'relative'
						});
						next_fs.css({'opacity': opacity});
					},
					duration: 500
				});
				setProgressBarWRCancel(++current);
			}

		});
		$('body').on("click",".cancelPendingWithdrawRequestUserFrm .previous", function(){
			current_fs = $(this).closest('fieldset');
			previous_fs = $(this).closest('fieldset').prev();
			// console.log( current );

			$(".cancelPendingWithdrawRequestUserFrm #progressbar li").eq($(".cancelPendingWithdrawRequestUserFrm fieldset").index(current_fs)).removeClass("active");

			previous_fs.show();

			current_fs.animate({opacity: 0}, {
				step: function(now) {
					opacity = 1 - now;

					current_fs.css({
					'display': 'none',
					'position': 'relative'
					});
					previous_fs.css({'opacity': opacity});
				},
				duration: 500
			});
			setProgressBarWRCancel(--current);
		});
		
		function setProgressBarWRCancel(curStep){
			var percent = parseFloat(100 / steps) * curStep;
			percent = percent.toFixed();
			$('body').find(".cancelPendingWithdrawRequestUserFrm .progress-bar").css("width",percent+"%")
		}

		$('body').on('click', '.close_cancel_pending_withdraw_request_user', function(){
			$("#cancelPendingWithdrawRequestUserModal").modal('hide');
			window.location.reload();
		});

		$("#cancelPendingWithdrawRequestUserModal").on('hide.bs.modal', function () {
			$('#cancelPendingWithdrawRequestUserModal .modal-body').html('');
		});
	}


	if( $('#gform_6').length > 0 ){
		$("#input_6_1_3, #input_6_1_6").bind("input", function () {
			var c = this.selectionStart,
			  r = /[^a-z-_ ]/gi,
			  v = $(this).val();
			if( r.test(v) ){
			  $(this).val(v.replace(r, ""));
			  c--;
			}
			this.setSelectionRange(c, c);
		});
		$("#input_6_3").bind("input", function () {
			var c = this.selectionStart,
			  r = /[^a-z0-9-_.+@]/gi,
			  v = $(this).val();
			if( r.test(v) ){
			  $(this).val(v.replace(r, ""));
			  c--;
			}
			this.setSelectionRange(c, c);
		});
		$("#input_6_30").bind("input", function () {
			var c = this.selectionStart,
			  r = /[^a-z0-9-_ ]/gi,
			  v = $(this).val();
			if( r.test(v) ){
			  $(this).val(v.replace(r, ""));
			  c--;
			}
			this.setSelectionRange(c, c);
		});
		$("#input_6_2").bind("input", function () {
			var c = this.selectionStart,
			  r = /[^a-z0-9-_/(). ]/gi,
			  v = $(this).val();
			if( r.test(v) ){
			  $(this).val(v.replace(r, ""));
			  c--;
			}
			this.setSelectionRange(c, c);
		});
	}

	if( $('#addNewCsrWalletAddress').length > 0 ){
		$('body').on('submit', '#addNewCsrWalletAddress', function(){
			$form = $(this);

			var csrwalletaddress = $form.find('input[name="csrwalletaddress"]').val();

			if( csrwalletaddress == "" ){
				swalToast({ type: 'error', title: 'Please enter CSR wallet address' });
				return false;
			}
			if( !web3.utils.isAddress(csrwalletaddress) ){
				swalToast({ type: 'error', title: 'Please enter valid CSR wallet address' });
				return false;
			}
			if (!ethereum) {
				swalToast({ type: 'question', title: 'MetaMask is not installed' });
				window.userWalletAddress = null;
				$form.unblock();
				return false;
			}

			$form.block( block_config_kyc );
			var formData = $form.serialize();
			var data = cipscript.actionValidateAddNewCsrWalletData;
			data['thiseth'] = csrwalletaddress;
			data['isChangeMicro']	=	$form.find('input[name="_micro"]').val();

			$.ajax({
				method: "POST",
				url: cipscript.ajax_url,
				data: data,
				success: async function ( response ) {
					var obj = JSON.parse( response );
		
					// console.log( obj );
		
					if( obj.error == 0 ){
						
						const accounts = await ethereum.request({
							method: 'eth_requestAccounts'
						}).catch((e) => {
							Swal.fire({ type: 'error', title: e.message, text: '',allowOutsideClick: false});
							$form.unblock();
							return
						});
						if (!accounts) {
							Swal.fire({ type: 'error', title: 'Your address is NOT verified.', text: '',allowOutsideClick: false});
							$form.unblock();
							return
						}
						if( obj.data.toLowerCase() != accounts[0] ){
							Swal.fire({ type: 'error', title: 'Please select '+obj.data+' in MetaMask and try again.', text: '',allowOutsideClick: false});
							$form.unblock();
							return
						}
						
						$.ajax({
							method: "POST",
							url: cipscript.ajax_url,
							data: { action: "cipGetAddWalletAddressSignatureMsg_act", 'thiseth' : obj.data },
							success: async function (response) {
								var objCsrMsg = JSON.parse( response );
								if( objCsrMsg.error == 0 && objCsrMsg.msg != "" ){
									var fromAddress = obj.data;
									var params = [objCsrMsg.msg, fromAddress];
									var method = 'personal_sign';
									const signature = await ethereum.request({
										method, 
										params, 
										fromAddress
									}).catch((e) => {
										Swal.fire({ type: 'error', title: e.message, text: '',allowOutsideClick: false});
										$form.unblock();
										return
									})
									if( !signature ){
										Swal.fire({ type: 'error', title: 'Your address is NOT verified.', text: '',allowOutsideClick: false});
										$form.unblock();
										return
									}
		
									/* if( obj.isConfirmResumeDistribution == 1 ){
										$('body').find('.confirm_resume_section').html( obj.confirmCheckboxHtml );
									} */
		
									formData = formData + '&verifyingProcess=yes&signature=' + signature;
		
									$.ajax({
										method: "POST",
										url: cipscript.ajax_url,
										data: formData,
										success: async function (response) {
											var objSign = JSON.parse( response );
											if( objSign.error == 0 ){
		
												if( objSign.isDirectAdded == 1 ){
													$('#addNewWalletAddressModel').modal('hide');
													Swal.fire({ type: 'success', title: objSign.msg, text: '',allowOutsideClick: true}).then(function(){ $('#addNewWalletAddressModel').modal('hide'); window.location.reload();});
												}
												
											}else{
												Swal.fire({ type: 'error', title: objSign.msg, text: '',allowOutsideClick: false});
											}
											$form.unblock();
										},
										error: function () {
											Swal.fire({ type: 'error', title: 'An error was encountered', text: '',allowOutsideClick: false});
											$form.unblock();
										}
									});
								}else{
									Swal.fire({ type: 'error', title: objCsrMsg.msg, text: '',allowOutsideClick: false});
									$form.unblock();
									return false;
								}
							},
							error: function () {
								Swal.fire({ type: 'error', title: 'An error was encountered', text: '',allowOutsideClick: false});
								$form.unblock();
							}
						});
		
					}else{
						Swal.fire({ type: 'error', title: obj.msg, text: '',allowOutsideClick: false});
						$form.unblock();
						return false;
					}
				},
				error: function () {
					Swal.fire({ type: 'error', title: 'An error was encountered', text: '',allowOutsideClick: false});
					$form.unblock();
				}
			});
			
			return false;
		});
	}

	if( $('#csr_withdrawal_report_details').length > 0 ){			
		var $table_csr_withdrawal_report_details = jQuery('#csr_withdrawal_report_details');
		$table_csr_withdrawal_report_details.bootstrapTable();
	}

	$("#csr_withdrawals_report_amount_settings_frm #csr_withdrawals_report_amount").bind("input", function () {
		var c = this.selectionStart,
		  r = /[^0-9]/gi,
		  v = $(this).val();
		if( r.test(v) ){
		  $(this).val(v.replace(r, ""));
		  c--;
		}
		this.setSelectionRange(c, c);
	});
	$('body').on('submit', '#csr_withdrawals_report_amount_settings_frm', function(){
		$form = $(this);
		$form.find('.form_response').html('');
		var data = $(this).serialize();
		$form.block( block_config );
		$.post(cipscript.ajax_url, data, function(response) {
			var obj = JSON.parse( response );
			$form.unblock();
			$form.find('.form_response').html( obj.msg );
			if( obj.error == 0 ){
				Swal.fire({ type: 'success', title: obj.msg, text: '',allowOutsideClick: false});
			}else{
				Swal.fire({ type: 'error', title: obj.msg, text: '',allowOutsideClick: false});
			}
		});
		return false;
	});

	if( $('#cip_amount_wallet_table .saving_start_date').length > 0 ){
		let dateFormatWD = 'DD/MM/YYYY';
		$('#cip_amount_wallet_table input.bootstrap-table-filter-control-saving_start_date[type="search"]')
		.daterangepicker({
				autoUpdateInput: false,
				locale: {
					format: dateFormatWD,
					separator: ' - ',
					firstDay: 1
				},
				opens: 'left',
				cancelButtonClasses: 'btn-default'
			},
		);
		jQuery('#cip_amount_wallet_table input.bootstrap-table-filter-control-saving_start_date[type="search"]').on('apply.daterangepicker', function(ev, picker) {
			$(this).val(picker.startDate.format(dateFormatWD) + ' - ' + picker.endDate.format(dateFormatWD));
			let eve = jQuery.Event("keyup");
			eve.which = 13
			eve.keyCode = 13
			$('#cip_amount_wallet_table input.bootstrap-table-filter-control-saving_start_date[type="search"]').trigger(eve);
		});
		$('#cip_amount_wallet_table input.bootstrap-table-filter-control-saving_start_date[type="search"]').on('cancel.daterangepicker', function(ev, picker) {
			$(this).val('');
			let eve = jQuery.Event("keyup");
			eve.which = 13
			eve.keyCode = 13
			$('#cip_amount_wallet_table .bootstrap-table-filter-control-saving_start_date').trigger(eve);
		});
	}

	if( $('.weekly_bonus_pools_split_wizard_frm').length > 0 ){
		
		var notifyErrorOpt = {position:"top",className: 'error',autoHide:true,autoHideDelay: 3000,clickToHide: true};
		var block_config = { message: null,overlayCSS:{ backgroundColor: '#fff',opacity:0.8} };

		var current_fs, next_fs, previous_fs; //fieldsets
		var opacity;
		var current = 1;
		var steps = $("fieldset").length;
		var $form = $('.weekly_bonus_pools_split_wizard_frm'); 
		var csr_spinner = $('.csr_spinner');
		var csr_split_spinner = $('.csr_split_spinner');
		var process_log = document.getElementById('process_log');
		var process_split_log = document.getElementById('process_split_log');
		var splited = false;
		var isError = true;
		var lastMsg = "";
		var lastMsg_total = "";
		setProgressBar(current);

		$(".next").click(function(){

			var this_next = $(this);
			current_fs = $(this).closest('fieldset');
			next_fs = $(this).closest('fieldset').next();
			if( current == 1 ){ //find all pool records

				var csr_segmentation = $('input[name="csr_segmentation"]').val();
				var bonus_pool_ref = $('select#bonus_pool_ref').val();
				if( bonus_pool_ref == "" ){
					$('select#bonus_pool_ref').notify( 'Please choose pool reference', notifyErrorOpt );
					return false;
				}
				if( csr_segmentation == "" ){
					$('input[name="csr_segmentation"]').notify( 'CSR Segmentation is required', notifyErrorOpt );
					return false;
				}
				if( !jQuery.isNumeric( csr_segmentation )  ){
					$('input[name="csr_segmentation"]').notify( 'Please enter valid CSR Segmentation', notifyErrorOpt );
					return false;
				}
				if( csr_segmentation != "" && parseInt( csr_segmentation ) < 10 ){
					$('input[name="csr_segmentation"]').notify( 'Minimum CSR Segmentation is 10', notifyErrorOpt );
					return false;
				}

				var data = new FormData( $form[0] );
				data.append("fieldmapping_pool_record", 'yes');
				$.ajax({
					url			: cipscript.ajax_url,
					type		: 'post',
					data		: data,
					processData	: false,
					contentType	: false,
					timeout		: 0,
					beforeSend	: function(){
					
						next_fs.find('.next').hide();
						next_fs.find('.previous').hide();
	
						$("#progressbar li").eq( $("fieldset").index(next_fs) ).addClass("active");
						next_fs.show();
						current_fs.animate({opacity: 0}, {
							step: function(now) {
								opacity = 1 - now;
	
								current_fs.css({
									'display': 'none',
									'position': 'relative'
								});
								next_fs.css({'opacity': opacity});
							},
							duration: 500
						});
						setProgressBar(++current);
						csr_spinner.show();
						$('.process_log').append('<li class="list-group-item d-flex align-items-center"><span class="mr-3 badge badge-info badge-pill" data-toggle="tooltip" data-placement="top" title="Fetching data"><i class="fa fa-check-"></i></span>Fetching data</li>');
						$('.process_log').append('<li class="list-group-item d-flex align-items-center"><span class="mr-3 badge badge-info badge-pill" data-toggle="tooltip" data-placement="top" title="Fetching data started..."><i class="fa fa-check-"></i></span>Fetching data started...</li>');
						$('[data-toggle="tooltip"]').tooltip();
						process_log.scrollTop = process_log.scrollHeight;
					},
					success : function(response){
						var obj = $.parseJSON(response);
						
						console.dir( obj );
						$('.process_log').append('<li class="list-group-item d-flex align-items-center"><span class="mr-3 badge badge-info badge-pill" data-toggle="tooltip" data-placement="top" title="Fetching data completed."><i class="fa fa-check-"></i></span>Fetching data completed.</li>');

						if( obj.error == 0 ){

							$('.process_log').append('<li class="list-group-item d-block align-items-center"><span class="mr-3 badge badge-info badge-pill" data-toggle="tooltip" data-placement="top" title="'+obj.msg2+'"><i class="fa fa-check-"></i></span>'+obj.msg+'</li>');
							csr_spinner.hide();

							next_fs.find('.next').prop('disabled', false);
							next_fs.find('.next').show();
							next_fs.find('.previous').show();

						}else{
							$('.process_log').append('<li class="list-group-item d-flex align-items-center"><span class="mr-3 badge badge-danger badge-pill" data-toggle="tooltip" data-placement="top" title="'+obj.msg2+'"><i class="fa fa-check-"></i></span>'+obj.msg+'</li>');
							next_fs.find('.next').prop('disabled', true);
							next_fs.find('.previous').show();
							csr_spinner.hide();
							process_log.scrollTop = process_log.scrollHeight;
						}
						$('[data-toggle="tooltip"]').tooltip();
						process_log.scrollTop = process_log.scrollHeight;
					}

				});
			}else if( current == 3 ){ // splitting process starting
				
				if( !splited ){

					var data = new FormData( $form[0] ); // splitting process
					data.append("splitting_bonus_start", 'yes');
					$.ajax({
						url: cipscript.ajax_url,
						type: 'post',
						data: data,
						processData: false,
						contentType: false,
						timeout: 0,
						beforeSend	: function(){
							
							next_fs.find('.next').hide();
							next_fs.find('.previous').hide();
		
							$("#progressbar li").eq( $("fieldset").index(next_fs) ).addClass("active");
							next_fs.show();
							current_fs.animate({opacity: 0}, {
								step: function(now) {
									opacity = 1 - now;
		
									current_fs.css({
										'display': 'none',
										'position': 'relative'
									});
									next_fs.css({'opacity': opacity});
								},
								duration: 500
							});
							setProgressBar(++current);
							csr_split_spinner.show();
						},
						success : async function(response){
							
							var obj = $.parseJSON(response);

							if( obj.error == 0 ){
		
								$('.process_split_log').append('<li class="list-group-item d-block align-items-center"><span class="mr-3 badge badge-info badge-pill" data-toggle="tooltip" data-placement="top" title="'+obj.msg2+'"><i class="fa fa-check-"></i></span>'+obj.msg+'<div class="total_process_split_log_counter">'+obj.totalmsg+'</div><div class="process_split_log_counter"></div></li>');

								// console.log( obj );
		
								var promises = [];
								for (let icsv = 1; icsv <= obj.total_paged; icsv++) {
										
									var isError = false;
									var data = new FormData( $form[0] );
									data.append("splitting_bonus_data", 'yes');
									data.append("page_id", icsv);
									var request = await $.ajax({
										url: cipscript.ajax_url,
										type: 'post',
										data: data,
										processData: false,
										contentType: false,
										timeout: 0,
										async: true,
										success : function(response){
											var obj = $.parseJSON(response);
											// console.log( obj );
											if( obj.error == 0 ){
												$('body').find('.process_split_log_counter').append(obj.msg);
											}else{
												$('.process_split_log').append('<li class="list-group-item d-flex align-items-center"><span class="mr-3 badge badge-danger badge-pill" data-toggle="tooltip" data-placement="top" title="'+obj.msg2+'"><i class="fa fa-check-"></i></span>'+obj.msg+'</li>');
												isError = true;
											}
											$('[data-toggle="tooltip"]').tooltip();
										}
									});
									if( isError == true ){
										csr_split_spinner.hide();
										break;
									}
									promises.push(request);
								}
								Promise.all(promises).then(responseList => {
									// console.dir( responseList );
									$('.process_split_log').append('<li class="list-group-item d-flex align-items-center"><span class="mr-3 badge badge-info badge-pill" data-toggle="tooltip" data-placement="top" title="Splitting 10% distributions completed."><i class="fa fa-check-"></i></span>Splitting 10% distributions completed.</li>');
									$('[data-toggle="tooltip"]').tooltip();
									if( isError ){
										next_fs.find('.next').prop('disabled', true);
										next_fs.find('.next').hide();
										next_fs.find('.previous').show();
									}else{
										next_fs.find('.next').prop('disabled', false);
										next_fs.find('.next').show();
										next_fs.find('.previous').show();
										splited = true;
									}
									csr_split_spinner.hide();
								});
		
							}else{
								$('.process_split_log').append('<li class="list-group-item d-flex align-items-center"><span class="mr-3 badge badge-danger badge-pill" data-toggle="tooltip" data-placement="top" title="'+obj.msg2+'"><i class="fa fa-check-"></i></span>'+obj.msg+'</li>');
								next_fs.find('.next').prop('disabled', true);
								next_fs.find('.previous').show();
								csr_split_spinner.hide();
							}
							$('[data-toggle="tooltip"]').tooltip();
						}
					});
				}else{
					$("#progressbar li").eq( $("fieldset").index(next_fs) ).addClass("active");
					next_fs.show();
					current_fs.animate({opacity: 0}, {
						step: function(now) {
							opacity = 1 - now;

							current_fs.css({
								'display': 'none',
								'position': 'relative'
							});
							next_fs.css({'opacity': opacity});
						},
						duration: 500
					});
					setProgressBar(++current);
				}

			}else if( current == 2 ){

				$("#progressbar li").eq( $("fieldset").index(next_fs) ).addClass("active");
				next_fs.show();
				current_fs.animate({opacity: 0}, {
					step: function(now) {
						opacity = 1 - now;

						current_fs.css({
							'display': 'none',
							'position': 'relative'
						});
						next_fs.css({'opacity': opacity});
					},
					duration: 500
				});
				setProgressBar(++current);

				$('.distribution_section_table').show();
				console.log('test');
				var $tableDistribution = $('#tokenholder_distribution_table');
				$tableDistribution.bootstrapTable('refresh');

			}else if( current == 4 ){

				$("#progressbar li").eq( $("fieldset").index(next_fs) ).addClass("active");
				next_fs.show();
				current_fs.animate({opacity: 0}, {
					step: function(now) {
						opacity = 1 - now;

						current_fs.css({
							'display': 'none',
							'position': 'relative'
						});
						next_fs.css({'opacity': opacity});
					},
					duration: 500
				});
				setProgressBar(++current);

				$('.distribution_10_section_table').show();
				var $tableDistribution_10 = $('#tokenholder_distribution_10_table');
				$tableDistribution_10.bootstrapTable('refresh');

				$('html, body').animate({
					scrollTop: $("#progressbar").offset().top - 100
				}, 1000);

			}else if( current == 5 ){

				setTimeout(() => {
					$("#progressbar li").eq( $("fieldset").index(next_fs) ).addClass("active");
					next_fs.show();
					current_fs.animate({opacity: 0}, {
						step: function(now) {
							opacity = 1 - now;

							current_fs.css({
								'display': 'none',
								'position': 'relative'
							});
							next_fs.css({'opacity': opacity});
						},
						duration: 500
					});
					setProgressBar(++current);


					/* $ajaxElem = $('.summary_data_at_append_step');
					$ajaxElem.html('');
					$ajaxElem.block( block_config );
					var data = { 'action' : 'getAppendDistributionDataAction' };
					$.post(cipscript.ajax_url, data, function(response) {
						var obj = JSON.parse( response );
						if( obj.error == 0 ){
							$ajaxElem.html( obj.html );
						}else{
							Swal.fire({ type: 'error', title: obj.msg, text: '',allowOutsideClick: false});
							// console.log( obj.msg );
						}
						$ajaxElem.unblock();
					}); */


				}, 100);


			}else{
				$("#progressbar li").eq( $("fieldset").index(next_fs) ).addClass("active");
				next_fs.show();
				current_fs.animate({opacity: 0}, {
					step: function(now) {
						opacity = 1 - now;

						current_fs.css({
							'display': 'none',
							'position': 'relative'
						});
						next_fs.css({'opacity': opacity});
					},
					duration: 500
				});
				setProgressBar(++current);
			}
		});

		$(".previous").click(function(){

			current_fs = $(this).closest('fieldset');
			previous_fs = $(this).closest('fieldset').prev();
			// console.log( current );
			if( current == 2 ){
				$('.process_log').html('');
				$("input[name='th_csv_file']").val('');
			}
			if( current == 6 ){
				$('.distribution_10_section_table').show();
				var $tableDistribution_10 = $('#tokenholder_distribution_10_table');
				$tableDistribution_10.bootstrapTable('refresh');

				$('html, body').animate({
					scrollTop: $("#progressbar").offset().top - 100
				}, 1000);
			}
			if( current == 4 ){
				$('.distribution_section_table').show();
				var $tableDistribution = $('#tokenholder_distribution_table');
				$tableDistribution.bootstrapTable('refresh');

				$('html, body').animate({
					scrollTop: $("#progressbar").offset().top - 100
				}, 1000);
			}

			//Remove class active
			$("#progressbar li").eq($("fieldset").index(current_fs)).removeClass("active");

			//show the previous fieldset
			previous_fs.show();

			//hide the current fieldset with style
			current_fs.animate({opacity: 0}, {
				step: function(now) {
					// for making fielset appear animation
					opacity = 1 - now;

					current_fs.css({
					'display': 'none',
					'position': 'relative'
					});
					previous_fs.css({'opacity': opacity});
				},
				duration: 500
			});
			setProgressBar(--current);
			
		});

		function setProgressBar(curStep){
			var percent = parseFloat(100 / steps) * curStep;
			percent = percent.toFixed();
			$(".progress-bar").css("width",percent+"%")
		}

		function arrayToTable(tableData) {
			var table = $('<table class="table table-sm table-hover table-bordered"></table>');
			$(tableData).each(function (i, rowData) {
				var row = $('<tr></tr>');
				$(rowData).each(function (j, cellData) {
					row.append($('<td>'+cellData+'</td>'));
				});
				table.append(row);
			});
			return table;
		}

		$('body').on('click', '.append_new_bonus_csr_holders_data_button', function(){

			$form = $(this).closest('fieldset');
			buttonAppend = $('.append_new_bonus_csr_holders_data_button');
			buttonCancelAppend = $('.append_bonus_cancel');
			
			buttonAppend.prop('disabled', true);
			buttonCancelAppend.prop('disabled', true);

			var csr_split_spinner = $('.csr_split_append_spinner');
			$formAppend = $('#append_new_bonus_csr_holders_data_frm');
			var data = $('#append_new_bonus_csr_holders_data_frm').serialize();
			data = data + '&get_append_bonus_data=yes';
			$form.block( block_config );
			$.post(cipscript.ajax_url, data, async function(response) {
				var obj = JSON.parse( response );
				console.dir( obj );
				if( obj.error == 0 ){

					$('.process_split_append_log').append('<li class="list-group-item d-block align-items-center"><span class="mr-3 badge badge-info badge-pill" data-toggle="tooltip" data-placement="top" title="'+obj.msg2+'"><i class="fa fa-check-"></i></span>'+obj.msg+'<div class="total_process_split_append_log_counter">'+obj.totalmsg+'</div><div class="process_split_append_log_counter"></div></li>');

					console.log( obj );

					var promisesAppend = [];
					for (let icsv = 1; icsv <= obj.total_paged; icsv++) {
							
						var isError = false;
						var data = new FormData( $formAppend[0] );
						data.append("appending_bonus_data", 'yes');
						data.append("page_id", icsv);
						data.append("total_paged", obj.total_paged);
						var requestAppend = await $.ajax({
							url: cipscript.ajax_url,
							type: 'post',
							data: data,
							processData: false,
							contentType: false,
							timeout: 0,
							async: true,
							success : function(response){
								var obj = $.parseJSON(response);
								console.log( obj );
								if( obj.error == 0 ){
									$('body').find('.process_split_append_log_counter').append(obj.msg);

									if( obj.isLastPage == 'yes' ){
										setTimeout(() => {
											$('.finish_step').trigger('click');
										}, 3000);
										// $('.append_response').html( obj.msg );
									}

								}else{
									$('.process_split_append_log').append('<li class="list-group-item d-flex align-items-center"><span class="mr-3 badge badge-danger badge-pill" data-toggle="tooltip" data-placement="top" title="'+obj.msg2+'"><i class="fa fa-check-"></i></span>'+obj.msg+'</li>');
									isError = true;
								}
								$('[data-toggle="tooltip"]').tooltip();
							}
						});
						if( isError == true ){
							csr_split_spinner.hide();
							buttonAppend.prop('disabled', false);
							buttonCancelAppend.prop('disabled', false);
							break;
						}
						promisesAppend.push(requestAppend);
					}
					Promise.all(promisesAppend).then(responseList => {
						console.dir( responseList );
						$('.process_split_append_log').append('<li class="list-group-item d-flex align-items-center"><span class="mr-3 badge badge-info badge-pill" data-toggle="tooltip" data-placement="top" title="Appending 10% distributions completed."><i class="fa fa-check-"></i></span>Appending 10% distributions completed.</li>');
						$('[data-toggle="tooltip"]').tooltip();
						if( isError ){
							/* next_fs.find('.next').prop('disabled', true);
							next_fs.find('.next').hide();
							next_fs.find('.previous').show(); */
							buttonAppend.prop('disabled', false);
							buttonCancelAppend.prop('disabled', false);
						}else{
							/* next_fs.find('.next').prop('disabled', false);
							next_fs.find('.next').show();
							next_fs.find('.previous').show(); */
							// splited = true;
						}
						csr_split_spinner.hide();
					});

					/* $('.finish_step').trigger('click');
					$('.append_response').html( obj.msg ); */
				}else{
					$('.process_split_append_log').append('<li class="list-group-item d-flex align-items-center"><span class="mr-3 badge badge-danger badge-pill" data-toggle="tooltip" data-placement="top" title="'+obj.msg2+'"><i class="fa fa-check-"></i></span>'+obj.msg+'</li>');
					/* next_fs.find('.next').prop('disabled', true);
					next_fs.find('.previous').show(); */
					csr_split_spinner.hide();
					
					buttonAppend.prop('disabled', false);
					buttonCancelAppend.prop('disabled', false);
					
					Swal.fire({ type: 'error', title: obj.msg, text: '',allowOutsideClick: false});
				}
				$form.unblock();
			});

			/* Swal({
			title: 'Are you sure?',
			text: "Are you sure you want to append new CSR Holders data",
			type: 'warning',
			showCancelButton: true,
			confirmButtonText: 'Yes'
			}).then((result) => {
			if (result.value) {
					$form = $(this).closest('fieldset');
					var data = $('#append_new_csr_holders_data_frm').serialize();
					$form.block( block_config );
					$.post(cipscript.ajax_url, data, function(response) {
						var obj = JSON.parse( response );
						console.dir( obj );
						if( obj.error == 0 ){
							$('.finish_step').trigger('click');
							$('.append_response').html( obj.msg );
						}else{
							Swal.fire({ type: 'error', title: obj.msg, text: '',allowOutsideClick: false});
						}
						$form.unblock();
					});
			}
			}); */
			return false;
		});
		$('body').on('click', '.append_bonus_cancel', function(){
			Swal({
			title: 'Are you sure?',
			text: "Are you sure you want to cancel",
			type: 'warning',
			showCancelButton: true,
			confirmButtonText: 'Yes'
			}).then((result) => {
			if (result.value) {
					$form = $(this).closest('fieldset');
					var data = $('#append_cancel_bonus_data_frm').serialize();
					$form.block( block_config );
					$.post(cipscript.ajax_url, data, function(response) {
						var obj = JSON.parse( response );
						console.dir( obj );
						if( obj.error == 0 ){
							window.location.href = cipscript.current_page;
						}else{
							Swal.fire({ type: 'error', title: obj.msg, text: '',allowOutsideClick: false});
						}
						$form.unblock();
					});
			}
			});
			return false;
		});

		if( cipscript.isDistributionDataTemp == 1 ){
			go_to_five_step();
			$('.back_disable').hide();
		}

		function go_to_five_step(){
			for (let step = 1; step < 6; step++) {
				var $next_button = $('.step_'+(step - 1 )).find('.next');
				
				var current_fs = $next_button.parent();
				var next_fs = $next_button.parent().next();

				$("#progressbar li").eq( $("fieldset").index(next_fs) ).addClass("active");
				next_fs.show();
				current_fs.css({
					'display': 'none',
					'position': 'relative'
				});
				next_fs.css({'opacity': opacity});
				setProgressBar(++current);
			}
		}

		$('.bonus_pool_ref_select').select2({
			minimumInputLength: 3,
			ajax: {
				url: cipscript.ajax_url,
				dataType: 'json',
				data: function (params) {
					var query = {
						search: params.term,
						action: 'pool_ref_fetch_act'
					}
					return query;
				}
			},
			processResults: function (response) {
				return {
				   results: response
				};
			},
			width: '100%',
			scrollAfterSelect: false,
			dropdownParent: $('.weekly_bonus_pools_split_wizard_frm .step_0 .form-card'),
		});
	}

	/* if( $('table#countries_management').length > 0 ){
		var $countries_management = $('body').find('table#countries_management');
		$countries_management.bootstrapTable({
			stickyHeader: true,
		});
	} */

	if( $('.withdrawal_disable_after_login_timer_section').length > 0 ){
		setTimeout(() => {
			// $('.withdrawal_disable_after_login_timer_section').removeClass('hide');
			const target = document.querySelector(".tippyTimerCounter");
			const dropdownTippyContent = document.querySelector(".tippyContent");
			const contentTimer = document.querySelector(".withdrawal_disable_after_login_timer_section");
			tippy(target, {
				content: dropdownTippyContent,
				interactive: true,
				onShow: () => {
					dropdownTippyContent.append(contentTimer);
				},
				onHidden: () => {
				  document.body.append(contentTimer);
				},
			  });
		}, 300);
		var updateTime = setInterval(displayTime, 1000);
	}
	function displayTime() {
		var data = {'action' : 'withdrawal_disable_after_login_timer'};
		var $clock = $('.clock');
		$.ajax({
			url: cipscript.ajax_url,
			data: data,
			dataType: "json",
			success: function(info) {
				
				var minutes    =  info.countDown.i,
					seconds    =  info.countDown.s,
					$msg       =  ''; 
					
				if( isZeroNegative( parseInt( info.value ) ) ){
					clearTimeout( updateTime );
					$clock.remove();
					if($('#pp-advanced-tabs-title-7871').hasClass('pp-tab-active')){
						window.location.reload();
					}else{
						$(document).on('click','#pp-advanced-tabs-title-7871',function(){
							window.location.reload();
						});
					}
					return false;
				}

				if( parseInt( minutes ) < 10 && parseInt( minutes ) > 0 ){
					minutes = '0' + minutes;
				}
				
				if( parseInt( seconds ) < 10 && parseInt( seconds ) > 0 ){
					seconds = '0' + seconds;	
				}

				// $msg = 'After ' + minutes + ' Minutes ' + seconds + ' Seconds' + ' you can able to withdraw';
				// $clock.html($msg);
				$('.coundown-container #minutes').text( minutes );
				$('.coundown-container #seconds').text( seconds );
			},
			error: function (response) {
				clearTimeout( updateTime );
				$clock.remove();
				return false;
			}
		});
	}

	$('body').on('submit', '#withdrawal_suspension_after_login_setting_frm', function(){
		$form = $(this);
		if( parseInt( $form.find('#withdrawal_suspension_minutes').val() ) <= 0 ){
			swalToast({ type: 'error', title: 'Please enter Withdrawal suspension minutes' });
			return false;
		}
		var data = $(this).serialize();
		$form.block( block_config_kyc );
		$.post(cipscript.ajax_url, data, function(response) {
			var obj = JSON.parse( response );
			$form.unblock();
			$form.find('.form_response').html( obj.msg );
			if( obj.error == 0 ){
				swalToast({ type: 'success', title: obj.msg });
			}else{
				swalToast({ type: 'error', title: obj.msg });
			}
		});
		return false;
	});

	if( $('[data-magnify]').length > 0 ){

		$('[data-magnify]').magnify({
			resizable: false,
			footerToolbar: ['zoomIn','zoomOut','fullscreen','actualSize','rotateRight'],
			multiInstances: false,
			initMaximized: true
		});
	}

	/**
	 * Create withdrawal block address script
	 */
	$('body').on('submit', '#create_withdrawal_block_address_frm', function(){
		var block_config = { css: { backgroundColor: 'transparent', border: 'none' }, message: '<div class="blockUIspinner"></div>', baseZ: 1500, overlayCSS: { backgroundColor: '#FFFFFF', opacity: 0.8, cursor: 'wait' } };
		
		$form = $(this);
		if( $(this).find('input[name="address_name"]').val() == "" ){
			swalToast({ type: 'error', title: 'Please enter address name' });
			return false;
		}
		
		if( $(this).find('input[name="withdrawal_block_address"]').val() == "" ){
			swalToast({ type: 'error', title: 'Please enter withdrawal block address' });
			return false;
		}

		if( !web3.utils.isAddress( $(this).find('input[name="withdrawal_block_address"]').val() ) ){
			swalToast({ type: 'error', title: 'Please enter valid withdrawal block address' });
			return false;
		}

		var data = $(this).serialize();
		$.blockUI(block_config);
		$.post(cipscript.ajax_url, data, function(response) {
			var obj = JSON.parse( response );
			if( obj.error == 0 ){
				swalToast({ type: 'success', title: obj.msg });
				$("#createWithdrawalBlockAddressModal").modal('hide');
				$form[0].reset();
				$('#cip_withdrawal_block_address_list').bootstrapTable('refresh');
			}else{
				swalToast({ type: 'error', title: obj.msg });
			}
			$.unblockUI();
		});
		return false;
	});

	/**
	 * Delete withdrawal block address script
	 */
	$('body').on('click', '.delete-withdrawal-block-address', function(e){
		var block_config = { css: { backgroundColor: 'transparent', border: 'none' }, message: '<div class="blockUIspinner"></div>', baseZ: 1500, overlayCSS: { backgroundColor: '#FFFFFF', opacity: 0.8, cursor: 'wait' } };
		
		var thisId = $(this).attr('data-delete');
		var micro = $(this).attr('data-micro');
		var thisTr = $(this).closest('tr');
		
		Swal({
			title: 'Are you sure?',
			text: "Do you want to remove address?",
			type: 'warning',
			showCancelButton: true,
			confirmButtonText: 'Yes'
		  }).then((result) => {
			if (result.value) {
				var data = { 'action' : 'delete_withdrawal_block_address_action', 'thisId' : thisId, '_micro' : micro };
				thisTr.block( block_config );
				$.post(cipscript.ajax_url, data, function(response) {
					var obj = JSON.parse( response );
					if( obj.error == 0 ){
						swalToast({ type: 'success', title: obj.msg });
						$('#cip_withdrawal_block_address_list').bootstrapTable('refresh');
					}else{
						swalToast({ type: 'error', title: obj.msg });
					}
					thisTr.unblock();
				});
			}
		});

	});

	/**
	 * Open create corporate user form
	 */
	$('body').on('click', '#create_corporate_user_popup', function(e){
		e.preventDefault();
		var micro = $(this).attr('data-_micro');
		var data = { 'action' : 'get_create_corporate_user_form_action', '_micro' : micro };
		$.blockUI( block_config_kyc );
		$.post(cipscript.ajax_url, data, function(response) {
			var obj = JSON.parse( response );
			if( obj.error == 0 ){

				const interval_id = window.setInterval(function(){}, Number.MAX_SAFE_INTEGER);
				for (let i = 1; i < interval_id; i++) {
					window.clearInterval(i);
				}

				$('#createCorporateUserModal .modal-body').html( obj.html );
				$('#createCorporateUserModal').modal('show');
			}else{
				swalToast({ type: 'error', title: obj.msg });
			}
			$.unblockUI();
		});
	});
	$('#createCorporateUserModal').on('hide.bs.modal', function (event) {
		var $form = $('#create_corporate_user_frm');
		$form[0].reset();
		var modal = $(this);
		modal.find('.modal-body').html('');
	});
	/**
	 * Resend OTP of add corporate user
	 */
	$('body').on('click', '#resend_corporate_user_add', function(){
		var $form = $('body').find('#create_corporate_user_frm');
		var micro = $('#create_corporate_user_popup').attr('data-_micro');
		var data = { 'action' : 'get_create_corporate_user_form_action', '_micro' : micro, 'resend' : 1 };
		var thisTr = $form;
		thisTr.block( block_config_kyc );
		$.post(cipscript.ajax_url, data, function(response) {
			var obj = JSON.parse( response );
			if( obj.error == 0 ){

				const interval_id = window.setInterval(function(){}, Number.MAX_SAFE_INTEGER);
				for (let i = 1; i < interval_id; i++) {
					window.clearInterval(i);
				}

				$('#EditCorporateUserModal .modal-body').html( obj.html );
				$('#EditCorporateUserModal').modal('show');
			}else{
				swalToast({ type: 'error', title: obj.msg });
			}
			thisTr.unblock();
		});
	});

	/**
	 * Create corporate user script
	 */
	$('body').on('submit', '#create_corporate_user_frm', function(){
		$form = $(this);
		if( $form.find('#corporate_user_first_name').val() == "" ){
			swalToast({ type: 'error', title: 'Please enter first name' });
			return false;
		}
		if( $form.find('#corporate_user_last_name').val() == "" ){
			swalToast({ type: 'error', title: 'Please enter last name' });
			return false;
		}
		if( $form.find('#corporate_email').val() == "" ){
			swalToast({ type: 'error', title: 'Please enter email' });
			return false;
		}
		if( $form.find('#csr_wallet_address').val() == "" ){
			swalToast({ type: 'error', title: 'Please enter CSR wallet address' });
			return false;
		}
		if( !web3.utils.isAddress( $form.find('#csr_wallet_address').val() ) ){
			swalToast({ type: 'error', title: 'Please enter valid CSR wallet address' });
			return false;
		}
		if( $form.find('input[name="user_otp"]').val() == "" ){
			swalToast({ type: 'error', title: 'Please enter the OTP' });
			return false;
		}
		if( $form.find('input[name="user_ga_otp"]').val() == "" ){
			swalToast({ type: 'error', title: 'Please enter the authentication code' });
			return false;
		}
		var data = $(this).serialize();
		$form.block( block_config_kyc );
		$.post(cipscript.ajax_url, data, function(response) {
			var obj = JSON.parse( response );
			$form.unblock();
			if( obj.error == 0 ){
				swalToast({ type: 'success', title: obj.msg });
				$("#createCorporateUserModal").modal('hide');
				$form[0].reset();

				var $tableCorporateUsers = $('#corporate_users_list');
				$tableCorporateUsers.bootstrapTable('refresh');

			}else{
				swalToast({ type: 'error', title: obj.msg });
			}
		});
		return false;
	});
	

	/**
	 * Edit corporate user form open
	 */
	$('body').on('click', '.edit-corporate-user', function(e){
		var thisId = $(this).attr('data-edit');
		var micro = $(this).attr('data-micro');
		var data = { 'action' : 'get_corporate_user_action', 'thisId' : thisId, '_micro' : micro };
		var thisTr = $(this).closest('tr');
		thisTr.block( block_config_kyc );
		$.post(cipscript.ajax_url, data, function(response) {
			var obj = JSON.parse( response );
			if( obj.error == 0 ){

				const interval_id = window.setInterval(function(){}, Number.MAX_SAFE_INTEGER);
				for (let i = 1; i < interval_id; i++) {
					window.clearInterval(i);
				}

				$('#EditCorporateUserModal .modal-body').html( obj.html );
				$('#EditCorporateUserModal').modal('show');
			}else{
				swalToast({ type: 'error', title: obj.msg });
			}
			thisTr.unblock();
		});
	});
	$('body').on('submit', '#edit_corporate_user_frm', function(){
		$form = $(this);
		if( $form.find('#corporate_user_first_name').val() == "" ){
			swalToast({ type: 'error', title: 'Please enter first name' });
			return false;
		}
		if( $form.find('#corporate_user_last_name').val() == "" ){
			swalToast({ type: 'error', title: 'Please enter last name' });
			return false;
		}
		if( $form.find('#corporate_email').val() == "" ){
			swalToast({ type: 'error', title: 'Please enter email' });
			return false;
		}
		if( $form.find('#csr_wallet_address').val() == "" ){
			swalToast({ type: 'error', title: 'Please enter CSR wallet address' });
			return false;
		}
		if( !web3.utils.isAddress( $form.find('#csr_wallet_address').val() ) ){
			swalToast({ type: 'error', title: 'Please enter valid CSR wallet address' });
			return false;
		}
		if( $form.find('input[name="user_otp"]').val() == "" ){
			swalToast({ type: 'error', title: 'Please enter the OTP' });
			return false;
		}
		if( $form.find('input[name="user_ga_otp"]').val() == "" ){
			swalToast({ type: 'error', title: 'Please enter the authentication code' });
			return false;
		}
		var data = $(this).serialize();
		$form.block( block_config_kyc );
		$.post(cipscript.ajax_url, data, function(response) {
			var obj = JSON.parse( response );
			$form.unblock();
			if( obj.error == 0 ){
				swalToast({ type: 'success', title: obj.msg });
				$("#EditCorporateUserModal").modal('hide');
				$form[0].reset();

				var $tableCorporateUsers = $('#corporate_users_list');
				$tableCorporateUsers.bootstrapTable('refresh');

			}else{
				swalToast({ type: 'error', title: obj.msg });
			}
		});
		return false;
	});
	$('#EditCorporateUserModal').on('hide.bs.modal', function (event) {
		var modal = $(this);
		modal.find('.modal-body').html('');
	});

	/**
	 * Resend OTP of edit corporate user
	 */
	$('body').on('click', '#resend_corporate_user_edit', function(){
		var $form = $('body').find('#edit_corporate_user_frm');
		var thisId = $form.find('input[name="cu_id"]').val();
		var micro = $form.find('input[name="_micro"]').val();
		var data = { 'action' : 'get_corporate_user_action', 'thisId' : thisId, '_micro' : micro, 'resend' : 1 };
		var thisTr = $form;
		thisTr.block( block_config_kyc );
		$.post(cipscript.ajax_url, data, function(response) {
			var obj = JSON.parse( response );
			if( obj.error == 0 ){

				const interval_id = window.setInterval(function(){}, Number.MAX_SAFE_INTEGER);
				for (let i = 1; i < interval_id; i++) {
					window.clearInterval(i);
				}

				$('#EditCorporateUserModal .modal-body').html( obj.html );
				$('#EditCorporateUserModal').modal('show');
			}else{
				swalToast({ type: 'error', title: obj.msg });
			}
			thisTr.unblock();
		});
	});

	/**
	 * corporate user request withdrawal
	 */
	$('body').on('submit', '#corporateuser_request_withdrawal_frm', function(){
		$form = $(this);
		if( $form.find('input[name="user_otp"]').val() == "" ){
			swalToast({ type: 'error', title: 'Please enter the OTP' });
			return false;
		}
		if( $form.find('input[name="user_ga_otp"]').val() == "" ){
			swalToast({ type: 'error', title: 'Please enter the authentication code' });
			return false;
		}
		var data = $(this).serialize();
		$form.block( block_config_kyc );
		$.post(cipscript.ajax_url, data, function(response) {
			var obj = JSON.parse( response );
			$form.unblock();
			if( obj.error == 0 ){
				swalToast({ type: 'success', title: obj.msg });
				$form[0].reset();
				$("#csrCorporateUserRequestWithdrawalModal").modal('hide');
				
				var $tableCorporateUsers = $('#corporate_user_request_withdrawal_list');
				$tableCorporateUsers.bootstrapTable('refresh');

			}else{
				swalToast({ type: 'error', title: obj.msg });
			}
		});
		return false;
	});

	/**
	 * Delete corporate user
	 */
	$('body').on('click', '.delete-corporate-user', function(e){
		var thisId = $(this).attr('data-delete');
		var micro = $(this).attr('data-micro');
		var data = { 'action' : 'get_corporate_user_delete_action', 'thisId' : thisId, '_micro' : micro };
		var thisTr = $(this).closest('tr');
		thisTr.block( block_config_kyc );
		$.post(cipscript.ajax_url, data, function(response) {
			var obj = JSON.parse( response );
			if( obj.error == 0 ){

				const interval_id = window.setInterval(function(){}, Number.MAX_SAFE_INTEGER);
				for (let i = 1; i < interval_id; i++) {
					window.clearInterval(i);
				}

				$('#DeleteCorporateUserModal .modal-body').html( obj.html );
				$('#DeleteCorporateUserModal').modal('show');
			}else{
				swalToast({ type: 'error', title: obj.msg });
			}
			thisTr.unblock();
		});
	});
	/**
	 * Resend OTP of delete corporate user
	 */
	$('body').on('click', '#resend_corporate_user_delete', function(){
		var $form = $('body').find('#delete_corporate_user_frm');
		var thisId = $form.find('input[name="cu_id"]').val();
		var micro = $form.find('input[name="_micro"]').val();
		var data = { 'action' : 'get_corporate_user_delete_action', 'thisId' : thisId, '_micro' : micro, 'resend' : 1 };
		var thisTr = $form;
		thisTr.block( block_config_kyc );
		$.post(cipscript.ajax_url, data, function(response) {
			var obj = JSON.parse( response );
			if( obj.error == 0 ){

				const interval_id = window.setInterval(function(){}, Number.MAX_SAFE_INTEGER);
				for (let i = 1; i < interval_id; i++) {
					window.clearInterval(i);
				}

				$('#DeleteCorporateUserModal .modal-body').html( obj.html );
				$('#DeleteCorporateUserModal').modal('show');
			}else{
				swalToast({ type: 'error', title: obj.msg });
			}
			thisTr.unblock();
		});
	});
	/**
	 * Delete corporate user
	 */
	$('body').on('submit', '#delete_corporate_user_frm', function(){
		$form = $(this);
		if( $form.find('input[name="user_otp"]').val() == "" ){
			swalToast({ type: 'error', title: 'Please enter the OTP' });
			return false;
		}
		if( $form.find('input[name="user_ga_otp"]').val() == "" ){
			swalToast({ type: 'error', title: 'Please enter the authentication code' });
			return false;
		}
		var data = $(this).serialize();
		$form.block( block_config_kyc );
		$.post(cipscript.ajax_url, data, function(response) {
			var obj = JSON.parse( response );
			$form.unblock();
			if( obj.error == 0 ){
				swalToast({ type: 'success', title: obj.msg });
				$form[0].reset();
				$("#DeleteCorporateUserModal").modal('hide');
				
				var $tableCorporateUsers = $('#corporate_users_list');
				$tableCorporateUsers.bootstrapTable('refresh');

			}else{
				swalToast({ type: 'error', title: obj.msg });
			}
		});
		return false;
	});

	/**
	 * CSR Pool Reports
	 */
	if( $('#create_csrpoolreport_frm select[name=distribution_status]').length > 0 ){
		$('#create_csrpoolreport_frm select[name=distribution_status]').select2({
			width: '100%',
			placeholder: 'Select Distribution Status',
			dropdownParent: $('#createCsrPoolReportModal'),
			allowClear: true
		});
	}
	if( $('#create_csrpoolreport_frm select[name=pool_reference]').length > 0 ){
		$('#create_csrpoolreport_frm select[name=pool_reference]').select2({
			minimumInputLength: 1,
			ajax: {
				url: cipscript.ajax_url,
				dataType: 'json',
				data: function (params) {
					var query = {
						search: params.term,
						action: 'pool_ref_fetch_act'
					}
					return query;
				}
			},
			processResults: function (response) {
				return {
				results: response
				};
			},
			width: '100%',
			scrollAfterSelect: false,
			dropdownParent: $('#createCsrPoolReportModal'),
			placeholder: 'Choose Pool Reference',
			allowClear: true
		});
	}
	if( $('#create_csrpoolreport_frm select[name=distribution_week]').length > 0 ){
		$('#create_csrpoolreport_frm select[name=distribution_week]').select2({
			minimumInputLength: 1,
			ajax: {
				url: cipscript.ajax_url,
				dataType: 'json',
				data: function (params) {
					var query = {
						search: params.term,
						action: 'distribution_week_fetch_act'
					}
					return query;
				}
			},
			processResults: function (response) {
				return {
				results: response
				};
			},
			width: '100%',
			scrollAfterSelect: false,
			dropdownParent: $('#createCsrPoolReportModal'),
			placeholder: 'Choose Distribution Week',
			allowClear: true
		});
	}

	/* $("#create_csrpoolreport_frm input[name='csr_initial_amount'], #create_csrpoolreport_frm input[name='csr_distributed'], #create_csrpoolreport_frm input[name='amount_due']").keypress(function(event) {
		if ((event.which != 46 || $(this).val().indexOf('.') != -1) &&
		  ((event.which < 48 || event.which > 57) &&
			(event.which != 0 && event.which != 8))) {
		  event.preventDefault();
		}
	
		var text = $(this).val();
	
		if ((text.indexOf('.') != -1) &&
		  (text.substring(text.indexOf('.')).length > 2) &&
		  (event.which != 0 && event.which != 8) &&
		  ($(this)[0].selectionStart >= text.length - 2)) {
		  event.preventDefault();
		}
	}); */

	$("input[name='amount_due_condition_value']").bind("input", function () {
		var c = this.selectionStart,
		  r = /[^0-9]/gi,
		  v = $(this).val();
		if( r.test(v) ){
		  $(this).val(v.replace(r, ""));
		  c--;
		}
		this.setSelectionRange(c, c);
	});

	$('body').on('submit', '#create_csrpoolreport_frm', function(){
		$form = $(this);
		if( ( $form.find('select[name="distribution_status"]').val() == "" || $form.find('select[name="distribution_status"]').val() == null ) && ( $form.find('select[name="pool_reference"]').val() == "" || $form.find('select[name="pool_reference"]').val() == null ) && ( $form.find('select[name="distribution_week"]').val() == "" || $form.find('select[name="distribution_week"]').val() == null ) && $form.find('input[name="amount_due_condition_value"]').val() == "" ){
			swalToast({ type: 'error', title: 'Please select at least one option' });
			return false;
		}

		if( $form.find('input[name="amount_due_condition_value"]').val() != "" ){
			if( $form.find('select[name="amount_due_condition"]').val() == "" ){
				swalToast({ type: 'error', title: 'Please select amount due condition' });
				return false;
			}
		}
		
		var data = $(this).serialize();
		$form.block( block_config_kyc );
		$.post(cipscript.ajax_url, data, function(response) {
			var obj = JSON.parse( response );
			$form.unblock();
			if( obj.error == 0 ){
				swalToast({ type: 'success', title: obj.msg });
				$form[0].reset();

				$form.find('select').val('').trigger("change");

				$("#createCsrPoolReportModal").modal('hide');
				
				var $tableCsrPoolReportList = $('#csr_pool_report_list');
				$tableCsrPoolReportList.bootstrapTable('refresh');

			}else{
				swalToast({ type: 'error', title: obj.msg });
			}
		});
		return false;
	});
	/**
	 * Delete csr pool report
	 */
	$('body').on('click', '.delete-pool-report', function(e){
		
		var thisId = $(this).attr('data-delete');
		var micro = $(this).attr('data-micro');
		var thisTr = $(this).closest('tr');
		
		Swal({
			title: 'Are you sure?',
			text: "Do you want to remove pool report?",
			type: 'warning',
			showCancelButton: true,
			confirmButtonText: 'Yes'
		  }).then((result) => {
			if (result.value) {
				var data = { 'action' : 'delete_csr_pool_report_action', 'thisId' : thisId, '_micro' : micro };
				thisTr.block( block_config_kyc );
				$.post(cipscript.ajax_url, data, function(response) {
					var obj = JSON.parse( response );
					if( obj.error == 0 ){
						swalToast({ type: 'success', title: obj.msg });
						$('[data-toggle-tt="tooltip"]').tooltip('dispose');
						$('#csr_pool_report_list').bootstrapTable('refresh');
					}else{
						swalToast({ type: 'error', title: obj.msg });
					}
					thisTr.unblock();
				});
			}
		});

	});
	/**
	 * Edit corporate user form open
	 */
	$('body').on('click', '.edit-pool-report', function(e){
		var thisId = $(this).attr('data-edit');
		var micro = $(this).attr('data-micro');
		var data = { 'action' : 'get_csr_pool_report_action', 'thisId' : thisId, '_micro' : micro };
		var thisTr = $(this).closest('tr');
		thisTr.block( block_config_kyc );
		$.post(cipscript.ajax_url, data, function(response) {
			var obj = JSON.parse( response );
			if( obj.error == 0 ){

				$('#EditCsrPoolReportModal .modal-body').html( obj.html );
				$('#EditCsrPoolReportModal').modal('show');

				if( $('body').find('#edit_csrpoolreport_frm select[name=distribution_status]').length > 0 ){
					$('body').find('#edit_csrpoolreport_frm select[name=distribution_status]').select2({
						width: '100%',
						dropdownParent: $('#EditCsrPoolReportModal')
					});
				}
				$('body').find('#edit_csrpoolreport_frm select[name=pool_reference]').select2({
					minimumInputLength: 1,
					ajax: {
						url: cipscript.ajax_url,
						dataType: 'json',
						data: function (params) {
							var query = {
								search: params.term,
								action: 'pool_ref_fetch_act'
							}
							return query;
						}
					},
					processResults: function (response) {
						return {
						   results: response
						};
					},
					width: '100%',
					scrollAfterSelect: false,
					dropdownParent: $('#EditCsrPoolReportModal'),
					placeholder: 'Choose Pool Reference'
				});
				$('body').find('#edit_csrpoolreport_frm select[name=distribution_week]').select2({
					minimumInputLength: 1,
					ajax: {
						url: cipscript.ajax_url,
						dataType: 'json',
						data: function (params) {
							var query = {
								search: params.term,
								action: 'distribution_week_fetch_act'
							}
							return query;
						}
					},
					processResults: function (response) {
						return {
						   results: response
						};
					},
					width: '100%',
					scrollAfterSelect: false,
					dropdownParent: $('#EditCsrPoolReportModal'),
					placeholder: 'Choose Distribution Week'
				});

			}else{
				swalToast({ type: 'error', title: obj.msg });
			}
			thisTr.unblock();
		});
	});
	$('body').on('submit', '#edit_csrpoolreport_frm', function(){
		$form = $(this);

		if( ( $form.find('select[name="distribution_status"]').val() == "" || $form.find('select[name="distribution_status"]').val() == null ) && ( $form.find('select[name="pool_reference"]').val() == "" || $form.find('select[name="pool_reference"]').val() == null ) && ( $form.find('select[name="distribution_week"]').val() == "" || $form.find('select[name="distribution_week"]').val() == null ) && $form.find('input[name="amount_due_condition_value"]').val() == "" ){
			swalToast({ type: 'error', title: 'Please select at least one option' });
			return false;
		}

		if( $form.find('input[name="amount_due_condition_value"]').val() != "" ){
			if( $form.find('select[name="amount_due_condition"]').val() == "" ){
				swalToast({ type: 'error', title: 'Please select amount due condition' });
				return false;
			}
		}

		var data = $(this).serialize();
		$form.block( block_config_kyc );
		$.post(cipscript.ajax_url, data, function(response) {
			var obj = JSON.parse( response );
			$form.unblock();
			if( obj.error == 0 ){
				swalToast({ type: 'success', title: obj.msg });
				$("#EditCsrPoolReportModal").modal('hide');
				$form[0].reset();

				$('#csr_pool_report_list').bootstrapTable('refresh');

			}else{
				swalToast({ type: 'error', title: obj.msg });
			}
		});
		return false;
	});
	$('#EditCsrPoolReportModal').on('hide.bs.modal', function (event) {
		var modal = $(this);
		modal.find('.modal-body').html('');
	});
	/**
	 * Refresh csr pool report script
	 */
	$('body').on('click', '#refresh_csr_pool_report', function(){
		var data = { 'action':'refresh_csr_pool_report_action', '_micro' : $(this).attr('data-_micro') };
		$.blockUI(block_config_kyc);
		$.post(cipscript.ajax_url, data, function(response) {
			var obj = JSON.parse( response );
			if( obj.error == 0 ){
				swalToast({ type: 'success', title: obj.msg });
				$('#csr_pool_report_list').bootstrapTable('refresh');
				$('body').find('.pool_report_last_update').html( obj.last_update );
			}else{
				swalToast({ type: 'error', title: obj.msg });
			}
			$.unblockUI();
		});
		return false;
	});

	/**
	 * amplivo api setting page
	 */
	$('body').on('submit', '#sm_amplivo_api_settings', function(){
		$form = $(this);
		var data = $(this).serialize();
		$form.block( block_config_kyc );
		$.post(cipscript.ajax_url, data, function(response) {
			var obj = JSON.parse( response );
			$form.unblock();
			swalToast({ type: 'success', title: obj.msg });
		});
		return false;
	});

	/**
	 * get user details from email
	 */
	$('#register_wp_member input[name=email]').on("focusout", function(){
		var $form = $('#register_wp_member');
		$form.find('.autofillsection').addClass('hide');
		
		$form.find('input[name=username]').val('');
		$form.find('input[name=first_name]').val('');
		$form.find('input[name=last_name]').val('');
		
		if( $form.find('input[name=email]').val() != "" ){
			var data = $form.serialize() + '&getDetails=yes';
			$form.block( block_config_kyc );
			$.post(cipscript.ajax_url, data, function(response) {
				var obj = JSON.parse( response );
				if( obj.error == 0 ){
					$form.find('.autofillsection').removeClass('hide');
					$form.find('input[name=first_name]').val( obj.first_name );
					$form.find('input[name=last_name]').val( obj.last_name );
					setTimeout(() => {
						$form.find('input[name=username]').val( obj.username ).focus();
					}, 200);
				}else{
					swalToast({ type: 'error', title: obj.msg });
				}
				$form.unblock();
			});
		}
	});

	$('#register_wp_member input[name=email]').keypress(function(event) {
		if (event.keyCode == 13) {
			event.preventDefault();
		}
	});

	/**
	 * Register wp user by support manager
	 */
	$('body').on('submit', '#register_wp_member', function(){
		$form = $(this);

		if( $form.find('input[name=email]').val() == "" ){
			swalToast({ type: 'error', title: 'Please enter an email' });
			return false;
		}
		if( $form.find('input[name=username]').val() == "" ){
			swalToast({ type: 'error', title: 'Please enter username' });
			return false;
		}
		if( $form.find('input[name=first_name]').val() == "" ){
			swalToast({ type: 'error', title: 'Please enter first name' });
			return false;
		}
		if( $form.find('input[name=last_name]').val() == "" ){
			swalToast({ type: 'error', title: 'Please enter last name' });
			return false;
		}

		var data = $(this).serialize() + '&getDetailsRegister=yes';
		$form.block( block_config_kyc );
		$.post(cipscript.ajax_url, data, function(response) {
			var obj = JSON.parse( response );
			if( obj.error == 0 ){
				$form[0].reset();
				$form.find('.autofillsection').addClass('hide');
				swalToast({ type: 'success', title: obj.msg });
			}else{
				swalToast({ type: 'error', title: obj.msg });
			}
			$form.unblock();
		});
		return false;
	});
	/**
	*
	* Selected tokenholder plastic credit table
	*
	**/
	if($('.view_selected_plastic_credit').length > 0){
		$(document).on('click', '.view_selected_plastic_credit', function(){
			var plastic_credit_type = $(this).attr('plastic_credit_type');
			$form = $(".tokenholder-plastic-credit-body");
			$form.block( block_config_kyc );
			var data = {
				type: "POST",
				dataType: 'json',
				action: 'load_selected_plastic_credit_type_table',
				plastic_credit_type: plastic_credit_type,
			};
			$.post(cipscript.ajax_url, data, function(response) {
				var obj = JSON.parse( response );
				if( obj.error == 0 ){
					$(".tokenholder-selected-plastic-credit-table").html(obj.html);
					$('[data-toggle-tt="tooltip"]').tooltip();
					$('[data-toggle-column="tooltip"]').tooltip();
					$(".tokenholder-plastic-credit-table-body").show();
					$form.hide();
				}else{
					swalToast({ type: 'error', title: obj.msg });
				}
				$form.unblock();
			});
			return false;
		});
		$(document).on('click','.back-to-tokenholder-plastic-credit',function(){
			$(".tokenholder-plastic-credit-table-body").hide();
			$(".tokenholder-plastic-credit-body").show();
			$(".tokenholder-selected-plastic-credit-table").html("");
		});
	}

	$(document).on('click','.js-burger',function( event ){
		event.preventDefault();
		var thisSection = $(this).attr('data-section');
		$('.custom_menu.'+ thisSection ).toggleClass('nav-open');
	});
	
	// Close menu when clicking on body, but not on the menu or burger
	$(document).on('click', 'body', function(event) {
		if (!$(event.target).closest('.js-burger, .custom_menu').length) {
			$('.custom_menu.nav-open').removeClass('nav-open');
		}
	});

});
function isZeroNegative(zero) {
	if (zero !== 0) return false;
  
	return zero.toLocaleString()[0] === "-";
}
window.addEventListener("pageshow", () => { //BFCache
	if( $('#tokenholder_wallet_delivery').length > 0 ){
		$('body').find('#tokenholder_wallet_delivery input').not(':button,:submit,:reset,:hidden').val('');
		$('body').find('#tokenholder_wallet_delivery select').val('');
		$('body').find('.wallet_delivery_frm #filter_by_notes')[0].reset();
		$('body').find('.wallet_delivery_frm #filter_by_pool_ref')[0].reset();
		$('body').find('.wallet_delivery_frm #filter_by_distribution_week')[0].reset();
		$('body').find('.wallet_delivery_frm #filter_by_username')[0].reset();
	}
	if( $('#tokenholder_wallet_delivery_report').length > 0 ){
		$('body').find('#tokenholder_wallet_delivery_report input').not(':button,:submit,:reset,:hidden').val('');
		$('body').find('#tokenholder_wallet_delivery_report select').val('');
		$('body').find('.wallet_delivery_frm #filter_by_notes')[0].reset();
		$('body').find('.wallet_delivery_frm #filter_by_pool_ref')[0].reset();
		$('body').find('.wallet_delivery_frm #filter_by_distribution_week')[0].reset();
		$('body').find('.wallet_delivery_frm #filter_by_username')[0].reset();
	}
	if( $('#tokenholder_table_sa').length > 0 ){
		var filterCookie = sessionStorage.getItem("tokenholder_table_sa_filter");
		if( filterCookie == "" || filterCookie == null ){
			$('body').find('#tokenholder_table_sa input').not(':button,:submit,:reset,:hidden').val('');
			$('body').find('#tokenholder_table_sa select').val('');
			$('body').find('#filter_by_notes')[0].reset();
		}
	}
});
const calculateSale = (listPrice, discount) => {
	listPrice = parseFloat(listPrice);
	discount  = parseFloat(discount);
	return Math.ceil( ( listPrice * discount / 100 ) );
}

const calculateDiscount = (listPrice, salePrice) => {
	listPrice = parseFloat(listPrice);
	salePrice = parseFloat(salePrice);
	return (salePrice * 100 / listPrice).toFixed(2);
}
var partial_delivery_total = 0;
function responseHandlerW(res){
	if( res.total_amount_due ){
		$('.total_amount_due_label').show().html( res.total_amount_due );
		$('.total_selected_amount_due_label').show().html( res.total_selected_amount_due );
	}else{
		$('.total_amount_due_label').hide();
		$('.total_selected_amount_due_label').hide();
	}
	// calculateWalletDeliveryAmountDueTotal();
	/* var $partialDeliverElement = $('.csr_partial_delivery');
	var $partialDeliveryFrmElem = $('#partialDeliveryFrm');
	partial_delivery_total = res.total;
	if( res.total > 0 && res.total <= 15 ){
		$partialDeliverElement.attr('data-original-title', 'For partial delivery you will confirm amounts to be delivered on the next page.').tooltip();
		$partialDeliverElement.removeClass('disabled').prop('disabled', false);
		$partialDeliveryFrmElem.find('input[name="partialDeliveryIds"]').val( res.partialDeliverIds );
	}else{
		$partialDeliverElement.attr('data-original-title', 'Partial Delivery only available for small delivery selections of under 15 rows.').tooltip();
		$partialDeliverElement.addClass('disabled').prop('disabled', true);
		$partialDeliveryFrmElem.find('input[name="partialDeliveryIds"]').val('');
	} */
	return res;
}
function responseHandlerBonus(res){
	if( res.total_issued_label ){
		$('.total_distribution_label').show().html( res.total_issued_label );
	}else{
		$('.total_distribution_label').hide();
	}
	return res;
}
function responseImportHandlerBonus(res){
	if( res.total_import_label ){
		$('.total_import_label').show().html( res.total_import_label );
	}else{
		$('.total_import_label').hide();
	}
	return res;
}
function responseHandlerWithdrawRequests(res){
	calculateWithdrawRequestTotal();
	return res;
}
function responseHandlerCURW(res){
	// if( res.total_amount_due ){
	// 	$('.total_amount_due_label').show().html( res.total_amount_due );
	// }else{
	// 	$('.total_amount_due_label').hide();
	// }
	// calculateWalletDeliveryAmountDueTotal();
	return res;
}
function calculateWithdrawRequestTotal(){
	setTimeout(() => {
		var totalReceivedAmount = 0;
		var totalReceivedAmountCsr25 = 0;
		$('body').find('input.rowiddata:checkbox:checked').each(function(){
			if( $(this).attr('data-token').toLowerCase() == 'csr25' ){
				totalReceivedAmountCsr25 += isNaN(parseFloat($(this).attr('data-receivedamount'))) ? 0 : parseFloat($(this).attr('data-receivedamount'));
			}else{
				totalReceivedAmount += isNaN(parseFloat($(this).attr('data-receivedamount'))) ? 0 : parseFloat($(this).attr('data-receivedamount'));
			}
		});
		$('.total_withdraw_request_label').show().html( 'Total CSR withdrawal amount : '+ addCommas( totalReceivedAmount.toFixed(2) ) +' CSR' );
		$('.total_withdraw_request_label25').show().html( 'Total CSR25 withdrawal amount : '+ addCommas( totalReceivedAmountCsr25.toFixed(2) ) +' CSR25' );
	}, 300);
}
function calculateWalletDeliveryAmountDueTotal(){
	setTimeout(() => {
		var totalAmountDue = 0;
		$('body').find('input.rowiddata:checkbox:checked').each(function(){
			totalAmountDue += isNaN(parseFloat($(this).attr('data-amountdue'))) ? 0 : parseFloat($(this).attr('data-amountdue'));
		});
		$('.total_wallet_delivery_amount_due_label').show().html( addCommas( totalAmountDue.toFixed(2) ) );
	}, 300);
}
function convertFormToJSON(form) {
	// const array = $(form).serializeArray();
	const array = $(form).serializeJSON();
	var json = {};
	/* $.each(array, function () {
	  json[this.name] = this.value || "";
	}); */

	json = array;

	return JSON.stringify(json);
}
function Searchcities(txtsearch, citiesname) {
	if ($(txtsearch).val() != "") {
		var count = 0;
		$(citiesname).children('div').each(function () {
			var match = false;
			$(this).children('label').each(function () {
				if ($(this).text().toUpperCase().indexOf($(txtsearch).val().toUpperCase()) > -1)
					match = true;
			});
			if (match) {
				$(this).show();
				count++;
			}
			else { $(this).hide(); }
		});
		// $('#spancount').html((count) + ' match');
	}
	else {
		$(citiesname).children('div').each(function () {
			$(this).show();
		});
		// $('#spancount').html('');
	}
}
function validatePhone(phone_number) {
    var a = phone_number;
    let regex = new RegExp("^\\+[1-9]{1}[0-9]{0,2}-[2-9]{1}[0-9]{2}-[2-9]{1}[0-9]{2}-[0-9]{4}$");  
    if (regex.test(a) == true) {
        return true;
    }else {
        return false;
    }
}
function getCookie(cname) {
	var name = cname + "=";
	var decodedCookie = decodeURIComponent(document.cookie);
	var ca = decodedCookie.split(';');
	for (var i = 0; i < ca.length; i++) {
		var c = ca[i];
		while (c.charAt(0) == ' ') {
			c = c.substring(1);
		}
		if (c.indexOf(name) == 0) {
			return c.substring(name.length, c.length);
		}
	}
	return "";
}
function setCookie(cname, cvalue, exdays) {
	var d = new Date();
	d.setTime(d.getTime() + (exdays * 24 * 60 * 60 * 1000));
	var expires = "expires=" + d.toUTCString();
	document.cookie = cname + "=" + cvalue + ";" + 0 + ";path=/";
}
function addCommas(nStr){
	nStr += '';
	x = nStr.split('.');
	x1 = x[0];
	x2 = x.length > 1 ? '.' + x[1] : '';
	var rgx = /(\d+)(\d{3})/;
	while (rgx.test(x1)) {
		x1 = x1.replace(rgx, '$1' + ',' + '$2');
	}
	return x1 + x2;
}

function clearFieldsExceptOne() {
	// Get all input and select elements in the form
	var elements = document.getElementById('partial_export_filter').elements;
	jQuery('.remove-fillter').addClass('active');
  
	// Iterate over the form elements
	for (var i = 0; i < elements.length; i++) {
	  // Check if the element is not the one to keep
	  if (elements[i].id !== 'corp_approved') {
		// Clear the value of input fields
		if (elements[i].tagName === 'SELECT' && $(elements[i]).data('select2')) {
			// Clear Select2 elements
			$(elements[i]).val(null).trigger('change');
		  } else if (elements[i].type === 'text') {
		  elements[i].value = '';
		}
		// Reset select elements
		else if (elements[i].tagName === 'SELECT') {
		  // Check if it's a multi-select
		  if (elements[i].multiple) {
			for (var j = 0; j < elements[i].options.length; j++) {
			  elements[i].options[j].selected = false;
			}
		  } else {
			elements[i].selectedIndex = -1;
		  }
		}
	  }
	}
	var hideexport = 1;
	jQuery('#partial_export_filter').trigger('submit');
}