
/*
Ctrl + K + Ctrl + 0: fold all levels (namespace, class, method, and block)
Ctrl + K + Ctrl + 1: namespace / @Component(For Angular)
Ctrl + K + Ctrl + 2: class / methods
Ctrl + K + Ctrl + 3: methods / blocks
Ctrl + K + Ctrl + 4: blocks / inner blocks
Ctrl + K + Ctrl + [ or Ctrl + k + ]: current cursor block
Ctrl + K + Ctrl + j: UnFold
 */


"use strict";

var accall_select_opt="";
var user_register='';
var line_alls=[];
var get_fb_fanpage_name_all=[];
var iProgress = 0;
var acc_all_count=0;
var inactive_friends_count=0;
var active_friends_count=0;
var problem_userId_count=0;
var memberSendErrorCount=0;
var prev_friend_loop=-1;
var iTableAllItems=0;
var iMessNumberActive=0;
var itemsSendErrorCount=0;
var iProgressAllItemsCount=0;
var iTotalMesageMustSend=0;
var iSendFriendsCount=0;
var iCountAgv=0;
var dtStartTime=new Date();
var lineCSRF="";
var setStop=0;
var my_broadcastline_idpage_token = "";
var my_broadcastline_label="";
var my_broadcastline_name="";
var my_broadcastline_delay="0";
var my_broadcastline_to_delay = "0";
var my_broadcastline_sdelay = 0;
var my_broadcastline_tdelay = 0;
var cfg_recipients_option_folder="";
var cfg_max_recipients = 0;
var cfg_start_seding_no=1;
var status_running=false;
var log_msg = "";
var user_name="";
var user_valid_date="";
var user_days_left="";
var accdate="";
var acctime="";
var server_date="";
var user_type="";
var tf_demo_ratelimit_setting=0;
var tf_demo_usage_ratelimit=0;
var tf_demo_usage_ratelimit_left=0;
var tf_maximum_speed_sender = 1;		//3 5 7 9 11
var permission_extract_member = 0;	//from auth;

var demo_usage_date="";
var ddData = [];
var oaAccountActiveImg="";
var oaAccountIdActiveName="";

var execSetTimeout=null;
var maxLimitChar = 2000;
var rateLimitedMaxPerMin = 44;
var txt_error_report=null;

var option="";
//var APP_VERSION = "";

var handler_move_row_up_event;
var handler_move_row_down_event;
var handler_del_row_event;
var handler_add_files_event;

//// FANPAGE ACTIVE /////
////////////////////////
var my_prev_broadcastline_label_id = "";	//previous page id that already got members
var my_prev_recipients_option_folder = "";	//previous folder that already got memdbers
var my_broadcastline_label_id = "";	//id
var my_broadcastline_idpage_token = "";	//token
var my_broadcastline_label_name = "";	//name
var my_prev_move_to_done_folder = false;	//previous checked move_to_done_folder after send completed each person


////folder type
var my_broadcastline_folder_label_type = "";	//type
var my_broadcastline_folder_label_name = "";	//label
var my_broadcastline_folder_label_selectedIndex = 0;	//type index

////////////////////////
var target_id ="",target_name ="",send_status ="";
var text_spintext_Preamble ="";	//
var text_spintext_Conclusion = "";
	
////////////////////////
var label_user_all = [];	//all members in page;
var label_user_all_copy = [];	//all members copy
var ct_tf_label_user_all_send_success = [];
var is_can_send_somthing_success = false;


//////////////////////
////// Threads //////
var tot_text_succescount=0;
var tot_text_failed=0;

var tot_send_items_count=0;
var tot_send_friends_count=0;

////
var count_send_completed_in_min = 0;
var count_send_bubble_completed_iterate = 0;
var count_send_person_completed_iterate = 0;
////

var tot_file_failed=0;
var tot_file_succescount=0;
var friendsTotLength=0;
var friendsTotSend=0;
////////////////////

var label_user_inactive=[];
var label_user_id_problem=[];
var fb_fanpage_paging = null;
var page_count=0;
var title = "";

var max_allow_archived_pages = 5;
var max_allow_archived_pages_counter = 0;
var is_process_archived = false;

const isToastErrShow = false;
const isToastSucShow = false;
const isToastGetMemberInboxPageShow = false;

var isStartBroadcastForContinue = true;
var status_stop_pause = 0;	//0 = stop,1=start,2=pause

var schTimeLeft = null;
var fbinboxstatusdone = 0;	//0=stop,1=running,2=pause,3=done;

var iziToast_position = "bottomRight";
var iziToast_bg_color = "#033055";	//backgroundColor

fanpage_all = [];	//in gui.js

String.prototype.right = function( qty )
{
	return this.slice( -( qty ) );
};
String.prototype.left = function( qty )
{
	return this.slice( 0, qty );
};
Number.prototype.pad = function(size) {
    var s = String(this);
    while (s.length < (size || 2)) {s = "0" + s;}
    return s;
};

const add_minutes =  function (dt, minutes) {
	return new Date(dt.getTime() + minutes*60000);
}
const add_secs =  function (dt, secs) {
	return new Date(dt.getTime() + secs*1000);
}
const diff_secs =  function (dt,secs){
	return new Date(dt.getTime()-(secs*1000));
}
const date_compare = function (d1,d2){
	if(d1.getTime() === d2.getTime()){
		return 1;
	}else{
		if(d1.getTime() > d2.getTime()){
			return 0;
		}else{
			return -1;
		}
	}
}

console.log('start tp_tf_broadcast_fanpage.js');
///ldb local database
! function () {
	function e(t, o) {
		return n ? void(n.transaction("s").objectStore("s").get(t).onsuccess = function (e) {
			var t = e.target.result && e.target.result.v || null;
			o(t)
		}) : void setTimeout(function () {
			e(t, o)
		}, 100)
	}
	var t = window.indexedDB || window.mozIndexedDB || window.webkitIndexedDB || window.msIndexedDB;
	if (!t) return void console.error("indexDB not supported");
	var n, o = {
			k: "",
			v: ""
		},
		r = t.open("d2", 1);
	r.onsuccess = function (e) {
		n = this.result
	}, r.onerror = function (e) {
		console.error("indexedDB request error"), console.log(e)
	}, r.onupgradeneeded = function (e) {
		n = null;
		var t = e.target.result.createObjectStore("s", {
			keyPath: "k"
		});
		t.transaction.oncomplete = function (e) {
			n = e.target.db
		}
	}, window.ldb = {	//local storage database
		get: e,
		set: function (e, t) {
			o.k = e, o.v = t, n.transaction("s", "readwrite").objectStore("s").put(o)
		}
	}
}();


var $=jQuery.noConflict();

defer(function () {
	console.log("jquery loaded");
	readyJQuery();
});
function defer(method) {
    if (window.jQuery) {
        method();
    } else {
        setTimeout(function() { defer(method) }, 50);
    }
}

if (typeof jQuery == 'undefined') {
    alert('jQuery HAS NOT been loaded exit app and reload again.');
}


window.onerror = function (errorMsg, url, lineNumber, column, errorObj) {
	console.error('Error: ' + errorMsg + ' Script: ' + url + ' Line: ' + lineNumber + ' Column: ' + column + ' StackTrace: ' +  errorObj);
    alert('Error: ' + errorMsg + ' Script: ' + url + ' Line: ' + lineNumber + ' Column: ' + column + ' StackTrace: ' +  errorObj);
	try{
		setStopJob(0,false,0);
	}catch(err){}
}
$(window).bind('beforeunload', function(){
	return 'Are you sure you want to leave?';
});

//return a promise that resolves with a File instance
class _DataTransfer {
  constructor() {
	  return new ClipboardEvent("").clipboardData || new DataTransfer();
  }
}
function urltoFile(url, filename, mimeType){
	return (fetch(url)
		.then(function(res){return res.arrayBuffer();})
		.then(function(buf){return new File([buf], filename,{type:mimeType});})
	);
}

function getAllItemsPromise(){
		let myOLBroadcastTable_check = document.querySelector("#myOLBroadcastTable").tBodies[0];
		if (typeof myOLBroadcastTable_check==="undefined"){return 0;}
		let num_rows_check = myOLBroadcastTable_check.rows.length;
		if(num_rows_check<1){return 0;}
			
		var irow_check=0;
		var iAllItems=0;
		//console.log(num_rows_check);
    return new Promise(resolve => {
		for (let irow_check = 0; irow_check < num_rows_check; irow_check++) {
			var my_broadcastline_file_check=document.getElementById("file-"+myOLBroadcastTable_check.rows[irow_check].id+"col2");	//file id file-row1col2
				if(typeof my_broadcastline_file_check!=='undefined'){
					iAllItems+=my_broadcastline_file_check.files.length;
				}
				
			var my_broadcastline_text_check=document.getElementById("text_"+myOLBroadcastTable_check.rows[irow_check].id+"col1");	//message id text_row1col1
			if(typeof my_broadcastline_text_check!=='undefined')
			{
				if(my_broadcastline_text_check.value!=""){
					iAllItems++;
				}
			}
			//irow_check++;
		}
		resolve(iAllItems);
    });		
}
async function checkTableDataPromise(){
		let myOLBroadcastTable_check = document.querySelector("#myOLBroadcastTable").tBodies[0];
		
		//if(num_rows_check<1){return false;}
			
		var irow_check=0;
		var iAllItems=0;
    return new Promise(resolve => {
		if (typeof myOLBroadcastTable_check==="undefined"){resolve(false);return false;}
		let num_rows_check = myOLBroadcastTable_check.rows.length;
		
		for (let irow_check = 0; irow_check < num_rows_check; irow_check++) {
			var my_broadcastline_file_check=document.getElementById("file-"+myOLBroadcastTable_check.rows[irow_check].id+"col2");	//file id file-row1col2
				if(typeof my_broadcastline_file_check!=='undefined'){
					if(my_broadcastline_file_check.files.length>0){
						iAllItems+=my_broadcastline_file_check.files.length;
						break;
					}
				}
				
			var my_broadcastline_text_check=document.getElementById("text_"+myOLBroadcastTable_check.rows[irow_check].id+"col1");	//message id text_row1col1
			if(typeof my_broadcastline_text_check!=='undefined')
			{
				if(my_broadcastline_text_check.value!=""){
					iAllItems++;
					break; 
				}
			}
		}
		if(iAllItems>0){
			resolve(true);
		}else{
			resolve(false);
		}
    });		
}

function addBase64toFileList(){
	var tableFiles=sessionStorage.getItem("#myOLBroadcastTableFiles");
	if(tableFiles==null){
		return;
	}
	if(tableFiles==""){return;}
	var json=JSON.parse(tableFiles);
	if(json==null){
		return;
	}
	let myOLBroadcastTable_check = document.querySelector("#myOLBroadcastTable").tBodies[0];
	if (typeof myOLBroadcastTable_check==="undefined"){return;}
	let num_rows_check = myOLBroadcastTable_check.rows.length;
	if(num_rows_check<1){return;}
		
	var irow_check=0;

	loopFiles();
	function loopFiles(){
		var inp=document.getElementById("file-"+myOLBroadcastTable_check.rows[irow_check].id+"col2");	//file id file-row1col2
		if(typeof inp!=='undefined'){
			if(typeof json['row'+(irow_check+1)] !=="undefined"){
				const dt = new _DataTransfer();
				for (let i=0;i<json['row'+(irow_check+1)].length;i++){
					var file=urltoFile(json['row'+(irow_check+1)][i].base64,json['row'+(irow_check+1)][i].fileName,json['row'+(irow_check+1)][i].fileType)
						.then(function(file){
							dt.items.add(file);
							if (dt.files.length==json['row'+(irow_check+1)].length) {
								inp.files = dt.files;
								//console.log('inp.files'+(irow_check+1));
								//console.log(inp.files);
								irow_check++
								if(irow_check<num_rows_check){
									loopFiles();
								}
							}
						});
				}
			}else{
				irow_check++
				if(irow_check<num_rows_check){
					loopFiles();
				}
			}
		}
		//irow_check++
	}
}

function padDigits(number, digits) {
    return Array(Math.max(digits - String(number).length + 1, 0)).join(0) + number;
}
function getNow(){
	var d = new Date();
	if(arguments.length>0){
		d = new Date(arguments[0]);
	}
	return d.getFullYear().toString()+"-"+padDigits(d.getMonth()+1,2)+"-"+padDigits(d.getDate(),2)+" "+padDigits(d.getHours(),2)+":"+padDigits(d.getMinutes(),2)+":"+padDigits(d.getSeconds(),2);
}
function getDate(){
	var d = new Date();
	if(arguments.length>0){
		d = new Date(arguments[0]);
	}
	return d.getFullYear().toString()+"-"+padDigits(d.getMonth()+1,2)+"-"+padDigits(d.getDate(),2);
}
function getTimeNow(){
	var d = new Date();
	if(arguments.length>0){
		d.setSeconds(d.getSeconds() + arguments[0]);
	}
	return padDigits(d.getHours(),2)+":"+padDigits(d.getMinutes(),2)+":"+padDigits(d.getSeconds(),2);
}
function getDateTime(dt){
	var d = new Date(dt);
	return d.getFullYear().toString()+"-"+padDigits(d.getMonth()+1,2)+"-"+padDigits(d.getDate(),2)+" "+padDigits(d.getHours(),2)+":"+padDigits(d.getMinutes(),2)+":"+padDigits(d.getSeconds(),2);
}
function edit(el) {
	if(el==null){return;};
	if(el=='undefined'){return;};
	let index=-1;
	////console.log(el);
	////console.log(el.childNodes[index]);
	////console.log(el.childNodes[1].className);
	////console.log(el.childNodes[index].id);
	/*
	if(el.id="text_add"){
		el.removeAttribute("disabled");
		el.removeAttribute("readonly");
		el.focus();
		countcharleft(el);
		let charactersLeft=counterCharLeft(el.id);
		if(charactersLeft!==""){
			let v = $('#spnCharLeft');
			v.css('display', 'block');
			v.text('นับ: '+charactersLeft + ' ตัวอักษรที่เหลือ');
		}
		return;
	}
	*/
	var c = document.getElementById(el.id).childNodes;//.length;
	var cl=c.length;
	let i=0;
	for(i=0;i<cl;i++){
		////console.log(c[i]);
		if(c[i].nodeName=="TEXTAREA"){
			index=i;
			break;
		}
	}
	if(index<0){return;};
	////console.log(el.childNodes[index]);
	////console.log(el.childNodes[1]);
	el.childNodes[index].removeAttribute("disabled");
	el.childNodes[index].removeAttribute("readonly");
	//el.childNodes[index].prop("readonly", false);
	el.childNodes[index].focus();
	
	//var index=0;
	//var id="text_"+el.id;
	//var el=document.getElementById(id);
	//if(el==null){return;}
	
	//window.getSelection().removeAllRanges();
	////console.log(el);
	countcharleft(el.childNodes[index]);
	let charactersLeft=counterCharLeft(el.childNodes[index].id);
	if(charactersLeft!==""){
		let v = $('#spnCharLeft');
		v.css('display', 'block');
		v.text('นับ: '+charactersLeft + ' ตัวอักษรที่เหลือ');
	}
}
function disable(el) {
	el.setAttribute("disabled","");
	el.setAttribute("readonly","");
	//$('#spnCharLeft').css('display', 'none');
	$('#spnCharLeft').text('count:');
}
function countcharleft(el) {
	////console.log(el.id);
	var element = document.getElementById(el.id);
	if(element==null) return;
	if(element.type != "textarea" && element.type!="text"){
	  return;
	}
	if(element.classList.length>0){
		if(element.classList[0]!="counterchar"){
			return;
		}
	}else{
		return;
	}
	
	element.title=element.value;
	
	if(element.type != "textarea"){
	  return;
	}
	
	$('#'+el.id).keyup(function () {
		if (typeof (this.value) === 'undefined') {
		  // color is undefined
		  return;
		}
		////console.log(this);
		var charactersLeft=counterCharLeft(this.id);
		if(charactersLeft!=""){
			$('#spnCharLeft').css('display', 'block');
			$('#spnCharLeft').text('count: '+ charactersLeft + ' Characters left');
		}
	});
}
function counterCharLeft(id){
	var element = document.getElementById(id);
	if(element==null) return "";
	if(element.type != "textarea"){
	  ////console.log('I must be textarea');
	  return "";
	}
	
	
	var thisid=document.getElementById(id);
	if (typeof thisid.value === 'undefined') {
	  // color is undefined
	  return "";
	}
	////console.log(thisid);
	var lengthCount = thisid.value.length; 
	
	if (lengthCount > maxLimitChar) {
		thisid.value = thisid.value.substring(0, maxLimitChar);
		var charactersLeft = maxLimitChar - lengthCount + 1;                   
	}
	else {                   
		var charactersLeft = maxLimitChar - lengthCount;                   
	}
	$('#spnCharLeft').css('display', 'block');
	$('#spnCharLeft').text('count: '+charactersLeft + ' Characters left');
	return charactersLeft;
}
function img_pathUrl(input,id,parrentid){
	////console.log("this.files[0]"+input.files[0]);
	////console.log(input.files[0]);
	////console.log(input);
	////console.log(input.files[0].name);
	
	//$('#'+id)[0].src = (window.URL ? URL : webkitURL).createObjectURL(input.files[0]);	//blob
	//document.getElementById(id).style.display = "inline";
	////console.log('id:'+id);
	////console.log('parrentid:'+parrentid);
	
	var reader = new FileReader();
	reader.onload = (e) => { // set onload *before* calling readAsDataURL()
		document.getElementById(id).innerText = e.target.result;
		document.getElementById(id).src = e.target.result;
		//document.getElementById('href_'+parrentid).parentNode.setAttribute('href',e.target.result);
	}
	reader.readAsDataURL(input.files[0]);
	
	var img=(window.URL ? URL : webkitURL).createObjectURL(input.files[0]);
	//document.getElementById(id).src = img;
	////console.log(img);
	//document.getElementById('href_'+parrentid).parentNode.setAttribute('href',img);
	
	document.getElementById('href_'+parrentid).setAttribute('href',img);
	
}
function setEmptyFileValue(oi){
	var id=oi.parentNode.parentNode.id;
	document.getElementById("file-"+id).value="";
	document.getElementById("file_"+id).value="";
	document.getElementById("img_"+id).style.display="none";
	if(id!="rmxfile_add_container"){
		document.getElementById("rmx"+id).remove();
	}else{
		document.getElementById("rmxfile_add_container").style.visibility="hidden";
	}
	document.getElementById("img_file_add_container").title="กดปุ่ม F8 หรือคลิ๊กที่นี่เพื่อเลือกไฟล์";
	document.getElementById("file_file_add_container").title="กดปุ่ม F8 หรือคลิ๊กที่นี่เพื่อเลือกไฟล์";
	document.getElementById("text_add").title="กดปุ่ม F7 เพื่อมายังช่องกรอกข้อมูลนี้ สามารถใช่ spintax หรือสุ่มเลือกข้อความคั่นด้วยเครื่องหมายไปป์คู่กัน || อยู่บนเครื่องหมายแบล็คสแลส \\";
	
	$("#file_image").hide();
	$("#remove_file_btn").hide();
	$("#pencil").hide();

	try{
		checkTableDataPromise().then(
			function (value){
				document.getElementById("start_broadcast").style.display = "inline-block";
				if(value){
					document.getElementById("start_broadcast").disabled = false;
				}else{
					document.getElementById("start_broadcast").disabled = true;
				}
			},
			function(error) {
				document.getElementById("start_broadcast").style.display = "inline-block";
				document.getElementById("start_broadcast").disabled = true;
			}
		);
	}catch(ee){}
}
function onTextKeyUp(el){
	var element = document.getElementById(el.id);
	////console.log(el);
	if(element==null) return;
	if(element.type != "textarea" && element.type!="text"){
	  return;
	}
	if(element.id=="text_add"){
			element.title="กดปุ่ม F7 เพื่อมายังช่องกรอกข้อมูลนี้ สามารถใช่ spintax หรือสุ่มเลือกข้อความคั่นด้วยเครื่องหมายไปป์คู่กัน || อยู่บนเครื่องหมายแบล็คสแลส \\";
	}else{
		element.title=element.value;
	}
	//$('#'+el.id).val(element.value);
	element.innerHTML=element.value;
}
function highlight(tableid,thisTrTableRow) {
	return;	//disable highlight
	// Just a simple check. If .highlight has reached the last, start again
	////console.log(thisTrTableRow);
	var tableRowIndex=thisTrTableRow.rowIndex;
	////console.log("tableRowIndex B:"+tableRowIndex);
	////console.log("thisTrTableRow.id:"+thisTrTableRow.id);
	if( (tableRowIndex+1) > $('#'+tableid+' tbody tr').length )
		tableRowIndex = 0;
	
	////console.log("tableRowIndex F:"+tableRowIndex);
	
	// Element exists?
	if($('#'+tableid+' tbody tr:eq('+tableRowIndex+')').length > 0)
	{
		////console.log("ele exists");
		// Remove other highlights
		$('#'+tableid+' tbody tr').removeClass('highlight');

		////console.log("tableRowIndex S:"+tableRowIndex);
		// Highlight your target
		//$('#'+tableid+' tbody tr:eq('+tableRowIndex+')').addClass('highlight');
		var element = document.getElementById(thisTrTableRow.id);
		element.classList.add("highlight");
	}else{
		////console.log("ele not exists");
	}
}
function addNewRow(isAdditem){
	var table=document.getElementById("myOLBroadcastTable");
	if(table==null){return;}
	if(table.rows.length>10){ 
		alert("ใส่ได้สูงสุด 10 แถวเท่านั้นก่อนนะค่ะ");
		return;
	}	//maximum 10 rows
	AddTableRow(undefined,isAdditem);
}
function AddTableRow(o,isAdditem){
	var mainBody = document.querySelector("#myOLBroadcastTable").tBodies[0];
	//console.log(o);
	
	var num_rows = mainBody.rows.length;
	if (num_rows > 10) return;	//limit maximum row
	
	if(typeof isAdditem!=="undefined" && isAdditem){
		var message=document.getElementById("text_add");
		if(num_rows>0){
			//var my_file_check=document.getElementById("file-"+rowid+"col2");	//file id file-row1col2
			var rowid=mainBody.rows[num_rows-1].id;
			var file=document.getElementById("file-"+mainBody.rows[num_rows-1].id+"col2");	//file id file-row1col2
			if(typeof file!=='undefined'){
				if( file.files.length==0){
					var txt=document.getElementById("text_"+mainBody.rows[num_rows-1].id+"col1");	//file id file-row1col2
					if(typeof txt!=='undefined')
					{
						if(txt.value==""){
							txt.value=message.value;
							txt.title=message.value;
							txt.innerHTML=message.value;
							document.getElementById("start_broadcast").disabled = false;
							
							var filz=document.getElementById("file-file_add_container");	//file_file_add_container
							if(typeof filz !=="undefined"){
								if (filz.files.length>0){
									const dt = new _DataTransfer();
									for (let i=0;i<filz.files.length;i++){
										dt.items.add(filz.files[i]);
									}
									file.files = dt.files;
									var filedetail=document.getElementById("file_"+rowid+"col2");
									filedetail.value=document.getElementById("file_file_add_container").value;
									filedetail.title=document.getElementById("file_file_add_container").value;
									filedetail.innerHTML=document.getElementById("file_file_add_container").value;
									
									// Only process image file.
									if(file.files.length>0){
										if (!file.files[0].type.match('image.*')) {
											document.getElementById('img_'+rowid+"col2").style.display = "none";
											//return;
										}else{
											document.getElementById('img_'+rowid+"col2").style.display = "inline";
											document.getElementById('img_'+rowid+"col2").title=name.value;
											
										}
										img_pathUrl(file,'img_'+rowid+"col2",''+rowid+"col2");
										//add element
										var xClearFile=document.getElementById(rowid+"col2");
										var domString='<i><i id="rmx'+rowid+"col2"+'" class="fa fa-times" aria-hidden="true" title="Clear file"></i></i>';
										

										var rmClearFile = document.getElementById("rmx"+rowid+"col2");
										////console.log(rmClearFile);
										if(rmClearFile!=null){
											//document.getElementById("element_id").remove();
										}else{
											xClearFile.insertAdjacentHTML('beforeend',domString);
											document.getElementById("rmx"+rowid+"col2").addEventListener("click", function(event) {
												event.preventDefault();
												setEmptyFileValue(this);
												event.stopPropagation();
												event.stopImmediatePropagation();
											});
										}
										
									}
									filz.value="";
									filz.value=null;
									$("#file-file_add_container").val('');  // this is working best ):
									$("#file-file_add_container").val(null);  // this is working best ):
									var x=document.getElementById("rmxfile_add_container");
									if(typeof x!=="undefined"){
										setEmptyFileValue(x);
									}
									document.getElementById("file_file_add_container").value="";
									document.getElementById("file_file_add_container").title="";
									document.getElementById("file_file_add_container").innerHTML="";
									$("#file_image").hide();
									$("#remove_file_btn").hide();
									$("#pencil").hide();
								}
							}
							message.value="";
							return;
						}
					}
				}
			}
		}
	}
	
	//var row = mainBody.insertRow();
	//row.setAttribute("onclick", "highlight('myOLBroadcastTable',this);");
	
	//var id="";
	var rowDeleting="";
	var rowid="";
	var numberrow="";
	if(o!==undefined){
		//id = o.id;
		////console.log(id);
		rowDeleting=o.parentNode.parentNode;
		rowid=rowDeleting.id;
		if (rowid==""){
			rowid=Math.floor(Math.random()*899999+100000);
		}
		numberrow=rowDeleting.cells[0].innerHTML;
	}else{
		rowid=Math.floor(Math.random()*899999+100000);
		numberrow="#"+(num_rows+1);
	}
	//var htmlrow='<tr id="'+rowid+'" onclick="highlight(\'myOLBroadcastTable\',this);">\n';
	
	var htmlrow='<tr id="'+rowid+'">\n';
		htmlrow+='<td id="'+rowid+'col0" style="width:2%;">'+numberrow+'</td>\n';
		htmlrow+='<td id="'+rowid+'col1" style="width:60%;"><textarea class="counterchar editable emojionearea" name="text_'+rowid+'col1" id="text_'+rowid+'col1" rows="3" placeholder="คลิ๊กเพื่อแก้ไขข้อความ"></textarea><i><i id="edit_'+rowid+'col1" class="fa fa-pencil" aria-hidden="true" title="คลิ๊กเพื่อแก้ไขข้อความ"></i></i></td>\n';
		
		var tmp='<td id="'+rowid+'col2" style="width:30%;" contenteditable=\'false\'><label for="file_'+rowid+'col2" class="active"></label><textarea id="file_'+rowid+'col2" name="file_'+rowid+'col2" placeholder="ดับเบิ้ลคลิ๊กเพื่อเลือกไฟล์" readonly></textarea><i><i id="edit_'+rowid+'col2" class="fa fa-pencil" aria-hidden="true" title="ดับเบิ้ลคลิ๊กเพื่อเลือกไฟล์"></i></i>\n';
			tmp+='<input hidden class="file-content" type="file" id="file-'+rowid+'col2" name="file-'+rowid+'col2" multiple />\n';
			tmp+='<div style="text-align:center; margin-top:2px;">\n';
			tmp+='<a id="href_'+rowid+'col2" href="#" target="_blank">\n';
			tmp+='<img src="#" id="img_'+rowid+'col2" alt="your image" style="display:none; width:50px; height:50px; text-align:center;" />\n';
			tmp+='</a>\n';
			tmp+='</div>\n';
			tmp+='</td>\n';
		htmlrow+=tmp;	//col index 2
		
			tmp='<td id="'+rowid+'col3" style="width:5%;">\n';
			tmp+='<button type="button" class="btn btn-info move-row-up" id="moveup_'+rowid+'col3" style="margin:2px 2px;padding:0px 2px; width:100%;" title="Move row up" />\n';
			tmp+='<i class="fas fa-angle-up"></i>';
			tmp+='</button>';
			tmp+='<button type="button" class="btn btn-primary move-row-down" id="movedown_'+rowid+'col3" style="margin:2px 2px;padding:0px 2px; width:100%;" title="Move row down" />\n';
			tmp+='<i class="fas fa-angle-down"></i>';
			tmp+='</button>';
			tmp+='</td>\n';
		htmlrow+=tmp;	//col index 3
		
			tmp='<td id="'+rowid+'col4" style="width:5%;">\n';
			tmp+='<button type="button" class="btn btn-danger del-row" id="del_'+rowid+'col4" name="del_'+rowid+'col4" style="margin:2px 2px;padding:0px 2px; width:100%;" title="Delete row">\n';
			tmp+='<i class="far fa-comment-times"></i>&nbsp;Del';
			tmp+='</button>';
			tmp+='</td>\n';
		htmlrow+=tmp;	//col index 4
			
			tmp='<td id="'+rowid+'col5" style="display:none;"></td>\n';
		htmlrow+=tmp;	//col index 5
		
			//tmp='<td id="'+rowid+'col5" style="width:5%;">\n';
			//tmp+='</td>\n';
		//htmlrow+=tmp;	//col index 5	//report

		htmlrow+='</tr>';
	$('#tablebody').append(htmlrow);
	
	document.getElementById("text_"+rowid+"col1").style.backgroundColor = "#f7f7f7";
	document.getElementById("file_"+rowid+"col2").style.backgroundColor = "#f7f7f7";
	
	document.getElementById("moveup_"+rowid+"col3").addEventListener("click", handler_move_row_up_event=function(event) {
		event.preventDefault();
		var td = event.target;
		upNdown('up',td.parentNode);
		event.stopPropagation();
		event.stopImmediatePropagation();
	});
	document.getElementById("movedown_"+rowid+"col3").addEventListener("click", handler_move_row_down_event=function(event) {
		event.preventDefault();
		var td = event.target;
		upNdown('down',td.parentNode);
		event.stopPropagation();
		event.stopImmediatePropagation();
	});
	document.getElementById("del_"+rowid+"col4").addEventListener("click", handler_del_row_event=function(event) {
		event.preventDefault();
		var td = event.target;
		funDel(td);
		event.stopPropagation();
		event.stopImmediatePropagation();
	});
	document.getElementById(rowid+"col2").addEventListener("click", handler_add_files_event=function(event) {
		//event.preventDefault();
		//var td = event.target;
		document.getElementById("file-"+rowid+"col2").click();
		//event.stopPropagation();
		//event.stopImmediatePropagation();
	});
	
	
	if(typeof isAdditem!=="undefined" && isAdditem){
		var message=document.getElementById("text_add");
		if(message.value!=""){
			var txt = document.getElementById("text_"+rowid+"col1");
			txt.value=message.value;
			txt.title=message.value;
			txt.innerHTML=message.value;
			document.getElementById("start_broadcast").disabled = false;
		}
		var filz=document.getElementById("file-file_add_container");
		if(typeof filz !=="undefined"){
			if (filz.files.length>0){
				document.getElementById("start_broadcast").disabled = false;
				var file=document.getElementById("file-"+rowid+"col2");	//file id file-row1col2
				const dt = new _DataTransfer();
				for (let i=0;i<filz.files.length;i++){
					dt.items.add(filz.files[i]);
				}
				file.files = dt.files;
				var filedetail=document.getElementById("file_"+rowid+"col2");
				filedetail.value=document.getElementById("file_file_add_container").value;
				filedetail.title=document.getElementById("file_file_add_container").value;
				filedetail.innerHTML=document.getElementById("file_file_add_container").value;
				
				// Only process image file.
				if(file.files.length>0){
					if (!file.files[0].type.match('image.*')) {
						document.getElementById('img_'+rowid+"col2").style.display = "none";
						//return;
					}else{
						document.getElementById('img_'+rowid+"col2").style.display = "inline";
						document.getElementById('img_'+rowid+"col2").title=name.value;
						
					}
					img_pathUrl(file,'img_'+rowid+"col2",''+rowid+"col2");
					//add element
					var xClearFile=document.getElementById(rowid+"col2");
					var domString='<i><i id="rmx'+rowid+"col2"+'" class="fa fa-times" aria-hidden="true" title="ลบไฟล์"></i></i>';

					var rmClearFile = document.getElementById("rmx"+rowid+"col2");
					////console.log(rmClearFile);
					if(rmClearFile!=null){
						//document.getElementById("element_id").remove();
					}else{
						xClearFile.insertAdjacentHTML('beforeend',domString);
						document.getElementById("rmx"+rowid+"col2").addEventListener("click", function(event) {
							event.preventDefault();
							setEmptyFileValue(this);
							event.stopPropagation();
							event.stopImmediatePropagation();
						});
					}
					
				}
				
				filz.value="";
				filz.value=null;
				$("#file-file_add_container").val('');  // this is working best ):
				$("#file-file_add_container").val(null);  // this is working best ):
				var x=document.getElementById("rmxfile_add_container");
				if(typeof x!=="undefined"){
					setEmptyFileValue(x);
				}
				document.getElementById("file_file_add_container").value="";
				document.getElementById("file_file_add_container").title="";
				document.getElementById("file_file_add_container").innerHTML="";
				$("#file_image").hide();
				$("#remove_file_btn").hide();
				$("#pencil").hide();
			}
		}
		message.value="";
		return;
	}
	
}

function funDel(o) {
	//no clue what to put here?
	var modal=document.getElementById('modalid01');
	modal.style.display='block';
	
	var confirm=modal.getAttribute('data-delete-confirm');
	////console.log("before confirm delete row:"+confirm);
	////console.log(o.id);
	modal.setAttribute('data-mark-delete-row-id',o.id);
	
	document.getElementById('del_row').innerHTML="&nbsp;"+o.parentNode.parentNode.cells[0].innerHTML;
	/*
	var p=o.parentNode.parentNode;
	funRowIdex(o);
	p.parentNode.removeChild(p);
	AddTableRow(o);
	*/
}
function funSubmitDeleteRow(){
	var modal=document.getElementById('modalid01');
	var confirm=modal.getAttribute('data-delete-confirm');
	////console.log("after sub delete row:"+confirm);
	if(confirm="yes"){
		var btnid=modal.getAttribute('data-mark-delete-row-id');
		////console.log(btnid);
		var btnInRow=document.getElementById(btnid);
		////console.log(btnInRow);
		var p=btnInRow.parentNode.parentNode;
		var rowindex=funRowIdex(btnInRow);
		//p.parentNode.removeChild(p);
		
		document.getElementById("myOLBroadcastTable").deleteRow(rowindex);
		//AddTableRow(btnInRow);

		reAssignRowNum();
	}
}
function funSubmitDeleteAllRow(){
	var modal=document.getElementById('modalid02');
	var confirm=modal.getAttribute('data-deleteAll-confirm');
	////console.log("after sub delete row:"+confirm);
	if(confirm="yes"){
		var tb=document.getElementById("myOLBroadcastTable");
		if(tb==null){return;}
		while(tb.rows.length > 1) {
			tb.deleteRow(1);
		}
		document.getElementById("start_broadcast").disabled = true;
	}
}
function reAssignRowNum(){
	var mainBody = document.querySelector("#myOLBroadcastTable").tBodies[0];
	var num_rows = mainBody.rows.length;
	if(num_rows==0){
		document.getElementById("start_broadcast").disabled = true;
		return;
	}
	var i=0;
	for (i=0;i<num_rows;i++){
		mainBody.rows[i].cells[0].innerHTML="#"+(i+1);
	}
	document.getElementById("start_broadcast").disabled = false;
}
function funRowIdex(tr) {	//button
	////console.log(tr);
	////console.log("Row index is: " + tr.parentNode.parentNode.rowIndex);
	try{
		return tr.parentNode.parentNode.rowIndex;
	}catch(e){
		return -1;
	}
}
function dellAllRow(){
	var modal=document.getElementById('modalid02');
	modal.style.display='block';
}
function upNdown(direction,tr){
	////console.log("upNdown");
	////console.log(tr);
	var rows = document.getElementById("myOLBroadcastTable").rows;
	if(rows.length==0){return;}
	var rowIndex = funRowIdex(tr);
	if(rowIndex== -1){return;}
	
	try{
		var parent = rows[rowIndex].parentNode;
		if(direction === "up")
		{
			 if(rowIndex > 1){
				parent.insertBefore(rows[rowIndex],rows[rowIndex - 1]);
				// when the row go up the index will be equal to index - 1
				//rowIndex--;
				//var row=document.getElementById(rows[rowIndex - 1].id);
				var $row = $("#"+rows[rowIndex - 1].id);
				$row.fadeOut(1000,function() {
					$row.fadeIn(1000,function() {
					
					});
				});
			}
		}else if(direction === "down"){
			 if(rowIndex < rows.length -1){
				parent.insertBefore(rows[rowIndex + 1],rows[rowIndex]);
				// when the row go down the index will be equal to index + 1
				//rowIndex++;
				var $row = $("#"+rows[rowIndex+1].id);
				$row.fadeOut(1000,function() {
					$row.fadeIn(1000,function() {
					
					});
				});
			}
		}
	}catch(e){}
}
function resz(){
	$("th:first-child,th:nth-child(2),th:nth-child(3),th:nth-child(4),th:nth-child(5),th:nth-child(6),th:nth-child(7)")
	.css({
		/* required to allow resizer embedding */
		position: "relative"
	})
	/* check .resizer CSS */
	//.prepend("<div class='resizer'></div>")
	.append("<div class='resizer'></div>")
	.resizable({
		resizeHeight: false,
		// we use the column as handle and filter
		// by the contained .resizer element
		handleSelector: "",
		onDragStart: function(e, $el, opt) {
		  // only drag resizer
		  if (!$(e.target).hasClass("resizer"))
			return false;
		  return true;
		}
	});
}
function isDataTableEmpty(){
	var irow_check=0
	var bpass=false;
	let myOLBroadcastTable_check = document.querySelector("#myOLBroadcastTable").tBodies[0];
	if(typeof myOLBroadcastTable_check==="undefined"){return true;}
	let num_rows_check = myOLBroadcastTable_check.rows.length;
	while (irow_check < num_rows_check) {
		var my_broadcastline_file_check=document.getElementById("file-"+myOLBroadcastTable_check.rows[irow_check].id+"col2");	//file id file-row1col2
		if(typeof my_broadcastline_file_check!=='undefined'){
			//console.log('my_broadcastline_file_check.value:'+my_broadcastline_file_check.value);
			if(my_broadcastline_file_check.value!=""){
				bpass=true;
				break;
			}
		}
		
		var my_broadcastline_text_check=document.getElementById("text_"+myOLBroadcastTable_check.rows[irow_check].id+"col1");	//message id text_row1col1
		if(typeof my_broadcastline_text_check!=='undefined')
		{
			//console.log('my_broadcastline_text_check.value:'+my_broadcastline_text_check.value);
			if(my_broadcastline_text_check.value!=""){
				bpass=true;
				break;
			}
		}
		irow_check++;
	}
	return !bpass;
}
function saveTable(){
	//console.log('save table');
	saveFile();
	var myFormData="";
	var table = $('#myOLBroadcastTable');
	sessionStorage.removeItem("#myOLBroadcastTable");
	sessionStorage.removeItem("#myOLBroadcastForm");
	sessionStorage.removeItem("#myOLBroadcastTableFiles");
	
	if (table==null){return;};
	
	if(isDataTableEmpty()==true){
		if (typeof iziToast != 'undefined') {
			iziToast.info({
				title: 'แจ้งเตือน',
				position: 'topLeft',
				timeout: 3000,
				message: 'คุณยังไม่ได้ใส่ข้อความหรือเลือกไฟล์ที่ต้องการจะส่ง',
			});
		}
		return;
	}
	sessionStorage.setItem("#myOLBroadcastTable", table.get(0).outerHTML);

	var my_broadcastline_except_unread=document.getElementById('my_broadcastline_except_unread').checked;
	var my_broadcastline_oldtonew=document.getElementById('my_broadcastline_oldtonew').checked;
	var cfg_start_seding_no=document.getElementById('cfg_start_seding_no').value;
	var cfg_max_recipients = document.getElementById('cfg_max_recipients').value;
	var cfg_delay=document.getElementById('cfg_delay').value;
	var my_broadcastline_select_type=document.getElementById("my_broadcastline_select_type").selectedIndex;
	var cfg_recipients_option_folder=document.getElementById("cfg_recipients_option_folder").selectedIndex;
	var cfg_recipients_option_tag=document.getElementById("cfg_recipients_option_tag").selectedIndex;
	var recipients_option_tag_msg=document.getElementById("recipients_option_tag_msg").innerHTML;
	var cfg_schedule_now=document.getElementById("cfg_schedule_now").checked;
	var cfg_schedule_later=document.getElementById("cfg_schedule_later").checked;
	
	var myFormData="";
		myFormData+='[{"my_broadcastline_except_unread":'+my_broadcastline_except_unread;
		myFormData+=',"my_broadcastline_oldtonew":'+my_broadcastline_oldtonew;
		myFormData+=',"cfg_start_seding_no":'+cfg_start_seding_no;
		myFormData+=',"cfg_max_recipients":'+cfg_max_recipients;
		myFormData+=',"cfg_delay":'+cfg_delay;
		myFormData+=',"my_broadcastline_select_type":'+my_broadcastline_select_type;
		myFormData+=',"cfg_recipients_option_folder":'+cfg_recipients_option_folder;
		myFormData+=',"cfg_recipients_option_tag":'+cfg_recipients_option_tag;
		myFormData+=',"recipients_option_tag_msg":"'+recipients_option_tag_msg+'"';
		myFormData+=',"cfg_schedule_now":'+cfg_schedule_now;
		myFormData+=',"cfg_schedule_later":'+cfg_schedule_later;
		myFormData+='}]';
	////console.log('myFormData:'+myFormData);
	if(myFormData!=='' ){
		sessionStorage.setItem("#myOLBroadcastForm", myFormData);
		iziToast.success({timeout: 2000, icon: 'fas fa-save', title: 'OK', message: 'Save data success'});
	}
}
function restoreTable(){
	var table=sessionStorage.getItem("#myOLBroadcastTable");
	////console.log(table);
	if(table==null){
		iziToast.info({timeout: 2000, icon: 'fa fa-chrome', title: 'INFO', message: 'No data loaded'});
		return;
	}
	
	var myobj = document.getElementById("myOLBroadcastTable");
	if(myobj==null){
		iziToast.info({timeout: 2000, icon: 'fa fa-chrome', title: 'INFO', message: 'No data loaded'});
		return;
	};
	myobj.remove();
	document.getElementById('container_myOLBroadcastTable').innerHTML += table;
	
	var myFormData=sessionStorage.getItem("#myOLBroadcastForm");
	if(myFormData==null){
		iziToast.info({timeout: 2000, icon: 'fa fa-chrome', title: 'INFO', message: 'No data loaded'});
		return;
	}
	
	var json=JSON.parse(myFormData)[0];
	if(json==null){
		iziToast.info({timeout: 2000, icon: 'fa fa-chrome', title: 'INFO', message: 'No data loaded'});
		return;
	}
	////console.log(myFormData);
	document.getElementById('my_broadcastline_except_unread').checked=json.my_broadcastline_except_unread;
	document.getElementById('my_broadcastline_oldtonew').checked=json.my_broadcastline_oldtonew;
	document.getElementById('cfg_start_seding_no').value=json.cfg_start_seding_no;
	document.getElementById('cfg_max_recipients').value=json.cfg_max_recipients;
	document.getElementById('cfg_delay').value=json.cfg_delay;
	document.getElementById("my_broadcastline_select_type").selectedIndex=json.my_broadcastline_select_type;
	document.getElementById("cfg_recipients_option_folder").selectedIndex=json.cfg_recipients_option_folder;
	document.getElementById("cfg_recipients_option_tag").selectedIndex=json.cfg_recipients_option_tag;
	document.getElementById("recipients_option_tag_msg").innerHTML=json.recipients_option_tag_msg;
	document.getElementById("cfg_schedule_now").checked=json.cfg_schedule_now;
	document.getElementById("cfg_schedule_later").checked=json.cfg_schedule_later;
	document.getElementById("cfg_schedule_now").value=json.cfg_schedule_now;
	document.getElementById("cfg_schedule_later").value=json.cfg_schedule_later;
	if(json.cfg_schedule_later==true){
		document.getElementById("lbl_schedule_later").classList.remove("active");
		document.getElementById("lbl_schedule_now").classList.remove("active");
		//document.getElementById("lbl_schedule_later").classList.classList.add("active");
		var c = document.getElementById("lbl_schedule_later");
			c.className += " active";
		//btn btn-outline-success active
	}else{
		document.getElementById("lbl_schedule_later").classList.remove("active");
		document.getElementById("lbl_schedule_now").classList.remove("active");
		//document.getElementById("lbl_schedule_now").classList.classList.add("active");
		var c = document.getElementById("lbl_schedule_now");
			c.className += " active";
	}
	
	addBase64toFileList();
	//Clear report
	/*
	var mainBody = document.querySelector("#myOLBroadcastTable").tBodies[0];
	var num_rows = mainBody.rows.length;
	if(num_rows>0){
		let i=0;
		for (i=0;i<num_rows;i++){
			mainBody.rows[i].cells[4].innerHTML="";
		}
	}
	*/
	/*
	$("#cfg_schedule_now").attr("checked", json.cfg_schedule_now);
	$("#cfg_schedule_later").attr("checked", json.cfg_schedule_later);
	$("#cfg_schedule_now").prop('checked', json.cfg_schedule_now);
	$("#cfg_schedule_later").prop('checked', json.cfg_schedule_later);
	$("#cfg_schedule_now").attr("checked", 0);
	$("#cfg_schedule_later").attr("checked", 1);
	$("#cfg_schedule_now").prop('checked', 0);
	$("#cfg_schedule_later").prop('checked', 1);
	$("#cfg_schedule_now").attr("value", false);
	$("#cfg_schedule_later").attr("value", true);
	*/
}
function getFiles(files) {
	//console.log(files);
	return Promise.all([...files].map(file => getFile(file)));
}
function getFile(file) {
	//take a single JavaScript File object
	var reader = new FileReader();
	return new Promise((resolve, reject) => {
		reader.onerror = () => { reader.abort(); reject(new Error("Error parsing file"));}
		/*
		reader.onload = function () {
			//This will result in an array that will be recognized by C#.NET WebApi as a byte[]
			let bytes = Array.from(new Uint8Array(this.result));
			//if you want the base64encoded file you would use the below line:
			let base64StringFile = btoa(bytes.map((item) => String.fromCharCode(item)).join(""));
			//Resolve the promise with your custom file structure
			resolve({ 
				bytes: bytes,
				base64StringFile: base64StringFile,
				fileName: file.name, 
				fileType: file.type
			});
		}
		reader.readAsArrayBuffer(file);
		*/
		reader.onload = (e) => { // set onload *before* calling readAsDataURL()
			resolve({ 
				base64StringFile: e.target.result,
				fileName: file.name, 
				fileType: file.type
			});
		}
		reader.readAsDataURL(file);
		
	});
}

function saveFile(){
	let myOLBroadcastTable_check = document.querySelector("#myOLBroadcastTable").tBodies[0];
	let num_rows_check = myOLBroadcastTable_check.rows.length;
	var irow_check=0;
	var json_all="";
	var json="";
	
	get_file_json(irow_check);
	async function get_file_json(irow_check){
		if(irow_check < num_rows_check){
		//while (irow_check < num_rows_check) {
			var my_broadcastline_file_check=document.getElementById("file-"+myOLBroadcastTable_check.rows[irow_check].id+"col2");	//file id file-row1col2
			if(typeof my_broadcastline_file_check!=='undefined'){
				var files = my_broadcastline_file_check.files;
				if(files.length>0){
					const customJsonFile = await getFiles(files);
					if(customJsonFile.length>0){
						let i=0;
						let json="";
						for(i=0;i<customJsonFile.length;i++){
							if(json!=""){json+=","}	//row
							json+='{"fileName":"'+customJsonFile[i].fileName+'","fileType":"'+customJsonFile[i].fileType+'","base64":"'+customJsonFile[i].base64StringFile+'"}';
						}
						if(json!=""){
							json='"row'+(irow_check+1)+'":['+json+']';
							if(json_all!=""){
								json_all+=",";
							}
							json_all+=json;
						}
						irow_check++;
						if(irow_check < num_rows_check){
							get_file_json(irow_check);
						}else{
							if(json_all!=""){
								json_all="{"+json_all+"}";
								//console.log(json_all);
								//save here
								sessionStorage.setItem("#myOLBroadcastTableFiles", json_all);
							}
						}
						
					}
					
				}else{
					irow_check++;
					if(irow_check < num_rows_check){
						get_file_json(irow_check);
					}else{
						if(json_all!=""){
							json_all="{"+json_all+"}";
							//console.log(json_all);
							//save here
							sessionStorage.setItem("#myOLBroadcastTableFiles", json_all);
						}
					}
				}
			}
			
		}
		
	}
		
}

function showStartButton(){
	$('#start_broadcast').show();
	$('#pause_broadcast').hide();
	$('#stop_broadcast').hide();
	$('#continue_broadcast').hide();
}
async function runningProgress(loop,job_status) {	//each member
	//job_status 0 stop,1=running,2=pause,3=done;
	if(!$("#footer-summary-container").is(':visible')){return;}
	var elem = document.getElementById("myBar");
	if(typeof elem!=="undefined"){
		if(active_friends_count>0){
			$('#footer-summary-container').show();
			$('#close-x').show();
			$('#open-o').hide();
			
			let width=Math.round((tot_send_friends_count/((Number(cfg_max_recipients)-Number(cfg_start_seding_no))+1))*100);
			//document.getElementById("xyz").innerHTML = "สำเร็จ "+(tot_send_friends_count - memberSendErrorCount)+" /ไม่สำเร็จ "+memberSendErrorCount+ " /จากทั้งหมด "+ active_friends_count+ " คน";
			document.getElementById("xyz").innerHTML = "สำเร็จ "+(tot_send_friends_count - memberSendErrorCount)+" /ไม่สำเร็จ "+memberSendErrorCount+ " /จากทั้งหมด "+ ((Number(cfg_max_recipients)-Number(cfg_start_seding_no))+1) + " คน";
			document.getElementById("rzf").innerHTML = "คนที่ "+tot_send_friends_count+" /จาก "+active_friends_count+ " /failed "+ memberSendErrorCount +" คน";
			
			if (width <= 100) {
				elem.style.width = width + "%";
				elem.innerHTML = width + "%";
			}
			if(typeof job_status!=="undefined" && job_status!=null){
				
			}else{
				job_status = 1;
			}
			if(status_stop_pause == 3 || status_stop_pause==0 || job_status==3 || job_status ==0){	//done	//stop
				showStartButton();
				await setStopJob(0,false,status_stop_pause);
				setStopClock();
			}
			/*
			else{
					elem.style.width = 100 + "%";
					elem.innerHTML = 100 + "%";
					
					let action = await checkActionStatus();
					console.log("progress action:"+action);
					if(action!=1){
						$('#start_broadcast').show();
						$('#pause_broadcast').hide();
						$('#stop_broadcast').hide();
						$('#continue_broadcast').hide();
						setStopClock();
						setStopJob(0,false,3);
					}
			}
			*/
		}

	}
}

function runningAllitemsProgress(param_nocounter) {
	if(!$("#footer-summary-container").is(':visible')){return;}
	var elem = document.getElementById("myBar");
	
	if(typeof elem!=="undefined"){
		if(active_friends_count>0){
			if (iTableAllItems>0){
				if(iTotalMesageMustSend<1){iTotalMesageMustSend=((Number(cfg_max_recipients)-Number(cfg_start_seding_no)+1) *iTableAllItems);}

				if (iProgressAllItemsCount>0){
					let width=Math.round((tot_send_items_count/(iTotalMesageMustSend))*100);	//iTotalMesageMustSend	//
					
					document.getElementById("mn").innerHTML = "ข้อความที่ "+iMessNumberActive+" /จาก "+iTableAllItems + " ข้อความ";
					//document.getElementById("rsfa").innerHTML = "ข้อความส่ง สำเร็จ "+(iTotalMesageMustSend-itemsSendErrorCount)+" /ไม่สำเร็จ "+itemsSendErrorCount + " /จาก "+ (iTotalMesageMustSend) + " ข้อความ";	
					document.getElementById("rsfa").innerHTML = "ข้อความส่ง สำเร็จ "+(tot_send_items_count-itemsSendErrorCount)+" /ไม่สำเร็จ "+itemsSendErrorCount + " /จาก "+ (iTotalMesageMustSend) + " ข้อความ";	
					
					if (width <= 100) {
						elem.style.width = width + "%";
						elem.innerHTML = width + "%";
					}
				}
			}
		}
	}
}

function clearSummary(){
	//footer-summary-container
	
	document.getElementById("NetRetry").innerHTML="Net retry 0";
	document.getElementById("NetMsg").innerHTML="Net message -";
	
	document.getElementById("start_time").innerHTML="starttime";
	document.getElementById("stop_time").innerHTML="finished?";
	
	document.getElementById("xyz").innerHTML = "สำเร็จ " + "x" +" /ไม่สำเร็จ " + "y" + " /จากทั้งหมด " + "z" + " คน";
	document.getElementById("rzf").innerHTML = "คนที่ " + "r" + " /จาก " + "z" + " /failed " + "f" + " คน";
			
	document.getElementById("mn").innerHTML = "ข้อความที่ " + "m" + " /จาก " + "n" + " ข้อความ";
	document.getElementById("rsfa").innerHTML = "ข้อความส่ง สำเร็จ "+ "s" +" /ไม่สำเร็จ " + "f" + " /จาก " + "a" + " ข้อความ";	
					
	var elem = document.getElementById("myBar");
	if(typeof elem!=="undefined"){
		elem.style.width = 0+"%";
		elem.innerHTML = 0 + "%";
	}
	
	$('#pause_send_detail').text('');
	$('#send_next_time').text('');
	$('#current_time').text('');
	$('#count_sending_bubble_per_min').text('');
	$('#count_sending_bubble_iterate').text('');
	$('#count_sending_person_iterate').text('');
	$('#my_header').text('ระบบกำลังทำงานอยู่');
	$("#processing_img").attr("src", 'app-assets/img/processing.gif');
	
}

function GetQueryStringParams(sParam){
    var sPageURL =decodeURIComponent(window.location.href);
	//var sPageURL =decodeURIComponent(sParam);
	var op=sPageURL.split('?');
	if(op.length<2){ return "";}
    var sURLVariables = op[1].split('&');
	////console.log(sURLVariables);
	
    for (var i = 0; i < sURLVariables.length; i++)
    {
        var sParameterName = sURLVariables[i].split('=');
        if (sParameterName[0].trim() == sParam)
        {
            return sParameterName[1];
        }
    }
}

function parseDate(str) {
    var dmy = str.split('/');
    return new Date(dmy[2], dmy[1], dmy[0]-1 );
}

function datediff(first, second) {
    // Take the difference between the dates and divide by milliseconds per day.
    // Round to nearest whole number to deal with DST.
    return Math.round((second-first)/(1000*60*60*24));
}

///////////////////// GET FB FANPAGE NAME/////////////
async function get_fanpage_old(next_url_page) {
	//fanpage_all = [];
	title = 'ข้อมูลคน inbox ในแฟนเพจ';
	if(fb_access_token=='' || fb_access_token=='null' || fb_access_token==null ){
		fb_access_token = await localStorage.getItem("token_poweredit");
		if(typeof fb_access_token=="undefined" || fb_access_token==null || fb_access_token==""){
			fb_access_token = "";
		}else{
			localStorage.setItem("fb_access_token",fb_access_token);
		}
	}
	
	let tokenx = localStorage.getItem('fb_token_instagram');
	await sleep(3000);
	if(typeof tokenx == "undefined" || tokenx == null || tokenx=='null'){tokenx = "";}	
	if(fb_access_token == ""){
		fb_access_token = tokenx;
		localStorage.setItem('fb_access_token',tokenx);
	}
	if(fb_token_power == "" || fb_token_power == 'token'){
		if(tokenx != ""){
			fb_token_power = tokenx;
			localStorage.setItem('fb_token_power',tokenx);
		}
	}


	let url = 'https://graph.facebook.com/v1.0/me/accounts?fields=access_token,id,name,picture&limit=40&access_token=' + fb_access_token;
    
	if(typeof next_url_page!=="undefined" && next_url_page!=null && next_url_page!=""){
		url = next_url_page;
	}
	//console.log(url);
	
	if(fb_token_power==""){
		Swal.fire({
			title: 'มีปัญหา',
			html: "ไม่สามารถดึงข้อมูลแฟนเพจได้ ไม่พบ token ตรวจสอบ ว่าทำการ login facebook แล้วหรือยัง แล้วลองเปิดโปแกรมใหม่อีกรอบ <br />",
			type: 'error',
			confirmButtonColor: '#3085d6',
			confirmButtonText: 'OK'
		});
		return;
	}
	
    $.getJSON(url, function (results) {
        var data_fetch = results.data;
        var paging = results.paging;
		
        $.each(data_fetch, function (i, data) {
            fanpage_all.push({
                'id': data.id,
                'name': data.name,
                'page_access_token': data.access_token,
				'picture':data.picture
            });

        });

        if (typeof paging != 'undefined') {

            if (typeof paging.next != 'undefined') {

                iziToast.info({
                    title: title,
                    position: 'topLeft',
                    timeout: 1000,
                    message: 'กำลังดึง' + title + 'รอสักครู่',
                });
                get_fanpage_old(paging.next)

            } else {

                let message = 'ดึงแฟนเพจของคุณ ' + fanpage_all.length + ' แฟนเพจ';
                iziToast.success({
                    title: message,
                    position: 'topLeft',
                    timeout: 3000,
                    message: '',
                });
                append_get_fanpage(JSON.stringify(fanpage_all));
            }
        } else {
            let message = 'ดึงแฟนเพจของคุณ ' + fanpage_all.length + ' แฟนเพจ';
            iziToast.success({
                title: message,
                position: 'topLeft',
                timeout: 3000,
                message: '',
            });
        }
		
	})
	.fail(function (e) {
		//console.log('get fb fanpage failed:');
		console.log(e);
		let err_msg = "";
		if(e.responseJSON){
			if(e.responseJSON.error){
				err_msg = "Code: "+ e.responseJSON.error.code + " -> "+ e.responseJSON.error.message
			}
		}
		Swal.fire({
			title: 'มีปัญหา',
			html: "ไม่สามารถดึงข้อมูลแฟนเพจได้ ตรวจสอบ ว่าทำการ login facebook แล้วหรือยัง แล้วลองเปิดโปแกรมใหม่อีกรอบ <br />"+err_msg,
			icon: 'error',
			confirmButtonColor: '#3085d6',
			confirmButtonText: 'OK'
		});
	});

}

async function append_get_fanpage(fanpage_all_json) {
	//console.log("append get fanpage");
    //var fanpage_allx = $.parseJSON((localStorage.getItem('fanpage_all')));
	if(fanpage_all_json==''){return "";}

	var fanpage_allx = $.parseJSON(fanpage_all_json);
	
	try{
		ldb.set('pop_server_date', user_name+'|'+server_date+'|'+curdate);
	}catch(e){}
	
	ldb.get('tf_demo_usage_ratelimit_'+user_name, function (usage_ratelimit) {
		let curdate = server_date;	//Hack server
		if(typeof usage_ratelimit!=="undefined" && usage_ratelimit!=null){
			var ul = usage_ratelimit.split("|");
			tf_demo_usage_ratelimit=0;
			if(ul.length>0){
				tf_demo_usage_ratelimit=Number(ul[0]);
				demo_usage_date=ul[1];
				tf_demo_usage_ratelimit_left=Number(ul[2]);
				if(user_type=="ทดลองใช้งาน" && Number(tf_demo_ratelimit_setting)>0){
					if(curdate!=demo_usage_date && demo_usage_date!=""){
						tf_demo_usage_ratelimit=0;
					}
					tf_demo_usage_ratelimit_left = Number(tf_demo_ratelimit_setting) - Number(tf_demo_usage_ratelimit);
					if(Number(tf_demo_usage_ratelimit_left)<0){tf_demo_usage_ratelimit_left=-1;}
					document.getElementById('plan_package').innerHTML=""+user_type+ " เหลือ "+ tf_demo_usage_ratelimit_left +" ข้อความ/วัน";
					document.getElementById('plan_demo_package').innerHTML=document.getElementById('plan_package').innerHTML
					ldb.set('tf_demo_usage_ratelimit_'+user_name, tf_demo_usage_ratelimit+'|'+curdate+'|'+ tf_demo_usage_ratelimit_left+'|'+tf_demo_ratelimit_setting);
				}
			}
		}else{
			if(user_type=="ทดลองใช้งาน" && Number(tf_demo_ratelimit_setting)>0){
				tf_demo_usage_ratelimit_left = Number(tf_demo_ratelimit_setting);
				if(Number(tf_demo_usage_ratelimit_left)<0){tf_demo_usage_ratelimit_left=-1;}
				document.getElementById('plan_package').innerHTML=""+user_type + " เหลือ " +tf_demo_ratelimit_setting +" ข้อความ/วัน";
				document.getElementById('plan_demo_package').innerHTML=document.getElementById('plan_package').innerHTML
				ldb.set('tf_demo_usage_ratelimit_'+user_name, tf_demo_usage_ratelimit+'|'+curdate+'|'+ tf_demo_usage_ratelimit_left+'|'+tf_demo_ratelimit_setting);
			}
		}
		
	});
	
	$(".get_fb_fanpage_name").html('');
	$("#my_broadcastline_idpage").empty();
	var x = document.getElementById("my_broadcastline_idpage");

	let i=0;
	for (i=x.length-1;i>0;i--) {
	  x.remove(i);
	}
	
    option = '';

	var options = [];
	var name="";
	var id="";
	var page_access_token="";
	var data_icon="";
	var dataAcc="";

	if(typeof token_fb_instagramx!=="undefined" && token_fb_instagramx!=null && token_fb_instagramx!=""){
		
	}
	if(typeof fb_user_id!=="undefined" && fb_user_id!=null && fb_user_id!=""){
		fb_user_id = await LocalStorage.getItem('fb_user_id');
	}

    $.each(fanpage_allx, function (index, data) {
        name = data.name;
        id = data.id;
        page_access_token = data.page_access_token;
		//data_icon ="https://graph.facebook.com/" + id + "/picture?type=small&access_token=" + token_fb_instagramx ;
		data_icon = data.picture.data.url;
        dataAcc = '<option value="' + id + '|' + page_access_token + '|' + name + '" data-icon="'+data_icon+'" title="'+data_icon+'"  >' + name + '</option>' + option;
		options.push(dataAcc);
    });

    //$(".get_fanpage").append('<option value=""   >เลือกแฟนเพจ</option>' + option);
    //$(".get_fanpage").formSelect();
	var idaccs=document.getElementById("my_broadcastline_idpage");//.selectedIndex = "2";
	if(options.length>0){
		//options.push('<option value=""   >เลือก Account Line</option>');
		options.reverse();
	}
	idaccs.innerHTML = options.join('\n'); 
	
	
	try {
		//var oHandler = $(".get_line").msDropDown().data("dd");
		var oHandler = $("#my_broadcastline_idpage").msDropDown().data("dd");
		if(oHandler){
			idaccs.selectedIndex=0;
			oHandler.set("selectedIndex", 0)	
		}
	} catch(e) {
		console.log("Error: "+e.message);
	}
	
    return;
}
/////////////////////////////////////////////////////

//new//
async function getFaceFanpageV3() {	//new
	//reset_friends_fanpage();
	//reset_friends_data_store();
	let fanpages_map = new Map();
	let tokenx = await LocalStorage.getItem('fb_token_instagram');

	console.log("Get Face Fanpage List");

	iziToast.info({
		title: 'กำลังรวบรวมแฟนเพจทั้งหมดให้คุณ กรุณารอสักครู่',
		position: iziToast_position,
		backgroundColor: iziToast_bg_color,
		timeout: 3000,
		message: '',
	});

	await sleep(3000);
	
	let pwt = await LocalStorage.getItem("fb_token_power");
	let act = await LocalStorage.getItem("fb_access_token");
	let pet = await LocalStorage.getItem("token_poweredit");

	if(typeof tokenx == "undefined" || tokenx == null || tokenx=='null'){tokenx = "";}	
	if(fb_access_token == ""){
		fb_access_token = tokenx;
		if(!fb_access_token){
			if (act){fb_access_token = act;}else if (pwt) {fb_access_token = pwt;} else if (pet){fb_access_token = pet;}
		}
		localStorage.setItem('fb_access_token',fb_access_token);
	}else{
		if(!act){
			localStorage.setItem('fb_access_token',fb_access_token);
		}
	}

	if(fb_token_power == "" || fb_token_power == 'token'){
		if(tokenx != ""){
			fb_token_power = tokenx;
			localStorage.setItem('fb_token_power',tokenx);
		}
	}
	
	if(fb_access_token=='' || fb_access_token=='null' || fb_access_token==null ){
		fb_access_token = await LocalStorage.getItem("token_poweredit");
		if(typeof fb_access_token=="undefined" || fb_access_token==null || fb_access_token==""){
			fb_access_token = "";
		}else{
			localStorage.setItem("fb_access_token",fb_access_token);
		}
	}

	if(!fb_token_power){
		if (pwt){fb_token_power = pwt;}else if (pet) {fb_token_power = pet;} else if (act){fb_token_power = act;}
		localStorage.setItem("fb_token_power",fb_token_power);
	}
	
	// if (fb_token_power == "") {
	// 	console.log("getFaceFanpage fb_token_power is empty");
	// 	Swal.fire({
	// 		title: 'มีปัญหา',
	// 		html: "ไม่สามารถดึงข้อมูลแฟนเพจได้ ไม่พบ token ตรวจสอบ ว่าทำการ login facebook แล้วหรือยัง แล้วลองเปิดโปแกรมใหม่อีกรอบ... <br />",
	// 		icon: 'error',
	// 		confirmButtonColor: '#3085d6',
	// 		confirmButtonText: 'OK'
	// 	});
	// 	return;
	// }
	
	
	try {
		if (fanpages_map == null) {
			fanpages_map = new Map();
		}
	} catch (e) { }
	try { fanpages_map.clear(); } catch (e) { }

	let jazoest = Math.floor(Math.random() * Math.pow(5, 5)).toString().padStart(5, "0");
	return new Promise(async (resolve) => {
		let url = null;
		let stopRequest = false;

		//while (!stopRequest) {
			var paramRequest = {
				"av": fb_user_id,
				"__user": fb_user_id,
				"doc_id": 5928348513932036,	//4593263290776700
				"jazoest": jazoest,
				"fb_api_caller_class": "RelayModern",
				"fb_api_req_friendly_name": "PagesCometLaunchPointUnifiedQueryPagesListRedesignedUpdatedPagesSectionQuery",
				"__a": "1",
				"fb_dtsg": fb_dtsg,
				"variables": JSON.stringify({
					"count": 10,
					"cursor": url,
					"scale": 3,
				})
			};

			// try{
			// 	chrome.runtime.sendMessage({type:'getfanpage',url:'https://www.facebook.com/api/graphql/',param:paramRequest},function(resp){
			// 		console.log(resp);
			// 	});
			// }catch(err){
			// 	console.log(err);
			// 	stopRequest = true
			// 	Swal.fire({
			// 		title: 'มีปัญหา',
			// 		html: "ไม่สามารถดึงข้อมูลแฟนเพจได้ โปรดตรวจสอบการ login facebook  หรือปิดแล้วเปิดโปรแกรมอีกที หรือสลับ facebook เป็นโปรไฟล์ตัวเอง แล้วลองเปิดโปแกรมใหม่อีกรอบ <br />" + err,
			// 		type: 'error',
			// 		confirmButtonColor: '#3085d6',
			// 		confirmButtonText: 'OK'
			// 	});
			// 	resolve(false);
			// 	return;
			// }
			debugger;
			
			try {
				
				// const response = await fetch("https://www.facebook.com/api/graphql/", {
				// 	method: "POST",
				// 	body: new URLSearchParams(paramRequest),
				// });
				// const data = await response.text();
				// const data2 = data.replace('for (;;);','');
				// const modifiedData = data2.replace('{"successful_results":1,"error_results":0,"skipped_results":0}', '');
				//.then((response) => {
				//var listData = async () => {
					//const [tab] = await chrome.tabs.query({active: true, lastFocusedWindow: true});
  					//const resp = await chrome.tabs.sendMessage(tab.id, {type:'getfanpage',url:'https://www.facebook.com/api/graphql/',param:paramRequest});

					//const resp = await chrome.runtime.sendMessage({type:'getfanpage',url:'https://www.facebook.com/api/graphql/',param:paramRequest});
					//chrome.runtime.sendMessage({type:'getfanpage',url:'https://www.facebook.com/api/graphql/',param:paramRequest}).then((resp) => {
					//chrome.runtime.sendMessage({type:'getfanpage',url:'https://www.facebook.com/api/graphql/',param:paramRequest},function(resp){
					
					async function startAsync()  {
						console.log("startAsync Fanpage");
						const result = await chrome.runtime.sendMessage({type:'getfanpage',url:'https://www.facebook.com/api/graphql/',param:paramRequest});
						console.log(result);
					}
					startAsync();

					// chrome.runtime.sendMessage({type:'getfanpage',url:'https://www.facebook.com/api/graphql/',param:paramRequest},(resp) => { 
					// 	console.log(resp);
					// 	const modifiedData = resp;
					
					// 	let parsedData = '';
					// 	try {
					// 		parsedData = JSON.parse(modifiedData);
					// 	} catch (e) {
					// 		stopRequest = true
					// 		Swal.fire({
					// 			title: "เกิดข้อผิดพลาด",
					// 			text: "ไม่สามารถให้ดึงแฟนเพจได้ ให้คุณลองปิดโปรแกรมเปิดใหม่ดูอีกครั้ง หรือไปที่ facebook.com ดูว่าเฟสที่ใช้งานอยู่ อยู่ในสถานะเฟสปกติ ไม่ใช่ในสถานะแอดมินเพจ ถ้าอยุ่ในสถานะเฟสปกติแล้ว ให้ปิดโปรแกรมแล้วเปิดใหม่อีกครั้งค่ะ",
					// 			type: "error"
					// 		});
					// 		resolve(false);
					// 		return;
					// 	}
						
					// 	if(parsedData?.error){
					// 		if(parsedData?.errorDescription){
					// 			console.log("getF", parsedData?.error)
					// 			Swal.fire({
					// 				title: 'มีปัญหา',
					// 				html: "ไม่สามารถดึงข้อมูลแฟนเพจได้ โปรดตรวจสอบการ login facebook หรือปิดแล้วเปิดโปรแกรมอีกที หรือสลับ facebook เป็นโปรไฟล์ตัวเอง แล้วลองเปิดโปแกรมใหม่อีกรอบ <br /> "+ parsedData?.error + ':' + parsedData?.errorDescription,
					// 				type: 'error',
					// 				confirmButtonColor: '#3085d6',
					// 				confirmButtonText: 'OK'
					// 			});

					// 			stopRequest = true
					// 			resolve(false);
					// 			return;
					// 			// setStopJob(0,false,0);
					// 			// status_running=false;
					// 			// showStartButton();
					// 			// $('#get_fb_fanpage').show();
					// 			// $('.processing').hide();
					// 		}
					// 	}

					// 	//var data_fetch = parsedData?.data?.viewer?.adminedPages?.edges;
					// 	//var pageInfo = parsedData?.data?.viewer?.adminedPages?.page_info;

					// 	var data_fetch = parsedData?.data?.viewer?.actor?.additional_profiles_with_biz_tools?.edges;
					// 	var pageInfo = parsedData?.data?.viewer?.actor.additional_profiles_with_biz_tools?.page_info;

					// 	$.each(data_fetch, function (i, data) {
					// 		// let pg = {
					// 		// 	'id': data.node.id,
					// 		// 	'name': data.node.name,
					// 		// 	'page_access_token': '',
					// 		// 	'picture': data.node.profilePic40.uri,
					// 		// 	'index': i,
					// 		// }
					// 		let pg = {
					// 			'id': data.node.delegate_page_id,
					// 			'name': data.node.name,
					// 			'page_access_token': '',
					// 			'picture': data.node.profile_picture.uri,
					// 			'index': i,
					// 		}

					// 		fanpages_map.set(data.node.delegate_page_id, pg);
					// 	});
					// 	if (pageInfo) {
					// 		if (pageInfo?.has_next_page) {
					// 			iziToast.info({
					// 				title: 'กำลังดึงแฟนเพจ ' + fanpages_map.size + ' กรุณารอสักครู่',
					// 				position: iziToast_position,
					// 				backgroundColor: iziToast_bg_color,
					// 				timeout: 1000,
					// 				// message: '<p style="font-size:15px;font-weight:bold;">กำลังดึง' + fanpages_map.size + 'รอสักครู่</p>',
					// 			});
					// 			url = pageInfo?.end_cursor	//next page
					// 			// if(url){
					// 			// 	listData();
					// 			// }
					// 		}
					// 		else {
					// 			stopRequest = true
					// 		}
					// 	} else {
					// 		stopRequest = true
					// 	}
					//  });



					// .catch((error) => {
					// 	console.warn("Popup could not send message", error)
					//  });

				//};

				//await listData;

			} catch (error) {
				console.log("getF", error)
				Swal.fire({
					title: 'มีปัญหา',
					html: "ไม่สามารถดึงข้อมูลแฟนเพจได้ โปรดตรวจสอบการ login facebook  หรือปิดแล้วเปิดโปรแกรมอีกที หรือสลับ facebook เป็นโปรไฟล์ตัวเอง แล้วลองเปิดโปแกรมใหม่อีกรอบ <br />",
					type: 'error',
					confirmButtonColor: '#3085d6',
					confirmButtonText: 'OK'
				});

				stopRequest = true
				resolve(false);
			}
			//stopRequest = true;
		//}

		// iziToast.success({
		// 	title: 'ดึงแฟนเพจของคุณ ' + fanpages_map.size + ' แฟนเพจ',
		// 	position: iziToast_position,
		// 	backgroundColor: iziToast_bg_color,
		// 	timeout: 3000,
		// 	message: '',
		// });

		// $(".select_fanpage-a").on('click', function (e) {
		// 	e.preventDefault();
		// 	$("#select_fanpage").change();
		// });
		// await appendFbFanpage(fanpages_map);
		// //await getLastFanPage()

		// resolve(true);
	});
	
}

//new//
async function getFaceFanpage() {	//new
	let fanpages_map = new Map();
	let tokenx = await LocalStorage.getItem('fb_token_instagram');

	iziToast.info({
		title: 'กำลังรวบรวมแฟนเพจทั้งหมดให้คุณ กรุณารอสักครู่',
		position: iziToast_position,
		backgroundColor: iziToast_bg_color,
		timeout: 3000,
		message: '',
	});

	await sleep(3000);
	
	let pwt = await LocalStorage.getItem("fb_token_power");
	let act = await LocalStorage.getItem("fb_access_token");
	let pet = await LocalStorage.getItem("token_poweredit");

	if(typeof tokenx == "undefined" || tokenx == null || tokenx=='null'){tokenx = "";}	
	if(fb_access_token == ""){
		fb_access_token = tokenx;
		if(!fb_access_token){
			if (act){fb_access_token = act;}else if (pwt) {fb_access_token = pwt;} else if (pet){fb_access_token = pet;}
		}
		localStorage.setItem('fb_access_token',fb_access_token);
	}else{
		if(!act){
			localStorage.setItem('fb_access_token',fb_access_token);
		}
	}

	if(fb_token_power == "" || fb_token_power == 'token'){
		if(tokenx != ""){
			fb_token_power = tokenx;
			localStorage.setItem('fb_token_power',tokenx);
		}
	}
	
	if(fb_access_token=='' || fb_access_token=='null' || fb_access_token==null ){
		fb_access_token = await LocalStorage.getItem("token_poweredit");
		if(typeof fb_access_token=="undefined" || fb_access_token==null || fb_access_token==""){
			fb_access_token = "";
		}else{
			localStorage.setItem("fb_access_token",fb_access_token);
		}
	}

	if(!fb_token_power){
		if (pwt){fb_token_power = pwt;}else if (pet) {fb_token_power = pet;} else if (act){fb_token_power = act;}
		localStorage.setItem("fb_token_power",fb_token_power);
	}
	
	try {
		if (fanpages_map == null) {
			fanpages_map = new Map();
		}
	} catch (e) { }
	try { fanpages_map.clear(); } catch (e) { }

	let jazoest = Math.floor(Math.random() * Math.pow(5, 5)).toString().padStart(5, "0");
	return new Promise(async (resolve) => {
		let url = null;
		let stopRequest = false;

		while (!stopRequest) {
			var paramRequest = {
				"av": fb_user_id,
				"__user": fb_user_id,
				"doc_id": 5928348513932036,	//4593263290776700
				"jazoest": jazoest,
				"fb_api_caller_class": "RelayModern",
				"fb_api_req_friendly_name": "PagesCometLaunchPointUnifiedQueryPagesListRedesignedUpdatedPagesSectionQuery",
				"__a": "1",
				"fb_dtsg": fb_dtsg,
				"variables": JSON.stringify({
					"count": 10,
					"cursor": url,
					"scale": 3,
				})
			};

			console.log('param:',paramRequest);
			let sparam = new URLSearchParams(paramRequest);
			console.log('sparam:',sparam);
			console.log(sparam.toString());
			
			try {
				const response = await fetch("https://www.facebook.com/api/graphql/", {
					method: "POST",
					body: new URLSearchParams(paramRequest),
				});
				const data = await response.text();
				const data2 = data.replace('for (;;);','');
				const modifiedData = data2.replace('{"successful_results":1,"error_results":0,"skipped_results":0}', '');
				console.log('modifiedData:',modifiedData);
				let parsedData = '';
				try {
					parsedData = JSON.parse(modifiedData);
				} catch (e) {
					stopRequest = true
					Swal.fire({
						title: "เกิดข้อผิดพลาด",
						text: "ไม่สามารถให้ดึงแฟนเพจได้ ให้คุณลองปิดโปรแกรมเปิดใหม่ดูอีกครั้ง หรือไปที่ facebook.com ดูว่าเฟสที่ใช้งานอยู่ อยู่ในสถานะเฟสปกติ ไม่ใช่ในสถานะแอดมินเพจ ถ้าอยุ่ในสถานะเฟสปกติแล้ว ให้ปิดโปรแกรมแล้วเปิดใหม่อีกครั้งค่ะ",
						type: "error"
					});
					resolve(false);
					return;
				}
				
				if(parsedData?.error){
					if(parsedData?.errorDescription){
						console.log("getF", parsedData?.error)
						Swal.fire({
							title: 'มีปัญหา',
							html: "ไม่สามารถดึงข้อมูลแฟนเพจได้ โปรดตรวจสอบการ login facebook หรือปิดแล้วเปิดโปรแกรมอีกที หรือสลับ facebook เป็นโปรไฟล์ตัวเอง แล้วลองเปิดโปแกรมใหม่อีกรอบ <br /> "+ parsedData?.error + ':' + parsedData?.errorDescription,
							type: 'error',
							confirmButtonColor: '#3085d6',
							confirmButtonText: 'OK'
						});

						stopRequest = true
						resolve(false);
						return;
					}
				}

				var data_fetch = parsedData?.data?.viewer?.actor?.additional_profiles_with_biz_tools?.edges;
				var pageInfo = parsedData?.data?.viewer?.actor.additional_profiles_with_biz_tools?.page_info;

				$.each(data_fetch, function (i, data) {
					let pg = {
						'id': data.node.delegate_page_id,
						'name': data.node.name,
						'page_access_token': '',
						'picture': data.node.profile_picture.uri,
						'index': i,
					}

					fanpages_map.set(data.node.delegate_page_id, pg);
				});
				if (pageInfo) {
					if (pageInfo?.has_next_page) {
						iziToast.info({
							title: 'กำลังดึงแฟนเพจ ' + fanpages_map.size + ' กรุณารอสักครู่',
							position: iziToast_position,
							backgroundColor: iziToast_bg_color,
							timeout: 1000,
							// message: '<p style="font-size:15px;font-weight:bold;">กำลังดึง' + fanpages_map.size + 'รอสักครู่</p>',
						});
						url = pageInfo?.end_cursor	//next page
					}
					else {
						stopRequest = true
					}
				} else {
					stopRequest = true
				}

			} catch (error) {
				console.log("getF", error)
				Swal.fire({
					title: 'มีปัญหา',
					html: "ไม่สามารถดึงข้อมูลแฟนเพจได้ โปรดตรวจสอบการ login facebook  หรือปิดแล้วเปิดโปรแกรมอีกที หรือสลับ facebook เป็นโปรไฟล์ตัวเอง แล้วลองเปิดโปแกรมใหม่อีกรอบ <br />",
					type: 'error',
					confirmButtonColor: '#3085d6',
					confirmButtonText: 'OK'
				});

				stopRequest = true
				resolve(false);
			}
		}

		iziToast.success({
			title: 'ดึงแฟนเพจของคุณ ' + fanpages_map.size + ' แฟนเพจ',
			position: iziToast_position,
			backgroundColor: iziToast_bg_color,
			timeout: 3000,
			message: '',
		});

		$(".select_fanpage-a").on('click', function (e) {
			e.preventDefault();
			$("#select_fanpage").change();
		});
		await appendFbFanpage(fanpages_map);
		//await getLastFanPage()

		resolve(true);
	});
	
}

async function getLastFanPage() {	//new
	let variables = {
		"page_id": ""
	};
	let jazoest = Math.floor(Math.random() * Math.pow(5, 5)).toString().padStart(5, "0");
	$.ajax({
		url: "https://business.facebook.com/api/graphql/",
		type: "POST",
		data: {
			av: "",
			fb_dtsg: fb_dtsg,
			jazoest: jazoest,
			fb_api_caller_class: 'RelayModern',
			fb_api_req_friendly_name: 'BizInboxFilterLabelSelectorContainerQuery',
			doc_id: 7967972616607116,
			__user: fb_user_id,
			variables: JSON.stringify(variables)
		},
		dataType: "json",
		complete: function (data) {
			var response = JSON.parse(data.responseText);
			console.log("https://business.facebook.com/api/graphql/", response)
		}
	});
}
function getFbFanpage(next_url_page,init_fanpage_all) {
	let url = 'https://graph.facebook.com/v1.0/me/accounts?fields=access_token,id,name,picture&limit=40&access_token=' + fb_access_token;
	if(init_fanpage_all==null){
		reset_friends_fanpage();
	}
	if(typeof next_url_page!=="undefined" && next_url_page!=null && next_url_page!=""){
		url = next_url_page;
	}
	if(fb_access_token==""){
		console.log("getFbFanpage next");
		Swal.fire({
			title: 'มีปัญหา',
			html: "ไม่สามารถดึงข้อมูลแฟนเพจได้ ไม่พบ token ตรวจสอบ ว่าทำการ login facebook แล้วหรือยัง แล้วลองเปิดโปแกรมใหม่อีกรอบ <br />",
			type: 'error',
			confirmButtonColor: '#3085d6',
			confirmButtonText: 'OK'
		});
		return;
	}
	
	$.getJSON(url, async function (results) {
		let data_fetch = results.data;
		let paging = results.paging;
		$.each(data_fetch, function (i, data) {
			let pg = {
				'id': data.id,
				'name': data.name,
				'page_access_token': data.access_token,
				'picture':data.picture,
				'index':i,
			};
			if(isConsole){
				console.log(pg);
			}
			//fanpage_all.push(pg);
			fanpages_map.set(data.id,pg);
		});
		if (typeof paging != 'undefined') {
			if (typeof paging.next != 'undefined') {

				iziToast.info({
					title: 'กำลังดึงแฟนเพจทั้งหมด',
					position: iziToast_position,
					backgroundColor: iziToast_bg_color,
					timeout: 1000,
					message: 'กำลังดึง' + fanpages_map.size + 'รอสักครู่',
				});
				getFbFanpage(paging.next)
			} else {
				iziToast.success({
					title: 'ดึงแฟนเพจของคุณ ' + fanpages_map.size + ' แฟนเพจ',
					position: iziToast_position,
					backgroundColor: iziToast_bg_color,
					timeout: 3000,
					message: '',
				});
				//await appendFbFanpage(JSON.stringify(fanpage_all));
				//await appendFbFanpage(JSON.stringify([...fanpages_map.entries()]));	//map
				await appendFbFanpage(fanpages_map);
			}
		} else {
			iziToast.success({
				title: 'ดึงแฟนเพจของคุณ ' + fanpages_map.size + ' แฟนเพจ',
				position: iziToast_position,
				backgroundColor: iziToast_bg_color,
				timeout: 3000,
				message: '',
			});
		}
	})
	.fail(function (e) {
		console.log(e);
		let err_msg = "";
		if(e.responseJSON){
			if(e.responseJSON.error){
				err_msg = "Code: "+ e.responseJSON.error.code + " -> "+ e.responseJSON.error.message
			}
		}
		Swal.fire({
			title: 'มีปัญหา',
			html: "ไม่สามารถดึงข้อมูลแฟนเพจได้ ตรวจสอบ ว่าทำการ login facebook แล้วหรือยัง แล้วลองเปิดโปแกรมใหม่อีกรอบ <br />"+err_msg,
			icon: 'error',
			confirmButtonColor: '#3085d6',
			confirmButtonText: 'OK'
		});
	});
}
function appendFbFanpage(fanpages) {
	return new Promise(async resolve=>{
		
		//var foo = new Set;
		//foo instanceof Set; // True!
		//foo instanceof Map; // False!
		if(fanpages instanceof Map){
			if(fanpages.size<1){resolve(false);return "";}
		}else if(Array.isArray(fanpages)){
			if(fanpages.length<1){resolve(false);return "";}
		}else{
			if(fanpages==''){resolve(false);return "";}
		}

		try{
			ldb.set('pop_server_date', user_name+'|'+server_date+'|'+curdate);
		}catch(e){}
		
		//let demo_usage_date = "";	//gui.js
		ldb.get('tf_demo_usage_ratelimit_'+user_name, function (usage_ratelimit) {
			let curdate = server_date;	//Hack server
			if(typeof usage_ratelimit!=="undefined" && usage_ratelimit!=null){
				let ul = usage_ratelimit.split("|");
				tf_demo_usage_ratelimit = 0;
				if(ul.length>0){
					tf_demo_usage_ratelimit=Number(ul[0]);
					demo_usage_date=ul[1];
					tf_demo_usage_ratelimit_left=Number(ul[2]);
					if(user_type=="ทดลองใช้งาน" && Number(tf_demo_ratelimit_setting)>0){
						if(curdate!=demo_usage_date && demo_usage_date!=""){
							tf_demo_usage_ratelimit = 0;
						}
						tf_demo_usage_ratelimit_left = Number(tf_demo_ratelimit_setting) - Number(tf_demo_usage_ratelimit);
						if(Number(tf_demo_usage_ratelimit_left)<0){tf_demo_usage_ratelimit_left=-1;}
						$('#user_plan').html(user_type+ " เหลือ "+ tf_demo_usage_ratelimit_left +" ข้อความ/วัน");
						ldb.set('tf_demo_usage_ratelimit_'+user_name, tf_demo_usage_ratelimit+'|'+curdate+'|'+ tf_demo_usage_ratelimit_left+'|'+tf_demo_ratelimit_setting);
					}
				}
			}else{
				if(user_type=="ทดลองใช้งาน" && Number(tf_demo_ratelimit_setting)>0){
					tf_demo_usage_ratelimit_left = Number(tf_demo_ratelimit_setting);
					if(Number(tf_demo_usage_ratelimit_left)<0){tf_demo_usage_ratelimit_left=-1;}
					$('#user_plan').html(user_type + " เหลือ " +tf_demo_ratelimit_setting +" ข้อความ/วัน");
					ldb.set('tf_demo_usage_ratelimit_'+user_name, tf_demo_usage_ratelimit+'|'+curdate+'|'+ tf_demo_usage_ratelimit_left+'|'+tf_demo_ratelimit_setting);
				}
			}
			
		});
		
		$("#my_broadcastline_idpage").empty();

		let options = [];
		let name="";
		let id="";
		let page_access_token="";
		let data_icon="";
		let dataAcc="";
		let idx = 1;
		if(fanpages instanceof Map){
			//fanpages.forEach(function(value, key) {
			//for(let i=0;i<fanpages.size;i++){
			//for (let key of fanpages.keys()) {
			//for (const [key, value] of fanpages.entries()) {
				// dataAcc = '<option value="' + id + '|' + name + '|' + index + '" data-botId="' + botId + '" data-icon="' + data.profileImageUrl + '" title="'+data.profileImageUrl+ '" >' + name + '</option>';         
				// options.push(dataAcc);
			for (let data of fanpages.values()){
				try{
					//let data = fanpages.get(key);	//await JSON.Parse(fanpages[i]);
					name = data.name;
					id = data.id;
					page_access_token = data.page_access_token;
					//data_icon = data.picture.data.url;
					data_icon = data.picture;
					dataAcc = '<option value="' + id + '|' + page_access_token + '|' + name + '" data-icon="'+data_icon+'" title="'+data_icon+'"  >'+ name + '</option>';
					//dataAcc = '<option value="' + id + '" data-icon="'+data_icon+'" title="'+data_icon+'"  >' + idx+ ' ' + name + '</option>';
					options.push(dataAcc);
					idx++;
				}catch(e){console.log(e);}
			}
		}else if(Array.isArray(fanpages)){
			for(let i=0;i<fanpages.length;i++){
				try{
					let data = fanpages[i];	//await JSON.Parse(fanpages[i]);
					name = data.name;
					id = data.id;
					page_access_token = data.page_access_token;
					//data_icon = data.picture.data.url;
					data_icon = data.picture;
					dataAcc = '<option value="' + id + '|' + page_access_token + '|' + name + '" data-icon="'+data_icon+'" title="'+data_icon+'"  >'+ name + '</option>';
					//dataAcc = '<option value="' + id + '" data-icon="'+data_icon+'" title="'+data_icon+'"  >' + idx+ ' ' + name + '</option>';
					options.push(dataAcc);
					idx++;
				}catch(e){console.log(e);}
			}
		}else{
			try{
				let fanpage_all_parse = $.parseJSON(fanpages);
				$.each(fanpage_all_parse, function (index, data) {
					name = data.name;
					id = data.id;
					page_access_token = data.page_access_token;
					//data_icon = data.picture.data.url;
					data_icon = data.picture;
					dataAcc = '<option value="' + id + '|' + page_access_token + '|' + name + '" data-icon="'+data_icon+'" title="'+data_icon+'"  >'+ name + '</option>';
					//dataAcc = '<option value="' + id + '" data-icon="'+data_icon+'" title="'+data_icon+'"  >' + idx+ ' ' + name + '</option>';
					options.push(dataAcc);
					idx++;
				});
			}catch(e){console.log(e);}
		}
		//if(options.length>0){
		//	options.reverse();
		//}
		//let idaccs=document.getElementById("my_broadcastline_idpage");//.selectedIndex = "2";
		//idaccs.innerHTML = options.join('\n'); 
		
		var idaccs=document.getElementById("my_broadcastline_idpage");//.selectedIndex = "2";
		if(options.length>0){
			//options.push('<option value=""   >เลือก Account Line</option>');
			options.reverse();
		}
		idaccs.innerHTML = options.join('\n'); 
		
		
		try {
			//var oHandler = $(".get_line").msDropDown().data("dd");
			var oHandler = $("#my_broadcastline_idpage").msDropDown().data("dd");
			if(oHandler){
				idaccs.selectedIndex=0;
				oHandler.set("selectedIndex", 0)	
			}
		} catch(e) {
			console.log("Error: "+e.message);
		}


		// let idaccs=$("#my_broadcastline_idpage");
		// idaccs.html(options.join('\n'));
		
		// try {
		// 	let oHandler = $("#my_broadcastline_idpage").msDropDown().data("dd");
		// 	if(oHandler){
		// 		//idaccs.selectedIndex=0;
		// 		$("#my_broadcastline_idpage").prop('selectedIndex',0);
		// 		oHandler.set("selectedIndex", 0);
		// 		$("#my_broadcastline_idpage_child").width(500);
		// 		//$("#my_broadcastline_idpage_child").width(document.getElementById("my_broadcastline_idpage").offsetWidth;
		// 		//$("#my_broadcastline_idpage_child").width($("#my_broadcastline_idpage").width());
		// 		//$(".ddChild ddchild_").width($("#my_broadcastline_idpage").width());
		// 	}
		// 	$('#my_broadcastline_idpage_msdd').css({'margin-left':'10px'});
		// } catch(e) {
		// 	console.log("Error: "+e.message);
		// }
		// $('.ddTitle').css('background-color', '#7daed5');
		// $('.ddTitle').css({'border-radius':'6px'});


		resolve(true);
		return;
	});
}
////


(() => { function fn() {
		// "On document ready" commands:
		////console.log(document.readyState);
		/*fun code to run*/
		// Get the modal
		// Like a document ready
		var modal = document.getElementById('modalid01');
		
		// When the user clicks anywhere outside of the modal, close it
		window.onclick = function(event) {
			if (event.target == modal) {
				////console.log("hit");
				modal.style.display = "none";
			}
		}
		
		/*
		$('#start_broadcast').show();
		$('#pause_broadcast').hide();
		$('#continue_broadcast').hide();
		$('#stop_broadcast').hide();
		$('#radio_schedule *').prop('disabled',false);
		$('#lbl_schedule_ *').prop('disabled',false);
		*/
		
	};  
	if (document.readyState != 'loading') {fn()}
	else {
		document.addEventListener('DOMContentLoaded', fn);
		//append_get_oaline();
	}
})();

function clearIndexDb(){
	return new Promise(resolve => {
		window.indexedDB.databases().then((r) => {
			for (var i = 0; i < r.length; i++){
				if(r[i].name.indexOf('d2')<0){
					window.indexedDB.deleteDatabase(r[i].name);
				}
			}
		}).then(() => {
			//console.log("clear indexDB");
			resolve(true);
		});
	});
}
//tf_demo_usage_ratelimit_
function myScheduleRadio(event){
	//console.log(event.target.id);
}

function runSchedule(schDate){
	document.getElementById("end").innerHTML = "";
	document.getElementById("schedule_setting").innerHTML = schDate;
	var countDownDate = new Date(schDate).getTime();
	schTimeLeft = setInterval(function() {
		var now = new Date().getTime();
		var timeleft = countDownDate - now;
		
		// Calculating the days, hours, minutes and seconds left
		var days = Math.floor(timeleft / (1000 * 60 * 60 * 24));
		var hours = Math.floor((timeleft % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
		var minutes = Math.floor((timeleft % (1000 * 60 * 60)) / (1000 * 60));
		var seconds = Math.floor((timeleft % (1000 * 60)) / 1000);
		
		//(9).pad();  //returns "09"
		// Result is output to the specific element
		document.getElementById("schedule_running").innerHTML = (days).pad() + "d "+(hours).pad() + "h "+(minutes).pad() + "m "+(seconds).pad() + "s ";
		// Display the message when countdown is over
		if (timeleft < 0) {
			clearInterval(schTimeLeft);
			document.getElementById("schedule_running").innerHTML = "";
			document.getElementById("end").innerHTML = "TIME UP!!";
			setTimeout(function () {
				document.getElementById('modalidSchedule').style.display='none';
				send_my_broadcastline_start();
			}, 2000);
			
		}
	}, 1000);
}

function setStopJob(loop,isShowContinue,actionFlagStopPauseDone){	//actionFlagStopPauseDone press 0=stop,1=running,2=pause,3=done
	return new Promise(resolve => {
		status_running=false;
		try{
			if(typeof loop ==="undefined"){loop=0;}
			if(typeof actionFlagStopPauseDone ==="undefined"){actionFlagStopPauseDone=3;}
			if(loop<0){loop=0;}
			if(isShowContinue){
				//localStorage.setItem('setstop', 2);	//Clear stop flag
				status_stop_pause = 2;
			}else{
				//localStorage.setItem('setstop', 0);	//Clear stop flag
				if(actionFlagStopPauseDone==0){
					status_stop_pause = 0;
				}else{
					status_stop_pause = 3;	//done
				}
			}
			localStorage.setItem('loops', loop);	//store sending no to local storage
			setStopClock();
			var dnow = new Date();
			var curdate = dnow.toJSON().slice(0,10);
			curdate = server_date;	//Hack server yyyy-mm-dd
			//console.log("server date:"+server_date);
			
			$('#download_fb_fanpage_success_members').hide();
			if(user_type=="ทดลองใช้งาน"){
				if (Number(tf_demo_ratelimit_setting)>0){
					tf_demo_usage_ratelimit_left = Number(tf_demo_ratelimit_setting) - Number(tf_demo_usage_ratelimit);
					if(Number(tf_demo_usage_ratelimit_left)<0){tf_demo_usage_ratelimit_left=-1;}
					document.getElementById('plan_package').innerHTML=""+user_type+ " เหลือ "+ tf_demo_usage_ratelimit_left +" ข้อความ/วัน";
					document.getElementById('plan_demo_package').innerHTML=document.getElementById('plan_package').innerHTML
		
					ldb.set('tf_demo_usage_ratelimit_'+user_name, tf_demo_usage_ratelimit+'|'+curdate+'|'+ tf_demo_usage_ratelimit_left+'|'+tf_demo_ratelimit_setting);
				}
			}else{
				if(actionFlagStopPauseDone==3){	//Send successfully
					if(ct_tf_label_user_all_send_success.length>0){
						$('#download_fb_fanpage_success_members').attr('title','ดาวน์โหลดลูกเพจเฉพาะผู้ที่ส่งสำเร็จเท่านั้นจากเพจ '+oaAccountIdActiveName + ' '+ct_tf_label_user_all_send_success.length+' คน');
						$('#download_fb_fanpage_success_members').show();
					}
				}
			}

			$('#radio_schedule *').prop('disabled',false);
			$('#lbl_schedule_ *').prop('disabled',false);
			$('#start_broadcast').show();
			$('#pause_broadcast').hide();
			$('#stop_broadcast').hide();
			$('#modalWorkingDelay').hide();
			
			document.getElementById('clock_status').innerHTML="stopped";
			
			if(typeof isShowContinue==="undefined"){isShowContinue=false;}
			if(isShowContinue){
				$('#continue_broadcast').show();
				$('#start_broadcast').hide();
				$('#stop_broadcast').show();
				$('#modalWorkingDelay').show();
			}else{
				$('#continue_broadcast').hide();
				document.getElementById("get_fb_fanpage").disabled = false;
			}
		}catch(err){
		}
		resolve(1);
	});
}

function setStopClock(){
	let clock_status = document.getElementById('clock_status');
	if(typeof clock_status!=="undefined"){
		if(clock_status!=null){
			clock_status.innerHTML="stopped";
			//clock_status.style.display="none";
		}
	}
}

async function checkActionStatus(){
	return new Promise(function (resolve) {
		//let actStatus = await localStorage.getItem('setstop');
		let actStatus = status_stop_pause;
		if (typeof actStatus==="undefined" || actStatus==""){
			actStatus=1;
		}
		try{
			actStatus=parseInt(actStatus);
		}catch(e){
			actStatus=1;
		}
			
		if (actStatus == 3) {	//job done
			iziToast.info({
				title: 'ทำงานเสร็จเรียบร้อยแล้ว',
				position: 'topLeft',
				timeout: 5000,
				message: '',
			});
			$('#start_broadcast').show();
			$('#pause_broadcast').hide();
			$('#stop_broadcast').hide();
			$('#continue_broadcast').hide();
			$('#radio_schedule *').prop('disabled',false);
			$('#lbl_schedule_ *').prop('disabled',false);
			$('#pause_broadcast').text('   pause');
			$('#stop_broadcast').text('   stop');
			
			var d=new Date();
			var esttime_date_format_str = d.getFullYear().toString()+"-"+padDigits(d.getMonth()+1,2)+"-"+padDigits(d.getDate(),2)+" "+padDigits(d.getHours(),2)+":"+padDigits(d.getMinutes(),2)+":"+padDigits(d.getSeconds(),2);
			document.getElementById("stop_time").innerHTML = "เสร็จ " + esttime_date_format_str;
			document.getElementById("clock").innerHTML = "เสร็จ " + esttime_date_format_str;
			status_running=false;
			showStartButton();
			//return 0;
			resolve(0);
		}else if (actStatus == 0) {	//press stop button
			iziToast.info({
				title: 'หยุดทำงานเรียบร้อยแล้ว',
				position: 'topLeft',
				timeout: 5000,
				message: '',
			});
			$('#start_broadcast').show();
			$('#pause_broadcast').hide();
			$('#stop_broadcast').hide();
			$('#continue_broadcast').hide();
			$('#radio_schedule *').prop('disabled',false);
			$('#lbl_schedule_ *').prop('disabled',false);
			$('#pause_broadcast').text('   pause');
			$('#stop_broadcast').text('   stop');
			
			var d=new Date();
			var esttime_date_format_str = d.getFullYear().toString()+"-"+padDigits(d.getMonth()+1,2)+"-"+padDigits(d.getDate(),2)+" "+padDigits(d.getHours(),2)+":"+padDigits(d.getMinutes(),2)+":"+padDigits(d.getSeconds(),2);
			document.getElementById("stop_time").innerHTML = "หยุดทำงาน " + esttime_date_format_str;
			document.getElementById("clock").innerHTML = "หยุดทำงาน " + esttime_date_format_str;
			status_running=false;
			
			//return 0;
			resolve(0);
		}else if (actStatus == 2) {	//press pause button
			iziToast.info({
				title: ' หยุดทำงานชั่วคราว',
				position: 'topLeft',
				timeout: 5000,
				message: '',
			});
			$('#start_broadcast').hide();
			$('#pause_broadcast').hide();
			$('#continue_broadcast').show();
			$('#stop_broadcast').show();
			$('#radio_schedule *').prop('disabled',false);
			$('#lbl_schedule_ *').prop('disabled',false);
			$('#pause_broadcast').text('   pause');
			$('#stop_broadcast').text('   stop');
			var d=new Date();
			var esttime_date_format_str = d.getFullYear().toString()+"-"+padDigits(d.getMonth()+1,2)+"-"+padDigits(d.getDate(),2)+" "+padDigits(d.getHours(),2)+":"+padDigits(d.getMinutes(),2)+":"+padDigits(d.getSeconds(),2);
			document.getElementById("stop_time").innerHTML="หยุดชั่วคราว " + esttime_date_format_str;
			status_running=false;
			
			//return 2;
			resolve(2);
		}else{
			//return 1;
			resolve(1);
		}
	});
}

///////////////////////////////////////
////// SEND Message Here /////////////
function send_my_broadcastline_start() {
	sleepMode.prevent();
	status_running=false;
	check_net().then((data) =>{
		sending_my_broadcastline_start();
	}).catch((error) =>{
		console.log(error);
		$('#start_broadcast').hide();
		$('#pause_broadcast').show();
		$('#stop_broadcast').show();
		$('#continue_broadcast').show();
		$('#footer-summary-container').hide();
		$('#close-x').hide();
		$('#open-o').show();
		
		setStopJob(0,false,0);

		$('#error_x_report').hide();
		$('#error_report').show();
		$('#txt_error_report').hide();
	
		log_msg = "ไม่สามารถสื่อสารกับ https://facebook.com/ ได้ตรวจสอบ Internet หรือ Login Line ใหม่อีกรอ"+"\r\n";
		//txt_error_report.value = log_msg;
		send_status = "0";
		show_msg_report(target_id,target_name,send_status,log_msg);
		
		alert("ไม่สามารถสื่อสารกับ https://facebook.com/ ได้ตรวจสอบ Internet หรือ Login Line ใหม่อีกรอบ");
		return
	});
	//////////////////////////////////////
}

function sending_my_broadcastline_start(){
	status_running=false;
	//localStorage.setItem('setstop', 1);	//Clear stop flag
	status_stop_pause = 1;
	
	$('#radio_schedule *').prop('disabled',true);
	$('#start_broadcast').hide();
	$('#pause_broadcast').show();
	$('#continue_broadcast').hide();
	$('#stop_broadcast').show();
	$('#radio_schedule *').prop('disabled',true);
	$('#lbl_schedule_ *').prop('disabled',true);
	
	$('#pause_broadcast').text('   pause');
	$('#stop_broadcast').text('   stop');
	

	iProgressAllItemsCount=0;
	acc_all_count=0;
	inactive_friends_count=0;
	problem_userId_count=0;
	active_friends_count=0;
	itemsSendErrorCount=0;
	iTableAllItems=0;
	prev_friend_loop=-1;
	memberSendErrorCount=0;
	iMessNumberActive=0;
	iTotalMesageMustSend=0;
	iSendFriendsCount=0;
	iCountAgv=0;
	lineCSRF="";
	tot_send_items_count=0;
	tot_send_friends_count=0;
	
	count_send_bubble_completed_iterate=0;
	count_send_person_completed_iterate=0
	
	iProgress = 0;

	label_user_inactive=[];
	label_user_id_problem=[];
	ct_tf_label_user_all_send_success=[];

	page_count=0;
	title = "";
	
	var elem = document.getElementById("myProgress");
	
	if(typeof elem!=="undefined" && elem!=null){
		elem.style.display="block";
	}
	////////////////////////////////////
	
	//count_my_broadcastline_success = 0;
	get_request_page_info();
	 
	getAllItemsPromise().then(x => iTableAllItems=x);
	
	/*
	///// page id and pagetoken
	my_broadcastline_label_id = $('#my_broadcastline_idpage').val().split('|')[0];	//id
	my_broadcastline_idpage_token = $('#my_broadcastline_idpage').val().split('|')[1];	//token
	my_broadcastline_label_name = $('#my_broadcastline_idpage').val().split('|')[2];	//name
	
	////folder type
	my_broadcastline_folder_label_type = $('#cfg_recipients_option_folder').val().split('|')[0];
	my_broadcastline_folder_label_name = $('#cfg_recipients_option_folder').val().split('|')[1];
	my_broadcastline_folder_label_selectedIndex=document.getElementById("cfg_recipients_option_folder").selectedIndex;	//except tag
	*/
	
	/////preamble
	//// conclusion
	//text_spintext_Preamble = document.getElementById("text_spintext_Preamble").value;
	//text_spintext_Conclusion = document.getElementById("text_spintext_Conclusion").value;
	text_spintext_Preamble=$("#text_spintext_Preamble").val();
	text_spintext_Conclusion=$("#text_spintext_Conclusion").val();
	
	$('#txt_error_report').html("");
	//document.getElementById("txt_error_report").value="";
	//$('#txt_error_report').hide();
	//$('#error_x_report').html("A");
	//$('#error_x_report').hide();
	
	$('#error_x_report').hide();
	$('#error_report').show();
	$('#txt_error_report').hide();
	
	$('#modalWorkingDelay').show();
		
	clearSummary();
	
	title = 'กำลังรวบรวมคนจากเพจ ' + '<i style="font-weight:900;color:#00d6fc;">'+my_broadcastline_label_name+'</i>' + ' ชนิดโฟลเดอร์ : ' + '<i style="font-weight:900;color:#fc8600;">&nbsp;&nbsp;'+my_broadcastline_folder_label_name+'</i>'+'<i style="font-weight:900;color:#fc00b9;">&nbsp;&nbsp;(เริ่มต้น)</i>';
	iziToast.info({
		title: title,
		position: 'topLeft',
		timeout: 10000,
		message: '',
	});
	show_msg_report("","","2",title);
	
	let folder = ["ALL"];
	setTimeout(function () {
		//var url = 'https://graph.facebook.com/v2.6/me/conversations?fields=senders,unread_count&' + my_broadcastline_folder_label_type + '&limit=300&access_token=' + my_broadcastline_idpage_token;
		//Modified 2021/05/10
		//
		let url = 'https://m.facebook.com/messages/?pageNum=1&selectable&pageID=' + my_broadcastline_label_id;
		if ($('#cfg_recipients_option_folder').val().split('|')[0] == 'folder=page_done') {
			url = 'https://m.facebook.com/messages/?folder=action%3Aarchived&pageID=' + my_broadcastline_label_id;
			folder = ["ARCHIVED"];
		}else if ($('#cfg_recipients_option_folder').val().split('|')[0] == 'folder=inbox') {
			folder = ["INBOX"];
		} else {
			url = 'https://m.facebook.com/messages/?pageNum=1&selectable&pageID=' + my_broadcastline_label_id;
			folder = ["ALL"];
		}
		get_start_label_user('',true,0,false,folder);
	}, 100);
}

function get_request_page_info(){
	///// page id and pagetoken
	label_user_inactive=[];
	label_user_id_problem=[];
	ct_tf_label_user_all_send_success=[];
	page_count=0;
	
	try{
		my_broadcastline_label_id = $('#my_broadcastline_idpage').val().split('|')[0];	//id
		my_broadcastline_idpage_token = $('#my_broadcastline_idpage').val().split('|')[1];	//token
		my_broadcastline_label_name = $('#my_broadcastline_idpage').val().split('|')[2];	//name
		
		////folder type
		my_broadcastline_folder_label_type = $('#cfg_recipients_option_folder').val().split('|')[0];
		my_broadcastline_folder_label_name = $('#cfg_recipients_option_folder').val().split('|')[1];
		my_broadcastline_folder_label_selectedIndex=document.getElementById("cfg_recipients_option_folder").selectedIndex;	//except tag
	}catch(e){}
}

//Pull fan of fanpage
async function get_start_label_user(url,iswith_sendmsg,loop_index_members,is_continue,folder){
	//console.log("get start label user");
	let message = "";
	
	$('#pause_broadcast').show();
	$('#stop_broadcast').show();
	
	document.getElementById("get_fb_fanpage").disabled = true;
	
	if(is_continue==false){
		max_allow_archived_pages_counter = 0;
		is_process_archived = false;
	}
	showTimeStart();
	
	let manual_input_data = false;
	
	
	if($('#fanpage_inbox_friend_ids_send_input').val().replace('\n').trim()!='' && iswith_sendmsg==true && permission_extract_member==1){
		//generate input data;
		await generateInputData();
		if(label_user_all.length==0){
			setStopJob(0,false,3);
			status_running=false;
			show_msg_report("","","0",'<i style="font-weight:900;color:#14f200;">&nbsp;&nbsp;(ไม่สามารถ Generate รายการส่งได้)</i>');
			return;
		}
		manual_input_data = true;
	}else{
		label_user_all = label_user_all_copy;	//copy data from standby to active 
	}

	if(my_prev_broadcastline_label_id==my_broadcastline_label_id 
		&& my_prev_recipients_option_folder==my_broadcastline_folder_label_type 
		&& label_user_all.length>0
		&& my_prev_move_to_done_folder==false
		|| manual_input_data == true
		){
		
		let stop_pause_get_fanpage_next = localStorage.getItem('stop_pause_get_fanpage_next');	//check next page after press pause and continue
		//console.log(stop_pause_get_fanpage_next);
		if(typeof stop_pause_get_fanpage_next!=="undefined" && stop_pause_get_fanpage_next!=null && stop_pause_get_fanpage_next!="" && manual_input_data==false){
			if(stop_pause_get_fanpage_next!="Done"){
				url = stop_pause_get_fanpage_next;
				//console.log("1");
				get_label_user(url,iswith_sendmsg,loop_index_members,folder);
				return;
			}
		}
		
		active_friends_count=label_user_all.length;
		iTotalMesageMustSend=active_friends_count*iTableAllItems;
		cfg_max_recipients = $('#cfg_max_recipients').val();
		cfg_start_seding_no = $('#cfg_start_seding_no').val();
				
		cfg_max_recipients = Number(cfg_max_recipients);
		cfg_start_seding_no = Number(cfg_start_seding_no);
		
		if(cfg_max_recipients>active_friends_count || cfg_max_recipients<1){cfg_max_recipients = active_friends_count;}
		if(cfg_start_seding_no>cfg_max_recipients){cfg_start_seding_no=cfg_max_recipients;}
		if(cfg_start_seding_no<1){cfg_start_seding_no=1;}
		
		iTotalMesageMustSend=(cfg_max_recipients-cfg_start_seding_no+1)*iTableAllItems;
		
		message = 'รวบรวมคนที่จะส่งจากเพจ "' + '<i style="font-weight:900;color:#00d6fc;">'+my_broadcastline_label_name+'</i>' + '" ชนิดโฟลเดอร์ : ' + '<i style="font-weight:900;color:#fc8600;">&nbsp;&nbsp;'+my_broadcastline_folder_label_name+'</i>'+'&nbsp;จำนวนลูกเพจ<i style="font-weight:900;color:#fc00b9;">&nbsp;&nbsp;'+ label_user_all.length +'</i>&nbsp;คน';
		
		if (typeof iziToast != 'undefined') {
			try{
				iziToast.success({
					title: message+ '<i style="font-weight:900;color:#14f200;">&nbsp;&nbsp;สำเร็จ</i>',
					position: 'topLeft',
					timeout: 5000,
					message: '',
				});
			}catch(ex){}
		}
		
		document.getElementById("abpc").innerHTML = "Active "+active_friends_count+" /Blocked "+inactive_friends_count+ " /Problem "+ problem_userId_count+ " /Total "+ acc_all_count + " คน";
		
		show_msg_report("","","2",message+ '<i style="font-weight:900;color:#14f200;">&nbsp;&nbsp;(สำเร็จ)</i>');
		
		
		if(iswith_sendmsg){
			if(loop_index_members>0){
				//console.log("2");
				send_my_broadcastline_loop(loop_index_members);	//continue
			}else{
				//console.log("3");
				removeDownloadSuccessLink();
				send_my_broadcastline_loop(cfg_start_seding_no-1);	//start
			}
		}else{
			setStopJob(0,false,3);
			status_running=false;
			return;
		}
		
		
		return;
	}else{
	
		status_running=false;
		//localStorage.setItem('setstop', 1);	//Clear stop flag
		status_stop_pause = 1;
		
		if (typeof is_continue!=="undefined" && is_continue!=null){
		}else{
			is_continue=false;
		}
		if(is_continue==false){
			label_user_all = [];
			label_user_all_copy = [];
			active_friends_count = 0;
			//console.log("4");
			get_label_user(url,iswith_sendmsg,loop_index_members,folder);
		}else{
			//console.log("5");
			get_label_user(url,iswith_sendmsg,loop_index_members,folder);
		}
	}
}

//let before_page='';
var isflagall = 0;
function get_label_user(url,iswith_sendmsg,loop_index_members,folder,isFlagAll=0) {
	let message = "";
	let result_title = "";
	let result_mfsm = "";
	let result_msg = "";
	isflagall = isFlagAll;

	my_prev_broadcastline_label_id = "";
	my_prev_recipients_option_folder = "";

	if(my_broadcastline_label_id=="" || my_broadcastline_folder_label_type==""){
		setStopJob(0,false,0);
		status_running=false;
		if(my_broadcastline_label_id==""){
			alert("ไม่ได้ระบุเพจที่ต้องการดึงลูกเพจ");
			document.getElementById("my_broadcastline_idpage").focus();
		// }else if (my_broadcastline_idpage_token=="") {
		// 	alert("ไม่พบ Token ของ facebook หรือ Token ของเพจนี้ กรุณา ตรวจสอบการ Login facebook ก่อนอีกครั้ง");
		// 	document.getElementById("my_broadcastline_idpage").focus();
		}else if (my_broadcastline_folder_label_type=="") {
			alert("กรุณาระบุโฟลเดอร์ที่ต้องการส่ง");
			document.getElementById("cfg_recipients_option_folder").focus();
		}
		
		return;
	}
	if ( typeof status_stop_pause !=="undefined" && status_stop_pause!=null) {
		if(status_stop_pause==0 || status_stop_pause==2){	//0 stop	2 pause
			setStopClock();
			localStorage.setItem('stop_pause_get_fanpage_next', url);	//Clear stop flag
			var d=new Date();
			var esttime_date_format_str = d.getFullYear().toString()+"-"+padDigits(d.getMonth()+1,2)+"-"+padDigits(d.getDate(),2)+" "+padDigits(d.getHours(),2)+":"+padDigits(d.getMinutes(),2)+":"+padDigits(d.getSeconds(),2);
			document.getElementById("stop_time").innerHTML=(status_stop_pause==0?"หยุดทำงาน":"หยุดชั่วคราว")+" "+esttime_date_format_str;
			status_running=false;
			message = 'รวบรวมคนที่จะส่งจากเพจ "' + '<i style="font-weight:900;color:#00d6fc;">'+my_broadcastline_label_name+'</i>' + '" ชนิดโฟลเดอร์ : ' + '<i style="font-weight:900;color:#fc8600;">&nbsp;&nbsp;'+my_broadcastline_folder_label_name+'</i>'+'&nbsp;จำนวนลูกเพจ<i style="font-weight:900;color:#fc00b9;">&nbsp;&nbsp;'+ label_user_all.length +'</i>&nbsp;คน';
			show_msg_report("","","2",message+ '<i style="font-weight:900;color:#14f200;">&nbsp;&nbsp;('+(status_stop_pause==0?"หยุดทำงาน":"หยุดชั่วคราว")+')</i>');
			return;
		}
	}
	
	txt_error_report=document.getElementById('txt_error_report');

	if(iswith_sendmsg==false){
		iswith_sendmsg = false;
	}else{
		iswith_sendmsg = true;
	}
	
	my_prev_move_to_done_folder = false;	//reset move_to_done_folder flag
	loop_index_members = Number(loop_index_members);

	try{
		if(loop_index_members==0){
			deleteDownloadLink();
			$('#fanpage_inbox_friend_ids_send_input').val('');
			$('#download_fb_fanpage_members').hide();
			if(iswith_sendmsg==true){
				removeDownloadSuccessLink();
				$('#download_fb_fanpage_success_members').hide();
			}
			$('#get_fb_fanpage').hide();
			$('.processing').show();
		}
		
		/*
		$.getJSON(url, async function (results) {
			var data_fetch = results.data;
			var paging = results.paging;

			if(typeof data_fetch=="undefined" || data_fetch==null || data_fetch.length==0){
				try{
					iziToast.error({
						title: "ไม่สามารถโหลดหรือไม่พบเพื่อนที่จะส่งข้อความในโฟลเดอร์ "+my_broadcastline_folder_label_name+" นี้ให้ได้",
						position: 'topLeft',
						timeout: 3000,
						message: '',
					});
				}catch(ex){}
				let elem = document.getElementById("myProgress");
				if(typeof elem!=="undefined"){
					if (elem!==null){
						elem.style.display="none";
					}
				}
				setStopJob(0,false,0);
				status_running=false;
				return;
			}

			page_count++;
			
			title = 'กำลังรวบรวมคนจากเพจ ' + '<i style="font-weight:900;color:#00d6fc;">'+my_broadcastline_label_name+'</i>' + ' ชนิดโฟลเดอร์ : ' + '<i style="font-weight:900;color:#fc8600;">&nbsp;&nbsp;'+my_broadcastline_folder_label_name+'</i>'+'<i>&nbsp;page no:'+(page_count+1) + '</i>';
			
			add_fb_page_members(data_fetch,iswith_sendmsg);
			
			active_friends_count = label_user_all.length;
			
			is_process_archived == false;
			
			//if (typeof paging != 'undefined' && paging!=null && typeof paging.next != 'undefined') {
			if ((typeof paging != 'undefined' && paging!=null && typeof paging.next != 'undefined' && is_process_archived==false) 
				|| (max_allow_archived_pages>0 && max_allow_archived_pages_counter>0) ) {
				try{
					iziToast.info({
						title: '',
						position: 'topLeft',
						timeout: 1000,
						message: title + 'รอสักครู่ กำลังรวบรวม page no:'+(page_count+1) + " ถึงคนที่: " + active_friends_count + " ",
					});
				}catch(ex){}
				
				setTimeout(function () {
					if(is_process_archived && max_allow_archived_pages_counter>0){
						max_allow_archived_pages_counter--;
						
					}
					get_label_user(paging.next,iswith_sendmsg,loop_index_members);
				}, 100);
			} else {
				is_process_archived=true;
				max_allow_archived_pages_counter = max_allow_archived_pages;
				if (url.indexOf('folder=page_done') > -1) {
					if (label_user_all.length == 0) {
						my_broadcastline_folder_label_type = "folder=page_done&tags=action:archived";
						var url_page_done = url.replace("folder=page_done", "tags=action:archived");
						setTimeout(function () {
							get_label_user(url_page_done,iswith_sendmsg,loop_index_members);
						}, 100);
						return false;
					}
				}else if (url.indexOf('tags=action:archived') > -1) {
					if (label_user_all.length > 0) {
						let unique = [...new Set(label_user_all.map(item => item.id))];
						
						label_user_all=[];
						label_user_all = unique;
						unique = [];
						active_friends_count = label_user_all.length;
					}
				}else if (my_broadcastline_folder_label_type=="folder=page_done"){
						my_broadcastline_folder_label_type = "folder=page_done&tags=action:archived";
						var url_page_done = 'https://graph.facebook.com/v2.6/me/conversations?fields=senders,unread_count&tags=action:archived&limit=300&access_token=' + my_broadcastline_idpage_token;
						setTimeout(function () {
							get_label_user(url_page_done,iswith_sendmsg,loop_index_members);
						}, 100);
						return false;
				}else if (my_broadcastline_folder_label_type=="folder=page_done&tags=action:archived"){
						my_broadcastline_folder_label_type = "folder=page_done";
						if (label_user_all.length > 0) {
							//let unique = [...new Set(label_user_all.map(item => item.id))];
							
							let unique = [];
							const map = new Map();
							for (const item of label_user_all) {
								if(!map.has(item.id)){
									map.set(item.id, true);    // set any value to Map
									if (typeof item.id != 'undefined') {
										if (typeof item.name != 'undefined') {
											if (item.name != '') {
												
												unique.push({
													'id': item.id,
													'name': item.name
												});
												
											}
										}
									}
								}
							}
							
							label_user_all=[];
							label_user_all = unique;
							unique = [];
							active_friends_count = label_user_all.length;
						}
				}
				
				//finished collect member
				message = 'รวบรวมคนที่จะส่งจากเพจ "' + '<i style="font-weight:900;color:#00d6fc;">'+my_broadcastline_label_name+'</i>' + '" ชนิดโฟลเดอร์ : ' + '<i style="font-weight:900;color:#fc8600;">&nbsp;&nbsp;'+my_broadcastline_folder_label_name+'</i>'+'&nbsp;จำนวนลูกเพจ<i style="font-weight:900;color:#fc00b9;">&nbsp;&nbsp;'+ label_user_all.length +'</i>&nbsp;คน';
				
				if (typeof iziToast != 'undefined') {
					try{
						iziToast.success({
							title: message+ '<i style="font-weight:900;color:#14f200;">&nbsp;&nbsp;สำเร็จ</i>',
							position: 'topLeft',
							timeout: 5000,
							message: '',
						});
					}catch(ex){}
				}
				if(isToastGetMemberInboxPageShow){
					var modalGrAlert = document.getElementById("modalGrAlert");
					modalGrAlert.style.display = "block";
					var modal_alert_content = document.getElementById("modal_alert_content");
					title = 'เพจ: ' + my_broadcastline_label_name + ' ' + my_broadcastline_folder_label_name+' หน้า: '+(page_count+1);
					modal_alert_content.innerHTML=title + " คนที่ " + label_user_all.length +" สำเร็จ";
				}
				document.getElementById("abpc").innerHTML = "Active "+active_friends_count+" /Blocked "+inactive_friends_count+ " /Problem "+ problem_userId_count+ " /Total "+ acc_all_count + " คน";

				localStorage.setItem('stop_pause_get_fanpage_next', "Done");	//Clear stop flag
				
				if(label_user_all.length>0){
					let elem = document.getElementById("myProgress");
					if(typeof elem!="undefined"){
						if (elem!==null){
							elem.style.display="block";
						}
					}
					
					my_prev_broadcastline_label_id = my_broadcastline_label_id;
					my_prev_recipients_option_folder = my_broadcastline_folder_label_type;
					
					cfg_max_recipients = $('#cfg_max_recipients').val();
					cfg_start_seding_no = $('#cfg_start_seding_no').val();
							
					cfg_max_recipients = Number(cfg_max_recipients);
					cfg_start_seding_no = Number(cfg_start_seding_no);
					
					if(cfg_max_recipients>active_friends_count || cfg_max_recipients<1){cfg_max_recipients = active_friends_count;}
					if(cfg_start_seding_no>cfg_max_recipients){cfg_start_seding_no=cfg_max_recipients;}
					if(cfg_start_seding_no<1){cfg_start_seding_no=1;}
					
					show_msg_report("","","2",message+ '<i style="font-weight:900;color:#14f200;">&nbsp;&nbsp;(สำเร็จ)</i>');
					
					if(iswith_sendmsg){
						if(loop_index_members>0){
							send_my_broadcastline_loop(loop_index_members);	//continue
						}else{
							send_my_broadcastline_loop(Number(cfg_start_seding_no)-1);	//start
						}
					}else{
						var d=new Date();
						var esttime_date_format_str = d.getFullYear().toString()+"-"+padDigits(d.getMonth()+1,2)+"-"+padDigits(d.getDate(),2)+" "+padDigits(d.getHours(),2)+":"+padDigits(d.getMinutes(),2)+":"+padDigits(d.getSeconds(),2);
						document.getElementById("stop_time").innerHTML="เสร็จ "+" "+esttime_date_format_str;
						setStopJob(0,false,3);
						status_running=false;
						showStartButton();
						return;
					}
					
				}else{
					try{
						iziToast.error({
							title: "ไม่สามารถโหลดหรือไม่พบเพื่อนที่จะส่งข้อความในโฟลเดอร์ "+my_broadcastline_folder_label_name+" นี้ให้ได้",
							position: 'topLeft',
							timeout: 3000,
							message: '',
						});
					}catch(ex){}
					show_msg_report("","","2","ไม่สามารถโหลดหรือไม่พบเพื่อนที่จะส่งข้อความในโฟลเดอร์นี้ "+  my_broadcastline_folder_label_name+ '<i style="font-weight:900;color:#red;">&nbsp;&nbsp;(ไม่สำเร็จ)</i>');
					
					localStorage.setItem('stop_pause_get_fanpage_next', "");	//Clear stop flag
			
					let elem = document.getElementById("myProgress");
					if(typeof elem!=="undefined"){
						if (elem!==null){
							elem.style.display="none";
						}
					}
					setStopJob(0,false,0);
					status_running=false;
					return;
				}
			}
		}).fail(function(jqXHR, textStatus, errorThrown){
			console.dir(jqXHR);
			console.log(textStatus);
			console.log(errorThrown);
			console.log(jqXHR.status);
			//console.log(jqXHR.response);
			//console.log(jqXHR.responseText)
			//console.log(jqXHR.statusText);
			
			try{
				iziToast.error({
					title: "ไม่สามารถโหลดเพื่อนที่จะส่งข้อความให้ได้  บางที internet อาจขัดข้อง หรือ Connection หลุดระหว่างดึงลูกเพจ "+textStatus + " " + errorThrown,
					position: 'topLeft',
					timeout: 3000,
					message: '',
				});
			}catch(ex){}
			show_msg_report("","","2", "" + '<i style="font-weight:900;color:red;">ไม่สามารถโหลดเพื่อนที่จะส่งข้อความให้ได้  บางที internet อาจขัดข้อง หรือ Connection หลุดระหว่างดึงลูกเพจ ' + textStatus + " " + errorThrown+' </i>');
			setStopJob(0,false,0);
			status_running=false;
			Swal.fire({
				title: 'เกิดข้อผิดพลาด',
				type: 'error',
				html: 'รวบรวมคนที่จะส่ง error หรือบางที internet อาจมีปัญหา,  หรือไม่ได้รับอนุญาติเป็นผู้ดูแล page หรือคุณใช้บัญชีธุรกิจอยู่, <br /> หรือลอง รีเฟรซหน้าเฟสบุ๊กดูอีกที เนื่องจาก connection หลุดขณะดึงลูกเพจ<br />'+textStatus + " " + errorThrown,
			});
			return;
		});
		*/
		
		/////////////////////////////////////////////////////////////
		/////////////////////////////////////////////////////////////
		//Modified on 2021/05/10
		// console.log(`รวมคน url: `+url);
		// $.ajax({
		// 	type: "GET",
		// 	url: url,
		// 	//complete: function(response) {
		// 		//let data_fetch = response.responseText;
		// 	success: async function(data_fetch) {
		// 		//handle success
		// 		//let data_fetch = response.responseText;
		// 		if(typeof data_fetch=="undefined" || data_fetch==null || data_fetch.length==0){
		// 			try{
		// 				iziToast.error({
		// 					title: "ไม่สามารถโหลดหรือไม่พบเพื่อนที่จะส่งข้อความในโฟลเดอร์ "+my_broadcastline_folder_label_name+" นี้ให้ได้",
		// 					position: 'topLeft',
		// 					timeout: 3000,
		// 					message: '',
		// 				});
		// 			}catch(ex){}
		// 			let elem = document.getElementById("myProgress");
		// 			if(typeof elem!=="undefined"){
		// 				if (elem!==null){
		// 					elem.style.display="none";
		// 				}
		// 			}
		// 			setStopJob(0,false,0);
		// 			status_running=false;
		// 			return;
		// 		}
				
		// 		page_count++;
			
		// 		title = 'กำลังรวบรวมคนจากเพจ ' + '<i style="font-weight:900;color:#00d6fc;">'+my_broadcastline_label_name+'</i>' + ' ชนิดโฟลเดอร์ : ' + '<i style="font-weight:900;color:#fc8600;">&nbsp;&nbsp;'+my_broadcastline_folder_label_name+'</i>'+'<i>&nbsp;page no:'+(page_count+1) + '</i>';

		// 		await add_fb_page_members(data_fetch,iswith_sendmsg);
		// 		active_friends_count = label_user_all.length;
				
		// 		//console.log("13");
				
		// 		let thread_paging = data_fetch.match(/see_older_threads",href(.+)/)
		// 		let paging = "";
		// 		if (typeof thread_paging != 'undefined' && thread_paging != null && thread_paging!="") {
		// 			paging = 'https://m.facebook.com/' + thread_paging[0].replace('see_older_threads",href:"/', '').split('paipv=1')[0] + 'paipv=1';
		// 		}
				
		// 		//////////////////
		// 		if (paging!="") {
		// 				try{
		// 					iziToast.info({
		// 						title: '',
		// 						position: 'topLeft',
		// 						timeout: 1000,
		// 						message: title + 'รอสักครู่ กำลังรวบรวม page no:'+(page_count+1) + " ถึงคนที่: " + active_friends_count + " ",
		// 					});
		// 				}catch(ex){}
						
		// 				setTimeout(function () {
		// 					get_label_user(paging,iswith_sendmsg,loop_index_members,tags);
		// 					return;
		// 				}, 50);
		// 				return;
		// 		}else{
		// 			let b_title = data_fetch.indexOf('<title>');
		// 			if(b_title>=0){
		// 				let c_title = data_fetch.indexOf('</title>',b_title+7);
		// 				if(c_title>b_title){
		// 					result_title = " " + data_fetch.substring(b_title+7, c_title);
		// 					console.log(result_title);
		// 					result_msg = result_title;
		// 				}

		// 				let d_mfsm = data_fetch.indexOf('<span class="mfsm">');
		// 				if(d_mfsm>=0){
		// 					let e_mfsm = data_fetch.indexOf('</span>',d_mfsm+19);
		// 					if(e_mfsm>d_mfsm){
		// 						result_mfsm =" "+ data_fetch.substring(d_mfsm+19,e_mfsm+7);
		// 						console.log(result_mfsm);
		// 						result_msg += result_mfsm;
		// 					}
		// 				}
		// 			}
		// 		}
				

		// 		//finished collect member
		// 		label_user_all = uniqueByKey(label_user_all, 'id');	//make unique by key
		// 		label_user_all_copy = label_user_all;	//copy data
		// 		active_friends_count = label_user_all.length;

		// 		message = 'รวบรวมคนที่จะส่งจากเพจ "' + '<i style="font-weight:900;color:#00d6fc;">'+my_broadcastline_label_name+'</i>' + '" ชนิดโฟลเดอร์ : ' + '<i style="font-weight:900;color:#fc8600;">&nbsp;&nbsp;'+my_broadcastline_folder_label_name+'</i>'+'&nbsp;จำนวนลูกเพจ<i style="font-weight:900;color:#fc00b9;">&nbsp;&nbsp;'+ label_user_all.length +'</i>&nbsp;คน'+result_msg;
				
		// 		if (typeof iziToast != 'undefined') {
		// 			try{
		// 				iziToast.success({
		// 					title: message+ '<i style="font-weight:900;color:#14f200;">&nbsp;&nbsp;สำเร็จ</i>',
		// 					position: 'topLeft',
		// 					timeout: 5000,
		// 					message: '',
		// 				});
		// 			}catch(ex){}
		// 		}
		// 		if(isToastGetMemberInboxPageShow){
		// 			var modalGrAlert = document.getElementById("modalGrAlert");
		// 			modalGrAlert.style.display = "block";
		// 			var modal_alert_content = document.getElementById("modal_alert_content");
		// 			title = 'เพจ: ' + my_broadcastline_label_name + ' ' + my_broadcastline_folder_label_name+' หน้า: '+(page_count+1);
		// 			modal_alert_content.innerHTML=title + " คนที่ " + label_user_all.length +" สำเร็จ";
		// 		}
		// 		document.getElementById("abpc").innerHTML = "Active "+active_friends_count+" /Blocked "+inactive_friends_count+ " /Problem "+ problem_userId_count+ " /Total "+ acc_all_count + " คน";

		// 		localStorage.setItem('stop_pause_get_fanpage_next', "Done");	//Clear stop flag

		// 		if(label_user_all.length>0){
		// 			let elem = document.getElementById("myProgress");
		// 			if(typeof elem!="undefined"){
		// 				if (elem!==null){
		// 					elem.style.display="block";
		// 				}
		// 			}
					
		// 			my_prev_broadcastline_label_id = my_broadcastline_label_id;
		// 			my_prev_recipients_option_folder = my_broadcastline_folder_label_type;
					
		// 			cfg_max_recipients = $('#cfg_max_recipients').val();
		// 			cfg_start_seding_no = $('#cfg_start_seding_no').val();
							
		// 			cfg_max_recipients = Number(cfg_max_recipients);
		// 			cfg_start_seding_no = Number(cfg_start_seding_no);
					
		// 			if(cfg_max_recipients>active_friends_count || cfg_max_recipients<1){cfg_max_recipients = active_friends_count;}
		// 			if(cfg_start_seding_no>cfg_max_recipients){cfg_start_seding_no=cfg_max_recipients;}
		// 			if(cfg_start_seding_no<1){cfg_start_seding_no=1;}
					
		// 			show_msg_report("","","2",message+ '<i style="font-weight:900;color:#14f200;">&nbsp;&nbsp;(สำเร็จ)</i>' + result_msg);
					
		// 			$('#download_fb_fanpage_members').show();

		// 			if(iswith_sendmsg){
		// 				$('.processing').hide();
		// 				if(loop_index_members>0){
		// 					//console.log("6");
		// 					//console.log(label_user_all.length);
		// 					send_my_broadcastline_loop(loop_index_members);	//continue
		// 				}else{
		// 					//console.log("7");
		// 					//console.log(label_user_all.length);
		// 					send_my_broadcastline_loop(Number(cfg_start_seding_no)-1);	//start
		// 				}
		// 			}else{
		// 				var d=new Date();
		// 				var esttime_date_format_str = d.getFullYear().toString()+"-"+padDigits(d.getMonth()+1,2)+"-"+padDigits(d.getDate(),2)+" "+padDigits(d.getHours(),2)+":"+padDigits(d.getMinutes(),2)+":"+padDigits(d.getSeconds(),2);
		// 				document.getElementById("stop_time").innerHTML="เสร็จ "+" "+esttime_date_format_str;
		// 				setStopJob(0,false,3);
		// 				status_running=false;
		// 				showStartButton();
		// 				$('#get_fb_fanpage').show();
		// 				$('.processing').hide();
		// 				return;
		// 			}
					
		// 		}else{
		// 			$('#download_fb_fanpage_members').hide();
		// 			$('#get_fb_fanpage').show();
		// 			$('.processing').hide();
		// 			try{
		// 				iziToast.error({
		// 					title: "ไม่สามารถโหลดหรือไม่พบเพื่อนที่จะส่งข้อความในโฟลเดอร์ "+my_broadcastline_folder_label_name+" นี้ให้ได้",
		// 					position: 'topLeft',
		// 					timeout: 3000,
		// 					message: '',
		// 				});
		// 			}catch(ex){}
		// 			show_msg_report("","","2","ไม่สามารถโหลดหรือไม่พบเพื่อนที่จะส่งข้อความในโฟลเดอร์นี้ "+  my_broadcastline_folder_label_name+ '<i style="font-weight:900;color:#red;">&nbsp;&nbsp;(ไม่สำเร็จ)</i>'+result_msg);
					
		// 			localStorage.setItem('stop_pause_get_fanpage_next', "");	//Clear stop flag
			
		// 			let elem = document.getElementById("myProgress");
		// 			if(typeof elem!=="undefined"){
		// 				if (elem!==null){
		// 					elem.style.display="none";
		// 				}
		// 			}
		// 			setStopJob(0,false,0);
		// 			status_running=false;
		// 			return;
		// 		}
		// 	},
		// 	error: function(jqXHR, textStatus, errorThrown) {
		// 		//handle error
		// 		//console.dir(jqXHR);
		// 		//console.log(textStatus);
		// 		//console.log(errorThrown);
		// 		//console.log(jqXHR.status);
		// 		$('#get_fb_fanpage').show();
		// 		$('.processing').hide();
		// 		try{
		// 			iziToast.error({
		// 				title: "ไม่สามารถโหลดเพื่อนที่จะส่งข้อความให้ได้  บางที internet อาจขัดข้อง หรือ Connection หลุดระหว่างดึงลูกเพจ "+textStatus + " " + errorThrown,
		// 				position: 'topLeft',
		// 				timeout: 3000,
		// 				message: '',
		// 			});
		// 		}catch(ex){}
		// 		show_msg_report("","","2", "" + '<i style="font-weight:900;color:red;">ไม่สามารถโหลดเพื่อนที่จะส่งข้อความให้ได้  บางที internet อาจขัดข้อง หรือ Connection หลุดระหว่างดึงลูกเพจ ' + textStatus + " " + errorThrown+' </i>');

		// 		setStopJob(0,false,0);
		// 		status_running=false;
		// 		Swal.fire({
		// 			title: 'เกิดข้อผิดพลาด',
		// 			type: 'error',
		// 			html: 'รวบรวมคนที่จะส่ง error หรือบางที internet อาจมีปัญหา,  หรือไม่ได้รับอนุญาติเป็นผู้ดูแล page หรือคุณใช้บัญชีธุรกิจอยู่, <br /> หรือลอง รีเฟรซหน้าเฟสบุ๊กดูอีกที เนื่องจาก connection หลุดขณะดึงลูกเพจ<br />'+textStatus + " " + errorThrown,
		// 		});
		// 		return;
		// 	}
		// });

		////////////////
		/////////////////////////////////////////////////////////////
		/////////////////////////////////////////////////////////////
		//Modified on 2024/02/21
		const now = new Date().getTime(); // get the current timestamp in milliseconds
		const filter_datestart = now - (1.5 * 365 * 24 * 60 * 60 * 1000); // calculate the timestamp for 1.5 year ago

		let tags = ['INBOX'];
		if(folder[0]=='ALL'){
			if (isFlagAll == 1) {
				tags = ["ARCHIVED"];
			} else{
				//send inbox first
				tags = ["INBOX"];
			}
		}else {
			tags = folder;
		}
		let data = '';
		if (url !== '') {
			data = {
				batch_name: "MessengerGraphQLThreadlistFetcher",
				__user: fb_user_id,
				__a: "1",
				fb_dtsg: fb_dtsg,
				jazoest: jazoest,
				av: my_broadcastline_label_id,
				queries: JSON.stringify({
					o0: {
						doc_id: "5947328892029037",	//4593263290776700
						query_params: {
							before: url,
							includeDeliveryReceipts: true,
							includeSeqID: false,
							is_work_teamwork_not_putting_muted_in_unreads: false,
							isWorkUser: false,
							limit: 20,
							source: "mercury",
							tags: tags,
							threadlistViewFieldsOnly: false,
						},
					},
				}),
			};
		} else {
			data = {
				batch_name: "MessengerGraphQLThreadlistFetcher",
				__user: fb_user_id,
				__a: "1",
				fb_dtsg: fb_dtsg,
				jazoest: jazoest,
				av: my_broadcastline_label_id,
				queries: JSON.stringify({
					o0: {
						doc_id: "5947328892029037",	//4593263290776700
						query_params: {
							before: (new Date()).getTime(),
							includeDeliveryReceipts: true,
							includeSeqID: false,
							is_work_teamwork_not_putting_muted_in_unreads: false,
							isWorkUser: false,
							limit: 20,
							source: "mercury",
							tags: tags,
							threadlistViewFieldsOnly: false,
						},
					},
				}),
			};
		}
		$.ajax({
			url: "https://www.facebook.com/api/graphqlbatch/",
			type: "POST",
			data: data,
			complete: async function(data) {
				////////////////////ดึงข้อมูล///////////////////
				const data2 = data.responseText.replace('for (;;);','');
				data = data2.replace('{"successful_results":1,"error_results":0,"skipped_results":0}', '');
				console.log(data);
				data = JSON.parse(data);
				if(data?.error){
					if(data?.errorDescription){
						console.log("getF", data?.error)
						Swal.fire({
							title: 'มีปัญหา',
							html: "ไม่สามารถดึงข้อมูลแฟนเพจได้ โปรดตรวจสอบการ login facebook หรือปิดแล้วเปิดโปรแกรมอีกที หรือสลับ facebook เป็นโปรไฟล์ตัวเอง แล้วลองเปิดโปแกรมใหม่อีกรอบ <br /> "+ data?.error + ':' + data?.errorDescription,
							icon: 'error',
							confirmButtonColor: '#3085d6',
							confirmButtonText: 'OK'
						});

						//stopRequest = true
						setStopJob(0,false,0);
						status_running=false;
						showStartButton();
						$('#get_fb_fanpage').show();
						$('.processing').hide();
						return;
					}
				}

				let o0 = data.o0;
				let viewer = o0.data.viewer;
				let nodes = viewer.message_threads.nodes;
				if (typeof nodes != 'undefined') {
					if (typeof nodes != 'undefined') {
						
						page_count++;
			
						title = 'กำลังรวบรวมคนจากเพจ ' + '<i style="font-weight:900;color:#00d6fc;">'+my_broadcastline_label_name+'</i>' + ' ชนิดโฟลเดอร์ : ' + '<i style="font-weight:900;color:#fc8600;">&nbsp;&nbsp;'+my_broadcastline_folder_label_name+'</i>'+'<i>&nbsp;page no:'+(page_count+1) + '</i>';

						await add_fb_page_members_v2(nodes,iswith_sendmsg);
						active_friends_count = label_user_all.length;
						
						// $.each(nodes, function(i, data_nodes) {
						// 	if (data_nodes.all_participants.edges[0].node.messaging_actor.id != 'undefined') {
						// 		let id = '';
						// 		if (data_nodes.all_participants.edges[0].node.messaging_actor.id != 'undefined') {
						// 			/////////////////////////////////////////
						// 			id = data_nodes.all_participants.edges[0].node.messaging_actor.id;
						// 			let name = '';
						// 			if (typeof data_nodes.all_participants.edges[0].node.messaging_actor.name != 'undefined') {
						// 				name = data_nodes.all_participants.edges[0].node.messaging_actor.name;
						// 			}


						// 			// let ids_tags = $('#adverra_premium_broadcastbylabel_tags').val().toString().split(",");
						// 			// ihave_tags = 0;
						// 			// if (ids_tags != '') {
						// 			// 	// ค้นหา ID ใน "custom_thread_labels" ของ "related_page_thread" โดยใช้ jQuery.each() และ $.grep()
						// 			// 	if (data_nodes.related_page_thread !== null && data_nodes.related_page_thread.custom_thread_labels !== null) {
						// 			// 		$.each(data_nodes.related_page_thread.custom_thread_labels.nodes, function(index, label) {
						// 			// 			var label_id = label.id;
						// 			// 			if (label_id != null) {
						// 			// 				var matching_id = $.grep(ids_tags, function(idxx) {
						// 			// 					return idxx === label_id;
						// 			// 				});
						// 			// 				if (matching_id.length > 0) {
						// 			// 					ihave_tags = 1;
						// 			// 				}
						// 			// 			}
						// 			// 		});
						// 			// 	}
						// 			// 	if (data_nodes.related_page_thread !== null && data_nodes.related_page_thread.corp_thread_labels !== null) {
						// 			// 		$.each(data_nodes.related_page_thread.corp_thread_labels.nodes, function(index, label) {
						// 			// 			var label_id = label.id;
						// 			// 			if (label_id != null) {
						// 			// 				var matching_id = $.grep(ids_tags, function(idxx) {
						// 			// 					return idxx === label_id;
						// 			// 				});
						// 			// 				if (matching_id.length > 0) {
						// 			// 					ihave_tags = 1;
						// 			// 				}
						// 			// 			}
						// 			// 		});
						// 			// 	}
						// 			// 	if (data_nodes.related_page_thread !== null && data_nodes.related_page_thread.custom_thread_tags !== null) {
						// 			// 		$.each(data_nodes.related_page_thread.custom_thread_tags.nodes, function(index, label) {
						// 			// 			var label_id = label.id;
						// 			// 			if (label_id != null) {
						// 			// 				var matching_id = $.grep(ids_tags, function(idxx) {
						// 			// 					return idxx === label_id;
						// 			// 				});
						// 			// 				if (matching_id.length > 0) {
						// 			// 					ihave_tags = 1;
						// 			// 				}
						// 			// 			}
						// 			// 		});
						// 			// 	}
						// 			// 	if (ihave_tags == 1) {
						// 			// 	} else {
						// 			// 		id = '';
						// 			// 	}
						// 			// } else {
						// 			// }


						// 			//if ($('#message_unsendability_status').prop("checked") == true) {
						// 				let now = new Date().getTime(); // get the current timestamp in milliseconds
						// 				let yearAgo = now - (1.5 * 365 * 24 * 60 * 60 * 1000); // calculate the timestamp for 1.5 year ago
						// 				if (data_nodes.cannot_reply_reason != null) {
						// 					id = '';
						// 				}
						// 				if (data_nodes.last_message.nodes[0].message_unsendability_status != 'can_unsend') {
						// 					id = '';
						// 				}
						// 				if (data_nodes.thread_unsendability_status == 'deny_if_canonical_thread_contains_blocked_users') {
						// 					id = '';
						// 				}
						// 				if (typeof data_nodes.last_message.nodes[0].timestamp_precise != 'undefined') {
						// 					if (data_nodes.last_message.nodes[0].timestamp_precise < yearAgo) {
						// 						id = '';
						// 					}
						// 				}
						// 			//}

						// 			//Filter
						// 			// if ($('#followup').prop("checked") == true) {
						// 			// 	if ($.inArray("FOLLOW_UP", data_nodes.page_comm_item.biz_inbox_tags) !== -1) { //ถ้าเจอ floowup
						// 			// 	} else {
						// 			// 		id = '';
						// 			// 	}
						// 			// }
						// 			// if ($("#gender_male").val() == 'MALE') { //เพศชาย
						// 			// 	if (data_nodes.all_participants.edges[0].node.messaging_actor.gender == 'MALE') {
						// 			// 	} else {
						// 			// 		id = '';
						// 			// 	}
						// 			// } else
						// 			// if ($("#gender_female").val() == 'FEMALE') { //เพศหญิง
						// 			// 	if (data_nodes.all_participants.edges[0].node.messaging_actor.gender == 'FEMALE') {
						// 			// 	} else {
						// 			// 		id = '';
						// 			// 	}
						// 			// }
						// 			// if ($('#unread_count').prop("checked") == true) { //อ่านข้อความแล้ว					
						// 			// 	if (data_nodes.unread_count == 0) {
						// 			// 	} else {
						// 			// 		id = '';
						// 			// 	}
						// 			// }

						// 			let timestamp = '';
						// 			if (typeof data_nodes.last_message.nodes[0].timestamp_precise != 'undefined') {
						// 				timestamp = data_nodes.last_message.nodes[0].timestamp_precise;
						// 				if (filter_datestart > timestamp) {
						// 					id = '';
						// 				}
						// 			}

						// 			if (id != '') {
						// 				if (label_user_all_c.indexOf(id) === -1) {
						// 					label_user_all.push({
						// 						'id': id,
						// 						'name': name
						// 					});
						// 					label_user_all_c.push(id);
						// 				}
						// 			}
						// 		}
						// 	}
						// });

					}
				}
				
				
				title = 'ดึงแล้ว ' + active_friends_count + ' คน<br>รอสักครู่...<br>';
				if ((nodes.length >= 20) && (filter_datestart < nodes[(nodes.length - 1)].last_message.nodes[0].timestamp_precise)) {
					iziToast.info({
						title: 'กำลังดึงข้อมุล',
						position: 'topRight',
						timeout: 1000,
						message: title,
					});
					
					setTimeout(function() {
						url = nodes[(nodes.length - 1)].last_message.nodes[0].timestamp_precise;
						get_label_user(url, iswith_sendmsg, loop_index_members++, tags)
					}, 100);
				} else {
					message = 'รวบรวมคนที่จะส่ง ' + label_user_all.length + ' คน';
					iziToast.success({
						title: message,
						position: 'topRight',
						timeout: 3000,
						message: 'Success',
					});
					//console.log(label_user_all);
					if (tags[0] == 'ALL') {
						if (isFlagAll == 0) {
							get_label_user(url, iswith_sendmsg, loop_index_members++, tags,1);
							return;
						} else {
							//send_premium_broadcastbylabel(premium_broadcastbylabel_startnumber);
						}
					} else {
						//send_premium_broadcastbylabel(premium_broadcastbylabel_startnumber);
					}

					//finished collect member
					label_user_all = uniqueByKey(label_user_all, 'id');	//make unique by key
					label_user_all_copy = label_user_all;	//copy data
					active_friends_count = label_user_all.length;

					message = 'รวบรวมคนที่จะส่งจากเพจ "' + '<i style="font-weight:900;color:#00d6fc;">'+my_broadcastline_label_name+'</i>' + '" ชนิดโฟลเดอร์ : ' + '<i style="font-weight:900;color:#fc8600;">&nbsp;&nbsp;'+my_broadcastline_folder_label_name+'</i>'+'&nbsp;จำนวนลูกเพจ<i style="font-weight:900;color:#fc00b9;">&nbsp;&nbsp;'+ label_user_all.length +'</i>&nbsp;คน'+result_msg;
					
					if (typeof iziToast != 'undefined') {
						try{
							iziToast.success({
								title: message+ '<i style="font-weight:900;color:#14f200;">&nbsp;&nbsp;สำเร็จ</i>',
								position: 'topLeft',
								timeout: 5000,
								message: '',
							});
						}catch(ex){}
					}
					if(isToastGetMemberInboxPageShow){
						var modalGrAlert = document.getElementById("modalGrAlert");
						modalGrAlert.style.display = "block";
						var modal_alert_content = document.getElementById("modal_alert_content");
						title = 'เพจ: ' + my_broadcastline_label_name + ' ' + my_broadcastline_folder_label_name+' หน้า: '+(page_count+1);
						modal_alert_content.innerHTML=title + " คนที่ " + label_user_all.length +" สำเร็จ";
					}
					document.getElementById("abpc").innerHTML = "Active "+active_friends_count+" /Blocked "+inactive_friends_count+ " /Problem "+ problem_userId_count+ " /Total "+ acc_all_count + " คน";

					localStorage.setItem('stop_pause_get_fanpage_next', "Done");	//Clear stop flag

					if(label_user_all.length>0){
						let elem = document.getElementById("myProgress");
						if(typeof elem!="undefined"){
							if (elem!==null){
								elem.style.display="block";
							}
						}
						
						my_prev_broadcastline_label_id = my_broadcastline_label_id;
						my_prev_recipients_option_folder = my_broadcastline_folder_label_type;
						
						cfg_max_recipients = $('#cfg_max_recipients').val();
						cfg_start_seding_no = $('#cfg_start_seding_no').val();
								
						cfg_max_recipients = Number(cfg_max_recipients);
						cfg_start_seding_no = Number(cfg_start_seding_no);
						
						if(cfg_max_recipients>active_friends_count || cfg_max_recipients<1){cfg_max_recipients = active_friends_count;}
						if(cfg_start_seding_no>cfg_max_recipients){cfg_start_seding_no=cfg_max_recipients;}
						if(cfg_start_seding_no<1){cfg_start_seding_no=1;}
						
						show_msg_report("","","2",message+ '<i style="font-weight:900;color:#14f200;">&nbsp;&nbsp;(สำเร็จ)</i>' + result_msg);
						
						$('#download_fb_fanpage_members').show();

						if(iswith_sendmsg){
							$('.processing').hide();
							if(loop_index_members>0){
								//console.log("6");
								//console.log(label_user_all.length);
								send_my_broadcastline_loop(loop_index_members);	//continue
							}else{
								//console.log("7");
								//console.log(label_user_all.length);
								send_my_broadcastline_loop(Number(cfg_start_seding_no)-1);	//start
							}
						}else{
							var d=new Date();
							var esttime_date_format_str = d.getFullYear().toString()+"-"+padDigits(d.getMonth()+1,2)+"-"+padDigits(d.getDate(),2)+" "+padDigits(d.getHours(),2)+":"+padDigits(d.getMinutes(),2)+":"+padDigits(d.getSeconds(),2);
							document.getElementById("stop_time").innerHTML="เสร็จ "+" "+esttime_date_format_str;
							setStopJob(0,false,3);
							status_running=false;
							showStartButton();
							$('#get_fb_fanpage').show();
							$('.processing').hide();
							return;
						}
						
					}else{
						$('#download_fb_fanpage_members').hide();
						$('#get_fb_fanpage').show();
						$('.processing').hide();
						try{
							iziToast.error({
								title: "ไม่สามารถโหลดหรือไม่พบเพื่อนที่จะส่งข้อความในโฟลเดอร์ "+my_broadcastline_folder_label_name+" นี้ให้ได้",
								position: 'topLeft',
								timeout: 3000,
								message: '',
							});
						}catch(ex){}
						show_msg_report("","","2","ไม่สามารถโหลดหรือไม่พบเพื่อนที่จะส่งข้อความในโฟลเดอร์นี้ "+  my_broadcastline_folder_label_name+ '<i style="font-weight:900;color:#red;">&nbsp;&nbsp;(ไม่สำเร็จ)</i>'+result_msg);
						
						localStorage.setItem('stop_pause_get_fanpage_next', "");	//Clear stop flag
				
						let elem = document.getElementById("myProgress");
						if(typeof elem!=="undefined"){
							if (elem!==null){
								elem.style.display="none";
							}
						}
						setStopJob(0,false,0);
						status_running=false;
						return;
					}

				}
				//get_label_user(url,iswith_sendmsg,loop_index_members,tags) 
			}
		});


	}catch(error){
		console.log(error);
		if (chrome.runtime.lastError){
			alert (chrome.runtime.lastError);
		}else{
			alert(error);
		}
		setStopJob(0,false,0);
		status_running=false;
		return;
	}
}

function get_inbox_page_start() {
	label_user_all = [];
	label_user_all_copy = [];
    let is_follow_up = false;
	let folders = 'INBOX';
	let url = 'https://business.facebook.com/api/graphqlbatch/';
    if ($('#cfg_recipients_option_folder').val() == 'folder=inbox') {
        // url = 'https://m.facebook.com/messages/?pageNum=1&selectable&pageID='+page_id;
        url = 'https://business.facebook.com/api/graphqlbatch/';
        folders = 'INBOX';
    } else
    if ($('#cfg_recipients_option_folder').val() == 'folder=page_done') {
        folders = 'ARCHIVED';
        // url = 'https://m.facebook.com/messages/?folder=action%3Aarchived&pageID='+page_id;
        url = 'https://business.facebook.com/api/graphqlbatch/';
    } else
    if ($('#cfg_recipients_option_folder').val() == 'folder=follow_up') {
        folders = 'null';
        is_follow_up = true;
        // url = 'https://m.facebook.com/messages/?folder=action%3Aarchived&pageID='+page_id;
        url = 'https://business.facebook.com/api/graphqlbatch/';
    }
	
	let page_id = my_broadcastline_label_id;
	let page_name = my_broadcastline_label_name;
	
	page_count = 0;
	
	document.getElementById('fanpage_inbox_friend_ids_send_input').title = '';
	$('#fanpage_inbox_friend_ids_send_input').val('');
	$('#get_fb_fanpage').hide();
	$('.processing').show();
	
	try{
		let x = document.getElementById("downloadLink");
		if(x){
			try{
				//x.remove();
				//document.body.removeChild(x);
				x.parentNode.removeChild(x);
			}catch(e){}
		}
	}catch(e){}
	get_request_page_info();
    get_inbox_page(null);
	
	/* in gfunc.js
	var fb_access_token = localStorage.getItem('fb_access_token');
	var fb_dtsg = localStorage.getItem('fb_dtsg');
	var fb_user_id = localStorage.getItem('fb_user_id');
	var fb_name = localStorage.getItem('fb_name');
	var __rev = localStorage.getItem('__rev');
	
	*/
	
    function get_inbox_page(pading_time) {
        let title = 'ดึงข้อมูลinbox ในแฟนเพจ';
        let docId = '1699057486820841';
        let dataString = '__user=' + fb_user_id + '&__a=1&fb_dtsg=' + fb_dtsg + '&av=' + my_broadcastline_label_id;
        docId = '1699057486820841';
        dataString +=
            '&queries=%7B%22' +
            'o0' + '%22%3A%7B%22' +
            'doc_id' + '%22%3A%22' + docId + '%22%2C%22' +
            'query_params' + '%22%3A%7B%22' +
            'limit' + '%22%3A' + 150 + '%2C%22' +
            'before%22%3A' + pading_time + '%2C%22' +
            'tags%22%3A%5B%22' + '' + folders + '%22%5D' + '%2C%22is_follow_up%22%3A' + is_follow_up + '%2C%22is_unread%22%3Afalse%7D%7D%7D';
        let data = dataString;
        //data = 'batch_name=MessengerGraphQLThreadlistFetcher&fb_dtsg=AQEMLZtThGskJMQ%3AAQHcccm5L44G1us&jazoest=22554&lsd=0_evz2FJka01t58josfNKa&__spin_r=1004003257&__spin_b=trunk&__spin_t=1624194296&__jssesw=1&av=1430991867135840&queries=%7B%22o0%22%3A%7B%22doc_id%22%3A%223983189078445172%22%2C%22query_params%22%3A%7B%22limit%22%3A22%2C%22before%22tags%22%3A[%22INBOX%22]%2C%22isWorkUser%22%3Afalse%2C%22includeDeliveryReceipts%22%3Atrue%2C%22includeSeqID%22%3Afalse%2C%22is_work_teamwork_not_putting_muted_in_unreads%22%3Afalse%2C%22threadlistViewFieldsOnly%22%3Afalse%7D%7D%7D';
        
		console.log(data);
		$.ajax({
            url: url,
            type: "post",
            data: data,
            complete: async function(data1) {
                let data_fetch = data1.responseText;
				
				if(typeof data_fetch=="undefined" || data_fetch==null || data_fetch.length==0){
					try{
						iziToast.error({
							title: "ไม่สามารถโหลดหรือไม่พบเพื่อนที่จะส่งข้อความใน "+my_broadcastline_folder_label_name+" นี้ได้",
							position: 'topLeft',
							timeout: 3000,
							message: '',
						});
					}catch(ex){}
					let elem = document.getElementById("myProgress");
					if(typeof elem!=="undefined"){
						if (elem!==null){
							elem.style.display="none";
						}
					}
					setStopJob(0,false,0);
					status_running=false;
					return;
				}
				page_count++;
				
                //console.log(JSON.parse(data_fetch.replace('{"successful_results":1,"error_results":0,"skipped_results":0}', '')));
                data_fetch = JSON.parse(data_fetch.replace('{"successful_results":1,"error_results":0,"skipped_results":0}', ''));
                let data_text_respone = data_fetch.o0.data.viewer.message_threads.nodes;
				//let ids = "";
				
                $.each(data_text_respone, function(key, id_fb) {
                    let participant = id_fb.all_participants.nodes[0].messaging_actor;
                    let unread_count = id_fb.unread_count;
                    let timestamps = id_fb.updated_time_precise;
                    let name = participant.name;
                    let id = participant.id;
                    if (id != '') {
                        let iddata = "'" + id + "'";
                        if (name != '') {
							let accountName = "";
							let folder = "";
							if(label_user_all.length==0){
								accountName = my_broadcastline_label_name;
								folder = my_broadcastline_folder_label_name;
							}
                            label_user_all.push({
                                'account_id': iddata,
                                'id': id,
                                'name': removeXMLInvalidChars(name),	//gfunc.js
                                'unread_count': unread_count,
                                'updated_time': getDateFormat(timestamps / 1000),	//gfunc.js
								'accountName':accountName,
								'folder':folder
                            });
                        }
                    }
                });
                let paging = data_text_respone[1];
                if (typeof paging != 'undefined' && paging != '') {
					title = 'กำลังรวบรวมคนจากเพจ: ' + '<i style="font-weight:900;color:#00d6fc;">'+my_broadcastline_label_name+'</i>' + ' ชนิดโฟลเดอร์ :  ' + '<i style="font-weight:900;color:#fc8600;">&nbsp;&nbsp;'+my_broadcastline_folder_label_name+'</i>'+'<i>&nbsp;page no: '+(page_count+1) + '</i>'+'<i>&nbsp;จำนวน: '+ label_user_all.length + ' คน' + '</i>';
                    let last_timstam = data_text_respone[(data_text_respone.length - 1)].updated_time_precise;
                    iziToast.info({
                        title: '',
                        position: 'topRight',
                        timeout: 3000,
                        message: title,//'กำลัง' + title + ' รอสักครู่ ' + label_user_all.length + ' คน',
                    });
                    get_inbox_page(last_timstam);
                } else {
					label_user_all = uniqueByKey(label_user_all, 'id');	//make unique by key
					title = 'เรียบร้อยแล้ว: ' + '<i style="font-weight:900;color:#00fc37;">'+my_broadcastline_label_name+'</i>' + ' ชนิดโฟลเดอร์ :  ' + '<i style="font-weight:900;color:#fc8600;">&nbsp;&nbsp;'+my_broadcastline_folder_label_name+'</i>'+'<i>&nbsp;page no: '+(page_count+1) + '</i><i style="font-weight:900;color:#fc00ac;">&nbsp;จำนวน: '+ label_user_all.length + ' คน</i>';
                    iziToast.success({
                        title: '',
                        position: 'topRight',
                        timeout: 8000,
                        message: title,	//title + 'เรียบร้อยแล้ว ' + label_user_all.length + ' คน',
                    });
					
					$('#get_fb_fanpage').show();
					
					if(label_user_all.length>0){
						//Load friends success
						//label_user_all = [...new Set(label_user_all.map(item => item.id))];;	//make a unique by key
						//label_user_all = [... new Set(label_user_all.map(JSON.stringify))].map(JSON.parse)	//unique all match
						//label_user_all = uniqueByKey(label_user_all, 'id');
						let ids = "";
						for (let u of label_user_all) 
						{
						  //ids+= await u.id+"\r\n";
						  ids+= await (u.id+','+u.name+"\r\n");
						}
						
						//$('#fanpage_inbox_friend_ids_send_input').val('เพจ: '+my_broadcastline_label_name+"\r\nPage ID: "+my_broadcastline_label_id+"\r\nจำนวน: "+label_user_all.length+"\r\nวันที่: "+getDate()+'\r\n'+ids);
						$('#download_fb_fanpage_members').show();
						
						label_user_all_copy = label_user_all;
						//createDownloadLink('เพจ: '+my_broadcastline_label_name+"\r\nPage ID: "+my_broadcastline_label_id+"\r\nจำนวน: "+label_user_all.length+"\r\nวันที่: "+getDate()+'\r\n'+ids);
						
						
						//ldb.set('fanpage_inbox_friend_ids_send_input', JSON.stringify(label_user_all));	//copy data to store
						
						document.getElementById('download_fb_fanpage_members').title = 'ดาวน์โหลดลูกเพจที่ดึงมาจากเพจ: '+my_broadcastline_label_name + ' โฟลเดอร์ ' + my_broadcastline_folder_label_name + ' จำนวน: '+ label_user_all.length + ' คน' ;
						document.getElementById('fanpage_inbox_friend_ids_send_input').title = 'ลูกเพจที่ดึงมาจากเพจ: '+my_broadcastline_label_name + ' โฟลเดอร์ ' + my_broadcastline_folder_label_name + ' จำนวน: '+ label_user_all.length + ' คน'
					}
					$('.processing').hide();
                }
            }
        });
    }
}

///////////////////////////////////
async function add_fb_page_members_v2(data_fetch,iswith_sendmsg){
	return new Promise(async (resolve) => {
		title = 'เพจ: ' + my_broadcastline_label_name + ' ' + my_broadcastline_folder_label_name+' หน้า: '+(page_count+1);
		
		if(isToastGetMemberInboxPageShow){
			
			var modalGrAlert = document.getElementById("modalGrAlert");
			if(iswith_sendmsg){
				modalGrAlert.style.width = "50%";
			}else{
				modalGrAlert.style.width = "50%";
			}
			
			modalGrAlert.style.display = "block";
		}
		var modal_alert_content = document.getElementById("modal_alert_content");
		const now = new Date().getTime(); // get the current timestamp in milliseconds
		const filter_datestart = now - (1.5 * 365 * 24 * 60 * 60 * 1000); // calculate the timestamp for 1.5 year ago

		$.each(data_fetch, function(i, data_nodes) {
			if (data_nodes.all_participants.edges[0].node.messaging_actor.id != 'undefined') {
				let id = '';
				if (data_nodes.all_participants.edges[0].node.messaging_actor.id != 'undefined') {
					/////////////////////////////////////////
					id = data_nodes.all_participants.edges[0].node.messaging_actor.id;
					let uname = '';
					if (typeof data_nodes.all_participants.edges[0].node.messaging_actor.name != 'undefined') {
						uname = data_nodes.all_participants.edges[0].node.messaging_actor.name;
					}

					if (data_nodes.cannot_reply_reason != null) {
						id = '';
					}
					// if (data_nodes.last_message.nodes[0].message_unsendability_status != 'can_unsend') {
					// 	id = '';
					// }
					if (data_nodes.thread_unsendability_status == 'deny_if_canonical_thread_contains_blocked_users') {
						id = '';
					}
					if (typeof data_nodes.last_message.nodes[0].timestamp_precise != 'undefined') {
						if (data_nodes.last_message.nodes[0].timestamp_precise < filter_datestart) {
							id = '';
						}
					}

					if (id != '') {
						if (label_user_all.indexOf(id) === -1) {
							if (uname != '') {
								let accountName = "";
								let folder = "";
								if(label_user_all.length==0){
									accountName = my_broadcastline_label_name;
									folder = my_broadcastline_folder_label_name;
								}
								label_user_all.push({
									'id': id,
									'name': removeXMLInvalidChars(uname),	//gfunc.js
									'accountName':accountName,
									'folder':folder
								});
							}
						}
					}
				}
			}
		});

		active_friends_count=label_user_all.length;
		iTotalMesageMustSend=active_friends_count*iTableAllItems;
		
		if(isToastGetMemberInboxPageShow){
			modal_alert_content.innerHTML=getFormattedDate()+ " " + title + " คนที่ " + active_friends_count;
		}
		
		if(cfg_max_recipients>active_friends_count || cfg_max_recipients<1){cfg_max_recipients = active_friends_count;}
		if(cfg_start_seding_no>cfg_max_recipients){cfg_start_seding_no=cfg_max_recipients;}
		if(cfg_start_seding_no<1){cfg_start_seding_no=1;}
		
		iTotalMesageMustSend=(cfg_max_recipients-cfg_start_seding_no+1)*iTableAllItems;
		resolve(true);
	});
}

async function add_fb_page_members(data_fetch,iswith_sendmsg){

	return new Promise(async (resolve) => {
		//title = 'กำลังรวบรวมคนจากเพจ ' + '<i style="font-weight:900;color:#00d6fc;">'+my_broadcastline_label_name+'</i>' + ' ชนิดโฟลเดอร์ : ' + '<i style="font-weight:900;color:#fc8600;">&nbsp;&nbsp;'+my_broadcastline_folder_label_name+'</i>'+'<i>&nbsp;page no:'+(page_count+1) + '</i>';
		title = 'เพจ: ' + my_broadcastline_label_name + ' ' + my_broadcastline_folder_label_name+' หน้า: '+(page_count+1);
		
		if(isToastGetMemberInboxPageShow){
			
			var modalGrAlert = document.getElementById("modalGrAlert");
			if(iswith_sendmsg){
				modalGrAlert.style.width = "50%";
			}else{
				modalGrAlert.style.width = "50%";
			}
			
			modalGrAlert.style.display = "block";
			var modal_alert_content = document.getElementById("modal_alert_content");
			
		}
		
		/*
		$.each(data_fetch, function (i, data) {
			if (typeof data.senders.data[0].id != 'undefined') {
				if (typeof data.senders.data[0].name != 'undefined') {
					if (data.senders.data[0].name != '') {
							
						label_user_all.push({
							'id': data.senders.data[0].id,
							'name': data.senders.data[0].name
						});
						
					}
				}
			}
		});
		*/
		
		//////////////////////////////////////
		//Modified on 2021/05/10
		//let id_thread_unread = data_fetch.match(/thread_unread_count:\d+/g);
		let thread_id = data_fetch.match(/tid=cid.c.\d+/g);
		let thread_name_sender = data_fetch.match(/sender_name:"\D+/g);
		
		if(!thread_name_sender){
			thread_name_sender=data_fetch.match(/#fua\">([^<]+)/g);
		}
		
		$.each(thread_id, function(idx, data) {
			let uname = "";
			if(thread_name_sender){
				//uname = thread_name_sender[idx].replace('#fua">','');
				uname = thread_name_sender[idx].replace('sender_name:"', '').split('",')[0];
				uname = uname.replace('#fua">','');
				
			}
			let tid = data.replace('tid=cid.c.', '');
			//let u_read = id_thread_unread[idx].replace('thread_unread_count:', '');
			if (uname != '') {
				let accountName = "";
				let folder = "";
				if(label_user_all.length==0){
					accountName = my_broadcastline_label_name;
					folder = my_broadcastline_folder_label_name;
				}
				label_user_all.push({
					'id': tid,
					'name': removeXMLInvalidChars(uname),	//gfunc.js
					'accountName':accountName,
					'folder':folder
				});
			}
			/*
			if ($('#broadcastbylabel_read').prop("checked") == true) {		
				if (u_read == 0) {
					label_user_all.push({
						'id': tid,
						'name': uname
					});
				}
			} else {
				label_user_all.push({
					'id': tid,
					'name': uname
				});
			}
			*/
		});
		
		//console.log("label_user_all.length "+ label_user_all.length);
		//console.log(label_user_all);
		
		
		active_friends_count=label_user_all.length;
		iTotalMesageMustSend=active_friends_count*iTableAllItems;
		
		if(isToastGetMemberInboxPageShow){
			modal_alert_content.innerHTML=getFormattedDate()+ " " + title + " คนที่ " + active_friends_count;
		}
		
		if(cfg_max_recipients>active_friends_count || cfg_max_recipients<1){cfg_max_recipients = active_friends_count;}
		if(cfg_start_seding_no>cfg_max_recipients){cfg_start_seding_no=cfg_max_recipients;}
		if(cfg_start_seding_no<1){cfg_start_seding_no=1;}
		
		iTotalMesageMustSend=(cfg_max_recipients-cfg_start_seding_no+1)*iTableAllItems;
		resolve(true);
	});
}

function check_correct_select_option(page_name){
	let textToFind = page_name.replace('Fanpage:','');
	textToFind = textToFind.trim();
	let dd = document.getElementById('my_broadcastline_idpage');
	return new Promise(async resolve => {
		for (let i = 0; i < dd.options.length; i++) {
			//await sleep(50);
			if (dd.options[i].text === textToFind) {
				try {
					let oHandler = await $("#my_broadcastline_idpage").msDropDown().data("dd");
					if(oHandler){
						dd.selectedIndex=i;
						await oHandler.set("selectedIndex", i)	
					}
				} catch(e) {
					//console.log("Error: "+e.message);
				}
				resolve(textToFind);
				return;
			}
		}
		resolve("");
	});
}

//////////////////////////////////
function generateInputData(){
	label_user_all = [];
	return new Promise(async resolve => {
		let have_page_name = false;
		let pageName = "";
		//$.each($('#fanpage_inbox_friend_ids_send_input').val().split(/\n/), async function(i, line){
		for(let line of $('#fanpage_inbox_friend_ids_send_input').val().split(/\n/)){
			let line_target = await extractNumber(line);
			//await sleep(50);
			if (!isNaN(line_target[0])) {
				if(line_target[0].trim()!=""){
					await label_user_all.push({
						'id': line_target[0].trim(),
						'name': line_target[1].trim(),
						'accountName':'',
						'folder':''
					});
				}
			}else{
				if(have_page_name==false){
					have_page_name = true;
					pageName = await check_correct_select_option(line_target[0]);
				}
			}
		}//);
		
		try{
			if(label_user_all.length>0){
				if(typeof label_user_all[0].accountName!="undefined" ){
					label_user_all[0].accountName = pageName;
				}
			}
		}catch(e){}
		resolve(true);
	});
}

//////////////////////////////////
async function send_my_broadcastline_loop(loop) {	//send from start sending no.
	loop = parseInt(loop);	//start sending no.
	localStorage.setItem('loops', (loop));	//store sending no to local storage
	//localStorage.setItem('fbinboxstatusdone', 1);	//0=stop,1=runnin,2=pause,3=done
	fbinboxstatusdone = 1;
	let my_broadcastline_data  = [];
	
	
	if(loop>label_user_all.length){
		status_stop_pause = 0;
	}
	//console.log("send my broadcastline loop "+loop);
	
	//if (localStorage.getItem('setstop') == 0) {	//press stop button
	if (status_stop_pause==0) {	//press stop button
		try{
			iziToast.info({
				title: 'ส่งถึงคนที่ ' + (loop+1)+"/"+active_friends_count + ' เรียบร้อยพร้อมหยุดทำงาน',
				position: 'topLeft',
				timeout: 5000,
				message: '',
			});
		}catch(ex){}
		$('#start_broadcast').show();
		$('#pause_broadcast').hide();
		$('#stop_broadcast').hide();
		$('#continue_broadcast').hide();
		$('#radio_schedule *').prop('disabled',false);
		$('#lbl_schedule_ *').prop('disabled',false);
		$('#pause_broadcast').text('   pause');
		$('#stop_broadcast').text('   stop');
		setStopClock();
		var d=new Date();
		var esttime_date_format_str = d.getFullYear().toString()+"-"+padDigits(d.getMonth()+1,2)+"-"+padDigits(d.getDate(),2)+" "+padDigits(d.getHours(),2)+":"+padDigits(d.getMinutes(),2)+":"+padDigits(d.getSeconds(),2);
		document.getElementById("stop_time").innerHTML="หยุดทำงาน "+loop+" "+esttime_date_format_str;
		status_running=false;
		runningProgress(loop,status_stop_pause);	//loop in friends
		return;
	}else if (status_stop_pause==2){	//press pause button
		try{
			iziToast.info({
				title: 'ส่งถึงคนที่ ' + (loop+1)+"/"+active_friends_count + ' เรียบร้อยพร้อมหยุดชั่วคราว',
				position: 'topLeft',
				timeout: 5000,
				message: '',
			});
		}catch(ex){}
		$('#start_broadcast').hide();
		$('#pause_broadcast').hide();
		$('#continue_broadcast').show();
		$('#stop_broadcast').show();
		$('#radio_schedule *').prop('disabled',false);
		$('#lbl_schedule_ *').prop('disabled',false);
		$('#pause_broadcast').text('   pause');
		$('#stop_broadcast').text('   stop');
		setStopClock();
		var d=new Date();
		var esttime_date_format_str = d.getFullYear().toString()+"-"+padDigits(d.getMonth()+1,2)+"-"+padDigits(d.getDate(),2)+" "+padDigits(d.getHours(),2)+":"+padDigits(d.getMinutes(),2)+":"+padDigits(d.getSeconds(),2);
		document.getElementById("stop_time").innerHTML="หยุดชั่วคราว "+loop+" "+esttime_date_format_str;
		status_running=false;
		runningProgress(loop,status_stop_pause);	//loop in friends
		return;
	}
	
	checkPackagePromise().then(x => {
		if(x==0){return false;}
	}).then(async function(result){
		if(result==false){return;}

			let my_broadcastline_oldtonew = $('#my_broadcastline_oldtonew').prop("checked");
			if(typeof my_broadcastline_oldtonew==='undefined'){my_broadcastline_oldtonew=false;}

			if(typeof label_user_all=="undefined" || label_user_all==null || label_user_all=="" || label_user_all.length<1){
				Swal.fire({
					title: 'เกิดข้อผิดพลาด',
					type: 'error',
					html: 'ไม่พบข้อมูลของคนที่จะส่งข้อความหาในแฟนเพจ',
				});
				status_running=false;
				return;
			}
			
			//console.log("10");
			//console.log("length " + label_user_all.length);
			
			my_broadcastline_data = label_user_all;
			
			if(my_broadcastline_oldtonew==true){
				//console.log('reverse data');
				my_broadcastline_data = my_broadcastline_data.reverse();
			}
			
			cfg_max_recipients = $('#cfg_max_recipients').val();
			cfg_max_recipients = Number(cfg_max_recipients);
			if(typeof cfg_max_recipients === 'undefined'){cfg_max_recipients = my_broadcastline_data.length;}
			if(cfg_max_recipients<1 || cfg_max_recipients>my_broadcastline_data.length){
				cfg_max_recipients = my_broadcastline_data.length;
			}
			cfg_max_recipients = parseInt(cfg_max_recipients);
			
			cfg_start_seding_no=$('#cfg_start_seding_no').val();
			cfg_start_seding_no = Number(cfg_start_seding_no);
			if(typeof cfg_start_seding_no==='undefined'){cfg_start_seding_no=1;}
			if(cfg_start_seding_no>cfg_max_recipients){cfg_start_seding_no=cfg_max_recipients;}
			if(cfg_start_seding_no<1){cfg_start_seding_no=1;}
			
			iTotalMesageMustSend=(cfg_max_recipients-cfg_start_seding_no+1)*iTableAllItems;
			
			var completed_counter=document.getElementById('completed_counter');
			var myOLBroadcastTable = document.querySelector("#myOLBroadcastTable").tBodies[0];
			var num_rows = myOLBroadcastTable.rows.length;
			
			if(num_rows<1){
				Swal.fire({
					title: 'เกิดข้อผิดพลาด',
					type: 'error',
					html: 'คุณต้องใส่รายการที่จะส่งลงในตารางด้านขวามือนี้ก่อน',
				});
				status_running=false;
				return;
			}
			
			////////////////////////////////////////////////////////
			//Start Sending
			//var rateLimitedStamp = null;
			var rateLimitedPrevStamp =null;
			var rateLimitedCounter = 0;
			var d=new Date();
			var starttime_date_format_str = d.getFullYear().toString()+"-"+padDigits(d.getMonth()+1,2)+"-"+padDigits(d.getDate(),2)+" "+padDigits(d.getHours(),2)+":"+padDigits(d.getMinutes(),2)+":"+padDigits(d.getSeconds(),2);
			document.getElementById("start_time").innerHTML = "เริ่ม "+starttime_date_format_str;
			
			
			//////////////////// Threads /////////////////////
			var my_threads_speed = 1;	//default
			try{
				var speed_send_option=document.getElementById("speed_send_option");
				var speed_val = 0;
				if(typeof speed_send_option!=="undefined" && speed_send_option!=null){
					speed_val = speed_send_option.selectedIndex;
				}
				//speed_val = speed_val+1;
				if(Number(speed_val)>Number(tf_maximum_speed_sender)){
					speed_val = Number(tf_maximum_speed_sender);
				}
				
				//var value_speed=speed_send_option.options[speed_send_option.selectedIndex].value;// get selected option value
				var text_speed=speed_send_option.options[speed_send_option.selectedIndex].text;
				if(text_speed=="ไม่จำกัด" && IS_TF_MAX_SPEED_UNLIMIT){
					my_threads_speed = 0;
				}else if(Number(speed_val)<1){	//ปกติ list index 1
					my_threads_speed = 1;
				}else{
					my_threads_speed = (Number(speed_val)*3);
				}
				//console.log("Max speed: " +speed_val+ " Speed threads: "+ my_threads_speed);
			}catch(err){}
			
			
			//if(loop>1){cfg_start_seding_no=loop;}
			
			var start_friends_index = (Number(cfg_start_seding_no) -1);	//start first
			if(Number(loop)>1){start_friends_index = Number(loop);}	//pause
			var end_friends_index = (Number(cfg_max_recipients));
			
			status_running=false;
			//localStorage.setItem('setstop', 1);	//Clear stop flag
			status_stop_pause = 1;
			
			
			/////////
			if (isNaN(my_broadcastline_delay)){my_broadcastline_delay=0;}
			if (isNaN(my_broadcastline_to_delay)){my_broadcastline_to_delay=0;}

			my_broadcastline_sdelay = Number(my_broadcastline_delay);
			my_broadcastline_tdelay = Number(my_broadcastline_to_delay);
			if(my_broadcastline_sdelay<0){my_broadcastline_sdelay=0;}
			if(my_broadcastline_tdelay<0){my_broadcastline_tdelay=0;}

			// if(my_broadcastline_sdelay>=my_broadcastline_tdelay){
			// 	my_broadcastline_sdelay=1;
			// }

			// var randomSleep = 0;
			// if(my_broadcastline_tdelay>0){
			// 	randomSleep = getRandomArbitrary((my_broadcastline_sdelay*1000),(my_broadcastline_tdelay*1000));
			// }

			// if(isNaN(randomSleep)){randomSleep=0;}
			// randomSleep = Number(randomSleep);
			// if(randomSleep>0){
			// 	try{
			// 		iziToast.info({
			// 			title: 'หน่วงเวลา '+ Math.floor(randomSleep/1000) + ' วินาที',
			// 			position: 'topLeft',
			// 			timeout: randomSleep,
			// 			message: '',
			// 		});
			// 	}catch(ex){}
			// 	await sleep(Number(randomSleep));
			// }

			if(end_friends_index<1){
				//console.log("11");
				//if(randomSleep>0){await sleep(Number(randomSleep));}
				start_bc(my_threads_speed,my_broadcastline_data.slice(start_friends_index));
			}else{
				//console.log("12");
				//if(randomSleep>0){await sleep(Number(randomSleep));}
				start_bc(my_threads_speed,my_broadcastline_data.slice(start_friends_index,end_friends_index));
			}
			return;
			/////////////////// End Treads //////////////////
	
	});

}
function getRandomArbitrary(min, max) {
	return Math.random() * (max - min) + min;
}

function send_my_broadcastline_continue(loop) {
	//console.log("send my broadcastline continue");
	check_net().then((data) =>{
		loop = parseInt(loop);
		$('#radio_schedule *').prop('disabled',true);
		var d=new Date();
		var esttime_date_format_str = d.getFullYear().toString()+"-"+padDigits(d.getMonth()+1,2)+"-"+padDigits(d.getDate(),2)+" "+padDigits(d.getHours(),2)+":"+padDigits(d.getMinutes(),2)+":"+padDigits(d.getSeconds(),2);
		document.getElementById("stop_time").innerHTML="เริ่มครั้งถัดไป "+ loop +" "+esttime_date_format_str;
		
		//localStorage.setItem('setstop', 1);	//Clear stop flag
		status_stop_pause = 1;
		//console.log("9");
		send_my_broadcastline_loop(loop);
	}).catch((error) =>{
		status_running=false;
		console.log(error);
		$('#start_broadcast').hide();
		$('#pause_broadcast').show();
		$('#stop_broadcast').show();
		$('#continue_broadcast').show();
		$('#footer-summary-container').hide();
		$('#close-x').hide();
		$('#open-o').show();
		setStopJob(loop,false,0);
		alert("ไม่สามารถสื่อสารกับ https://facebook.com/ ได้ตรวจสอบ Internet หรือ Login Line ใหม่อีกรอบ");
		return
	});
}
































///////////////////////////////////////
function send_fb_messager(msg_text,target_id,target_name,img_pass,img_status,row_number,send_success_count_in_each_row,send_failed_count_in_each_row){
	var my_broadcastbylabel_photo_all_img_pass = img_pass;
	var my_broadcastbylabel_photo_all_img_status = img_status;
	var my_broadcastline_text = "";
	var msg_type="";
	var status_response=false;
	let this_item_send_count=Number(send_success_count_in_each_row)+Number(send_failed_count_in_each_row);
	
	
	if(typeof my_broadcastbylabel_photo_all_img_pass==="undefined" || my_broadcastbylabel_photo_all_img_pass==null){
		my_broadcastbylabel_photo_all_img_pass="";
	}
	if(typeof my_broadcastbylabel_photo_all_img_status==="undefined" || my_broadcastbylabel_photo_all_img_status==null || my_broadcastbylabel_photo_all_img_status==""){
		my_broadcastbylabel_photo_all_img_status="";
	}
	if(typeof msg_text==="undefined" || msg_text==null || msg_text==""){
		msg_text="";
	}
	if(msg_text==""){
		msg_type="ไฟล์";
	}else{
		msg_type="ข้อความ";
		if(my_broadcastbylabel_photo_all_img_status=="true"){
			msg_type="ข้อความและไฟล์";
		}
	}
	

	//my_broadcastline_text = encodeURIComponent(spintax(msg_text));
	my_broadcastline_text = spintax(msg_text);
	my_broadcastline_text = randomContent(my_broadcastline_text);
	if(my_broadcastline_text.trim()!=""){
		if(text_spintext_Preamble.trim()!=""){
			my_broadcastline_text = randomtax(text_spintext_Preamble.trim()) +"\r\n"+ my_broadcastline_text;
		}
		if(text_spintext_Conclusion.trim()!=""){
			my_broadcastline_text +=  "\r\n"+ randomtax(text_spintext_Conclusion.trim());
		}
	}
	my_broadcastline_text = encodeURIComponent(my_broadcastline_text);
	my_broadcastline_text = my_broadcastline_text.replace(/random_str/g, make_it_id1(3) + make_it_id2(3));
	my_broadcastline_text = my_broadcastline_text.replace(/random_sub/g, make_it_id3(6));
	if(__rev == null || __rev==""){
		__rev = localStorage.getItem('__rev');
	}
	if(__rev==""){
		__rev = "1004708602";
	}
	var newtimestamp = (new Date).getTime();
	var sendidx = Math.floor(Math.random() * 100000000000000) + 1;
	var parms = 'client=mercury&action_type=ma-type%3Auser-generated-message&body=' + (my_broadcastline_text) + '&ephemeral_ttl_mode=0&has_attachment=' + my_broadcastbylabel_photo_all_img_status + my_broadcastbylabel_photo_all_img_pass + '&message_id=' + sendidx + '&offline_threading_id=' + sendidx + '&other_user_fbid=' + target_id + '&source=source%3Apage_unified_inbox&specific_to_list[0]=fbid%3A' + target_id + '&specific_to_list[1]=fbid%3A' + my_broadcastline_label_id + '&timestamp='+newtimestamp+'&request_user_id=' + my_broadcastline_label_id + '&__user=' + fb_user_id + '&__a=1&__req=1n&__be=1&dpr=1.5&__rev=' + __rev + '&__s=%3A38ai1u%3Amxgv29&fb_dtsg=' + fb_dtsg + '&jazoest=' + jazoest + '&__spin_r=' + __rev + '&__spin_b=trunk';
	    //parms = 'client=mercury&action_type=ma-type%3Auser-generated-message&body=' + (adverra_premium_broadcastbylabel_text) + '&ephemeral_ttl_mode=0&has_attachment=' + adverra_premium_broadcastbylabel_photo_all_img_status + adverra_premium_broadcastbylabel_photo_all_img_okx + '&message_id=' + adverra_premium_broadcastbylabel_number + '&offline_threading_id=' + adverra_premium_broadcastbylabel_number + '&other_user_fbid=' + target_id + '&source=source%3Apage_unified_inbox&specific_to_list[0]=fbid%3A' + target_id + '&specific_to_list[1]=fbid%3A' + adverra_premium_broadcastbylabel_idpage + '&timestamp=' + getCurrentTimestamp() + '&request_user_id=' + adverra_premium_broadcastbylabel_idpage + '&__user=' + user_id + '&__a=1&__req=1n&__be=1&dpr=1.5&__rev=' + __rev + '&__s=%3A38ai1u%3Amxgv29&fb_dtsg=' + fb_dtsg + '&jazoest=' + jazoest + '&__spin_r=' + __rev + '&__spin_b=trunk';
                       
	return new Promise(function (resolve) {
		chrome.runtime.sendMessage({
			url: "https://www.facebook.com/messaging/send/",
			type: "post",
			data: parms,
		}, function (resp) {
			try{
				var textresp = give_error_description(resp);
				var total_items_each_row=send_success_count_in_each_row+send_failed_count_in_each_row;
				if(textresp.code!="0"){
					if(isToastErrShow || textresp.code=="1357004"){	//description: "Please try closing and re-opening your browser window." facebook connection lose
						try{
							iziToast.error({
								title: "Error recipient "+target_id+":"+target_name+" -> Code "+ textresp.code +":"+ textresp.description,
								position: 'topLeft',
								timeout: 5000,
								icon:'far fa-times-circle',
								imageWidth: 50,
								message: "",
							});
						}catch(ex){}
					}
					
					status_response = false;
					itemsSendErrorCount+=Number(total_items_each_row);	//count file send error
					
					show_msg_report(target_id,target_name,"1","["+0+"/"+total_items_each_row+"] "+ textresp.code +":"+ textresp.description,row_number,msg_type);
				}else{
					status_response = true;
					is_can_send_somthing_success==true;
					textresp=give_success_description(resp);
					if(textresp.status==1){
						if (isToastSucShow){
							try{
								iziToast.info({
									title: "Success "+"recipient "+target_id+":"+target_name+" -> "+"Ref. "+textresp.ref,
									position: 'topLeft',
									timeout: 5000,
									icon:'fas fa-check-circle',
									imageWidth: 50,
									message: "",
								});
							}catch(ex){}
						}
					}else{
						if(isToastErrShow){
							try{
								iziToast.error({
									title: "Error recipient "+target_id+":"+target_name+" -> Code "+ textresp.code +":"+ textresp.description,
									position: 'topLeft',
									timeout: 5000,
									icon:'far fa-times-circle',
									imageWidth: 50,
									message: "",
								});
							}catch(ex){}
						}
						status_response = false;
						itemsSendErrorCount+=total_items_each_row;	//count file send error
						
					}
					show_msg_report(target_id,target_name,textresp.status==1?"0":"1","["+send_success_count_in_each_row+"/"+total_items_each_row+"] Ref. "+textresp.ref+textresp.description,row_number,msg_type);
				}
				
			}catch(e){}
			
			if(msg_text!="" || my_broadcastbylabel_photo_all_img_pass!=""){	//increase progrees , files increase in sendFile fg already
				iProgressAllItemsCount = (Number(iProgressAllItemsCount) + Number(this_item_send_count));
				tot_send_items_count = (Number(tot_send_items_count) + Number(this_item_send_count)); 
				count_send_bubble_completed_iterate = (Number(count_send_bubble_completed_iterate) + Number(this_item_send_count));
				$('#count_sending_bubble_iterate').text(count_send_bubble_completed_iterate);
				
				try{
					count_send_completed_in_min = Number(count_send_completed_in_min) + Number(this_item_send_count);
				}catch(e){};
				$('#count_sending_bubble_per_min').text(count_send_completed_in_min);
				
				runningAllitemsProgress();
			}
			
			resolve(status_response);
		});
	});
	
}
//////////////////////////////////////


//////////////////////////////////////////////
///// Threads /////////
//////////////////////////////////////////////
async function start_bc(threads,beginfriends){
	tot_text_failed=0;
	tot_file_failed=0;
	tot_file_succescount=0;
	tot_text_succescount=0;
	status_running=true;
	
	let pause_send_time = null;
	let pause_seding_every_min = 0;
	let pause_seding_time_min = 0;
	
	
	pause_seding_every_min = $('#pause_seding_every_min').val();
	pause_seding_time_min = $('#pause_seding_time_min').val();
	
	if(!pause_seding_every_min){pause_seding_every_min=0;}
	if(!pause_seding_time_min){pause_seding_time_min=0;}
	if (isNaN(pause_seding_every_min)) {pause_seding_every_min=0;}
	if (isNaN(pause_seding_time_min)) {pause_seding_time_min=0;}
	
	let cfg_tf_msg_rate_limit_per_min = 0;
	count_send_completed_in_min = 0;
	$('#count_sending_bubble_per_min').text(count_send_completed_in_min);
	
	cfg_tf_msg_rate_limit_per_min = $('#cfg_tf_msg_rate_limit_per_min').val();
	if(!cfg_tf_msg_rate_limit_per_min){cfg_tf_msg_rate_limit_per_min=0;}
	if (isNaN(cfg_tf_msg_rate_limit_per_min)) {cfg_tf_msg_rate_limit_per_min=0;}
	cfg_tf_msg_rate_limit_per_min = Number(cfg_tf_msg_rate_limit_per_min);
	
	let now_limit_per_min_time = new Date().getTime()+60000;	// 1 minute
	
	
	///////////
	let cfg_tf_msg_rate_limit_bubble_iterate = $('#cfg_tf_msg_rate_limit_bubble_iterate').val();
	if(!cfg_tf_msg_rate_limit_bubble_iterate){cfg_tf_msg_rate_limit_bubble_iterate=0;}
	if (isNaN(cfg_tf_msg_rate_limit_bubble_iterate)) {cfg_tf_msg_rate_limit_bubble_iterate=0;}
	CFG_TF_MSG_RATE_LIMIT_BUBBLE_ITERATE = Number(cfg_tf_msg_rate_limit_bubble_iterate);
	//
	let cfg_tf_msg_rate_limit_bubble_pause_time_sec = $('#cfg_tf_msg_rate_limit_bubble_pause_time_sec').val();
	if(!cfg_tf_msg_rate_limit_bubble_pause_time_sec){cfg_tf_msg_rate_limit_bubble_pause_time_sec=0;}
	if (isNaN(cfg_tf_msg_rate_limit_bubble_pause_time_sec)) {cfg_tf_msg_rate_limit_bubble_pause_time_sec=0;}
	CFG_TF_MSG_RATE_LIMIT_BUBBLE_PAUSE_TIME_SEC = Number(cfg_tf_msg_rate_limit_bubble_pause_time_sec);
	//
	let cfg_tf_msg_rate_limit_person_iterate = $('#cfg_tf_msg_rate_limit_person_iterate').val();
	if(!cfg_tf_msg_rate_limit_person_iterate){cfg_tf_msg_rate_limit_person_iterate=0;}
	if (isNaN(cfg_tf_msg_rate_limit_person_iterate)) {cfg_tf_msg_rate_limit_person_iterate=0;}
	CFG_TF_MSG_RATE_LIMIT_PERSON_ITERATE = Number(cfg_tf_msg_rate_limit_person_iterate);
	//
	let cfg_tf_msg_rate_limit_person_pause_time_sec = $('#cfg_tf_msg_rate_limit_person_pause_time_sec').val();
	if(!cfg_tf_msg_rate_limit_person_pause_time_sec){cfg_tf_msg_rate_limit_person_pause_time_sec=0;}
	if (isNaN(cfg_tf_msg_rate_limit_person_pause_time_sec)) {cfg_tf_msg_rate_limit_person_pause_time_sec=0;}
	CFG_TF_MSG_RATE_LIMIT_PERSON_PAUSE_TIME_SEC = Number(cfg_tf_msg_rate_limit_person_pause_time_sec);
	//////////
	
	
	document.getElementById("processing_img").src="app-assets/img/processing.gif";
	//$("#processing_img").attr("src", 'app-assets/img/processing.gif');
	
	if(pause_seding_every_min>0){
		if(pause_seding_time_min>0){
			pause_send_time = new Date().getTime() + (Number(pause_seding_every_min)*60*1000);
		}
	}
	
	if(threads<1){	//async none block
		//const awsj = asyncSend(beginfriends,0,beginfriends.length);
		//let action = await checkActionStatus();
		$('#my_header').text('ระบบกำลังทำงานอยู่ '+' ไม่จำกัดความเร็ว');
		let friend = 0;
		//for (friend=0;friend<beginfriends.length;friend++){
				var isbreak=false;
				broad_none_block();

				function broad_none_block() {
					setTimeout(async function () {
						
						try{
							if(status_running==false){
								isbreak=true;
							}
							const result = broadcast_msg(beginfriends[friend]);
							if(Number(status_stop_pause)!=1){
								//break;
								isbreak=true;
							}
						}catch(e){console.log(e)}
						
						friend++;
						count_send_person_completed_iterate++;
						$('#count_sending_person_iterate').text(count_send_person_completed_iterate);
						
						if(friend<beginfriends.length){
							if(isbreak==false){
								
								let isSleep = false;
								if(pause_send_time!=null){
									let send_now = new Date().getTime();
									if(send_now>pause_send_time){
										var d = new Date(send_now+ (Number(pause_seding_time_min)*60*1000));
										var esttime_date_format_str = d.getFullYear().toString()+"-"+padDigits(d.getMonth()+1,2)+"-"+padDigits(d.getDate(),2)+" "+padDigits(d.getHours(),2)+":"+padDigits(d.getMinutes(),2)+":"+padDigits(d.getSeconds(),2);
										document.getElementById("stop_time").innerHTML="ถัดไป "+" "+esttime_date_format_str;
										$("#processing_img").attr("src","app-assets/img/waiting.gif");
										$("#pause_send_detail").text('พักส่ง '+pause_seding_time_min+' นาที');
										$("#send_next_time").text('ส่งถัดไปเวลา '+esttime_date_format_str);
										
										await sleep(Number(pause_seding_time_min)*60*1000);
										
										$("#pause_send_detail").text('');
										$("#send_next_time").text('');
										$("#processing_img").attr("src","app-assets/img/processing.gif");
										pause_send_time = new Date().getTime() + (Number(pause_seding_every_min)*60*1000);
										isSleep = true;
									}
								}
								
								//count_send_completed_in_min++;
								$('#count_sending_bubble_per_min').text(count_send_completed_in_min);
								
								if(cfg_tf_msg_rate_limit_per_min>0){
									if(count_send_completed_in_min>=cfg_tf_msg_rate_limit_per_min){
										let time_now_this = new Date.getTime();
										if(now_limit_per_min_time>time_now_this){
											$('#count_sending_bubble_per_min').text(cfg_tf_msg_rate_limit_per_min + ' หยุดชั่วคราว');
											var d = new Date(now_limit_per_min_time+ (now_limit_per_min_time-time_now_this));
											var esttime_date_format_str = d.getFullYear().toString()+"-"+padDigits(d.getMonth()+1,2)+"-"+padDigits(d.getDate(),2)+" "+padDigits(d.getHours(),2)+":"+padDigits(d.getMinutes(),2)+":"+padDigits(d.getSeconds(),2);
											
											$("#processing_img").attr("src","app-assets/img/waiting.gif");
											$("#pause_send_detail").text('พักส่ง '+ ((now_limit_per_min_time-time_now_this)/1000) +' วินาที');
											$("#send_next_time").text('ส่งถัดไปเวลา '+esttime_date_format_str);
											
											await sleep(now_limit_per_min_time-time_now_this);
											
											count_send_completed_in_min = 0;
											$('#count_sending_bubble_per_min').text(0);
											$("#pause_send_detail").text('');
											$("#send_next_time").text('');
											$("#processing_img").attr("src","app-assets/img/processing.gif");
											isSleep = true;
										}else{
											count_send_completed_in_min = 0;
											$('#count_sending_bubble_per_min').text(0);
										}
										now_limit_per_min_time = new Date.getTime()+60000;	//next friend 1 minute
									}
								}
								if(CFG_TF_MSG_RATE_LIMIT_BUBBLE_ITERATE){
									if(CFG_TF_MSG_RATE_LIMIT_BUBBLE_PAUSE_TIME_SEC){
										if(CFG_TF_MSG_RATE_LIMIT_BUBBLE_ITERATE>0 && CFG_TF_MSG_RATE_LIMIT_BUBBLE_PAUSE_TIME_SEC>0){
											if(isSleep==false){
												if(count_send_bubble_completed_iterate>=CFG_TF_MSG_RATE_LIMIT_BUBBLE_ITERATE){
													$('#count_sending_bubble_iterate').text(count_send_bubble_completed_iterate + ' หยุดชั่วคราว');
													
													var d = new Date(new Date().getTime()+ (Number(CFG_TF_MSG_RATE_LIMIT_BUBBLE_PAUSE_TIME_SEC)*1000));
													var esttime_date_format_str = d.getFullYear().toString()+"-"+padDigits(d.getMonth()+1,2)+"-"+padDigits(d.getDate(),2)+" "+padDigits(d.getHours(),2)+":"+padDigits(d.getMinutes(),2)+":"+padDigits(d.getSeconds(),2);
													document.getElementById("stop_time").innerHTML="ถัดไป "+" "+esttime_date_format_str;
													$("#processing_img").attr("src","app-assets/img/waiting.gif");
													$("#pause_send_detail").text('พักส่ง '+CFG_TF_MSG_RATE_LIMIT_BUBBLE_PAUSE_TIME_SEC+' วินาที');
													$("#send_next_time").text('ส่งถัดไปเวลา '+esttime_date_format_str);
													
													await sleep(Number(CFG_TF_MSG_RATE_LIMIT_BUBBLE_PAUSE_TIME_SEC)*1000);
													
													count_send_bubble_completed_iterate = 0;
													$('#count_sending_bubble_iterate').text(0);
													$("#pause_send_detail").text('');
													$("#send_next_time").text('');
													$("#processing_img").attr("src","app-assets/img/processing.gif");
													isSleep = true;
												}
											}
										}
									}
								}
								if(CFG_TF_MSG_RATE_LIMIT_PERSON_ITERATE){
									if(CFG_TF_MSG_RATE_LIMIT_PERSON_PAUSE_TIME_SEC){
										if(CFG_TF_MSG_RATE_LIMIT_PERSON_ITERATE>0 && CFG_TF_MSG_RATE_LIMIT_PERSON_PAUSE_TIME_SEC>0){
											if(isSleep==false){
												if(count_send_person_completed_iterate>=CFG_TF_MSG_RATE_LIMIT_PERSON_ITERATE){
													$('#count_sending_person_iterate').text(count_send_person_completed_iterate + ' หยุดชั่วคราว');
													
													var d = new Date(new Date().getTime()+ (Number(CFG_TF_MSG_RATE_LIMIT_PERSON_PAUSE_TIME_SEC)*1000));
													var esttime_date_format_str = d.getFullYear().toString()+"-"+padDigits(d.getMonth()+1,2)+"-"+padDigits(d.getDate(),2)+" "+padDigits(d.getHours(),2)+":"+padDigits(d.getMinutes(),2)+":"+padDigits(d.getSeconds(),2);
													document.getElementById("stop_time").innerHTML="ถัดไป "+" "+esttime_date_format_str;
													$("#processing_img").attr("src","app-assets/img/waiting.gif");
													$("#pause_send_detail").text('พักส่ง '+CFG_TF_MSG_RATE_LIMIT_PERSON_PAUSE_TIME_SEC+' วินาที');
													$("#send_next_time").text('ส่งถัดไปเวลา '+esttime_date_format_str);

													await sleep(Number(CFG_TF_MSG_RATE_LIMIT_PERSON_PAUSE_TIME_SEC)*1000);
													
													count_send_person_completed_iterate = 0;
													$('#count_sending_person_iterate').text(0);
													$("#pause_send_detail").text('');
													$("#send_next_time").text('');
													$("#processing_img").attr("src","app-assets/img/processing.gif");
													isSleep = true;
												}
											}
										}
									}
								}
								
								broad_none_block();
							}else{
								draw_report();
							}
						}else{
							draw_report();
						}
					},100);
				}
		//}

		async function draw_report(){
			action = await checkActionStatus();

			let act_msg = "";
			if(action==2){	//pause
				act_msg = "หยุดขั่วคราว";
				status_stop_pause = 2;	//
				fbinboxstatusdone = 2;
				await setStopJob(tot_send_friends_count,true,2);
				//localStorage.setItem('fbinboxstatusdone', 2);
			}else{
				if(action==0){
					act_msg = "หยุดส่งข้อความ";
					//localStorage.setItem('fbinboxstatusdone', 0);
					fbinboxstatusdone = 0;
					status_stop_pause = 0;	//
				}else{
					act_msg = "เสร็จ";
					//localStorage.setItem('fbinboxstatusdone', 3);
					fbinboxstatusdone = 3;
					status_stop_pause = 3;	//
				}
				await setStopJob(0,false,3);
				showStartButton();
			}
			var d=new Date();
			var esttime_date_format_str = d.getFullYear().toString()+"-"+padDigits(d.getMonth()+1,2)+"-"+padDigits(d.getDate(),2)+" "+padDigits(d.getHours(),2)+":"+padDigits(d.getMinutes(),2)+":"+padDigits(d.getSeconds(),2);
			document.getElementById("stop_time").innerHTML=act_msg+" "+esttime_date_format_str;
			show_msg_report("","","2",'<i style="font-weight:900;color:#14f200;">&nbsp;&nbsp;'+act_msg+'</i>');
			
			//runningProgress(beginfriends.length,status_stop_pause);
			runningProgress(friend,status_stop_pause);
		}
		
	}else if(threads<2){	//single thread
		$('#my_header').text('ระบบกำลังทำงานอยู่ '+' single '+threads);
		const awsj = await asyncSend(beginfriends,1,beginfriends.length);
		let action = await checkActionStatus();
		//console.log("finished "+awsj);
		
		let act_msg = "";
		if(action==2){	//pause
			act_msg = "หยุดขั่วคราว";
			status_stop_pause = 2;	//
			fbinboxstatusdone = 2;
			await setStopJob(tot_send_friends_count,true,2);
			//localStorage.setItem('fbinboxstatusdone', 2);
			
		}else{
			await setStopJob(0,false,3);
			if(action==0){
				act_msg = "หยุดส่งข้อความ";
				fbinboxstatusdone = 0;
				//localStorage.setItem('fbinboxstatusdone', 0);
				status_stop_pause = 0;	//
			}else{
				act_msg = "เสร็จ";
				fbinboxstatusdone = 3;
				//localStorage.setItem('fbinboxstatusdone', 3);
				status_stop_pause = 3;	//
			}
			showStartButton();
		}
		var d=new Date();
		var esttime_date_format_str = d.getFullYear().toString()+"-"+padDigits(d.getMonth()+1,2)+"-"+padDigits(d.getDate(),2)+" "+padDigits(d.getHours(),2)+":"+padDigits(d.getMinutes(),2)+":"+padDigits(d.getSeconds(),2);
		document.getElementById("stop_time").innerHTML=act_msg+" "+esttime_date_format_str;
		show_msg_report("","","2",'<i style="font-weight:900;color:#14f200;">&nbsp;&nbsp;'+act_msg+'</i>');
		
		runningProgress(beginfriends.length,status_stop_pause);
	}else{
		$('#my_header').text('ระบบกำลังทำงานอยู่ '+' multiple '+threads);
		let iii=(-1);
		const allFriendsLength = beginfriends.length;
		let tasks = [];
		
		iii=(-1);
		const flagment = 5; //10;	//5;	//flagment	//10
		
		timeout();
		async function timeout() {
			setTimeout(async function () {
				iii++;	//start at loop 0	next loop
				const start = (iii*flagment);	//thread flagment
				
				const end = (start+flagment)<allFriendsLength?(start+flagment):allFriendsLength;
				const friends = await beginfriends.slice(start,end);	//split flagment = 10;
				
				const xfn=async function f(){
					const aws = await asyncSend(friends,threads,allFriendsLength);
					//console.log("After async Send");
					//console.log(aws);
					//console.log("task:"+(iii+1)+" completed->"+aws.friendsSend+"/"+aws.friendsLength+" Total->"+aws.friendsTotSend+"/"+aws.friendsTotLength+" friends");
					return new Promise(resolve => { resolve(aws);});
				};
				
				setTimeout(async function () {
					tasks.push(xfn);
					
					
					if(iii%threads==0 || end==allFriendsLength){
						//console.log(tasks);
						//const promises = await tasks.map(p => p());
						
						//const promises = await tasks.map(async function (anAsyncFunc){ await anAsyncFunc()});
						//console.log(promises);
						//console.log('All done start '+(iii+1));
						const results = await Promise.all(tasks.map(async (anAsyncFunction) => await anAsyncFunction()));
						
						
						//console.log(results);
						const lastResult= results[results.length-1];
						//console.log(lastResult);
						//console.log('All done completed '+(iii+1));

						if(typeof lastResult!=="undefined" && lastResult!=null){
							//console.log("task:"+(iii+1)+" completed->"+lastResult.friendsSend+"/"+lastResult.friendsLength+" Total->"+lastResult.friendsTotSend+"/"+lastResult.friendsTotLength+" friends");
						}
						
							tasks.length=0;
							tasks=[];
							
							let action = status_stop_pause;//await checkActionStatus();
							if(typeof action!="undefined" && action!=null){
								action = Number(action);
							}else{
								action = 1;
							}
							if (end==allFriendsLength || status_running==false || Number(action)!=1){
								//console.log('stop job in:'+(iii+1));
								if(Number(action)==3 || end==allFriendsLength){	//
									await setStopJob(tot_send_friends_count,false,3);
									await checkActionStatus();
									status_stop_pause = 3;	//done
									fbinboxstatusdone = 3;
									var d=new Date();
									var esttime_date_format_str = d.getFullYear().toString()+"-"+padDigits(d.getMonth()+1,2)+"-"+padDigits(d.getDate(),2)+" "+padDigits(d.getHours(),2)+":"+padDigits(d.getMinutes(),2)+":"+padDigits(d.getSeconds(),2);
									document.getElementById("stop_time").innerHTML="เสร็จ "+" "+esttime_date_format_str;
									show_msg_report("","","1",'<i style="font-weight:900;color:#14f200;">&nbsp;&nbsp;เสร็จ</i>');
									//localStorage.setItem('fbinboxstatusdone', 3);	//done
									//console.log("Finished...."+status_stop_pause);
									runningProgress(active_friends_count,status_stop_pause);
									showStartButton();
									return 0;
								}else if(Number(action)==2){	//pause
									/*
									setStopJob(tot_send_friends_count,true).then((data)=>{
										//console.log(data);
										checkActionStatus();
										return 0;
									});
									*/
									await setStopJob(tot_send_friends_count,true,2);
									await checkActionStatus();
									status_stop_pause = 2;	//pause
									fbinboxstatusdone = 2;
									var d=new Date();
									var esttime_date_format_str = d.getFullYear().toString()+"-"+padDigits(d.getMonth()+1,2)+"-"+padDigits(d.getDate(),2)+" "+padDigits(d.getHours(),2)+":"+padDigits(d.getMinutes(),2)+":"+padDigits(d.getSeconds(),2);
									document.getElementById("stop_time").innerHTML="หยุดชั่วคราว "+" "+esttime_date_format_str;
									show_msg_report("","","2",'<i style="font-weight:900;color:#14f200;">&nbsp;&nbsp;หยุดขั่วคราว</i>');
									//localStorage.setItem('fbinboxstatusdone', 2);	//pause
									runningProgress(active_friends_count,status_stop_pause);
									
									return 0;
								}else{
									/*
									setStopJob().then((data)=>{
										//console.log(data);
										checkActionStatus();
										return 0;
									});
									*/
									await setStopJob(0,false,0);
									await checkActionStatus();
									status_stop_pause = 0;	//stop
									fbinboxstatusdone = 0;
									var d=new Date();
									var esttime_date_format_str = d.getFullYear().toString()+"-"+padDigits(d.getMonth()+1,2)+"-"+padDigits(d.getDate(),2)+" "+padDigits(d.getHours(),2)+":"+padDigits(d.getMinutes(),2)+":"+padDigits(d.getSeconds(),2);
									document.getElementById("stop_time").innerHTML="หยุดทำงาน "+" "+esttime_date_format_str;
									show_msg_report("","","2",'<i style="font-weight:900;color:#14f200;">&nbsp;&nbsp;หยุดส่งข้อความแล้ว</i>');
									
									runningProgress(active_friends_count,status_stop_pause);
									//localStorage.setItem('fbinboxstatusdone', 0);	//stop
									return 0;
								}

							}else{
								(async function() {
									let action = status_stop_pause;//await checkActionStatus();
									//console.log("action in: "+ action);
									if(typeof action!="undefined" && action!=null){
										if(Number(action)!=1){
											//merge friends not implementation yet
											if(Number(action)==2){	//pause
												await setStopJob(tot_send_friends_count,true,2);
												await checkActionStatus();
												return 0;
											}else{
												await setStopJob(0,false,0);
												await checkActionStatus();
												return 0;
											}
										}
									}
								})();
								timeout();	//next friend
							}
							
						
					}else{
						timeout();	//next friend
					}
					
					
				},100);
				
			}, 100);
		}

	}
}

//split friends
const asyncSend = async (split_flagment_frns,threads,allFriendsLength) => {
	let friend=(-1);
	let completed_this_text=0;
	let completed_this_file=0;
	let failed_this_text=0;
	let failed_this_file=0;
	let friends=[];
	if(!Array.isArray(split_flagment_frns)){friends.push(split_flagment_frns);}else{friends=split_flagment_frns;}
	let tasks = [];
	////////////////
	
	let pause_send_time = null;
	let pause_seding_every_min = 0;
	let pause_seding_time_min = 0;
	
	pause_seding_every_min = $('#pause_seding_every_min').val();
	pause_seding_time_min = $('#pause_seding_time_min').val();
	
	if(!pause_seding_every_min){pause_seding_every_min=0;}
	if(!pause_seding_time_min){pause_seding_time_min=0;}
	if (isNaN(pause_seding_every_min)) {pause_seding_every_min=0;}
	if (isNaN(pause_seding_time_min)) {pause_seding_time_min=0;}
	pause_seding_every_min = Number(pause_seding_every_min);
	pause_seding_time_min = Number(pause_seding_time_min);
	
	let cfg_tf_msg_rate_limit_per_min = 0;
	//count_send_completed_in_min = 0;
	//$('#count_sending_bubble_per_min').text(count_send_completed_in_min);
	
	cfg_tf_msg_rate_limit_per_min = $('#cfg_tf_msg_rate_limit_per_min').val();
	if(!cfg_tf_msg_rate_limit_per_min){cfg_tf_msg_rate_limit_per_min=0;}
	if (isNaN(cfg_tf_msg_rate_limit_per_min)) {cfg_tf_msg_rate_limit_per_min=0;}
	cfg_tf_msg_rate_limit_per_min = Number(cfg_tf_msg_rate_limit_per_min);
	
	let now_limit_per_min_time = new Date().getTime()+60000;	// 1 minute
	
	if(pause_seding_every_min>0){
		if(pause_seding_time_min>0){
			pause_send_time = new Date().getTime() + (Number(pause_seding_every_min)*60*1000);
		}
	}
	////////////////
	
	//signle thread
	if(threads<2){
		let lastResult="";
		let friendsTotSend=0;
		let friendsTotSendErrorCount=0;
		let action = 1;	//running
		friendsTotLength = friends.length;
		////////////////
		
		$('#my_header').text('ระบบกำลังทำงานอยู่ '+' single '+threads);
		for (friend=0;friend<friends.length;friend++){
				try{
					if(status_running==false){
						break;
					}
					
					let isSleep = false;
					if(pause_send_time!=null){
						let send_now = new Date().getTime();
						if(send_now>pause_send_time){
							//console.log("now 2 "+send_now +"\t"+ "pause_send_time "+pause_send_time);
							var d = new Date(send_now+ (Number(pause_seding_time_min)*60*1000));
							var esttime_date_format_str = d.getFullYear().toString()+"-"+padDigits(d.getMonth()+1,2)+"-"+padDigits(d.getDate(),2)+" "+padDigits(d.getHours(),2)+":"+padDigits(d.getMinutes(),2)+":"+padDigits(d.getSeconds(),2);
							document.getElementById("stop_time").innerHTML="ถัดไป "+" "+esttime_date_format_str;
							$("#processing_img").attr("src","app-assets/img/waiting.gif");
							$("#pause_send_detail").text('พักส่ง '+ pause_seding_time_min +' นาที');
							$("#send_next_time").text('ส่งถัดไปเวลา '+esttime_date_format_str);
					
							await sleep(Number(pause_seding_time_min)*60*1000);
							
							$("#pause_send_detail").text('');
							$("#send_next_time").text('');
							$("#processing_img").attr("src","app-assets/img/processing.gif");
							pause_send_time = new Date().getTime() + (Number(pause_seding_every_min)*60*1000);
							isSleep = true;
							//console.log("continue sending 2 " +pause_send_time);
						}
					}
					
					//console.log("continue 2");
					const result = await broadcast_msg(friends[friend]);//.then((result)=>{
					
					count_send_person_completed_iterate++;
					$('#count_sending_person_iterate').text(count_send_person_completed_iterate);
	
					//count_send_completed_in_min++;
					$('#count_sending_bubble_per_min').text(count_send_completed_in_min);
					
					if(cfg_tf_msg_rate_limit_per_min>0){
						if(count_send_completed_in_min>=cfg_tf_msg_rate_limit_per_min){
							let time_now_this = new Date.getTime();
							if(now_limit_per_min_time>time_now_this){
								$('#count_sending_bubble_per_min').text(cfg_tf_msg_rate_limit_per_min + ' หยุดชั่วคราว');
								var d = new Date(now_limit_per_min_time+ (now_limit_per_min_time-time_now_this));
								var esttime_date_format_str = d.getFullYear().toString()+"-"+padDigits(d.getMonth()+1,2)+"-"+padDigits(d.getDate(),2)+" "+padDigits(d.getHours(),2)+":"+padDigits(d.getMinutes(),2)+":"+padDigits(d.getSeconds(),2);
								$("#processing_img").attr("src","app-assets/img/waiting.gif");
								$("#pause_send_detail").text('พักส่ง '+ ((now_limit_per_min_time-time_now_this)/1000) +' วินาที');
								$("#send_next_time").text('ส่งถัดไปเวลา '+esttime_date_format_str);
								
								await sleep(now_limit_per_min_time-time_now_this);
								
								count_send_completed_in_min = 0;
								$('#count_sending_bubble_per_min').text(0);
								$("#pause_send_detail").text('');
								$("#send_next_time").text('');
								$("#processing_img").attr("src","app-assets/img/processing.gif");
								isSleep = true;
							}else{
								count_send_completed_in_min = 0;
								$('#count_sending_bubble_per_min').text(0);
							}
							now_limit_per_min_time = new Date.getTime()+60000;	//next friend 1 minute
						}
					}
					if(CFG_TF_MSG_RATE_LIMIT_BUBBLE_ITERATE){
						if(CFG_TF_MSG_RATE_LIMIT_BUBBLE_PAUSE_TIME_SEC){
							if(CFG_TF_MSG_RATE_LIMIT_BUBBLE_ITERATE>0 && CFG_TF_MSG_RATE_LIMIT_BUBBLE_PAUSE_TIME_SEC>0){
								if(isSleep==false){
									if(count_send_bubble_completed_iterate>=CFG_TF_MSG_RATE_LIMIT_BUBBLE_ITERATE){
										$('#count_sending_bubble_iterate').text(count_send_bubble_completed_iterate + ' หยุดชั่วคราว');
										
										var d = new Date(new Date().getTime()+ (Number(CFG_TF_MSG_RATE_LIMIT_BUBBLE_PAUSE_TIME_SEC)*1000));
										var esttime_date_format_str = d.getFullYear().toString()+"-"+padDigits(d.getMonth()+1,2)+"-"+padDigits(d.getDate(),2)+" "+padDigits(d.getHours(),2)+":"+padDigits(d.getMinutes(),2)+":"+padDigits(d.getSeconds(),2);
										document.getElementById("stop_time").innerHTML="ถัดไป "+" "+esttime_date_format_str;
										$("#processing_img").attr("src","app-assets/img/waiting.gif");
										$("#pause_send_detail").text('พักส่ง '+ CFG_TF_MSG_RATE_LIMIT_BUBBLE_PAUSE_TIME_SEC +' วินาที');
										$("#send_next_time").text('ส่งถัดไปเวลา '+esttime_date_format_str);
										
										await sleep(Number(CFG_TF_MSG_RATE_LIMIT_BUBBLE_PAUSE_TIME_SEC)*1000);
										
										count_send_bubble_completed_iterate = 0;
										$('#count_sending_bubble_iterate').text(0);
										$("#pause_send_detail").text('');
										$("#send_next_time").text('');
										$("#processing_img").attr("src","app-assets/img/processing.gif");
										isSleep = true;
									}
								}
							}
						}
					}
					if(CFG_TF_MSG_RATE_LIMIT_PERSON_ITERATE){
						if(CFG_TF_MSG_RATE_LIMIT_PERSON_PAUSE_TIME_SEC){
							if(CFG_TF_MSG_RATE_LIMIT_PERSON_ITERATE>0 && CFG_TF_MSG_RATE_LIMIT_PERSON_PAUSE_TIME_SEC>0){
								if(isSleep==false){
									if(count_send_person_completed_iterate>=CFG_TF_MSG_RATE_LIMIT_PERSON_ITERATE){
										$('#count_sending_person_iterate').text(count_send_person_completed_iterate + ' หยุดชั่วคราว');
										
										var d = new Date(new Date().getTime()+ (Number(CFG_TF_MSG_RATE_LIMIT_PERSON_PAUSE_TIME_SEC)*1000));
										var esttime_date_format_str = d.getFullYear().toString()+"-"+padDigits(d.getMonth()+1,2)+"-"+padDigits(d.getDate(),2)+" "+padDigits(d.getHours(),2)+":"+padDigits(d.getMinutes(),2)+":"+padDigits(d.getSeconds(),2);
										document.getElementById("stop_time").innerHTML="ถัดไป "+" "+esttime_date_format_str;
										$("#processing_img").attr("src","app-assets/img/waiting.gif");
										$("#pause_send_detail").text('พักส่ง '+ CFG_TF_MSG_RATE_LIMIT_PERSON_PAUSE_TIME_SEC +' วินาที');
										$("#send_next_time").text('ส่งถัดไปเวลา '+esttime_date_format_str);
										
										await sleep(Number(CFG_TF_MSG_RATE_LIMIT_PERSON_PAUSE_TIME_SEC)*1000);
										
										count_send_person_completed_iterate = 0;
										$('#count_sending_person_iterate').text(0);
										$("#pause_send_detail").text('');
										$("#send_next_time").text('');
										$("#processing_img").attr("src","app-assets/img/processing.gif");
										isSleep = true;
									}
								}
							}
						}
					}
					
					completed_this_text+=result.thisSendTextSuccess;
					completed_this_file+=result.thisSendFileSuccess;
					failed_this_text+=result.thisSendTextFailed;
					failed_this_file+=result.thisSendFileFailed;
					friendsTotSend = result.totMemberSendCount;
					friendsTotSendErrorCount = result.totMemberSendErrorCount;

					if(Number(status_stop_pause)!=1){
						break;
					}
					
				}catch(exc){console.log(exc);}
		}
		
		////// Sending completed //////
		return new Promise(resolve => {
			resolve({
					statusCode:(friend>=friends.length?true:false),
					friendsTotLength: allFriendsLength,
					friendsTotSend: friendsTotSend,
					friendsTotSendErr: friendsTotSendErrorCount,
					friendsLength: friends.length,
					friendsSend: friend,
					thisSendTextSuccess: completed_this_text,
					thisSendTextFailed: failed_this_text,
					thisSendFileSuccess: completed_this_file,
					thisSendFileFailed: failed_this_file,
					tot_file_succescount: tot_file_succescount,
					tot_file_failed: tot_file_failed,
					tot_text_succescount: tot_text_succescount,
					tot_text_failed: tot_text_failed,
					tot_send_friends_count: tot_send_friends_count,
					data: lastResult,
					action: Number(action)
			});
		});
	}
	//else
	////// Multiple thread //////////
	////// Threads sender here //////
	//console.log("before sendthread");
	//$('#my_header').text('ระบบกำลังทำงานอยู่ '+' multiple '+threads);
	$('#my_header').text('ระบบกำลังทำงานอยู่ '+ APP_VERSION + ' : ' + LOGIN_EMAIL);
	let sendthread = await timeout();
	
	return new Promise(resolve => {
		//console.log(sendthread);
		resolve(sendthread);
	});
	function timeout() {
		return new Promise(async (resolve) => {
				//friend++;
				//const target_id=friend.id;
				//const target_name=friend.name;
				let friendsTotSend=0;
				let friendsTotSendErrorCount=0;
				friendsTotLength += friends.length;
				for(friend=0;friend<friends.length;friend++){
					//tot_send_friends_count++;
					const frn = await friends[friend];	//flagment = 10;
					const xfn=async function f(){

						const result = await broadcast_msg(frn);//.then((result)=>{
						completed_this_text+=result.thisSendTextSuccess;
						completed_this_file+=result.thisSendFileSuccess;
						failed_this_text+=result.thisSendTextFailed;
						failed_this_file+=result.thisSendFileFailed;
						friendsTotSend = result.totMemberSendCount;
						friendsTotSendErrorCount = result.totMemberSendErrorCount;
						
						count_send_person_completed_iterate++;
						$('#count_sending_person_iterate').text(count_send_person_completed_iterate);
						
						//console.log("friendsTotSend: "+friendsTotSend);
						//console.log("friendsTotSendErrorCount: "+ friendsTotSendErrorCount);
						//console.log("friend count: "+(friendsTotSend)+"->text:"+result.totTextCompleted+"/"+result.totTextFailed+", files:"+result.totFileCompleted+"/"+result.totFileFailed);
						//return result;
						
						//---/////////
						let isSleep = false;
						///////////////
						if(pause_send_time!=null){
							let send_now = new Date().getTime();
							if(send_now>pause_send_time){
								var d = new Date(send_now+ (Number(pause_seding_time_min)*60*1000));
								var esttime_date_format_str = d.getFullYear().toString()+"-"+padDigits(d.getMonth()+1,2)+"-"+padDigits(d.getDate(),2)+" "+padDigits(d.getHours(),2)+":"+padDigits(d.getMinutes(),2)+":"+padDigits(d.getSeconds(),2);
								document.getElementById("stop_time").innerHTML="ถัดไป "+" "+esttime_date_format_str;
								$("#processing_img").attr("src","app-assets/img/waiting.gif");
								$("#pause_send_detail").text('พักส่ง '+ pause_seding_time_min +' นาที');
								$("#send_next_time").text('ส่งถัดไปเวลา '+esttime_date_format_str);
								
								await sleep(Number(pause_seding_time_min)*60*1000);
								
								$("#pause_send_detail").text('');
								$("#send_next_time").text('');
								$("#processing_img").attr("src","app-assets/img/processing.gif");
								pause_send_time = new Date().getTime() + (Number(pause_seding_every_min)*60*1000);
								isSleep = true;
							}
						}
						
						//count_send_completed_in_min++;
						$('#count_sending_bubble_per_min').text(count_send_completed_in_min);
						
						if(cfg_tf_msg_rate_limit_per_min>0){
							if(count_send_completed_in_min>=cfg_tf_msg_rate_limit_per_min){
								let time_now_this = new Date.getTime();
								if(now_limit_per_min_time>time_now_this){
									$('#count_sending_bubble_per_min').text(cfg_tf_msg_rate_limit_per_min + ' หยุดชั่วคราว');
									var d = new Date(now_limit_per_min_time+ (now_limit_per_min_time-time_now_this));
									var esttime_date_format_str = d.getFullYear().toString()+"-"+padDigits(d.getMonth()+1,2)+"-"+padDigits(d.getDate(),2)+" "+padDigits(d.getHours(),2)+":"+padDigits(d.getMinutes(),2)+":"+padDigits(d.getSeconds(),2);
									document.getElementById("stop_time").innerHTML="ถัดไป "+" "+esttime_date_format_str;
									$("#processing_img").attr("src","app-assets/img/waiting.gif");
									$("#pause_send_detail").text('พักส่ง '+ ((now_limit_per_min_time-time_now_this)/1000) +' วินาที');
									$("#send_next_time").text('ส่งถัดไปเวลา '+esttime_date_format_str);
									
									await sleep(now_limit_per_min_time-time_now_this);
									
									count_send_completed_in_min = 0;
									$('#count_sending_bubble_per_min').text(0);
									$("#pause_send_detail").text('');
									$("#send_next_time").text('');
									$("#processing_img").attr("src","app-assets/img/processing.gif");
									isSleep = true;
								}else{
									count_send_completed_in_min = 0;
									$('#count_sending_bubble_per_min').text(0);
								}
								now_limit_per_min_time = new Date.getTime()+60000;	//next friend 1 minute
							}
						}
						if(CFG_TF_MSG_RATE_LIMIT_BUBBLE_ITERATE){
							if(CFG_TF_MSG_RATE_LIMIT_BUBBLE_PAUSE_TIME_SEC){
								if(CFG_TF_MSG_RATE_LIMIT_BUBBLE_ITERATE>0 && CFG_TF_MSG_RATE_LIMIT_BUBBLE_PAUSE_TIME_SEC>0){
									if(isSleep==false){
										if(count_send_bubble_completed_iterate>=CFG_TF_MSG_RATE_LIMIT_BUBBLE_ITERATE){
											$('#count_sending_bubble_iterate').text(count_send_bubble_completed_iterate + ' หยุดชั่วคราว');
											count_send_bubble_completed_iterate = 0;
											var d = new Date(new Date().getTime()+ (Number(CFG_TF_MSG_RATE_LIMIT_BUBBLE_PAUSE_TIME_SEC)*1000));
											var esttime_date_format_str = d.getFullYear().toString()+"-"+padDigits(d.getMonth()+1,2)+"-"+padDigits(d.getDate(),2)+" "+padDigits(d.getHours(),2)+":"+padDigits(d.getMinutes(),2)+":"+padDigits(d.getSeconds(),2);
											document.getElementById("stop_time").innerHTML="ถัดไป "+" "+esttime_date_format_str;
											$("#processing_img").attr("src","app-assets/img/waiting.gif");
											$("#pause_send_detail").text('พักส่ง '+ CFG_TF_MSG_RATE_LIMIT_BUBBLE_PAUSE_TIME_SEC +' วินาที');
											$("#send_next_time").text('ส่งถัดไปเวลา '+esttime_date_format_str);
											
											await sleep(Number(CFG_TF_MSG_RATE_LIMIT_BUBBLE_PAUSE_TIME_SEC)*1000);
											
											$('#count_sending_bubble_iterate').text(0);
											$("#pause_send_detail").text('');
											$("#send_next_time").text('');
											$("#processing_img").attr("src","app-assets/img/processing.gif");
											isSleep = true;
										}
									}
								}
							}
						}
						if(CFG_TF_MSG_RATE_LIMIT_PERSON_ITERATE){
							if(CFG_TF_MSG_RATE_LIMIT_PERSON_PAUSE_TIME_SEC){
								if(CFG_TF_MSG_RATE_LIMIT_PERSON_ITERATE>0 && CFG_TF_MSG_RATE_LIMIT_PERSON_PAUSE_TIME_SEC>0){
									if(isSleep==false){
										if(count_send_person_completed_iterate>=CFG_TF_MSG_RATE_LIMIT_PERSON_ITERATE){
											$('#count_sending_person_iterate').text(count_send_person_completed_iterate + ' หยุดชั่วคราว');
											count_send_person_completed_iterate = 0;
											var d = new Date(new Date().getTime()+ (Number(CFG_TF_MSG_RATE_LIMIT_PERSON_PAUSE_TIME_SEC)*1000));
											var esttime_date_format_str = d.getFullYear().toString()+"-"+padDigits(d.getMonth()+1,2)+"-"+padDigits(d.getDate(),2)+" "+padDigits(d.getHours(),2)+":"+padDigits(d.getMinutes(),2)+":"+padDigits(d.getSeconds(),2);
											document.getElementById("stop_time").innerHTML="ถัดไป "+" "+esttime_date_format_str;
											$("#processing_img").attr("src","app-assets/img/waiting.gif");
											$("#pause_send_detail").text('พักส่ง '+ CFG_TF_MSG_RATE_LIMIT_PERSON_PAUSE_TIME_SEC +' วินาที');
											$("#send_next_time").text('ส่งถัดไปเวลา '+esttime_date_format_str);
											
											await sleep(Number(CFG_TF_MSG_RATE_LIMIT_PERSON_PAUSE_TIME_SEC)*1000);
											
											$('#count_sending_person_iterate').text(0);
											$("#pause_send_detail").text('');
											$("#send_next_time").text('');
											$("#processing_img").attr("src","app-assets/img/processing.gif");
											isSleep = true;
										}
									}
								}
							}
						}
						///////////////
						
						//-----////////
						
						return new Promise(resolve => { resolve(result);});
					};
					
					tasks.push(xfn);
					
					
				}
				
				//console.log(tasks);
				//const results = await getData(tasks);
				const promises = await tasks.map(p => p());
				const results = await Promise.all(promises);
				const lastResult= results[results.length-1];
				tasks.length=0;
				tasks = [];
				//console.log('done '+(results.length));
				//console.log(results);
				//console.log("tot friend: "+(results.length)+"->text:"+lastResult.totTextCompleted+"/"+lastResult.totTextFailed+", files:"+lastResult.totFileCompleted+"/"+lastResult.totFileFailed);
				
				//tot_send_friends_count += results.length;

				resolve({
					statusCode:(friend>=friends.length?true:false),
					friendsTotLength: allFriendsLength,
					friendsTotSend: friendsTotSend,
					friendsTotSendErr: friendsTotSendErrorCount,
					friendsLength: friends.length,
					friendsSend: friend,
					thisSendTextSuccess: completed_this_text,
					thisSendTextFailed: failed_this_text,
					thisSendFileSuccess: completed_this_file,
					thisSendFileFailed: failed_this_file,
					tot_file_succescount:tot_file_succescount,
					tot_file_failed:tot_file_failed,
					tot_text_succescount:tot_text_succescount,
					tot_text_failed:tot_text_failed,
					tot_send_friends_count:tot_send_friends_count,
					data: lastResult
				});
				
		});
	}
}

//each friend
async function broadcast_msg(friend){
	const tbl = document.querySelector("#myOLBroadcastTable").tBodies[0];
	const num_rows = tbl.rows.length;
	let row_nums=0;
	let completed_text=0;
	let completed_file=0;
	let failed_text=0;
	let failed_file=0;
	
	let completed_this_text=0;
	let completed_this_file=0;
	let failed_this_text=0;
	let failed_this_file=0;
	
	let ratelimit=0;
	let target_id = friend.id;
	let target_name = friend.name;
	
	let something_send_failed = false;
	
	iSendFriendsCount++;
	tot_send_friends_count=iSendFriendsCount;

	for(row_nums=0;row_nums<num_rows;row_nums++){
		const tblrow=tbl.rows[row_nums];
		const msg=document.getElementById("text_"+tblrow.id+"col1").value;	//message id text_row1col1
		
		////Send text
		//// Separate text
		/*
		if (msg.match(/^\s*$/)){
			msg="";
		}else{
			const data = await sendText(friend,msg,row_nums);
			completed_text=data.totsendsuccess;
			failed_text=data.totsendfailed;
			completed_this_text+=data.thisSendSuccess;
			failed_this_text+=data.thisSendFailed;
			if(data.thiserror){
				something_send_failed = true;
			}
		}
		*/
		////////////
		
		////Send file
		const file=document.getElementById("file-"+tblrow.id+"col2");	//file id file-row1col2
		if (jQuery('#'+file.id).val().match(/^\s*$/)) {
			///// Send text only
			if (msg.match(/^\s*$/)){
				msg="";
			}else{
				const data = await sendText(friend,msg,row_nums);
				completed_text=data.totsendsuccess;
				failed_text=data.totsendfailed;
				completed_this_text+=data.thisSendSuccess;
				failed_this_text+=data.thisSendFailed;
				if(data.thiserror){
					something_send_failed = true;
				}
			}
		}else{
			const data = await sendFile(friend,file,row_nums);
			if(!data.thiserror){
				if(data.fbSendFiles!=""){
					//Send both text and picture
					let resp_fb_mes = await send_fb_messager(msg,target_id,target_name,data.fbSendFiles,"true",row_nums,data.thisSendSuccess,data.thisSendFailed);
					data.thiserror = !resp_fb_mes;
					if(data.thiserror){
						let prev_thisSendSuccess = data.thisSendSuccess;
						data.totsendfailed += prev_thisSendSuccess;
						data.thisSendFailed += prev_thisSendSuccess;
						data.totsendsuccess -= prev_thisSendSuccess;
						data.thisSendSuccess -= prev_thisSendSuccess;
						//totsendsuccess
						///////////////
						completed_file=data.totsendsuccess;
						failed_file=data.totsendfailed;
						
						completed_this_file+=data.thisSendSuccess;
						failed_this_file+=data.thisSendFailed;
						ratelimit +=data.thisSendSuccess;
					}else{
						completed_file=data.totsendsuccess;
						failed_file=data.totsendfailed;
						
						completed_this_file+=data.thisSendSuccess;
						failed_this_file+=data.thisSendFailed;
						ratelimit +=data.thisSendSuccess;
					}
				}else{
					completed_file=data.totsendsuccess;
					failed_file=data.totsendfailed;
					
					completed_this_file+=data.thisSendSuccess;
					failed_this_file+=data.thisSendFailed;
					ratelimit +=data.thisSendSuccess;
				}
			}else{
				completed_file=data.totsendsuccess;
				failed_file=data.totsendfailed;
				
				completed_this_file+=data.thisSendSuccess;
				failed_this_file+=data.thisSendFailed;
				ratelimit +=data.thisSendSuccess;
			}
			if(data.thiserror){
				something_send_failed = true;
			}
		}
		
	}
	
	if(something_send_failed){
		memberSendErrorCount++;
	}
	

	if(completed_this_text>0 || completed_this_file>0){
		//push to success list
		if(ct_tf_label_user_all_send_success.length==0){
			let accountName = "";
			let folder ="";
			if(typeof label_user_all[0].accountName!="undefined"){accountName=label_user_all[0].accountName;}
			if(typeof label_user_all[0].folder!="undefined"){folder=label_user_all[0].folder;}
			ct_tf_label_user_all_send_success.push({
				'account_id': "'"+target_id,
				'id': target_id,
				'name': removeXMLInvalidChars(target_name),	//gfunc.js
				'accountName':accountName,
				'folder':folder
			});
		}else{
			ct_tf_label_user_all_send_success.push({
				'account_id': "'"+target_id,
				'id': target_id,
				'name': removeXMLInvalidChars(target_name),	//gfunc.js
				'accountName':'',
				'folder':''
			});
		}
		move_to_done_folder(target_id,target_name);

		let randomSleep = 0;
		if(my_broadcastline_tdelay>0){
			randomSleep = getRandomArbitrary((my_broadcastline_sdelay*1000),(my_broadcastline_tdelay*1000));
		}
		if(isNaN(randomSleep)){randomSleep=0;}
		randomSleep = Number(randomSleep);
		if(randomSleep>0){
			try{
				iziToast.info({
					title: 'หน่วงเวลา '+ Math.floor(randomSleep/1000) + ' วินาที',
					position: 'topLeft',
					timeout: randomSleep,
					message: '',
				});
			}catch(ex){}
			show_msg_report("","","2","หน่วงเวลา "+ Math.floor(randomSleep/1000) + " วินาที");
			await sleep(Number(randomSleep));
		}
	}
	
	runningProgress(iSendFriendsCount,1);	//loop in friends
	
	///// Estimated time ///
	
	iCountAgv++;
	if(iCountAgv>100){
		var timeused=new Date().getTime() - dtStartTime.getTime();
		var avg=timeused/iCountAgv;
		var esttime = new Date().getTime()+Math.ceil( (Number(active_friends_count) - Number(tot_send_friends_count) ) *avg);
		var d=new Date(esttime);
		var esttime_date_format_str = d.getFullYear().toString()+"-"+padDigits(d.getMonth()+1,2)+"-"+padDigits(d.getDate(),2)+" "+padDigits(d.getHours(),2)+":"+padDigits(d.getMinutes(),2)+":"+padDigits(d.getSeconds(),2);
		document.getElementById("stop_time").innerHTML = "<i style='color:blue;'>ประมาณ "+esttime_date_format_str+"</i>";
		dtStartTime=new Date();
		iCountAgv=0;
	}
	
	/////////////////////
	
	///////////////////// Demo type rate limit /////////////////////
	if(user_type=="ทดลองใช้งาน" && Number(tf_demo_ratelimit_setting)>0){
		tf_demo_usage_ratelimit = Number(tf_demo_usage_ratelimit) + (Number(completed_this_text)+Number(completed_this_file));
		tf_demo_usage_ratelimit_left = Number(tf_demo_ratelimit_setting) - Number(tf_demo_usage_ratelimit);
		if(Number(tf_demo_usage_ratelimit_left)<0){tf_demo_usage_ratelimit_left=-1;}
		
		document.getElementById('plan_package').innerHTML=""+user_type+ " เหลือ "+ tf_demo_usage_ratelimit_left +" ข้อความ/วัน";
		document.getElementById('plan_demo_package').innerHTML=document.getElementById('plan_package').innerHTML
		
		if(Number(tf_demo_usage_ratelimit) > Number(tf_demo_ratelimit_setting)){
			Swal.fire({
				title: 'ไม่สามารถทำรายการได้ ',
				html: "ท่านได้ส่งข้อความครบตามจำนวนที่กำหนด ของตัวทดลองใช้งานฟรีแล้ว<br />หากต้องการปลดฟังชั่น ไม่จัดกัดการส่งข้อความต่อวัน กรุณาสอบถามโปรโมชั่นจากแอดมินได้ที่<br /><a href='" + LINE_URL_QRCODE + "'>Line : " + LINE_AT_ID + "</a>",
				showCancelButton: true,
				confirmButtonColor: '#3085d6',
				cancelButtonColor: '#d33',
				confirmButtonText: 'Yes'
			}).then((result) => {
				if (result.value) {
					var mywinUrl = window.open(LINE_URL_QRCODE, '_blank');
					mywinUrl.focus();
				}
			});
			var dnow = new Date();
			var curdate = dnow.toJSON().slice(0,10);
			curdate = server_date;	//Hack server
			if(tf_demo_usage_ratelimit_left<0){tf_demo_usage_ratelimit_left=-1;}
			ldb.set('tf_demo_usage_ratelimit_'+user_name, '0|'+curdate+'|'+ tf_demo_usage_ratelimit_left+'|'+tf_demo_ratelimit_setting);
			setStopJob(0,false,0);
		}
	}
	//////////////////////////////////////////////
	
	return({
		statusCode:(row_nums>0?true:false),
		statusText: (row_nums>0?"completed":"failed"),
		thisSendTextSuccess: completed_this_text,
		thisSendTextFailed: failed_this_text,
		thisSendFileSuccess: completed_this_file,
		thisSendFileFailed: failed_this_file,
		totTextCompleted: completed_text,
		totTextFailed: failed_text,
		totFileCompleted: completed_file,
		totFileFailed: failed_file,
		totMemberSendCount:iSendFriendsCount,
		totMemberSendErrorCount:memberSendErrorCount
	});
	
}

function postData(ajaxurl,data) {
		return $.ajax({
			url: ajaxurl,
			data: data,
			cache: false,
			contentType: false,
			processData: false,
			//async: true,   // this will solve the problem
			method: 'POST',
			type: 'POST', // For jQuery < 1.9
			//new
			beforeSend: function (xhr) {
				xhr.withCredentials = true; //Include this line
				//xhr.setRequestHeader('Accept', 'application/json, text/plain, */*');
				//xhr.setRequestHeader('x-xsrf-token', lineCSRF);
				//xhr.setRequestHeader('dataType', 'json');
			},
			mode: 'cors', // no-cors, *cors, same-origin
			cache: 'no-cache', // *default, no-cache, reload, force-cache, only-if-cached
			credentials: 'same-origin', // include, *same-origin, omit
		});
};

async function doAjax(ajaxurl,fdata,target_name,file_active) {
    let result="";
    try {
		try{
			$("#ufmn").show();
			$("#ufmn").css('color', 'white');
			$("#ufmn").html("กำลังอัพโหลดไฟล์ ของ " + target_name + " ไฟล์ที่ [" +file_active+"]");
		}catch(e){}
        result = await $.ajax({
            url: ajaxurl,
			data: fdata,
			cache: false,
			contentType: false,
			processData: false,
			//async: true,   // this will solve the problem
			method: 'POST',
			type: 'POST', // For jQuery < 1.9
			beforeSend: function (xhr) {
				xhr.withCredentials = true; //Include this line
			},
			mode: 'cors', // no-cors, *cors, same-origin
			cache: 'no-cache', // *default, no-cache, reload, force-cache, only-if-cached
			credentials: 'same-origin', // include, *same-origin, omit
        });
		try{
			$("#ufmn").show();
			$("#ufmn").css('color', 'green');
			$("#ufmn").html("อัพโหลดไฟล์ ของ " + target_name + " ไฟล์ที่ [" +file_active+"] สำเร็จ");
		}catch(e){}
        return result;
    } catch (error) {
		try{
			$("#ufmn").show();
			$("#ufmn").css('color', 'red');
			$("#ufmn").html("อัพโหลดไฟล์ ของ " + target_name + " ไฟล์ที่ [" +file_active+"] ไม่สำเร็จ");
		}catch(e){}
        console.log(error);
		return "";
    }
}

function sendText(friend,msg,row_nums){
	return new Promise(async function(resolve){
		if (!msg.match(/^\s*$/) && msg!=""){
			const target_id=friend.id;
			const target_name=friend.name;
			const done_file_ref="";
			
			let status_response = await send_fb_messager(msg,target_id,target_name,done_file_ref,"",row_nums,1,0);
			//console.log("status_response:"+status_response);
			if(status_response){
				tot_text_succescount++;
				is_can_send_somthing_success=true;
				//console.log("tot_text_succescount:"+tot_text_succescount);
			}else{
				tot_text_failed++;
				//console.log("tot_text_failed:"+tot_text_failed);
			}
			
			runningAllitemsProgress();
			
			resolve({
				thispost: true,
				thiserror: !status_response,
				thisSendSuccess: (status_response==true?1:0),
				thisSendFailed: (status_response==true?0:1),
				totsendsuccess: tot_text_succescount,
				totsendfailed: tot_text_failed,
				responseStatus: 200,
				responseText: "ส่งข้อความเรียบร้อย",
				responseJSON: "",
				fbSendFiles: ""
			});
		}else{
			tot_text_failed++;
			resolve({
				thispost:false,
				thiserror: true,
				thisSendSuccess: 0,
				thisSendFailed: 1,
				totsendsuccess: tot_text_succescount,
				totsendfailed: tot_text_failed,
				responseStatus: -1,
				responseText: "ไม่อนุญาติข้อความว่าง",
				responseJSON: "",
				fbSendFiles: ""
			});
		}
	});
}

async function sendFile(friend,fileele,row_nums){
		let thisSendSuccess=0;
		let thisSendFailed=0;
		let fbSendFiles="";
		var promises_ = [];
		if (jQuery('#'+fileele.id).val() !== '') {
			const target_id=friend.id;
			const target_name = friend.name;
			const files=jQuery('#'+fileele.id)[0];
			const files_length=files.files.length;
			var fileList=[];
			
			for (let file=0;file<files_length;file++){
				
				let data = new FormData();
				let sendid_rnd_id = target_id + '_' + Math.floor(Date.now()) + '_' + Math.floor(10000000 + Math.random() * 90000000);
				
				data.append('upload_1024', files.files[file]);
				data.append('sendId', sendid_rnd_id);
				
				fileList.push(data);
				
				iMessNumberActive++;
				
				//promises_.push(doAjax('https://upload.facebook.com/ajax/mercury/upload.php?request_user_id=' + my_broadcastline_label_id + '&__user=' + fb_user_id + '&__a=1&__req=3d&__be=1&dpr=1.5&__rev=' + __rev + '&__s=%3Aidl0z4%3A9y9r1n&fb_dtsg=' + fb_dtsg + '&jazoest=' + jazoest + '&__spin_r=' + __rev + '&__spin_b=trunk',data));
				
				/*
				try {
					
					/////////////
					const res = await doAjax('https://upload.facebook.com/ajax/mercury/upload.php?request_user_id=' + my_broadcastline_label_id + '&__user=' + fb_user_id + '&__a=1&__req=3d&__be=1&dpr=1.5&__rev=' + __rev + '&__s=%3Aidl0z4%3A9y9r1n&fb_dtsg=' + fb_dtsg + '&jazoest=' + jazoest + '&__spin_r=' + __rev + '&__spin_b=trunk',data);
					//console.log(res);
					////////////////////////
					let response = res.replace("for (;;);", "");
					parsed_response = JSON.parse(response);
					let ftype = parsed_response.payload.metadata[0].filetype;
					let fb_filetype = "file_ids";
					let media_id="";
					if (typeof ftype != 'undefined') {
						let filetype = ftype.toLowerCase().split("/");
						if(filetype.length>0){
							if(filetype[0]=="image"){
								media_id = parsed_response.payload.metadata[0].image_id;
								fb_filetype="image_ids";
							}else if(filetype[0]=="video"){
								media_id = parsed_response.payload.metadata[0].video_id;
								fb_filetype="video_ids";
							}else if(filetype[0]=="audio"){
								media_id = parsed_response.payload.metadata[0].audio_id;
								fb_filetype="audio_ids";
							}else{
								media_id = parsed_response.payload.metadata[0].file_id;
								fb_filetype="file_ids";
							}
						}
						fbSendFiles += '&'+fb_filetype+'[' + file + ']=' + media_id;
					}
					//////////////////////////////////////

					runningAllitemsProgress();
					tot_file_succescount++;
					thisSendSuccess++;
				} catch(err) {
					console.log(err);
					tot_file_failed+=files.files.length-file;
					thisSendFailed+=files.files.length-file;
					return({
						thispost:true,
						thiserror: true,
						thisSendSuccess: thisSendSuccess,
						thisSendFailed: thisSendFailed,
						totsendsuccess: tot_file_succescount,
						totsendfailed: tot_file_failed,
						responseStatus: "XMLHttpRequest.status",
						responseText: "XMLHttpRequest.responseText",
						responseJSON: "XMLHttpRequest.responseJSON",
						fbSendFiles: ""
					});
				}
				*/
			}
			
			//var fileList = [/*... list of files ...*/];
			fbSendFiles="";
			//console.log("before promise send file");
			return new Promise(resolve => {
				Promise.all(fileList.map((data, findex) => doAjax('https://upload.facebook.com/ajax/mercury/upload.php?request_user_id=' + my_broadcastline_label_id + '&__user=' + fb_user_id + '&__a=1&__req=3d&__be=1&dpr=1.5&__rev=' + __rev + '&__s=%3Aidl0z4%3A9y9r1n&fb_dtsg=' + fb_dtsg + '&jazoest=' + jazoest + '&__spin_r=' + __rev + '&__spin_b=trunk',data,target_name,findex+'/'+files_length)))
				.then(responseList => {
					//console.log("responseList file");
					//console.log(responseList);
					//console.dir(responseList);
					for (let file=0;file<responseList.length;file++){
						let res = responseList[file];
						if(res!=""){
							if (res.indexOf("for (;;);") !== -1) {
								let response = res.replace("for (;;);", "");
								if(response!=""){
									try{
										let parsed_response = JSON.parse(response);
										let ftype = parsed_response.payload.metadata[0].filetype;
										let fb_filetype = "file_ids";
										let media_id="";
										if (typeof ftype != 'undefined') {
											let filetype = ftype.toLowerCase().split("/");
											if(filetype.length>0){
												if(filetype[0]=="image"){
													media_id = parsed_response.payload.metadata[0].image_id;
													fb_filetype="image_ids";
												}else if(filetype[0]=="video"){
													media_id = parsed_response.payload.metadata[0].video_id;
													fb_filetype="video_ids";
												}else if(filetype[0]=="audio"){
													media_id = parsed_response.payload.metadata[0].audio_id;
													fb_filetype="audio_ids";
												}else{
													media_id = parsed_response.payload.metadata[0].file_id;
													fb_filetype="file_ids";
												}
											}
											fbSendFiles += '&'+fb_filetype+'[' + file + ']=' + media_id;
										}
									}catch(e){}
								}
							}
						}
						//////////////////////////////////////
						
						
						runningAllitemsProgress(0);
						tot_file_succescount++;
						thisSendSuccess++;
					}
					//$("#ufmn").hide();
					
					resolve({
						thispost:true,
						thiserror: false,
						thisSendSuccess: thisSendSuccess,
						thisSendFailed: thisSendFailed,
						totsendsuccess: tot_file_succescount,
						totsendfailed: tot_file_failed,
						responseStatus: 200,
						responseText: "อัพโหลดไฟล์เรียบร้อยแล้ว",
						responseJSON: "",
						fbSendFiles: fbSendFiles
					});
					
				});
			});
			/*
			Promise.all(promises_)
			.then(responseList => {
				console.log("responseList");
				console.log(responseList);
				console.dir(responseList);
			})
			*/
			
			//console.log("after promise send file");
			/*
			return({
				thispost:true,
				thiserror: false,
				thisSendSuccess: thisSendSuccess,
				thisSendFailed: thisSendFailed,
				totsendsuccess: tot_file_succescount,
				totsendfailed: tot_file_failed,
				responseStatus: 200,
				responseText: "อัพโหลดไฟล์เรียบร้อยแล้ว",
				responseJSON: "",
				fbSendFiles: fbSendFiles
			});
			*/
		}else{
			//$("#ufmn").hide();
			return new Promise(resolve => {resolve({
				thispost:false,
				thiserror: true,
				thisSendSuccess: thisSendSuccess,
				thisSendFailed: thisSendFailed,
				totsendsuccess: tot_file_succescount,
				totsendfailed: tot_file_failed,
				responseStatus: -1,
				responseText: "ไม่พบไฟล์ที่จะส่ง",
				responseJSON: "",
				fbSendFiles: ""
				})
			});
		}
}


function move_to_done_folder(target_id,target_name){
	try{
		if ($('#move_to_done_folder').prop("checked") == true) {
			let data_req = 'ids[' + target_id + ']=true&source=PagesManagerMessagesInterface&request_user_id=' + my_broadcastline_label_id + '&__user=' + fb_user_id + '&__a=1&__dyn=&__csr=&__req=dt&__beoa=0&__pc=PHASED%3ADEFAULT&dpr=1.5&__ccg=EXCELLENT&__rev=1002879894&__s=c932t4%3Al8o5ju%3Aka2huc&__hsi=6887303140274378056-0&__comet_req=0&fb_dtsg=' + fb_dtsg + '&jazoest=' + jazoest + '&__spin_r=1002879894&__spin_b=trunk&__spin_t=1603566787';
			//console.log(data_req);
			$.ajax({
				url: "https://www.facebook.com/ajax/mercury/change_archived_status.php",
				type: "post",
				data: data_req,
				
				//Promise.all(fileList.map((data, findex) => doAjax('https://upload.facebook.com/ajax/mercury/upload.php?request_user_id=' + my_broadcastline_label_id + '&__user=' + fb_user_id + '&__a=1&__req=3d&__be=1&dpr=1.5&__rev=' + __rev + '&__s=%3Aidl0z4%3A9y9r1n&fb_dtsg=' + fb_dtsg + '&jazoest=' + jazoest + '&__spin_r=' + __rev + '&__spin_b=trunk',data,target_name,findex+'/'+files_length)))
				
				complete: function (res_data) {
					
					my_prev_move_to_done_folder = true;	//Checked move to done folder after send message
					
					//console.log("move to done folder successfully.");
					//console.log(res_data);
					/*
					iziToast.success({
						title: 'ย้าย ' + target_name + ' เข้าโฟลเดอร์เรียบร้อย',
						position: 'topRight',
						timeout: 3000,
						message: '',
					});
					*/
					
				}
			});
		}
	}catch(e){}
}

///////////////////////////////////
//////////// End Treads ///////////
//////////////////////////////////

function saveTextAsFile(text_input,save_to_file_name){
	//let textToSave = text_input.replace(/(?:\\[rn]|[\r\n]+)+/g, "%0D%0A");
	let textToSave = text_input.replace(/(?:\\[rn]|[\r\n]+)+/g, "\r\n");
    let textToSaveAsBlob = new Blob([textToSave], {type:"text/plain;charset=utf-8"});
    let textToSaveAsURL = window.URL.createObjectURL(textToSaveAsBlob);
	let fileNameToSaveAs = save_to_file_name;
	
    let downloadLink = document.createElement("a");
    downloadLink.download = fileNameToSaveAs;
    downloadLink.innerHTML = "Download File";
    downloadLink.href = textToSaveAsURL;
    downloadLink.onclick = destroyClickedElement;
    downloadLink.style.display = "none";
    document.body.appendChild(downloadLink);

    downloadLink.click();
	try{
		document.body.removeChild(downloadLink);
	}catch(e){}
}

function deleteDownloadLink(){
	try{
		let x = document.getElementById("downloadLink");
		if(typeof x!="undefined" && x!=null){
			try{
				//x.remove();
				document.body.removeChild(x);
			}catch(e){}
			x.parentNode.removeChild(x);
		}
	}catch(e){}
}
async function createDownloadLink(ids){
	if(ids==""){return;}
	try{
		let textToSave = ids;
		let save_to_file_name = my_broadcastline_label_name+'_'+my_broadcastline_folder_label_name+'_'+getDate()+'_'+label_user_all.length;
		//let textToSave = text_input.replace(/(?:\\[rn]|[\r\n]+)+/g, "\r\n");
		let textToSaveAsBlob = new Blob([textToSave], {type:"text/plain;charset=utf-8"});
		let textToSaveAsURL = window.URL.createObjectURL(textToSaveAsBlob);
		let fileNameToSaveAs = save_to_file_name;
		
		let x = document.getElementById("downloadLink");
		if(typeof x!="undefined" && x!=null){
			try{
				//x.remove();
				//document.body.removeChild(x);
				x.parentNode.removeChild(x);
			}catch(e){}
		}
		let downloadLink = document.createElement("a");
		downloadLink.setAttribute("id", "downloadLink");
		downloadLink.download = fileNameToSaveAs;
		downloadLink.innerHTML = "Download Fanpage";
		downloadLink.href = textToSaveAsURL;
		//downloadLink.onclick = destroyClickedElement;
		downloadLink.style.display = "none";
		document.body.appendChild(downloadLink);

		//downloadLink.click();
		try{
			//document.body.removeChild(downloadLink);
		}catch(e){}
	}catch(ex){
		alert("บันทึกไฟล์เกิดข้อผิดพลาด:"+ex);
	}
}
async function DownloadLink(){
	if(permission_extract_member!=1){
		contact_detail("<strong><u>สิทธิ์การใช้งานฟังก์ชั่นนี้ ยังไม่ได้รับอนุญาติ</u></strong>");
		return;
	}
	var ids = "";
	var xx = document.getElementById("downloadLink");
	if (label_user_all_copy.length==0){
		deleteDownloadLink();
		return;
	}
	try{
		if(typeof xx!="undefined" && xx!=null){
			xx.click();
			return;	//already create;
		}
		for (let u of label_user_all_copy) 
		{
		  ids+= await (u.id+','+u.name+"\r\n");
		}
		if(ids==""){return;}
		
		label_user_all_copy[0].accountName = $('#my_broadcastline_idpage_title').text().substring(0,30);

		ids = 'Fanpage: '+label_user_all_copy[0].accountName+"\r\nFolder: "+label_user_all_copy[0].folder+"\r\nจำนวน: "+label_user_all_copy.length+"\r\nวันที่: "+getNow()+"\r\n" + ids;
		
		let textToSave = ids;
		let save_to_file_name = label_user_all_copy[0].accountName+'_'+label_user_all_copy[0].folder+'_'+getDate()+'_'+label_user_all_copy.length+".txt";
		let textToSaveAsBlob = new Blob([textToSave], {type:"text/plain;charset=utf-8"});
		let textToSaveAsURL = window.URL.createObjectURL(textToSaveAsBlob);
		let fileNameToSaveAs = save_to_file_name;
		deleteDownloadLink();
		
		let downloadLink = document.createElement("a");
		downloadLink.setAttribute("id", "downloadLink");
		downloadLink.setAttribute("title", label_user_all_copy[0].accountName);
		downloadLink.download = fileNameToSaveAs;
		downloadLink.innerHTML = "Download Fanpage";
		downloadLink.href = textToSaveAsURL;
		downloadLink.style.display = "none";
		document.body.appendChild(downloadLink);
		downloadLink.click();
	}catch(ex){
		alert("บันทึกไฟล์เกิดข้อผิดพลาด:"+ex);
	}
}
function removeDownloadSuccessLink(){
	var xx = document.getElementById("downloadSuccessLink");
	if(typeof xx!="undefined" && xx!=null){
		try{
			try{
				document.body.removeChild(xx);
			}catch(ee){}
			xx.parentNode.removeChild(xx);
		}catch(e){}
	}
}
async function downloadSuccessLink(){
	if(permission_extract_member!=1){
		contact_detail("<strong><u>สิทธิ์การใช้งานฟังก์ชั่นนี้ ยังไม่ได้รับอนุญาติ</u></strong>");
		return;
	}
	var ids = "";
	var xx = document.getElementById("downloadSuccessLink");
	if (ct_tf_label_user_all_send_success.length==0){
		removeDownloadSuccessLink();
		return;
	}
	try{
		if(typeof xx!="undefined" && xx!=null){
			xx.click();
			return;	//already create;
		}
		for (let u of ct_tf_label_user_all_send_success) 
		{
		  //ids+= await u.id+"\r\n";
		  ids+= await (u.id+','+u.name+"\r\n");
		}
		if(ids==""){return;}
		
		ids = 'Fanpage: '+ct_tf_label_user_all_send_success[0].accountName+"\r\nFolder: "+ct_tf_label_user_all_send_success[0].folder+'\r\nOnly: Successfully'+"\r\nจำนวน: "+ct_tf_label_user_all_send_success.length+"\r\nวันที่: "+getNow()+"\r\n" + ids;
		
		let textToSave = ids;
		let save_to_file_name = ct_tf_label_user_all_send_success[0].accountName+'_'+ct_tf_label_user_all_send_success[0].folder+'_Successfully'+'_'+getDate()+'_'+ct_tf_label_user_all_send_success.length+".txt";
		let textToSaveAsBlob = new Blob([textToSave], {type:"text/plain;charset=utf-8"});
		let textToSaveAsURL = window.URL.createObjectURL(textToSaveAsBlob);
		let fileNameToSaveAs = save_to_file_name;

		if(typeof xx!="undefined" && xx!=null){
			removeDownloadSuccessLink();
		}
		let dlSuccessLink = document.createElement("a");
		dlSuccessLink.setAttribute("id", "downloadSuccessLink");
		dlSuccessLink.setAttribute("title", ct_tf_label_user_all_send_success[0].accountName);
		dlSuccessLink.download = fileNameToSaveAs;
		dlSuccessLink.innerHTML = "Download Fanpage";
		dlSuccessLink.href = textToSaveAsURL;
		dlSuccessLink.style.display = "none";
		document.body.appendChild(dlSuccessLink);
		dlSuccessLink.click();
	}catch(ex){
		alert("บันทึกไฟล์เกิดข้อผิดพลาด:"+ex);
	}
}

function destroyClickedElement(event){
    document.body.removeChild(event.target);
}
function getFormattedDate() {
	var d = new Date();
	return d.getFullYear().toString()+"-"+padDigits(d.getMonth()+1,2)+"-"+padDigits(d.getDate(),2)+" "+padDigits(d.getHours(),2)+":"+padDigits(d.getMinutes(),2)+":"+padDigits(d.getSeconds(),2)+ "." +padDigits(d.getMilliseconds(),3);
}

function show_msg_report(target_id,target_name,send_status,msg,row_number,msg_type){
	var color_status = "red";
	if(send_status=="2"){
		color_status = "blue";
	}else if(send_status!="" && send_status!="0"){
		msg='<i style="font-weight:900;color:red;">&nbsp;&nbsp;(ไม่สำเร็จ)&nbsp;</i>code:&nbsp;'+msg;
	}else{
		color_status = "green";
		msg = '<i style="font-weight:900;color:#14f200;">&nbsp;&nbsp;(สำเร็จ)&nbsp;</i>'+msg;
	}
	
	if(target_id!=""){
		msg = "Id: "+ target_id + " ,ขื่อ: "+ target_name + "->" +msg;
	}
	if(typeof row_number!=="undefined"){
		msg = getFormattedDate() + "     " + msg + "&nbsp;บรรทัดที่&nbsp;"+(row_number+1);
	}else{
		msg = getFormattedDate() + "     " + msg;
	}
	if(typeof msg_type!=="undefined" && msg_type!=""){
		if(msg_type=="ข้อความ"){
			msg +=" ชนิด "+ '<i style="font-weight:900;color:#fcf803;">'+ msg_type+'</i>';
		}else{
			msg +=" ชนิด "+ '<i style="font-weight:900;color:#b503fc;">'+ msg_type+'</i>';
		}
	}
	
	var report = `<li style="color:${color_status}">${msg}</li>`;
    $("#txt_error_report").append(report);
}

function make_it_id1(length) {
	var result = '';
	var characters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
	var charactersLength = characters.length;
	for (var i = 0; i < length; i++) {
		result += characters.charAt(Math.floor(Math.random() * charactersLength));
	}
	return result + 'icx' + Math.floor((Math.random() * 2545555) + 25487); ;
}

function make_it_id2(length) {
	var result = '';
	var characters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
	var charactersLength = characters.length;
	for (var i = 0; i < length; i++) {
		result += characters.charAt(Math.floor(Math.random() * charactersLength));
	}
	return 'xoi' + result;
}

function make_it_id3(length) {
	var result = '';
	var characters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
	var charactersLength = characters.length;
	for (var i = 0; i < length; i++) {
		result += characters.charAt(Math.floor(Math.random() * charactersLength));
	}
	return result;
}


function checkPackagePromise(){
	document.getElementById('plan_package').innerHTML=""+user_type;
	document.getElementById('plan_demo_package').innerHTML=document.getElementById('plan_package').innerHTML
	
	return new Promise(resolve => {
		if(user_type=="ทดลองใช้งาน" && Number(tf_demo_ratelimit_setting)>0){
			var dnow = new Date();
			var curdate = dnow.toJSON().slice(0,10);
			curdate = server_date;	//Hack server
			ldb.get('tf_demo_usage_ratelimit_'+user_name, function (usage_ratelimit) {
				if(typeof usage_ratelimit!=="undefined" && usage_ratelimit!=null){
					var ul = usage_ratelimit.split("|");
					//console.log("server date:"+server_date);
					
					if(ul.length>0){
						tf_demo_usage_ratelimit=Number(ul[0]);
						demo_usage_date=ul[1];
						tf_demo_usage_ratelimit_left=Number(ul[2]);
						if(demo_usage_date!=null && demo_usage_date!=curdate ){
							tf_demo_usage_ratelimit=0;
							tf_demo_usage_ratelimit_left = Number(tf_demo_ratelimit_setting);
							if(Number(tf_demo_usage_ratelimit_left)<0){tf_demo_usage_ratelimit_left=-1;}
							document.getElementById('plan_package').innerHTML=""+user_type+ " เหลือ "+ (tf_demo_ratelimit_setting) +" ข้อความ/วัน";
							document.getElementById('plan_demo_package').innerHTML=document.getElementById('plan_package').innerHTML
	
							ldb.set('tf_demo_usage_ratelimit_'+user_name, '0|'+curdate+'|'+ tf_demo_usage_ratelimit_left+'|'+tf_demo_ratelimit_setting);
							resolve(1);
						}
						else if(Number(tf_demo_usage_ratelimit)>Number(tf_demo_ratelimit_setting)){
							tf_demo_usage_ratelimit_left = Number(tf_demo_ratelimit_setting) - Number(tf_demo_usage_ratelimit);
							if(Number(tf_demo_usage_ratelimit_left)<0){tf_demo_usage_ratelimit_left=-1;}
							document.getElementById('plan_package').innerHTML=""+user_type+ " เหลือ "+ tf_demo_usage_ratelimit_left +" ข้อความ/วัน";
							document.getElementById('plan_demo_package').innerHTML=document.getElementById('plan_package').innerHTML
	
							Swal.fire({
								title: 'ไม่สามารถทำรายการได้ ',
								html: "ท่านได้ส่งข้อความครบตามจำนวนที่กำหนด ของตัวทดลองใช้งานฟรีแล้ว<br />หากต้องการปลดฟังชั่น ไม่จัดกัดการส่งข้อความต่อวัน กรุณาสอบถามโปรโมชั่นจากแอดมินได้ที่<br /><a href='" + LINE_URL_QRCODE + "'>Line : " + LINE_AT_ID + "</a>",
								//type: 'warning',
								//footer: footer_swal(),
								showCancelButton: true,
								confirmButtonColor: '#3085d6',
								cancelButtonColor: '#d33',
								confirmButtonText: 'Yes'
							}).then((result) => {
								if (result.value) {
									var mywinUrl = window.open(LINE_URL_QRCODE, '_blank');
									mywinUrl.focus();
								}
							});
							setStopJob(0,false,0);
							resolve(0);
						}else{
							tf_demo_usage_ratelimit_left = Number(tf_demo_ratelimit_setting) - Number(tf_demo_usage_ratelimit);
							if(Number(tf_demo_usage_ratelimit_left)<0){tf_demo_usage_ratelimit_left=-1;}
							document.getElementById('plan_package').innerHTML=""+user_type+ " เหลือ "+ tf_demo_usage_ratelimit_left +" ข้อความ/วัน";
							document.getElementById('plan_demo_package').innerHTML=document.getElementById('plan_package').innerHTML
	
							resolve(1);
						}
					}else{
						tf_demo_usage_ratelimit=0;
						demo_usage_date=curdate;
						tf_demo_usage_ratelimit_left= Number(tf_demo_ratelimit_setting);
						ldb.set('tf_demo_usage_ratelimit_'+user_name, '0|'+curdate+'|'+ tf_demo_ratelimit_setting+'|'+tf_demo_ratelimit_setting);
						resolve(1);
					}
				}else{
					//tf_demo_usage_ratelimit=0;
					//demo_usage_date=curdate;
					//tf_demo_usage_ratelimit_left=tf_demo_ratelimit_setting;
					//ldb.set('tf_demo_usage_ratelimit_'+user_name, '0|'+curdate+'|'+ tf_demo_ratelimit_setting+'|'+tf_demo_ratelimit_setting);
					alert("เวอร์ชั่น ทดลองใช้ ไม่สามารถทำรายการ ในวันนี้ได้ ไว้มาส่งข้อความใหม่พรุ่งนี้นะค่ะ");
					resolve(0);
				}
			});
		}else{
			resolve(1);
		}
    });
}


////param 'Text1|Text2|Text3|Text4'
function spintax(textmsg) {
	var text = textmsg;
	var matches, options, random;

	var regEx = new RegExp(/{([^{}]+?)}/);

	while((matches = regEx.exec(text)) !== null) {
	  options = matches[1].split(",");
	  random = Math.floor(Math.random() * options.length);
	  text = text.replace(matches[0], options[random]);
	}
	return text;
}
function randomtax(text_msg) {
	let options, random;
	if(text_msg.trim()!=""){
		options = text_msg.split(",");
		random = Math.floor(Math.random() * options.length);
		if(Array.isArray(options)){
			return options[random];
		}else{
			return options;
		}
	}else{return "";}
}
function randomContent(text_msg) {
	let options, random;
	if(text_msg.trim()!=""){
		options = text_msg.split("||");
		random = Math.floor(Math.random() * options.length);
		if(Array.isArray(options)){
			return options[random];
		}else{
			return options;
		}
	}else{return "";}
}

function footer_swal() {
	return "<span style='color:#FF0000'>*คุณสามารถย่อแท็บลงได้ เปิดแท็บอื่นได้ แต่อย่าปิดหน้านี้ หากปิดแท็บนี้ระบบจะหยุดลง แและถ้าต้องการให้ระบบปิดการทำงาน ให้กดปิดแท็บนี้</span>";
}
function clearLastInterval () {
  var i = setInterval (function () {}, 10000);
  clearInterval (i-1);
  clearInterval (i);
}

function wait_net_online(){
	//localStorage.setItem('setstop', 2);	//Set pause flag
	status_stop_pause = 2;
	
	$('#radio_schedule *').prop('disabled',false);
	$('#start_broadcast').hide();
	$('#pause_broadcast').hide();
	//$('#continue_broadcast').show();
	$('#stop_broadcast').show();
	var isShowErrBox=true;
	var NetStatus = document.getElementById('NetStatus');
	var NetRetry = document.getElementById("NetRetry");
	var NetMsg = document.getElementById("NetMsg");
	var tnetId = null;
	var inetretrycount=0;
	var interval_preroid=5;	//30 seconds
	
	//var ipreriod_cound=0;
	//var prev_interval_preroid=5;
	

	run_interval(interval_preroid);
	
	function run_interval(interval_preroid){
		var tId = setInterval(function() {
			inetretrycount++;
			
			/*//dynamic interval
			ipreriod_cound++;
			interval_preroid=Math.round(ipreriod_cound/5);
			if(interval_preroid<10){
				interval_preroid=5;
			}else if(interval_preroid>130){
				ipreriod_cound=0;
				interval_preroid=5;
			}
			if(prev_interval_preroid!=interval_preroid){
				//change interval period
				prev_interval_preroid=interval_preroid;
				clearInterval(tId);
				run_interval(interval_preroid);
			}
			*///
			
			if(inetretrycount>9000000){inetretrycount=0;}
			NetRetry.innerHTML="Next "+getTimeNow(interval_preroid) +" -> "+inetretrycount;
			check_net(isShowErrBox).then((data) => {
				clearInterval(tId);
				$('#start_broadcast').hide();
				$('#pause_broadcast').show();
				$('#stop_broadcast').show();
				$('#continue_broadcast').hide();
				$('#footer-summary-container').show();
				$('#close-x').show();
				$('#open-o').hide();
				
				//localStorage.setItem('setstop', 1);	//Clear stop flag
				status_stop_pause = 1;
				
				NetStatus.innerHTML="FB Online";
				NetStatus.style.backgroundColor = "#fced20";
				NetStatus.style.color = "#000";
				
				NetMsg.innerHTML="FB Good.";
				NetMsg.style.backgroundColor = "#fced20";
				NetMsg.style.color = "#000";
				try{
					if(tnetId!==null){
						clearInterval(tnetId);
						//tnetId=null;
					}
					//clearLastInterval();
				}catch(err){}
				setTimeout(function () {
					$('#radio_schedule *').prop('disabled',true);
					//send_my_broadcastline_continue(localStorage.getItem('loops'));
					send_my_broadcastline_continue(tot_send_friends_count+1);
				}, (2000));
			}).catch((error) => {
				NetStatus.innerHTML="FB Offline";
				NetStatus.style.backgroundColor = "red";
				NetStatus.style.transition = "0.4s"
				tnetId = setInterval(function() {
					NetStatus.style.opacity = (NetStatus.style.opacity == 0 ? 1 : 0);
				}, 1000);
				
				NetMsg.innerHTML="FB Offline";
				NetMsg.style.backgroundColor = "red";
				
			});
			isShowErrBox=false;
		}, (1000*interval_preroid));
	}
	
}

function check_net(isShowErrBox) {
	if (typeof isShowErrBox==='undefined' ){isShowErrBox=true;}
	return new Promise((resolve, reject) => {	
    $.ajax({
		url: 'https://facebook.com/',	//document.location.origin,	//'https://chat.line.biz/'
		type: 'HEAD',
		//async: true,   // this will solve the problem
		data: {
			key: '',
		},
		success: function (data) {
			var NetStatus = document.getElementById('NetStatus');
			NetStatus.innerHTML="FB Online";
			NetStatus.style.backgroundColor = "#fced20";
			NetStatus.style.color = "#000";
			resolve("successfully")
		},
		error: function (error) {
			if(isShowErrBox){
				console.log("you are offline");
				try{
					iziToast.error({
						title: 'Facebook Offline กรุณาเช็คการเชื่อมต่อ Facebook https://www.facebook.com/ ของท่าน',
						position: 'topCenter',
						timeout: 5000,
						message: '',
					});
				}catch(ex){}
			}
			var NetMsg = document.getElementById("NetMsg");
			NetStatus.innerHTML="FB Offline";
			NetStatus.style.backgroundColor = "red";
			
			reject("Internet offline")
		},
    })
  })
}

function Append_To_Head(elemntType, content){
	// if provided content is "link" or "inline codes"
	var Is_Link = content.split(/\r\n|\r|\n/).length <= 1  &&  content.indexOf("//") > -1;
	if(Is_Link){
		if (elemntType=='script')    { var x=document.createElement('script');x.id=id;  x.src=content;  x.type='text/javascript'; }
		else if (elemntType=='style'){ var x=document.createElement('link');  x.id=id;  x.href=content; x.type='text/css';  x.rel = 'stylesheet'; }
	}
	else{
		var x = document.createElement(elemntType);
		if (elemntType=='script')    { x.type='text/javascript';    x.innerHTML = content;  }
		else if (elemntType=='style'){ x.type='text/css';    if (x.styleSheet){ x.styleSheet.cssText=content; } else { x.appendChild(document.createTextNode(content)); }   }
	}
	//append in head
	(document.head || document.getElementsByTagName('head')[0]).appendChild(x);
}
function loadjscssfile(filename, filetype,defer){
    if (filetype=="js"){ //if filename is a external JavaScript file
        var fileref=document.createElement('script');
        fileref.setAttribute("type","text/javascript");
        fileref.setAttribute("src", filename);
    }
    else if (filetype=="css"){ //if filename is an external CSS file
        var fileref=document.createElement("link")
        fileref.setAttribute("rel", "stylesheet")
        fileref.setAttribute("type", "text/css")
        fileref.setAttribute("href", filename)
    }
    if (typeof fileref!="undefined")
        document.getElementsByTagName("head")[0].appendChild(fileref)
	if (typeof defer!="undefined")
		fileref.setAttribute("defer", "");
}
function appendjsfile(filename,defer){
	var script_url = document.createElement('script');
	script_url.type = 'text/javascript';	
	script_url.src = filename;
	if (typeof defer!="undefined")
		script_url.setAttribute("defer", "");
	document.getElementsByTagName('body')[0].appendChild(script_url);
}

function DifferenceInDays(firstDate, secondDate) { 
    return Math.round((secondDate-firstDate)/(1000*60*60*24)); 
}
function getdatenow() {
	var now     = new Date(); 
	var year    = now.getFullYear();
	var month   = now.getMonth()+1; 
	var day     = now.getDate();
	var hour    = now.getHours();
	var minute  = now.getMinutes();
	var second  = now.getSeconds(); 
	if(month.toString().length == 1) {
		 month = '0'+month;
	}
	if(day.toString().length == 1) {
		 day = '0'+day;
	}   
	if(hour.toString().length == 1) {
		 hour = '0'+hour;
	}
	if(minute.toString().length == 1) {
		 minute = '0'+minute;
	}
	if(second.toString().length == 1) {
		 second = '0'+second;
	}   
	var dateTime = year+'/'+month+'/'+day+' '+hour+':'+minute+':'+second;   
	return dateTime;
}

function doOpenFile(event){
    event = event || window.event;
    if(event.target.id != 'file-file_add_container'){
        document.getElementById("file-file_add_container").click();
    }

}

function showTimeStart(){
	let clock_status = document.getElementById('clock_status');
	if (typeof clock_status !=="undefined" && clock_status!==null){
		if (clock_status.innerHTML!==null){
			clock_status.innerHTML=""
			clock.style.display = 'block';
			startTime();
		}
	}
}
function startTime() {
	//<div id="clock"></div>
	let clock = document.getElementById('clock');
	if (typeof clock ==="undefined" || clock===null){return;}
	if (clock.innerHTML===null){return;}
	
	let today = new Date();
	let h = today.getHours();
	let m = today.getMinutes();
	let s = today.getSeconds();
	m = checkTime(m);
	s = checkTime(s);
	
	
	let clock_status = document.getElementById('clock_status');
	if (typeof clock_status !=="undefined" && clock_status!==null){
		if (clock_status.innerHTML!==null){
			if(clock_status.innerHTML==="stopped"){
				clock.style.display = 'none';
				return;
			}
		}
	}
	
	
	clock.innerHTML = h + ":" + m + ":" + s;
	$('#current_time').text(h + ":" + m + ":" + s);
	
	let t = setTimeout(startTime, 1000);
}
function checkTime(i) {
	if (i < 10) {i = "0" + i};  // add zero in front of numbers < 10
	return i;
}

function b64EncodeUnicode(str) {
    return btoa(encodeURIComponent(str).replace(/%([0-9A-F]{2})/g, function(match, p1) {
        return String.fromCharCode('0x' + p1);
    }));
}

//b64EncodeUnicode('✓ à la mode'); // "4pyTIMOgIGxhIG1vZGU="
//b64EncodeUnicode('\n'); // "Cg=="

function b64DecodeUnicode(str) {
    return decodeURIComponent(Array.prototype.map.call(atob(str), function(c) {
        return '%' + ('00' + c.charCodeAt(0).toString(16)).slice(-2);
    }).join(''));
}

///////////////////////////////////
//validates URL
function is_valid_url(url) {
    return url.match(/^(ht|f)tps?:\/\/[a-z0-9-\.]+\.[a-z]{2,4}\/?([^\s<>\#%"\,\{\}\\|\\\^\[\]`]+)?$/);
}

//gives error description from JSON data of XHR
function give_error_description(text) {
    var str = '';
	var code = "0";
	var status = 1;
	var recipientid = "";
    if (text) {
        if (text.replace("for (;;);", "")) {
            try {
                var o = JSON.parse(text.replace("for (;;);", ""));
                if (o && typeof o === "object" && o !== null) {
                    if (JSON.parse(text.replace("for (;;);", ""))) {
                        if (JSON.parse(text.replace("for (;;);", "")).errorDescription) {

                            if (JSON.parse(text.replace("for (;;);", "")).errorDescription.__html) {
                                str = JSON.parse(text.replace("for (;;);", "")).errorDescription.__html;
                            } else {

                                str = JSON.parse(text.replace("for (;;);", "")).errorDescription;
                            }
							
							code = JSON.parse(text.replace("for (;;);", "")).error;
							if(code!="" && code!="0"){
								status=0;
							}
                            if (code == '1404102') {
                                //stop_when_error(id_element, 'เนื่องจากลิ้งที่ท่านใส่ Facebook มองว่าเป็นแสปมให้ลบลิ้งตามที่แจ้งออก แล้วจึงกดปุ่มสีเขียวเพื่อทำต่อไป<br>' + str)

                            }
							
                        }
                    }
                }
            } catch (e) {}
        }

    }
    return {"status":status,"recipientid":recipientid,"code":code,"ref":"","description":str};
}

function give_success_description(text) {
    var ref = '';
	var status = 1;	//success
	var code = "0";
	var recipientid = "";
	var descp = "";
	//console.log(text);
    if (text) {
        if (text.replace("for (;;);", "")) {
            try {
                var o = JSON.parse(text.replace("for (;;);", ""));
                if (o && typeof o === "object" && o !== null) {
                    if (JSON.parse(text.replace("for (;;);", ""))) {
                        if (JSON.parse(text.replace("for (;;);", "")).payload) {
							
                            if (JSON.parse(text.replace("for (;;);", "")).payload.success) {
                                str = JSON.parse(text.replace("for (;;);", "")).payload.success;
                            } else
                                if (JSON.parse(text.replace("for (;;);", "")).payload.actions[0]) {
									status = JSON.parse(text.replace("for (;;);", "")).payload.actions[0].status;
                                    ref = JSON.parse(text.replace("for (;;);", "")).payload.actions[0].client_message_id;
									recipientid = JSON.parse(text.replace("for (;;);", "")).payload.actions[0].other_user_fbid;
								}

                        }
                    }
                }
            } catch (e) {}
        }

    }
	
	if(ref==""){status = 0;descp="อัพโหลดไฟล์สำเร็จแต่ไม่สามารถส่งไฟล์ได้"}
	return {"status":status,"recipientid":recipientid,"code":code,"ref":ref,"description":descp};
    //return str;
}

//returns graph api errors
function give_graph_api_error(text) {
    return JSON.parse(text).error.message.replace(/\(\#\d+\)/igm, "");
}

//display errors
function show_errors(error_array, title) {
    for (var a = 0; error_array[a]; a++) {
        toastr.error(error_array[a], title);
    }
}

function uniqueByKey(array, key) {
  return [...new Map(array.map((x) => [x[key], x])).values()];
}

function extractNumber(n){
	let tar = n.split(',');
	let target = tar[0];
	let name = "";
	let resp = ["",""];
	if(tar.length>1){
		name = tar[1];
	}
	resp[0]=target;
	resp[1]=name;
	let regexp = /^[0-9]|'/;
	if (regexp.test(target))
	{
		target=target.replace(/'/g, '');
		name=name.replace(/'/g, '');
		resp[0]=target;
		resp[1]=name;
		return resp;
	}
	return resp;
}

// utility to clear the database of all entries
async function clearDb() {
	
	return new Promise(async resolve => {
		let transaction = await ldb.transaction(["storeFanpage"], "readwrite");
		let objectStore = await transaction.objectStore("storeFanpage");

		// Make a request to clear all the data out of the object store
		let objectStoreRequest = await objectStore.clear();
		resolve(true);
	});
	return;
	
	const dbs = await window.indexedDB.databases()
	//indexedDB.databases().then(dbs => dbs.forEach(db => indexedDB.deleteDatabase(db.name)))
    return new Promise(resolve => {
		dbs.forEach(async db => { 
			//const transaction = db.transaction(['theStore'], 'readwrite');
			//const objStore = transaction.objectStore('theStore');

			//objStore.clear();

			//transaction.oncomplete = _ => resolve();
			try{
				await window.indexedDB.deleteDatabase(db.name) ;
			}catch(e){}
		});
        resolve(true);
    });
}

//Disable default IE help popup
window.onhelp = function() {
    return false;
};
document.onreadystatechange = function () {
	if (document.readyState == "complete") {
		// document is ready. Do your stuff here
		console.log('completed state');
		
	}
}

window.addEventListener('load', function() {
	console.log('window load');
})
window.addEventListener('error', function(e) { 
	console.log('ooops error');
	try{
		clearInterval(idvideo);
	}catch(e){}
});

window.onkeyup = evt => {
    switch (evt.keyCode) {
        //ESC
        case 27:
            //this.onEsc();
            break;
        //F1
        case 112:
            //this.onF1();
            break;
		case 118:	//F7
			evt.preventDefault();
			evt.stopPropagation();
			evt.stopImmediatePropagation();
			document.getElementById("text_add").focus();
			document.getElementById("text_add").select();
			break;
		case 119:	//F8
			evt.preventDefault();
			evt.stopPropagation();
			evt.stopImmediatePropagation();
			doOpenFile(evt);
			if($("#text_add").val()=="" && $('#file-file_add_container')[0].files.length<1){
				return false;
			}
			break;
		case 120:	//F9
			evt.preventDefault();
			evt.stopPropagation();
			evt.stopImmediatePropagation();
			
			document.getElementById('add_new_item').click();
			break;
		case 121:	//F10
			evt.preventDefault();
			evt.stopPropagation();
			evt.stopImmediatePropagation();
			document.getElementById('start_broadcast').click();
			break;
        //Fallback to default browser behaviour
        default:
            return true;
    }
    return false;
};

var sleepMode = {
    prevent: function() {
        if (!this._video) {
            this._init();
        }

		if(this._video.paused){
			this._video.setAttribute('loop', 'loop');
			this._video.play();
		}
    },
    allow: function() {
        if (!this._video) {
            return;
        }

        this._video.removeAttribute('loop');
        this._video.pause();
    },
    _init: function() {
        this._video = document.createElement('video');
        this._video.setAttribute('width', '10');
        this._video.setAttribute('height', '10');
		//this._video.setAttribute('muted', 'muted');
		//this._video.setAttribute('autoplay','autoplay');
		this._video.setAttribute('allow','autoplay');
		
		this._video.autoplay = true;
		this._video.muted = true;
        this._video.style.position = 'absolute';
        this._video.style.top = '-10px';
        this._video.style.left = '-10px';
		
		//webm: "data:video/webm;base64,GkXfo0AgQoaBAUL3gQFC8oEEQvOBCEKCQAR3ZWJtQoeBAkKFgQIYU4BnQI0VSalmQCgq17FAAw9CQE2AQAZ3aGFtbXlXQUAGd2hhbW15RIlACECPQAAAAAAAFlSua0AxrkAu14EBY8WBAZyBACK1nEADdW5khkAFVl9WUDglhohAA1ZQOIOBAeBABrCBCLqBCB9DtnVAIueBAKNAHIEAAIAwAQCdASoIAAgAAUAmJaQAA3AA/vz0AAA=",
		//mp4: "data:video/mp4;base64, "
		//<source src="/media/cc0-videos/flower.webm" type="video/webm">
		//<source src="/media/cc0-videos/flower.mp4" type="video/mp4">
			
        var source_mp4 = document.createElement('source');
        source_mp4.setAttribute('src', 'data:video/mp4;base64, ');
        source_mp4.setAttribute('type', 'video/mp4');
		//source_mp4.setAttribute('src', MAIN_URL + 'openline/tools/resources/muted-blank.mp4');	//'https://linebroadcast.com/openline/tools/resources/muted-blank.mp4');
        //source_mp4.setAttribute('type', 'video/mp4');
		source_mp4.setAttribute('allow','autoplay');
        this._video.appendChild(source_mp4);

        var source_ogg = document.createElement('source');
        source_ogg.setAttribute('src', 'data:video/webm;base64,GkXfo0AgQoaBAUL3gQFC8oEEQvOBCEKCQAR3ZWJtQoeBAkKFgQIYU4BnQI0VSalmQCgq17FAAw9CQE2AQAZ3aGFtbXlXQUAGd2hhbW15RIlACECPQAAAAAAAFlSua0AxrkAu14EBY8WBAZyBACK1nEADdW5khkAFVl9WUDglhohAA1ZQOIOBAeBABrCBCLqBCB9DtnVAIueBAKNAHIEAAIAwAQCdASoIAAgAAUAmJaQAA3AA/vz0AAA=');
        source_ogg.setAttribute('type', 'video/webm');
		//source_ogg.setAttribute('src', MAIN_URL + 'openline/tools/resources/muted-blank.ogv'); //'https://linebroadcast.com/openline/tools/resources/muted-blank.ogv');
        //source_ogg.setAttribute('type', 'video/ogg');
		source_ogg.setAttribute('allow','autoplay');
        this._video.appendChild(source_ogg);

        document.body.appendChild(this._video);
    },
    _video: null
}

function sleep(ms) {
  return new Promise(resolve => setTimeout(resolve, ms));
}

function readyJQuery(){
	console.log("readyJQuery clear console");
	
	$('#save_table').on('click','',function(){
		saveTable(this);
	});
	$('#restore_table').on('click','',function(){
		//let txt_error_report =document.getElementById('txt_error_report');
		//txt_error_report.value = getNow()+" lastActivityExpiresAt:" +"\r\n"+txt_error_report.value;
		restoreTable(this);
	});
	
	$('#delAll_row').on('click','',function(){
		dellAllRow(this);
	});

	$("#close-x").on("click", function (e) {
		$('#footer-summary-container').hide();
		$('#close-x').hide();
		$('#open-o').show();
	});
	$("#open-o").on("click", function (e) {
		$('#footer-summary-container').show();
		$('#close-x').show();
		$('#open-o').hide();
	});
	$("#error_x_report").on("click", function (e) {
		$('#txt_error_report').hide();
		$('#error_x_report').hide();
		$('#error_report').show();
	});
	$("#error_report").on("click", function (e) {
		$('#txt_error_report').show();
		$('#error_x_report').show();
		$('#error_report').hide();
	});
	
	$("#add_new_item").on("click", function (e) {
		//console.log(arguments.length);
		e.preventDefault();
		//e.stopPropagation();
		//var e = !(arguments.length > 1 && void 0 !== arguments[1]) || arguments[1]
		
		if($("#text_add").val()=="" && $('#file-file_add_container')[0].files.length<1){
			$("#file-file_add_container").val('');
			$("#file-file_add_container").val(null);
			var x=document.getElementById("rmxfile_add_container");
			if(typeof x!=="undefined"){
				setEmptyFileValue(x);
			}
			document.getElementById("file_file_add_container").value="";
			document.getElementById("file_file_add_container").title="";
			document.getElementById("file_file_add_container").innerHTML="";
			alert("กรุณาระบุข้อความหรือว่าเลือกไฟล์ที่จะส่งด้วยค่ะ");
			return;
		}else{
			addNewRow(true);
			$("#text_add").title="กดปุ่ม F7 เพื่อมายังช่องกรอกข้อมูลนี้ สามารถใช่ spintax หรือสุ่มเลือกข้อความคั่นด้วยเครื่องหมายไปป์คู่กัน || อยู่บนเครื่องหมายแบล็คสแลส \\";
		}
		
		e.stopImmediatePropagation();
		e.stopPropagation();
		return true;
	});

	$("#pause_broadcast").on("click", async function (e) {
	
		//localStorage.setItem('setstop', 2);	//Set pause flag
		status_stop_pause = 2;
		
		$('#pause_broadcast').text('   pausing');
		$('#stop_broadcast').text('   stop');
		//console.log("pause waiting");
		document.getElementById("stop_time").innerHTML="pause waiting";
		$('#radio_schedule *').prop('disabled',false);
		$('#pause_broadcast').prop('disabled',true);
		$('#stop_broadcast').prop('disabled',false);
		if(execSetTimeout!=null){
			clearTimeout(execSetTimeout);
		}
			
			//localStorage.setItem('fbinboxstatusdone', 2);	//0=stop,1=running,2=pause,3=job done;
			fbinboxstatusdone = 2;
			await setStopJob(tot_send_friends_count+Number(cfg_start_seding_no)-1,true,2);
			var d=new Date();
			var esttime_date_format_str = d.getFullYear().toString()+"-"+padDigits(d.getMonth()+1,2)+"-"+padDigits(d.getDate(),2)+" "+padDigits(d.getHours(),2)+":"+padDigits(d.getMinutes(),2)+":"+padDigits(d.getSeconds(),2);
			document.getElementById("stop_time").innerHTML="หยุดชั่วคราว "+esttime_date_format_str;
			status_running=false;
			let action = await checkActionStatus();
			//$('#continue_broadcast').show();
			//$('#start_broadcast').hide();
			//$('#stop_broadcast').show();
			document.getElementById("get_fb_fanpage").disabled = true;

	});
	
	$('#start_broadcast').on('click', async function () {
		///// Check input data ////
		var dnow = new Date();
		var curdate = dnow.toJSON().slice(0,10);
		//console.log("user:"+user_name);
		//await clearIndexDb();
		isStartBroadcastForContinue = true;
		checkPackagePromise()
			.then(x => {
				if(x==0){
					return false;
				}else{
					return true;
				}
			}).then(async function(result) { // (***)
				if(!result){return false;}

				$('#pause_broadcast').text('   pause');
				$('#stop_broadcast').text('   stop');
				$('#pause_broadcast').prop('disabled',false);
				$('#stop_broadcast').prop('disabled',false);
				
				var my_broadcastline_idpage = $('#my_broadcastline_idpage').val();
				my_broadcastline_delay = $('#cfg_delay').val();
				my_broadcastline_to_delay = $('#cfg_to_delay').val();
				cfg_max_recipients = $('#cfg_max_recipients').val();
				cfg_start_seding_no = $('#cfg_start_seding_no').val();
				
				cfg_max_recipients = Number(cfg_max_recipients);
				cfg_start_seding_no = Number(cfg_start_seding_no);
				
				if (typeof my_broadcastline_delay==='undefined'){my_broadcastline_delay=0;}
				if (typeof my_broadcastline_to_delay==='undefined'){my_broadcastline_to_delay=0;}

				if (my_broadcastline_idpage == '') {
					Swal.fire({
						title: 'เกิดข้อผิดพลาด',
						type: 'error',
						html: 'ต้องเลือกบัญชีของ Line OA ที่ต้องการส่งข้อความก่อน',
					});
					$('#my_broadcastline_idpage').focus();
					return false;
				}
				
				cfg_recipients_option_folder = $('#cfg_recipients_option_folder').val();	//cfg_recipients_option_folder
				if (cfg_recipients_option_folder == '' || cfg_recipients_option_folder==null) {
					Swal.fire({
						title: 'เกิดข้อผิดพลาด',
						type: 'error',
						html: 'เลือกโฟลเดอร์ที่ต้องการส่ง',
					});
					$('#cfg_recipients_option_folder').focus();
					return false;
				}
				
				if (isNaN(my_broadcastline_delay)){
					my_broadcastline_delay = 0;
				}
				if (isNaN(my_broadcastline_to_delay)){
					my_broadcastline_to_delay = 0;
				}
				

				if ((my_broadcastline_delay == '') || (my_broadcastline_delay < 0)) {
					my_broadcastline_delay=0;
					$('#cfg_delay').val(my_broadcastline_delay);
				}
				if ((my_broadcastline_to_delay == '') || (my_broadcastline_to_delay < 0)) {
					my_broadcastline_to_delay=0;
					$('#cfg_to_delay').val(my_broadcastline_to_delay);
				}

				if (typeof cfg_max_recipients === 'undefined'){cfg_max_recipients = 0;}
				if ((cfg_max_recipients == '') || (cfg_max_recipients < 0)) {
					cfg_max_recipients = 0;
					$('#cfg_max_recipients').val(cfg_max_recipients);
				}
				
				if (typeof cfg_start_seding_no==='undefined'){cfg_start_seding_no=1;}
				if ((cfg_start_seding_no == '') || (cfg_start_seding_no < 0)) {
					cfg_start_seding_no=1;
					$('#cfg_start_seding_no').val(cfg_start_seding_no);
				}
				
				if(document.getElementById('cfg_schedule_later').checked){
					var dtschedule=document.getElementById('dtschedule');
					if(typeof dtschedule!=='undefined'){
						var timestamp = Date.parse(dtschedule.value);
						if (isNaN(timestamp)) {
							Swal.fire({
								title: 'เกิดข้อผิดพลาด',
								type: 'error',
								html: 'คุณยังไม่ได้ระบุวลา Schedule ที่จะทำการ Broadcast ไม่ถูกต้อง',
							});
							
							return false;
						}else{
							if (timestamp< (new Date()).getTime()){
								Swal.fire({
									title: 'เกิดข้อผิดพลาด',
									type: 'error',
									html: 'กรุณาระบุวลา Schedule ที่จะทำการ Broadcast ให้มากกว่าเวลาปัจจุบันด้วย',
								});
								return false;
							}
						}
					}
				}
				let myOLBroadcastTable_check = document.querySelector("#myOLBroadcastTable").tBodies[0];
				let num_rows_check = myOLBroadcastTable_check.rows.length;
				if(num_rows_check<1){
					Swal.fire({
						title: 'เกิดข้อผิดพลาด',
						type: 'error',
						html: 'คุณยังไม่ได้ใส่ข้อความหรือเลือกไฟล์ที่ต้องการจะส่ง',
					});
					$('#text_add').focus();
					return false;
				}
				
				var irow_check=0
				var bpass=false;
				while (irow_check < num_rows_check) {
					var my_broadcastline_file_check=document.getElementById("file-"+myOLBroadcastTable_check.rows[irow_check].id+"col2");	//file id file-row1col2
					if(typeof my_broadcastline_file_check!=='undefined'){
						//console.log('my_broadcastline_file_check.value:'+my_broadcastline_file_check.value);
						if(my_broadcastline_file_check.value!=""){
							bpass=true;
							break;
						}
					}
					
					var my_broadcastline_text_check=document.getElementById("text_"+myOLBroadcastTable_check.rows[irow_check].id+"col1");	//message id text_row1col1
					if(typeof my_broadcastline_text_check!=='undefined')
					{
						//console.log('my_broadcastline_text_check.value:'+my_broadcastline_text_check.value);
						if(my_broadcastline_text_check.value!=""){
							bpass=true;
							break;
						}
					}
					irow_check++;
				}
				
				if(bpass==false){
					Swal.fire({
						title: 'เกิดข้อผิดพลาด',
						type: 'error',
						html: 'คุณยังไม่ได้ใส่ข้อความหรือเลือกไฟล์ที่ต้องการจะส่ง',
					})
					$('#text_add').focus();
					return false;
				}
				///////////////
				///////////////
				
				if($('#fanpage_inbox_friend_ids_send_input').val().replace('\n').trim()!='' && permission_extract_member==1){
					//Find page name and set select to correct
					let have_page_name = false;
					//$.each($('#fanpage_inbox_friend_ids_send_input').val().split(/\n/), async function(i, line){
						for(let line of $('#fanpage_inbox_friend_ids_send_input').val().split(/\n/)){
							let line_target = await extractNumber(line);
							//sleep(50);
							if (isNaN(line_target[0])) {
								if(line_target[0]!=""){
									if(have_page_name==false){
										have_page_name = true;
										await check_correct_select_option(line_target[0]);
										continue; //continue for
										//return true;	//continue for each
									}
								}
							}else{
								if(line_target[0]!=""){
									break;
									//return false;	//break for each
								}
							}
						}
					//);
					await sleep(2000);
				}
				
				let sel=document.getElementById("my_broadcastline_idpage");
				
				if(typeof sel!=="undefined" && sel!=null ){
					let opt = sel.options[sel.selectedIndex];
					if(typeof opt!=="undefined" && opt!=null ){
						oaAccountIdActiveName=opt.text;
						oaAccountActiveImg = opt.getAttribute('title');
						if(oaAccountActiveImg!=""){
							oaAccountActiveImg='<i style="justify-content:center;"><img src="'+oaAccountActiveImg+'" alt="oaacc-logo" id="oaacc_logo_img" style="width: 48px; height: 48px;"></i>';
						}
					}
				}
				var oaImg="";
				if(oaAccountActiveImg!=""){
					oaImg="<br />"+oaAccountActiveImg;
				}
				Swal.fire({
					title: 'คุณต้องการส่งข้อความรายการนี้?',
					html: "เพจ "+oaImg+"<h2 style='color:#039639'>'"+ oaAccountIdActiveName +"'</h2>", 
					type: 'warning',
					//footer: footer_swal(),
					showCancelButton: true,
					confirmButtonColor: '#3085d6',
					cancelButtonColor: '#d33',
					confirmButtonText: 'Yes'
				}).then((result) => {
					if (result.value) {
						//Validate data input
						$('#start_broadcast').show();
						$('#pause_broadcast').hide();
						$('#stop_broadcast').hide();
						$('#continue_broadcast').hide();
						$('#footer-summary-container').show();
						$('#close-x').show();
						$('#open-o').hide();
						
						if(document.getElementById('cfg_schedule_later').checked){
							//console.log('later');
							var dtschedule=document.getElementById('dtschedule');
							if(typeof dtschedule!=='undefined'){
								if (dtschedule.value!=''){
									var modal=document.getElementById('modalidSchedule');
									modal.style.display='block';
									runSchedule(dtschedule.value);	//pop.js
								}
							}
						}else{
							send_my_broadcastline_start();	//pop.js
						}
						
					}
				});
		});
		
	});
	
	$("#continue_broadcast").on("click", function (e) {
		$('#start_broadcast').hide();
		$('#pause_broadcast').show();
		$('#stop_broadcast').show();
		$('#continue_broadcast').hide();
		$('#footer-summary-container').show();
		$('#close-x').show();
		$('#open-o').hide();
		$('#pause_broadcast').text('   pause');
		$('#stop_broadcast').text('   stop');
		$('#pause_broadcast').prop('disabled',false);
		$('#stop_broadcast').prop('disabled',false);

		//localStorage.setItem('setstop', 1);	//0 stop, 1 running, 2 pause
		status_stop_pause = 1;
		
		//let loop_index_members = localStorage.getItem('loops');
		//console.log("total send friend:"+tot_send_friends_count);
		let loop_index_members = tot_send_friends_count;
		if(typeof loop_index_members!=="undefined" && loop_index_members!=null && loop_index_members!=""){
			loop_index_members = Number(loop_index_members);
		}else{
			loop_index_members = 0;
		}
		let stop_pause_get_fanpage_next = localStorage.getItem('stop_pause_get_fanpage_next');	//check next page after press pause and continue
		
		if(typeof stop_pause_get_fanpage_next!=="undefined" && stop_pause_get_fanpage_next!=null && stop_pause_get_fanpage_next!=""){
		}else{
			stop_pause_get_fanpage_next = "";
		}
		
		let tags=["ALL"];
		let url = 'https://m.facebook.com/messages/?pageNum=1&selectable&pageID=' + my_broadcastline_label_id;
		if ($('#cfg_recipients_option_folder').val().split('|')[0] == 'folder=page_done') {	//tags = ["ARCHIVED"];
			url = 'https://m.facebook.com/messages/?folder=action%3Aarchived&pageID=' + my_broadcastline_label_id;
			tags = ["ARCHIVED"];
		} else {	//tags = ["INBOX"];
			url = 'https://m.facebook.com/messages/?pageNum=1&selectable&pageID=' + my_broadcastline_label_id;
			tags = ["INBOX"];
		}
		
		setTimeout(function () {
			//$('#radio_schedule *').prop('disabled',true);
			if(stop_pause_get_fanpage_next!=""){
				
				get_start_label_user(stop_pause_get_fanpage_next,isStartBroadcastForContinue,loop_index_members,true,tags);
				
			}else{
				//let fbinboxstatusdone = localStorage.setItem('fbinboxstatusdone', 1);	//0=stop,1=running,2=pause,3=job done;
				//fbinboxstatusdone = 1;
				if(fbinboxstatusdone==3){
					$('#start_broadcast').show();
					$('#pause_broadcast').hide();
					$('#stop_broadcast').hide();
					$('#continue_broadcast').hide();
					alert(" คุณทำรายการนี้เสร็จเรียบร้อยแล้ว ");
					return;
				}else{
					send_my_broadcastline_continue(loop_index_members);
				}
			}
			
		}, 100);
	});
	
	$('#stop_broadcast').on('click', function () {
		Swal.fire({
			title: 'คุณต้องการหยุดการทำรายการหรือไม่?',
			text: "คุณต้องการหยุดส่งข้อความอินบ๊อกหาลูกค้าใช่หรือไม่?",
			type: 'warning',
			//footer: footer_swal(),
			showCancelButton: true,
			confirmButtonColor: '#3085d6',
			cancelButtonColor: '#d33',
			confirmButtonText: 'Yes'
		}).then(async (result) => {
			if (result.value) {
				//console.log("stop waiting");
				document.getElementById("stop_time").innerHTML="stop waiting";
				
				localStorage.setItem('loops', 0);	//store sending no to local storage
				//localStorage.setItem('setstop', 0);	//Clear stop flag
				status_stop_pause = 0;
				
				$('#radio_schedule *').prop('disabled',false);
				$('#pause_broadcast').text('   pause');
				$('#stop_broadcast').text('   stopping');
				$('#pause_broadcast').prop('disabled',false);
				$('#stop_broadcast').prop('disabled',true);
				if(execSetTimeout!=null){
					clearTimeout(execSetTimeout);
				}
				
				//localStorage.setItem('fbinboxstatusdone', 0);	//0=stop,1=running,2=pause,3=job done;
				fbinboxstatusdone = 0;
				
				await setStopJob(0,false,0);
				var d=new Date();
				var esttime_date_format_str = d.getFullYear().toString()+"-"+padDigits(d.getMonth()+1,2)+"-"+padDigits(d.getDate(),2)+" "+padDigits(d.getHours(),2)+":"+padDigits(d.getMinutes(),2)+":"+padDigits(d.getSeconds(),2);
				
				document.getElementById("stop_time").innerHTML="หยุดทำงาน "+esttime_date_format_str;
				status_running=false;
				checkActionStatus();
				
				$('#modalWorkingDelay').hide();
			}
		});
	});
	
	$("#modal_alert_close").on("click", function (e) {
		var modalGrAlert = document.getElementById("modalGrAlert");
		modalGrAlert.style.display = "none";
	});
	
	//<span class="button"></span>
	// $("#file_file_add_container").on("click", function (e) {
	// 	//document.getElementById("file_file_add_container").addEventListener("click", function(e){
	// 	document.getElementById('file-file_add_container').click();
	// });

	
	// $(".button_file_file_add_container").on("click", function (e) {
	// 		document.getElementById('file-file_add_container').click();
	// });

	$('#file_file_add_container').prop('disabled', false);
	$('#file_file_add_container').prop('readonly', true);
	$('#file_file_add_container').css('background-color', 'f7f7f7');
	
	/*
	$("#btn_menu_manual_fb_fp").on("click", function (e) {
		try{
			manual_detail();	//from host customer.js
		}catch(e){
			alert('Error:'+e);
		}
	});
	$("#btn_menu_contact_fb_fp").on("click", function (e) {
		try{
			contact_detail();	//from host customer.js
		}catch(e){
			alert('Error:'+e);
		}
	});
	$("#btn_menu_moreinfo_fb_fp").on("click", function (e) {
		try{
			moreinfo_detail();	//from host customer.js
		}catch(e){
			alert('Error:'+e);
		}
	});
	$("#btn_menu_downloadapp_fb_fp").on("click", function (e) {
		try{
			download_software();	//from host customer.js
		}catch(e){
			alert('Error:'+e);
		}
	});
	*/
	
}

async function onCompleteFbFanpage(){
	//console.clear();
	var isGetPageList=false;
	console.log("ready use on Complete Fb Fanpage");
	
	//clearIndexDb();
	
	var dtschedule = document.getElementById('dtschedule');
	for (var radioCounter = 0 ; radioCounter < document.getElementsByName('cfg_schedule').length; radioCounter++) {
		  document.getElementsByName('cfg_schedule')[radioCounter].onchange = function() {
			//VALUE OF THE CLICKED RADIO ELEMENT
			this.value=true;
			if (this.id=='cfg_schedule_now'){
				document.getElementById('cfg_schedule_later').value=false;
				document.getElementById('lbl_dtschedule').style.display='none';
			}else if(this.id=='cfg_schedule_later'){
				document.getElementById('cfg_schedule_now').value=false;
				document.getElementById('lbl_dtschedule').style.display='block';
				//var now = new Date();
				//now.setDate(now.getDate() + 10);
				//rome(dtschedule,{initialValue: new Date(),min: new Date(), max: now });
				rome(dtschedule).setValue(new Date());
			}
			
		  }
	}
	document.getElementById("file_add_container").addEventListener("click", function(e){
		//e.preventDefault();
		document.getElementById('file-file_add_container').click();
		//alert("The paragraph was double-clicked");
		//e.stopPropagation();
		//e.stopImmediatePropagation();
	});
	document.getElementById("file_file_add_container").addEventListener("click", function(e){
		e.preventDefault();
		document.getElementById('file-file_add_container').click();
		e.stopPropagation();
		e.stopImmediatePropagation();
	});
	
	document.getElementById("add_new_file").addEventListener("click", function(e){
		e.preventDefault();
		document.getElementById('file-file_add_container').click();
		e.stopPropagation();
		e.stopImmediatePropagation();
	});
	document.getElementById("file-file_add_container").addEventListener("change", function(e){
		e.preventDefault();
		let target = e.target || e.srcElement;
		if (target.value.length == 0) {
			$("#file-file_add_container").val('');
			$("#file-file_add_container").val(null);
			let x=document.getElementById("rmxfile_add_container");
			if(typeof x!=="undefined"){
				setEmptyFileValue(x);
			}
			document.getElementById("file_file_add_container").value="";
			document.getElementById("file_file_add_container").title="";
			document.getElementById("file_file_add_container").innerHTML="";
		}
	});
	document.getElementById("file-row1col2").addEventListener("change", function(e){
		e.preventDefault();
		let target = e.target || e.srcElement;
		if (target.value.length == 0) {
			let x=document.getElementById("rmxrow1col2");
			if(typeof x!=="undefined"){
				setEmptyFileValue(x);
			}
			document.getElementById("file_row1col2").value="";
			document.getElementById("file_row1col2").title="";
			document.getElementById("file_row1col2").innerHTML="";
		}
	});
	
	document.getElementById("text_add").style.backgroundColor = "#f7f7f7";
	document.getElementById("text_add").addEventListener("blur", function(e){
		e.preventDefault();
		this.style.backgroundColor = "#f7f7f7";
		e.stopPropagation();
		e.stopImmediatePropagation();
	});
	
	document.getElementById("text_add").addEventListener("focus", function(e){
		var el = this;
		this.style.backgroundColor = "#fff";
		el.removeAttribute("disabled");
		el.removeAttribute("readonly");
	});
	
	document.getElementById("text_add").addEventListener("change", function(e){
		e.preventDefault();
		onTextKeyUp(this);
		e.stopPropagation();
		e.stopImmediatePropagation();
	});
	document.getElementById("text_add").addEventListener("keyup", function(e){
		e.preventDefault();
		countcharleft(this);
		var el = this;
		el.removeAttribute("disabled");
		el.removeAttribute("readonly");
		e.stopPropagation();
		e.stopImmediatePropagation();
	});

	document.getElementById("close_modal_xrow").addEventListener("click", function(event) {
		event.preventDefault();
		var td = event.target;
		document.getElementById(td.parentNode.id).style.display='none';document.getElementById(td.parentNode.id).setAttribute('data-delete-confirm','yes');
		
		event.stopPropagation();
		event.stopImmediatePropagation();
	});
	document.getElementById("cancelbtn").addEventListener("click", function(event) {
		event.preventDefault();
		var td = event.target;
		document.getElementById(td.form.offsetParent.id).setAttribute('data-delete-confirm','yes');
		document.getElementById(td.form.offsetParent.id).style.display='none';		
		event.stopPropagation();
		event.stopImmediatePropagation();
	});
	document.getElementById("deletebtn").addEventListener("click", function(event) {
		event.preventDefault();
		var td = event.target;
		document.getElementById(td.form.offsetParent.id).setAttribute('data-delete-confirm','yes');
		document.getElementById(td.form.offsetParent.id).style.display='none';
		funSubmitDeleteRow();
		event.stopPropagation();
		event.stopImmediatePropagation();
	});
	document.getElementById("close_modal_allrow").addEventListener("click", function(event) {
		event.preventDefault();
		var td = event.target;
		document.getElementById(td.parentNode.id).style.display='none';document.getElementById(td.parentNode.id).setAttribute('data-deleteAll-confirm','yes');
		event.stopPropagation();
		event.stopImmediatePropagation();
	});
	document.getElementById("cancelAllbtn").addEventListener("click", function(event) {
		event.preventDefault();
		var td = event.target;
		document.getElementById(td.form.offsetParent.id).setAttribute('data-deleteAll-confirm','yes');
		document.getElementById(td.form.offsetParent.id).style.display='none';
		event.stopPropagation();
		event.stopImmediatePropagation();
	});
	document.getElementById("deleteAllbtn").addEventListener("click", function(event) {
		event.preventDefault();
		var td = event.target;
		document.getElementById(td.form.offsetParent.id).setAttribute('data-deleteall-confirm','yes');
		document.getElementById(td.form.offsetParent.id).style.display='none';
		funSubmitDeleteAllRow();
		event.stopPropagation();
		event.stopImmediatePropagation();
	});
	document.querySelector(".close-x").addEventListener("click", function(event) {
		event.preventDefault();
		var td = event.target;
		if(typeof schTimeLeft!=="undefined" && schTimeLeft!=null){
			clearInterval(schTimeLeft);
		}
		document.getElementById(td.parentNode.id).style.display='none';
		event.stopPropagation();
		event.stopImmediatePropagation();
	});
	document.getElementById("cancelErrMsg").addEventListener("click", function(event) {
		event.preventDefault();
		var td = event.target;
		document.getElementById(td.form.offsetParent.id).style.display='none';
		event.stopPropagation();
		event.stopImmediatePropagation();
	});
	document.querySelector(".move-row-up").addEventListener("click", handler_move_row_up_event=function(event) {
		event.preventDefault();
		var td = event.target;
		upNdown('up',td.parentNode);
		event.stopPropagation();
		event.stopImmediatePropagation();
	});
	document.querySelector(".move-row-down").addEventListener("click", handler_move_row_down_event=function(event) {
		event.preventDefault();
		var td = event.target;
		upNdown('down',td.parentNode);
		event.stopPropagation();
		event.stopImmediatePropagation();
	});
	document.querySelector(".del-row").addEventListener("click", function(event) {
		event.preventDefault();
		var td = event.target;
		funDel(td);
		event.stopPropagation();
		event.stopImmediatePropagation();
	});
	document.getElementById("rmxfile_add_container").addEventListener("click", function(event) {
		event.preventDefault();
		var td = event.target;
		setEmptyFileValue(td);
		event.stopPropagation();
		event.stopImmediatePropagation();
	});
	document.getElementById("row1col2").addEventListener("click", handler_add_files_event=function(event) {
		//event.preventDefault();
		//var td = event.target;
		document.getElementById("file-row1col2").click();
		//$('#file-row1col2').focus().trigger('click');
		//$("#file-row1col2").click();
		//event.stopPropagation();
		//event.stopImmediatePropagation();
	});
	document.getElementById("get_fb_fanpage").addEventListener("click", function(event) {
		event.preventDefault();
		$('#download_fb_fanpage_members').hide();
		isStartBroadcastForContinue = false;
		let tags = ["ALL"];

		get_request_page_info();
		setTimeout(function () {
			//let url = 'https://graph.facebook.com/v2.6/me/conversations?fields=senders,unread_count&' + my_broadcastline_folder_label_type + '&limit=300&access_token=' + my_broadcastline_idpage_token;
			let url = 'https://m.facebook.com/messages/?pageNum=1&selectable&pageID=' + my_broadcastline_label_id;
			if ($('#cfg_recipients_option_folder').val().split('|')[0] == 'folder=page_done') {	//tags = ["ARCHIVED"];
				url = 'https://m.facebook.com/messages/?folder=action%3Aarchived&pageID=' + my_broadcastline_label_id;
				tags = ["ARCHIVED"];
			} else {	//tags = ["INBOX"];
				url = 'https://m.facebook.com/messages/?pageNum=1&selectable&pageID=' + my_broadcastline_label_id;
				tags = ["INBOX"];
			}
			let d=new Date();
			let starttime_date_format_str = d.getFullYear().toString()+"-"+padDigits(d.getMonth()+1,2)+"-"+padDigits(d.getDate(),2)+" "+padDigits(d.getHours(),2)+":"+padDigits(d.getMinutes(),2)+":"+padDigits(d.getSeconds(),2);
			document.getElementById("start_time").innerHTML = "เริ่ม "+starttime_date_format_str;
			//for page_done
			//https://graph.facebook.com/v2.6/me/conversations?tags=action:archived&fields=senders,updated_time,unread_count&folder=page_done&limit=300&access_token=EAAAAZAw4FxQIBAEl7EM0mQt1JzySK6GC5bzVbWw2JleY1CSmdExgL9YAkkAyrlkJZA9itLMGMdV3YU0a2SqqfmZCtM5ZAqUeRwxF3qEJrzQAUeH1JDMmrK4AC2KNyQ2CFkELZCNPmfqZC37BbtmLKGkzCZCh6ntM6VoENQtBY4hqB4uL5E3DP1ZA
			
			//TEST
			//get_inbox_page_start();
			//return;
			
			$('#fanpage_inbox_friend_ids_send_input').val('');
			
			get_start_label_user('',false,0,false,tags);
			
			event.stopPropagation();
			event.stopImmediatePropagation();
		}, 500);
	});
	document.getElementById("cancelSchedule").addEventListener("click", function(event) {
		event.preventDefault();
		if(typeof schTimeLeft!=="undefined" && schTimeLeft!=null){
			clearInterval(schTimeLeft);
		}
		document.getElementById('modalidSchedule').style.display='none';
	});
	
	
	document.getElementById("text_row1col1").style.backgroundColor = "#f7f7f7";
	document.getElementById("file_row1col2").style.backgroundColor = "#f7f7f7";
	
	
	document.querySelector("#myOLBroadcastTable tbody").addEventListener("click", function(event) {
		//event.preventDefault();
		var td = event.target;
		while (td !== this && !td.matches("td")) {
			td = td.parentNode;
		}
		if (td === this) {
			console.log("No table cell found");
		} else {
			//console.log(td.innerHTML);
			//console.log(td.cellIndex);
			//console.log(td.parentNode.rowIndex);
			if(td.cellIndex==1){	//col text
				document.getElementById("text_"+td.id).style.backgroundColor = "#fff";
			}
		}
		//event.stopPropagation();
		//event.stopImmediatePropagation();
	});
	document.querySelector("#myOLBroadcastTable tbody").addEventListener("focusout", function(event) {
		//event.preventDefault();
		var td = event.target;
		while (td !== this && !td.matches("td")) {
			td = td.parentNode;
		}
		if (td === this) {
			console.log("No table cell found");
		} else {
			//console.log(td.innerHTML);
			//console.log(td.cellIndex);
			//console.log(td.parentNode.rowIndex);
			if(td.cellIndex==1){	//col text
				//edit(td);
				document.getElementById("text_"+td.id).style.backgroundColor = "#f7f7f7";
			}else if(td.cellIndex==2){
				document.getElementById("file_"+td.id).style.backgroundColor = "#f7f7f7";
			}
		}
		//event.stopPropagation();
		//event.stopImmediatePropagation();
	});
	document.getElementById("download_fb_fanpage_members").addEventListener("click",function(event){
		event.preventDefault();
		
		DownloadLink();
		
		//let downloadLink = document.getElementById('downloadLink');
		//if(downloadLink){
		//	downloadLink.click();
		//}
		
	});
	document.getElementById("download_fb_fanpage_success_members").addEventListener("click",function(event){
		event.preventDefault();
		
		downloadSuccessLink();
		
	});
	document.getElementById("dtschedule").addEventListener("click", function(event) {
		var now = new Date();
		now.setSeconds(now.getSeconds() + 60);
		rome(dtschedule).setValue(new Date(now));
		now.setDate(now.getDate() + 10);
		rome(dtschedule,{initialValue: new Date(now),min: new Date(), max: now });
	});
	
	document.addEventListener('DOMContentLoaded', function(event) {
	  //the event occurred
	  console.log('DOMContentLoaded');
	})
	
	document.querySelector(":not(#text_add),.counterchar.editable.emojionearea").addEventListener("change", async function(event) {
		//event.preventDefault();
		var td = event.target;
		
		var mainBody = document.querySelector("#myOLBroadcastTable").tBodies[0];
		
		//console.log(td);
		//console.log(td.value);
		let tbdata = checkTableDataPromise();
		
		tbdata.then(
			function (value){
				document.getElementById("start_broadcast").style.display = "inline-block";
				if(value){
					document.getElementById("start_broadcast").disabled = false;
				}else{
					document.getElementById("start_broadcast").disabled = true;
				}
			},
			function(error) {
				document.getElementById("start_broadcast").style.display = "inline-block";
				document.getElementById("start_broadcast").disabled = true;
			}
		);
	});
	
	$('#start_broadcast').show();
	$('#pause_broadcast').hide();
	$('#continue_broadcast').hide();
	$('#stop_broadcast').hide();
	$('#download_fb_fanpage_members').hide();
	$('#download_fb_fanpage_success_members').hide();
	$('#get_fb_fanpage').show();
	$('.processing').hide();
	
	txt_error_report = document.getElementById("txt_error_report");
	if(typeof txt_error_report!=="undefined" && txt_error_report!=null){
		txt_error_report.innerHTML="";
		//$("#txt_error_report").html("");
		//$("#txt_error_report").append("<li>Appended item</li>");
	}
	
	//speed_conig.js
	try{
		$('#cfg_tf_msg_rate_limit_per_min').val(0);
		if (typeof CFG_TF_MSG_RATE_LIMIT_PER_MIN != 'undefined' && CFG_TF_MSG_RATE_LIMIT_PER_MIN!=null) { 
			if(!isNaN(CFG_TF_MSG_RATE_LIMIT_PER_MIN)){
				$('#cfg_tf_msg_rate_limit_per_min').val(Number(CFG_TF_MSG_RATE_LIMIT_PER_MIN));
			}
		}
		console.log('CFG_TF_MSG_RATE_LIMIT_PER_MIN:'+CFG_TF_MSG_RATE_LIMIT_PER_MIN+ ' type:'+(typeof CFG_TF_PAUSE_SENDING_EVERY_MIN));
	}catch(e){}
	try{
		$('#pause_seding_every_min').val(0);
		if (typeof CFG_TF_PAUSE_SENDING_EVERY_MIN != 'undefined' && CFG_TF_PAUSE_SENDING_EVERY_MIN!=null) { 
			if(!isNaN(CFG_TF_PAUSE_SENDING_EVERY_MIN)){
				$('#pause_seding_every_min').val(Number(CFG_TF_PAUSE_SENDING_EVERY_MIN));
			}
		}
		console.log('CFG_TF_PAUSE_SENDING_EVERY_MIN:'+CFG_TF_PAUSE_SENDING_EVERY_MIN+ ' type:'+(typeof CFG_TF_PAUSE_SENDING_EVERY_MIN));
	}catch(e){}
	try{
		$('#pause_seding_time_min').val(0);
		if (typeof CFG_TF_PAUSE_SENDING_TIME_MIN != 'undefined' && CFG_TF_PAUSE_SENDING_TIME_MIN!=null) { 
			if(!isNaN(CFG_TF_PAUSE_SENDING_TIME_MIN)){
				$('#pause_seding_time_min').val(Number(CFG_TF_PAUSE_SENDING_TIME_MIN));
			}
		}
		console.log('CFG_TF_PAUSE_SENDING_TIME_MIN:'+CFG_TF_PAUSE_SENDING_TIME_MIN+ ' type:'+(typeof CFG_TF_PAUSE_SENDING_EVERY_MIN));
	}catch(e){}
	try{
		if (typeof CFG_IS_SHOW_SPEED_LIMIT_GROUP != 'undefined' && CFG_IS_SHOW_SPEED_LIMIT_GROUP!=null) { 
			if(CFG_IS_SHOW_SPEED_LIMIT_GROUP==true){
				$('#speed_limit_group').show();
			}else{
				$('#speed_limit_group').hide();
			}
		}
		console.log('CFG_IS_SHOW_SPEED_LIMIT_GROUP:'+CFG_IS_SHOW_SPEED_LIMIT_GROUP+ ' type:'+(typeof CFG_TF_PAUSE_SENDING_EVERY_MIN));
	}catch(e){}
	
	
	try{
		if (typeof header_detail == 'function') { 
			header_detail();
		}
	}catch(e){}
	try{
		if (typeof footer_detail == 'function') {
			footer_detail();
		}
	}catch(e){console.log(e);}
	try{
		if (typeof footer_remark == 'function') {
			footer_remark();
		}
	}catch(e){console.log(e);}
	
	try{
		var dnow = new Date();
		var curdate = dnow.toJSON().slice(0,10);
		server_date = curdate;
		ldb.get('pop_server_date', function (pop_server_date) {
			if(typeof pop_server_date!=="undefined" && pop_server_date!=null){
				var ul = pop_server_date.split("|");
				if(ul.length>1){
					//user_name|server_date|curdate
					//console.log("server: date:"+ul[1]);
					server_date = ul[1];
				}
			}
		});
	}catch(e){}
	
	try{
		populate_receive_options_folder();
	}catch(e){}
	
	$(document).delegate(':file', 'change', function(e) {	// jQuery < 1.7
		var x = document.getElementById(e.target.id);
		var geekss = "";
		if(e.target.files.length>0){
			var ele = e.target.files[0];
			if (typeof ele != undefined){
				if (typeof ele.name != undefined){
					geekss = ele.name;
				}
			}
		}
		if(geekss===""){return;}
		var id=x.parentNode.id;
		var name=document.getElementById("file_"+id);	//textarea
		if(name!==null){
			try{
				name.value=geekss +" ("+e.target.files.length+" files)";
			}catch(e){
				name.innerHTML=geekss +" ("+e.target.files.length+" files)";
			}
			name.innerHTML=geekss;
			if(name.type == "textarea" || name.type=="text"){
				if(name.id!=="text_add"){ name.title=name.value;}
				name.innerHTML=name.value;
				$("#file_image").show();
				$("#remove_file_btn").show();
				$("#pencil").show();
			}
		}

		var files = e.target.files; // FileList object
		// Only process image files.
		if(files.length>0){
			if (!files[0].type.match('image.*')) {
				document.getElementById('img_'+id).style.display = "none";
				//return;
			}else{
				document.getElementById('img_'+id).style.display = "inline";
				document.getElementById('img_'+id).title=name.value;
				
			}
			img_pathUrl(this,'img_'+id,id);
			//add element
			var xClearFile=document.getElementById(e.target.parentNode.id);
			var domString='<i><i id="rmx'+id+'" class="fa fa-times" aria-hidden="true" title="ลบไฟล์"></i></i>';

			var rmClearFile = document.getElementById("rmx"+id);
			////console.log(rmClearFile);
			if(rmClearFile!=null){
				//document.getElementById("element_id").remove();
			}else{
				xClearFile.insertAdjacentHTML('beforeend',domString);
				document.getElementById("rmx"+id).addEventListener("click", function(event) {
					event.preventDefault();
					setEmptyFileValue(this);
					event.stopPropagation();
					event.stopImmediatePropagation();
				});
			}
			if(id=="file_add_container"){
				document.getElementById("rmxfile_add_container").style.visibility="visible";
			}
		}
	});
	
	//login modal
	document.getElementById("logmecancel").addEventListener("click", function(event) {
		//event.preventDefault();
		document.getElementById('id01login').style.display='none';
	});
	
	$("#speed_limit_group").hide();
	
	
	////////////////////////////////////////////
	/// Show Facebook Profile name and image ///
	////////////////////////////////////////////
	/*
	var iretry = 0;
	var tpId = setInterval(async function() {
		//console.log("xxxxx");
		
		try{
				$('#fb_profile_img').css('display', 'inline-block').hide();
				if(!fb_name){
					fb_name = await LocalStorage.getItem('fb_name');
				}
				if(!fb_user_id){
					fb_user_id = await LocalStorage.getItem('fb_user_id');
				}
				if(!fb_dtsg){
					fb_dtsg = await LocalStorage.getItem('fb_dtsg');
				}
				if(!fb_access_token){
					fb_access_token = await LocalStorage.getItem('fb_access_token');
				}
				
				if(typeof fb_user_id!=="undefined" && fb_user_id!=null && fb_user_id!=""){
					$('#face_login_status').text(fb_name);	//fb_name in tp_tf_gfunc.js
					console.log("พบชื่อของโปรไฟล์นี้");
					if(fb_name=='' || fb_dtsg==null){	//fb_dtsg in gfunc
						$('#face_login_status').text('ไม่สามารถใช้โปรไฟล์นี้ได้ในขณะนี้');
					}else{
						clearInterval(tpId);
					}
					
				}else{
					fb_user_id = await LocalStorage.getItem('fb_user_id');
					console.log("not found fb user id");
					$('#face_login_status').text('ไม่สามารถใช้โปรไฟล์นี้ได้ในตอนนี้');
				}
				$('#face_profile').css('display', 'inline-block').hide().fadeIn(5000);
				
				//token_fb_instagramx = "xxxmmmlll";
				token_fb_instagramx = fb_access_token;	//oken_fb_instagramx in, fb_access_token in tp_tf_gfunc 
				if(!token_fb_instagramx){
					token_fb_instagramx = await LocalStorage.getItem('fb_token_power');
					if (!token_fb_instagramx){
						await get_token_power_find_old(fb_user_id);
						token_fb_instagramx = await LocalStorage.getItem('fb_token_power');
					}
				}
				if(typeof token_fb_instagramx!=="undefined" && token_fb_instagramx!=null && token_fb_instagramx!=""){
					fb_access_token = token_fb_instagramx;
					clearInterval(tpId);
					console.log("FB:"+fb_name);
					try{
						var fbimg=document.getElementById("face_profile_img");
						fbimg.src = "https://graph.facebook.com/" + fb_user_id + "/picture?type=large&access_token=" + token_fb_instagramx;	//token_fb_instagramx in tp_tf_gfunc.js	
						$('#face_profile_img').attr("src", "https://graph.facebook.com/" + fb_user_id + "/picture?type=large&access_token=" + token_fb_instagramx);

						//fbimg.src = "https://linebroadcast.com/openline/tools/img/ollogo128.png";
						var tId = setInterval(function() {
							try{
								if (fbimg.complete == true && fbimg.naturalHeight !== 0 && fbimg.naturalWidth!==0) {
									clearInterval(tId);
									$('#fb_profile_img').css('display', 'inline-block').show();
									$('#face_profile').css('display', 'inline-block').hide().fadeIn(5000);
								}
							}catch(e){clearInterval(tId);}
						}, 1000);
					}catch(e){}
					
					
					// if(typeof fb_access_token!=="undefined" && fb_access_token!=null && fb_access_token!="" && isGetPageList==false){
					// 	isGetPageList = true;
					// 	get_fanpage();
					// }
					
				}

		}catch(e){

		}
		if (iretry>3){
			clearInterval(tpId);
		}
		iretry++;
	}, 10000);
	*/

	/////////////////////////////
	/*
	if(typeof fb_access_token!=="undefined" && fb_access_token!=null && fb_access_token!="" && isGetPageList==false){
		isGetPageList = true;
		get_fanpage();
	}
	*/
	
	/////////////////////////////
	/*
	if(typeof fb_access_token!=="undefined" && fb_access_token!=null && fb_access_token!="" && isGetPageList==false){
		isGetPageList = true;
		await get_fanpage();
		document.querySelector("#dialog_loading").style.display = "none"; 
		document.querySelector("body").style.visibility = "visible";
	}else{
		////Unload loading and show page
		document.querySelector("#dialog_loading").style.display = "none"; 
		document.querySelector("body").style.visibility = "visible";
	}
	*/
	
	//start_ext(null);
}


function populate_receive_options_folder(){
	/*
	var ele = document.getElementById('cfg_recipients_option_folder');
	var i, L = ele.options.length - 1;
	for(i = L; i >= 0; i--) {
		ele.remove(i);
	}
	
	var opt_folder_list = [];
	opt_folder_list.push('<option value="folder=inbox|โฟลเดอร์หลัก" selected="selected">โฟลเดอร์หลัก</option>');
	opt_folder_list.push('<option value="folder=page_done|เรียบร้อยแล้ว">เรียบร้อยแล้ว</option>');
	*/
	
	if(typeof ENABLED_FB_PAGE_DONE_OLD_ARCHIVED!="undefined" && ENABLED_FB_PAGE_DONE_OLD_ARCHIVED!=null && ENABLED_FB_PAGE_DONE_OLD_ARCHIVED!=""){
		//append one
		let ele = document.getElementById('cfg_recipients_option_folder');
		let opt = document.createElement("option");
		let xval = ENABLED_FB_PAGE_DONE_OLD_ARCHIVED.split('|');
		opt.text = "เรียบร้อยแล้วเก่ากว่า 2 ปี";
		opt.value = "tags=action:archived|เรียบร้อยแล้วเก่ากว่า 2 ปี";
		opt.value = ENABLED_FB_PAGE_DONE_OLD_ARCHIVED;
		if(xval.length>1){
			
			if(xval[1]!=""){
				opt.text = xval[1];
			}
			
		}
		
		
		ele.add(opt, ele[opt.length]);
		
		//let opt_folder_list = [];
		//opt_folder_list.push('<option value="tags=action:archived|เรียบร้อยแล้วเก่ากว่า 2 ปี">เรียบร้อยแล้วเก่ากว่า 2 ปี</option>');
		//ele.innerHTML = opt_folder_list.join('\n');
	}
	if(typeof ENABLED_FB_ALL_PAGES!="undefined" && ENABLED_FB_ALL_PAGES!=null && ENABLED_FB_ALL_PAGES!=""){
		//append one
		let ele = document.getElementById('cfg_recipients_option_folder');
		let opt = document.createElement("option");
		let xval = ENABLED_FB_ALL_PAGES.split('|');
		opt.text = "ทุกโฟล์เดอร์";
		opt.value = "folder=all|ทุกโฟล์เดอร์";
		opt.value = ENABLED_FB_ALL_PAGES;
		if(xval.length>1){
			
			if(xval[1]!=""){
				opt.text = xval[1];
			}
			
		}
		ele.add(opt, ele[opt.length]);
	}
	
	/*
	if(opt_folder_list.length>0){
		//options.push('<option value=""   >เลือก Account Line</option>');
		opt_folder_list.reverse();
	}
	*/
	//ele.innerHTML = opt_folder_list.join('\n');
	
}

async function startFbFanpageLoad(){
	console.log("startFbFanpageLoad login_fb_get_token");
	await login_fb_get_token();	//in tf_gfunc.js

	if(!fb_dtsg){fb_dtsg = localStorage.getItem('fb_dtsg');}
	if(!fb_user_id){fb_user_id = localStorage.getItem('fb_user_id');}
	if(!__rev){__rev = localStorage.getItem('__rev');}

	
	console.log("fb_user_id: "+fb_user_id);
	//__rev="";
	if(typeof __rev =='undefined' || __rev==null || __rev==""){
		if(fb_user_id!=""){
			console.log("call login_fb_get_token_step2");
			await login_fb_get_token_step2(fb_user_id);	//in tf_gfunc.js
		}
	}
	
	if(!fb_access_token){fb_access_token = localStorage.getItem('fb_access_token');}
	if(!fb_dtsg){fb_dtsg = localStorage.getItem('fb_dtsg');}
	if(!fb_user_id){fb_user_id = localStorage.getItem('fb_user_id');}
	if(!fb_name){fb_name = localStorage.getItem('fb_name');}
	if(!__rev){__rev = localStorage.getItem('__rev');}
	if(!fb_token_feed){fb_token_feed = localStorage.getItem('fb_token_feed');}

	/*
	///// 2023-01-04 ///////
	var poweredit_token = await localStorage.getItem("token_poweredit");
	if(typeof poweredit_token!="undefined" && poweredit_token!=null && poweredit_token!=""){
		localStorage.setItem("fb_access_token",poweredit_token);
		fb_access_token = poweredit_token
	}
	/////////////////////
	*/
	
	await getFaceFanpage();
	document.querySelector("#dialog_loading").style.display = "none"; 
	document.querySelector("body").style.visibility = "visible";
}

//////////
// Make the DIV element draggable:
dragElement(document.getElementById("modalWorkingDelay"),"my_header");
//dragElement(document.getElementById("modalWorkingDelay"));
function dragElement(elmnt,dragTitleId) {
  var pos1 = 0, pos2 = 0, pos3 = 0, pos4 = 0;
  if (typeof dragTitleId!="undefined" && dragTitleId!=null && dragTitleId){
	document.getElementById(dragTitleId).onmousedown = dragMouseDown;
  }else if (document.getElementById(elmnt.id + "header")) {
  //if (document.getElementById(elmnt.id + "header")) {
    // if present, the header is where you move the DIV from:
    document.getElementById(elmnt.id + "header").onmousedown = dragMouseDown;
  } else {
    // otherwise, move the DIV from anywhere inside the DIV:
    elmnt.onmousedown = dragMouseDown;
  }

  function dragMouseDown(e) {
    e = e || window.event;
    e.preventDefault();
    // get the mouse cursor position at startup:
    pos3 = e.clientX;
    pos4 = e.clientY;
    document.onmouseup = closeDragElement;
    // call a function whenever the cursor moves:
    document.onmousemove = elementDrag;
  }

  function elementDrag(e) {
    e = e || window.event;
    e.preventDefault();
    // calculate the new cursor position:
    pos1 = pos3 - e.clientX;
    pos2 = pos4 - e.clientY;
    pos3 = e.clientX;
    pos4 = e.clientY;
    // set the element's new position:
    elmnt.style.top = (elmnt.offsetTop - pos2) + "px";
    elmnt.style.left = (elmnt.offsetLeft - pos1) + "px";
  }

  function closeDragElement() {
    // stop moving when mouse button is released:
    document.onmouseup = null;
    document.onmousemove = null;
  }
}
/////////

function ready(fn) {
  if (document.readyState != 'loading'){
    fn();
  } else if (document.addEventListener) {
    document.addEventListener('DOMContentLoaded', fn);
	console.log("ready state");
  } else {
    document.attachEvent('onreadystatechange', function() {
      if (document.readyState != 'loading')
        fn();
    });
  }
}

function showFbProfile(){
	////////////////////////////////////////////
	/// Show Facebook Profile name and image ///
	////////////////////////////////////////////
	var iretry = 0;
	var tpId = setInterval(async function() {
		try{
				$('#fb_profile_img').css('display', 'inline-block').hide();
				if(!fb_name){
					fb_name = await LocalStorage.getItem('fb_name');
				}
				let cook_fb_user_id = "";
				cook_fb_user_id = await LocalStorage.getItem('fb_user_id');
				if(!cook_fb_user_id){cook_fb_user_id="";}
				if(!fb_user_id){
					fb_user_id = cook_fb_user_id;
				}else{
					await LocalStorage.setItem('fb_user_id',fb_user_id);
					cook_fb_user_id = await LocalStorage.getItem('fb_user_id');
				}
				if(!fb_dtsg){
					fb_dtsg = await LocalStorage.getItem('fb_dtsg');
				}
				if(!fb_access_token){
					fb_access_token = await LocalStorage.getItem('fb_access_token');
				}
				
				if(typeof fb_user_id!=="undefined" && fb_user_id!=null && fb_user_id!=""){
					$('#face_login_status').text(fb_name);	//fb_name in tp_tf_gfunc.js
					console.log("พบชื่อของโปรไฟล์นี้");
					if(fb_name=='' || fb_dtsg==null){	//fb_dtsg in gfunc
						$('#face_login_status').text('ไม่สามารถใช้โปรไฟล์นี้ได้ในขณะนี้');
					}else{
						clearInterval(tpId);
					}
				}else{
					fb_user_id = await LocalStorage.getItem('fb_user_id');
					console.log("not found fb user id");
					$('#face_login_status').text('ไม่สามารถใช้โปรไฟล์นี้ได้ในตอนนี้');
				}
				$('#face_profile').css('display', 'inline-block').hide().fadeIn(5000);

				token_fb_instagramx = fb_access_token;	//oken_fb_instagramx in, fb_access_token in tp_tf_gfunc 
				if(!token_fb_instagramx){
					token_fb_instagramx = await LocalStorage.getItem('fb_token_power');
					if (!token_fb_instagramx){
						await get_token_power_find_old(fb_user_id);
						token_fb_instagramx = await LocalStorage.getItem('fb_token_power');
					}
				}
				if(typeof token_fb_instagramx!=="undefined" && token_fb_instagramx!=null && token_fb_instagramx!=""){
					fb_access_token = token_fb_instagramx;
					clearInterval(tpId);
					console.log("FB:"+fb_name);
					try{
						var fbimg=document.getElementById("face_profile_img");
						fbimg.src = "https://graph.facebook.com/" + fb_user_id + "/picture?type=large&access_token=" + token_fb_instagramx;	//token_fb_instagramx in tp_tf_gfunc.js	
						$('#face_profile_img').attr("src", "https://graph.facebook.com/" + fb_user_id + "/picture?type=large&access_token=" + token_fb_instagramx);

						var tId = setInterval(function() {
							try{
								if (fbimg.complete == true && fbimg.naturalHeight !== 0 && fbimg.naturalWidth!==0) {
									clearInterval(tId);
									$('#fb_profile_img').css('display', 'inline-block').show();
									$('#face_profile').css('display', 'inline-block').hide().fadeIn(5000);
								}
							}catch(e){clearInterval(tId);}
						}, 1000);
					}catch(e){}
				}

		}catch(e){

		}
		if(iretry>0){
			console.log("retry get facebook profile times: "+iretry)
		}
		if (iretry>3){
			clearInterval(tpId);
		}
		
		iretry++;
	}, 10000);
}



// Function to send message to worker.js
var listData = async () => {

	chrome.runtime.sendMessage({type:'execute-script'},function(resp){
	  window.close();
	});

	// content script
	// chrome.runtime.sendMessage({ type: 'image', url: '<https://www.notion.so/image/https%3A%2F%2Fs3-us-west-2.amazonaws.com%2Fsecure.notion-static.com%2F958e1994-be0c-4d8a-ac7c-ea26c8971188%2FUntitled.png?id=57ffe85c-75f2-43fa-8d9c-372f58809836&table=block&spaceId=9047f58e-5ddf-46fd-a4b7-6d1a8d133c25&width=1900&userId=5cbec8d7-83db-40b8-9fbe-9f6c37c38b1d&cache=v2>' }, response => {
	// 	console.log(response)
  	// })

};


(function(){
    var tId = setInterval(function() {
		try{
			if (document.readyState === "complete") {
				clearInterval(tId);
				tId = setInterval(function() {
					if (document.getElementsByName('cfg_schedule').length>1) {
						clearInterval(tId);
						console.log("Call onCompleteFbFanpage");
						onCompleteFbFanpage();
					}
				}, 500);
			}
		}catch(e){}
    }, 500);
})()
