
"user strict";
var lineMeCookie={};
var lineMeAdmin=null;
var usrfToken="";
var is_allowed_rich_msg=0;
var ct_tl_line_alls=[];
var ct_tl_tag_list=[];

var ct_tl_card_list=[];
var ct_tl_card_prev_oa_page="";
var ct_tl_card_prev_obj="";

/*
ct_tl_richId_stored_list.push({
	'basicSearchId':basicSearchId,
	'richId': richId,
	'richTitle': richTitle,
	'richType': richType,
	'created': created,
	'richStoredId': richStoredId,
	'richData':datax
});
*/

var ct_tl_richId_stored_list={};

var ct_tl_rich_list=[];
var ct_tl_rich_prev_oa_page="";
var ct_tl_rich_prev_obj="";
var ct_tl_rich_id_select_oa_page="";

var ct_tl_acc_all_count=0;
var ct_tl_inactive_friends_count=0;
var ct_tl_active_friends_count=0;
var ct_tl_problem_userId_count=0;
var ct_tl_send_txt_err_count=0;
var ct_tl_prev_friend_loop=-1;
var ct_tl_iTableAllItems=0;
var ct_tl_iMessNoActive=0;
var ct_tl_itemsSendErrorCount=0;
var ct_tl_iProgressAllItemsCount=0;
var ct_tl_iTotalMesageMustSend=0;
var ct_tl_iSendFriendsCount=0;
var ct_tl_iCountAgv=0;
var ct_tl_dtStartTime=new Date();
var ct_tl_lineCSRF="";

var ct_tl_my_broadcastline_idpage_token = "";
var ct_tl_my_broadcastline_label_name = "";
var ct_tl_my_broadcastline_select_index = 0;
var ct_tl_my_broadcastline_label="";
var ct_tl_my_broadcastline_name="";
var ct_tl_my_broadcastline_delay=0;
var ct_tl_cfg_recipients_option_folder="";
var ct_tl_cfg_recipients_option_folder_selectedIndex=0;

var ct_tl_my_prev_broadcastline_idpage_token="";
var ct_tl_cfg_prev_recipients_option_folder="";
var ct_tl_my_prev_broadcastline_select_type="";
var ct_tl_my_prev_cfg_recipients_option_tag="";

var ct_tl_cfg_max_recipients=0;
var ct_tl_cfg_start_seding_no=1;
var ct_tl_status_running=false;

var ct_tl_user_name="";
//var user_valid_date="";
//var user_days_left="";
//var accdate="";
//var acctime="";
var ct_tl_server_date="";
var ct_tl_user_type="";
var ct_tl_demo_ratelimit=0;
var ct_tl_demo_usage_ratelimit=0;
var ct_tl_demo_usage_ratelimit_left=0;
var ct_tl_demo_usage_date="";
//var ddData = [];
var ct_tl_oaAccountActiveImg="";
var ct_tl_oaAccountIdActiveName="";

var ct_tl_execSetTimeout=null;
var ct_tl_maxLimitChar = 2000;
var ct_tl_rateLimitedMaxPerMin = 20;	//25
var ct_tl_txt_error_report=null;
var ct_tl_send_msg_next_time_gettime=0;
var ct_tl_delay_per_msg_ms = 3500;	//Delay each message;
var is_use_avg_time_send = true;
var permission_extract_member = 0;	//from auth;

var ct_tl_option="";

var ct_tl_label_user_all = [];
var ct_tl_label_user_all_copy = [];
var ct_tl_label_user_inactive=[];
var ct_tl_label_user_id_problem=[];
var ct_tl_label_user_all_send_success = [];
var ct_tl_label_user_all_send_failed = [];
//var ct_tl_lable_user_all_send_skip = [];

var ct_tl_status_stop_pause = 0;	//0 = stop,1=start,2=pause, 3=already done
var ct_tl_MsgCircleSend_counter = 1;
var ct_tl_is_finished_get_friends_list = 3;
var ct_tl_continue_get_friends_url = "";

var ct_tl_send_msg_limit_person_before_delay_counter = 0;	//CT_TL_SEND_MSG_LIMIT_PERSON_BEFORE_DELAY in tp_tl_customer_v4.js

var backlog_table = null;
var ct_tl_oHandler = null;

var noSleep = null;

//var oa_card_list_url = 'https://manager.line.biz/api/bots/@142trbgp/cardTypeMessages?sortType=desc';
var oa_card_list_url = 'https://chat.line.biz/api/v1/bots/ct_tl_my_broadcastline_idpage_token/cardTypeMessages?limit=25';
var oa_rich_list_url = 'https://manager.line.biz/api/bots/ct_tl_my_broadcastline_idpage_token/richImage/list?page=1&sortType=desc';
var oa_rich_list_video_url = 'https://manager.line.biz/api/bots/ct_tl_my_broadcastline_idpage_token/richVideo/list?page=1&count=10&title=&sortType=desc';

var timest = null; 
var g_err_msg = "";

//webm: "data:video/webm;base64,GkXfo0AgQoaBAUL3gQFC8oEEQvOBCEKCQAR3ZWJtQoeBAkKFgQIYU4BnQI0VSalmQCgq17FAAw9CQE2AQAZ3aGFtbXlXQUAGd2hhbW15RIlACECPQAAAAAAAFlSua0AxrkAu14EBY8WBAZyBACK1nEADdW5khkAFVl9WUDglhohAA1ZQOIOBAeBABrCBCLqBCB9DtnVAIueBAKNAHIEAAIAwAQCdASoIAAgAAUAmJaQAA3AA/vz0AAA=",
//mp4: "data:video/mp4;base64, "

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

var add_minutes =  function (dt, minutes) {
	return new Date(dt.getTime() + minutes*60000);
};

var add_secs =  function (dt, secs) {
	return new Date(dt.getTime() + secs*1000);
};
var diff_secs =  function (dt,secs){
	return new Date(dt.getTime()-(secs*1000));
};
var 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 pop.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);
    try{
		setStopJob(0,false,0);
	}catch(err){}
	alert('Error: ' + errorMsg + ' Script: ' + url + ' Line: ' + lineNumber + ' Column: ' + column + ' StackTrace: ' +  errorObj);
}
$(window).bind('beforeunload', function(){
	return 'Are you sure you want to leave?';
});

//return a promise that resolves with a File instance
class ct_tl_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 sleep(ms) {
	return new Promise(resolve => setTimeout(resolve, ms));
}

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++;
				}
			}
			
			var my_broadcastline_card=document.getElementById("edit_"+myOLBroadcastTable_check.rows[irow_check].id+"col3");	//card-row1col3
			if (typeof my_broadcastline_card!=='undefined' && my_broadcastline_card!=null && my_broadcastline_card.value != '') {
				my_broadcastline_card = $("#edit_"+myOLBroadcastTable_check.rows[irow_check].id+"col3").val();	//value
				if(typeof my_broadcastline_card!="undefined" && my_broadcastline_card!=null && my_broadcastline_card!=""){
					my_broadcastline_card = my_broadcastline_card.split('|')[0];	//id
				}else{
					my_broadcastline_card="";
				}
			}else{
				my_broadcastline_card="";
			}
			if(typeof my_broadcastline_card=='undefined' || my_broadcastline_card==null){my_broadcastline_card="";}
			my_broadcastline_card=my_broadcastline_card.trim();
			if(my_broadcastline_card!=""){
				iAllItems++;
			}
			
			var my_broadcastline_rich=document.getElementById("edit_"+myOLBroadcastTable_check.rows[irow_check].id+"col4");
			if (typeof my_broadcastline_rich!=='undefined' && my_broadcastline_rich!=null && my_broadcastline_rich.value != '') {
				my_broadcastline_rich = $("#edit_"+myOLBroadcastTable_check.rows[irow_check].id+"col4").val();	//value
				if(typeof my_broadcastline_rich!="undefined" && my_broadcastline_rich!=null && my_broadcastline_rich!=""){
					my_broadcastline_rich = my_broadcastline_rich.split('|')[0];	//id
				}else{
					my_broadcastline_rich="";
				}
			}else{
				my_broadcastline_rich="";
			}
			if(typeof my_broadcastline_rich=='undefined' || my_broadcastline_rich==null){my_broadcastline_rich="";}
			
			my_broadcastline_rich=my_broadcastline_rich.trim();
			if(my_broadcastline_rich!=""){
				iAllItems++;
			}
		}
		resolve(iAllItems);
    });		
}

async function checkTableDataPromise(){
	let myOLBroadcastTable_check = document.querySelector("#myOLBroadcastTable").tBodies[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; 
				}
			}

			
			var my_broadcastline_card=document.getElementById("edit_"+myOLBroadcastTable_check.rows[irow_check].id+"col3");	//card-row1col3
			if (typeof my_broadcastline_card!=='undefined' && my_broadcastline_card!=null && my_broadcastline_card.value != '') {
				my_broadcastline_card = $("#edit_"+myOLBroadcastTable_check.rows[irow_check].id+"col3").val();	//value
				if(typeof my_broadcastline_card!="undefined" && my_broadcastline_card!=null && my_broadcastline_card!=""){
					my_broadcastline_card = my_broadcastline_card.split('|')[0];	//id
				}else{
					my_broadcastline_card="";
				}
			}else{
				my_broadcastline_card="";
			}
			if(typeof my_broadcastline_card=='undefined' || my_broadcastline_card==null){my_broadcastline_card="";}
			my_broadcastline_card=my_broadcastline_card.trim();
			if(my_broadcastline_card!=""){
				iAllItems++;
				break;
			}
			
			var my_broadcastline_rich=document.getElementById("edit_"+myOLBroadcastTable_check.rows[irow_check].id+"col4");
			if (typeof my_broadcastline_rich!=='undefined' && my_broadcastline_rich!=null && my_broadcastline_rich.value != '') {
				my_broadcastline_rich = $("#edit_"+myOLBroadcastTable_check.rows[irow_check].id+"col4").val();	//value
				if(typeof my_broadcastline_rich!="undefined" && my_broadcastline_rich!=null && my_broadcastline_rich!=""){
					my_broadcastline_rich = my_broadcastline_rich.split('|')[0];	//id
				}else{
					my_broadcastline_rich="";
				}
			}else{
				my_broadcastline_rich="";
			}
			if(typeof my_broadcastline_rich=='undefined' || my_broadcastline_rich==null){my_broadcastline_rich="";}
			
			my_broadcastline_rich=my_broadcastline_rich.trim();
			if(my_broadcastline_rich!=""){
				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 ct_tl_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;
	
	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;};

	el.childNodes[index].removeAttribute("disabled");
	el.childNodes[index].removeAttribute("readonly");
	el.childNodes[index].focus();
	
	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').text('count:');
}
function countcharleft(el) {
	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;
		}
		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"){
	  return "";
	}

	var thisid=document.getElementById(id);
	if (typeof thisid.value == 'undefined') {
	  return "";
	}
	var lengthCount = thisid.value.length; 
	
	if (lengthCount > ct_tl_maxLimitChar) {
		thisid.value = thisid.value.substring(0, ct_tl_maxLimitChar);
		var charactersLeft = ct_tl_maxLimitChar - lengthCount + 1;                   
	}
	else {                   
		var charactersLeft = ct_tl_maxLimitChar - lengthCount;                   
	}
	$('#spnCharLeft').css('display', 'block');
	$('#spnCharLeft').text('count: '+charactersLeft + ' Characters left');
	return charactersLeft;
}
function img_pathUrl(input,id,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;
	}
	reader.readAsDataURL(input.files[0]);
	
	var img=(window.URL ? window.URL : webkitURL).createObjectURL(input.files[0]);

	document.getElementById('href_'+parrentid).setAttribute('href',img);
	
}
function setEmptyFileValue(oi){
	if(!oi){
		return;
	}
	let parentId = oi.parentNode;
	if(typeof parentId=="undefined"){
		return;
	}
	let 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=window.lang.translate("F8");
	document.getElementById("file_file_add_container").title=window.lang.translate("F8");
	document.getElementById("text_add").title=window.lang.translate("F7");

	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=window.lang.translate("F7");
	}else{
		element.title=element.value;
	}
	element.innerHTML=element.value;
}
function highlight(tableid,thisTrTableRow) {
	return;	//disable highlight

	var tableRowIndex=thisTrTableRow.rowIndex;

	if( (tableRowIndex+1) > $('#'+tableid+' tbody tr').length )
		tableRowIndex = 0;

	if($('#'+tableid+' tbody tr:eq('+tableRowIndex+')').length > 0)
	{
		$('#'+tableid+' tbody tr').removeClass('highlight');
		var element = document.getElementById(thisTrTableRow.id);
		element.classList.add("highlight");
	}else{
		
	}
}
function addNewRow(isAdditem){
	var table=document.getElementById("myOLBroadcastTable");
	if(table==null){return;}
	if(table.rows.length>10){ 
		alert(window.lang.translate('Enter a maximum of 10 rows only'));
		return;
	}
	AddTableRow(undefined,isAdditem);
}
function AddTableRow(o,isAdditem){
	var mainBody = document.querySelector("#myOLBroadcastTable").tBodies[0];

	var num_rows = mainBody.rows.length;
	if (num_rows > 10) return;
	
	if(typeof isAdditem!=="undefined" && isAdditem!=null && isAdditem){
		var message=document.getElementById("text_add");
		if(num_rows>0){
			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' && file!=null){
				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' && txt!=null)
					{
						if(txt.value==""){
							txt.value=message.value;
							txt.title=message.value;
							txt.innerHTML=message.value;
							
							document.getElementById("start_broadcast").style.display = "inline-block";
							//document.getElementById("start_broadcast").disabled = false;
							
							var filz=document.getElementById("file-file_add_container");	//file_file_add_container
							if(typeof filz !=="undefined" && filz!=null){
								if (filz.files.length>0){
									const dt = new ct_tl_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");
										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('');
									$("#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="";
								}
							}
							message.value="";
							return;
						}
					}
				}
			}
		}
	} else if(isAdditem==false){
		//Add empty value
	}
	
	
	var rowDeleting="";
	var rowid="";
	var numberrow="";
	
	if(o!==undefined && o!=null){
		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+'">\n';
		htmlrow+='<td id="'+rowid+'col0" style="width:2%;">'+numberrow+'</td>\n';
		htmlrow+='<td id="'+rowid+'col1" style="width:25%;"><textarea lang="en" class="counterchar editable emojionearea" name="text_'+rowid+'col1" id="text_'+rowid+'col1" rows="3" placeholder="Click to edit content"></textarea><i><i lang="en" id="edit_'+rowid+'col1" class="fa fa-pencil" aria-hidden="true" title="Click to edit content"></i></i></td>\n';
		
		var tmp='<td id="'+rowid+'col2" style="width:20%;" contenteditable=\'false\'><label for="file_'+rowid+'col2" class="active"></label><textarea lang="en" id="file_'+rowid+'col2" name="file_'+rowid+'col2" placeholder="Click to choose files" readonly></textarea><i><i lang="en" id="edit_'+rowid+'col2" class="fa fa-pencil" aria-hidden="true" title="Click to choose files"></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="row'+rowid+'col3" style="width:30%;">';
			tmp+='<em id="'+rowid+'col3">';
			tmp+='<select id="edit_'+rowid+'col3" class="custom-select" title="Click to edit card." style="background-color:#f7f7f7;" >';
			tmp+='<option lang="en" value="" selected="selected">0-None</option>';
			tmp+='</select>';
			tmp+='</em>';
			tmp+='</td>\n';
		htmlrow+=tmp;	//col index 3

			tmp='<td id="row'+rowid+'col4" style="width:30%;">';
			tmp+='<em id="'+rowid+'col4">';
			tmp+='<select id="edit_'+rowid+'col4" class="custom-select" title="Click to select rich." style="background-color:#f7f7f7;" >';
			tmp+='<option lang="en" value="" selected="selected">0-None</option>';
			tmp+='</select>';
			tmp+='</em>';
			tmp+='</td>\n';
		htmlrow+=tmp;	//col index 4
		
			tmp='<td id="'+rowid+'col5" style="width:5%;">\n';
			tmp+='<button lang="en" type="button" class="btn btn-info move-row-up" id="moveup_'+rowid+'col5" 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 lang="en" type="button" class="btn btn-primary move-row-down" id="movedown_'+rowid+'col5" 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 5
		
			tmp='<td id="'+rowid+'col6" style="width:5%;">\n';
			tmp+='<button type="button" class="btn btn-danger del-row" id="del_'+rowid+'col6" name="del_'+rowid+'col6" 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 6
			
			tmp='<td id="'+rowid+'col7" style="display:none;"></td>\n';
		htmlrow+=tmp;	//col index 7

		htmlrow+='</tr>';
	$('#tablebody').append(htmlrow);
	
	var text_col1 = document.getElementById("text_"+rowid+"col1");
	if(typeof text_col1!="undefined" && text_col1!=null){
		document.getElementById("text_"+rowid+"col1").style.backgroundColor = "#f7f7f7";
	}
	var file_col2 = document.getElementById("file_"+rowid+"col2");
	if(typeof file_col2!="undefined" && file_col2!=null){
		document.getElementById("file_"+rowid+"col2").style.backgroundColor = "#f7f7f7";
		var row_col2 = document.getElementById(rowid+"col2");
		if(typeof row_col2!="undefined" && row_col2!=null){
			document.getElementById(rowid+"col2").addEventListener("click", handler_add_files_event=function(event) {
				document.getElementById("file-"+rowid+"col2").click();
			});
			document.getElementById("file-"+rowid+"col2").addEventListener("change", handler_files_change_event=function(event) {
				let target = event.target || event.srcElement;
				if (target.value.length == 0) {
					$("#file-"+rowid+"col2").val('');
					$("#file-"+rowid+"col2").val(null);
					var x=document.getElementById("rmx"+rowid+"col2");
					if(typeof x!=="undefined"){
						setEmptyFileValue(x);
					}
					document.getElementById("file_"+rowid+"col2").value="";
					document.getElementById("file_"+rowid+"col2").title="";
					document.getElementById("file_"+rowid+"col2").innerHTML="";
				}
			});
		}
	}
	document.getElementById("edit_"+rowid+"col3").addEventListener("change", function(e){
		e.preventDefault();
		this.title=this.options[this.selectedIndex].text;
	});			
	document.getElementById("edit_"+rowid+"col3").addEventListener("click", function(e){
		e.preventDefault();
		if(ct_tl_line_alls.length>0){
			if (ct_tl_my_broadcastline_idpage_token!=""){
				if (ct_tl_card_prev_oa_page==ct_tl_my_broadcastline_idpage_token){
					if(ct_tl_card_list.length>0){
						if(this.options.length>1){
							return;
						}else{
							populate_card_list(this,ct_tl_my_broadcastline_idpage_token);
							return;
						}
					}
				}
			}
			console.log("Get card list");
			getMsgCardList(oa_card_list_url,1,this);
		}
	});
	
	var col_col4 = document.getElementById("row"+rowid+"col4");
	if(typeof col_col4!="undefined" && col_col4!=null){
		//document.getElementById(rowid+"col4").style.backgroundColor = "#f7f7f7";
		col_col4.style.display = "None";
	}
	
	document.getElementById("edit_"+rowid+"col4").addEventListener("change", function(e){
		e.preventDefault();
		if(is_allowed_rich_msg==0){
			Swal.fire({
				type: 'info',
				html: 'user: <b>'+$('#user_name').text()+'</b> <br /><b style="color:red;">Function not allowed ยังไม่ได้รับอนุญาติให้ใช้งานฟังก์ชั่น Rich message นี้ ติดต่อ @Linebroadcast หมดอายุใช้งานฟรี ตั้งแต่วันที่ 2023-03-01 ถึง 2023-05-31</b><br />',
				showCloseButton: true,
				showCancelButton: false,
				confirmButtonColor: '#3085d6',
				confirmButtonText: window.lang.translate('Ok'),
			}).then((result) => {
				
			});
			this.value=this.options[0].value;
			this.title=this.options[0].text;
			return;
		}
		this.title=this.options[this.selectedIndex].text;
	});			
	document.getElementById("edit_"+rowid+"col4").addEventListener("click", function(e){
		e.preventDefault();
		if(ct_tl_line_alls.length>0){
			if (ct_tl_my_broadcastline_idpage_token!=""){
				if (ct_tl_rich_prev_oa_page==ct_tl_my_broadcastline_idpage_token){
					if(ct_tl_rich_list.length>0){
						if(is_allowed_rich_msg==0){
							Swal.fire({
								//title: '<strong>INFO</strong>',
								type: 'info',
								html: 'user: <b>'+$('#user_name').text()+'</b> <br /><b style="color:red;">Function not allowed ยังไม่ได้รับอนุญาติให้ใช้งานฟังก์ชั่น Rich message นี้ ติดต่อ @Linebroadcast หมดอายุใช้งานฟรี ตั้งแต่วันที่ 2023-03-01 ถึง 2023-05-31</b><br />',
								showCloseButton: true,
								showCancelButton: false,
								confirmButtonColor: '#3085d6',
								confirmButtonText: window.lang.translate('Ok'),
							}).then((result) => {
								
							});
							this.value=this.options[0].value;
							this.title=this.options[0].text;
							return;
						}else{
							if(this.options.length>1){
								return;
							}else{
								populate_rich_list(this,ct_tl_my_broadcastline_idpage_token);
								return;
							}
						}
					}
				}
			}
			console.log("Get rich list");
			getMsgRichList(oa_rich_list_url,1,this);
		}
	});
	document.getElementById("moveup_"+rowid+"col5").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+"col5").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+"col6").addEventListener("click", handler_del_row_event=function(event) {
		event.preventDefault();
		var td = event.target;
		funDel(td);
		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").style.display = "inline-block";
			//document.getElementById("start_broadcast").disabled = false;
		}
		var filz=document.getElementById("file-file_add_container");
		if(typeof filz !=="undefined" && filz!=null){
			if (filz.files.length>0){
				document.getElementById("start_broadcast").style.display = "inline-block";
				//document.getElementById("start_broadcast").disabled = false;
				var file=document.getElementById("file-"+rowid+"col2");	//file id file-row1col2
				const dt = new ct_tl_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 lang="en" id="rmx'+rowid+"col2"+'" class="fa fa-times" aria-hidden="true" title="Delete 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="";
			}
		}
		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');

	modal.setAttribute('data-mark-delete-row-id',o.id);
	
	document.getElementById('del_row').innerHTML="&nbsp;"+o.parentNode.parentNode.cells[0].innerHTML;

}
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);
		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").style.display = "inline-block";
	//document.getElementById("start_broadcast").disabled = false;
}
function funRowIdex(tr) {	//button
	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){
	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]);
				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]);
				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"
	})
	.append("<div class='resizer'></div>")
	.resizable({
		resizeHeight: false,
		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'){
			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')
		{
			if(my_broadcastline_text_check.value!=""){
				bpass=true;
				break;
			}
		}
		irow_check++;
	}
	return !bpass;
}
function saveTable(){
	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: window.lang.translate('Warning'),
				position: 'topLeft',
				timeout: 3000,
				message: window.lang.translate('You have not entered a message or choosed the file you want to send'),
			});
		}
		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;
	ct_tl_cfg_start_seding_no=document.getElementById('cfg_start_seding_no').value;
	ct_tl_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;
	ct_tl_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":'+ct_tl_cfg_start_seding_no;
		myFormData+=',"cfg_max_recipients":'+ct_tl_cfg_max_recipients;
		myFormData+=',"cfg_delay":'+cfg_delay;
		myFormData+=',"my_broadcastline_select_type":'+my_broadcastline_select_type;
		myFormData+=',"cfg_recipients_option_folder":'+ct_tl_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+='}]';
	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");
	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;
	}
	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");
		var c = document.getElementById("lbl_schedule_later");
			c.className += " active";
	}else{
		document.getElementById("lbl_schedule_later").classList.remove("active");
		document.getElementById("lbl_schedule_now").classList.remove("active");
		var c = document.getElementById("lbl_schedule_now");
			c.className += " active";
	}
	
	addBase64toFileList();

}
function getFiles(files) {
	return Promise.all([...files].map(file => getFile(file)));
}
function getFile(file) {
	var reader = new FileReader();
	return new Promise((resolve, reject) => {
		reader.onerror = () => { reader.abort(); reject(new Error("Error parsing 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){
			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+"}";
								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+"}";
							sessionStorage.setItem("#myOLBroadcastTableFiles", json_all);
						}
					}
				}
			}
			
		}
		
	}
		
}

function showStartButton(){
	$('#start_broadcast').show();
	$('#pause_broadcast').hide();
	$('#stop_broadcast').hide();
	$('#continue_broadcast').hide();
}

function runningProgress(loop) {
	if(!$("#footer-summary-container").is(':visible')){return;}
	var elem = document.getElementById("myBar");
	if(typeof elem!=="undefined"){
		if(ct_tl_active_friends_count>0){
			$('#footer-summary-container').show();
			$('#close-x').show();
			$('#open-o').hide();
			
			loop = ct_tl_iSendFriendsCount;

			if(ct_tl_cfg_max_recipients<1){ct_tl_cfg_max_recipients=ct_tl_active_friends_count;}
			if(ct_tl_cfg_max_recipients>ct_tl_active_friends_count){ct_tl_cfg_max_recipients=ct_tl_active_friends_count;}
			let actual_friends_must_send = (Number(ct_tl_cfg_max_recipients)-Number(ct_tl_cfg_start_seding_no))+1;
			
			let width=Math.round((loop/actual_friends_must_send)*100);
			let start_to = "Start "+ ct_tl_cfg_start_seding_no +" to "+ ct_tl_cfg_max_recipients;
			console.log("ct_tl_send_txt_err_count:"+ct_tl_send_txt_err_count);
			console.log("loop:"+loop);
			
			//$('#modalGrAlert_OA_Status').text('กำลังส่งข้อมูล กรุณารอสักครู่ ...');
			//$('#modalGrAlert_OA_Status').css('color','blue');
			if(loop%25==0){
				if(timest != null){
					var ctime_milli = new Date()- timest;
					var ctime_sec = Math.floor(ctime_milli / 1000);
					var remain_person = actual_friends_must_send - loop;
					var est_time_sec = Math.floor((remain_person/25)*ctime_sec);
					var dnow = new Date();
					var estdate = new Date(dnow.getTime() + (est_time_sec*1000)+65*1000);
					$('#modalGrAlert_OA_Status').text('กำลังส่งข้อมูล กรุณารอสักครู่ ...ประมาณการ ' + getDateTime(estdate));
				}
				timest = new Date();
				
			}
			
			document.getElementById("xyz").innerHTML = window.lang.translate("Completed")+" "+((loop) - ct_tl_send_txt_err_count)+" /"+window.lang.translate("Unsuccessful")+ " "+ct_tl_send_txt_err_count+ " /"+window.lang.translate("All")+ " "+ actual_friends_must_send+ " "+window.lang.translate("Person");
			document.getElementById("rzf").innerHTML = window.lang.translate("Person number")+" "+(loop)+" /"+ window.lang.translate("From")+ " " +actual_friends_must_send+ " /failed "+ ct_tl_send_txt_err_count +" "+window.lang.translate("Person");
			//document.getElementById("xyz").innerHTML = "สำเร็จ "+(loop - ct_tl_send_txt_err_count)+" /ไม่สำเร็จ "+ct_tl_send_txt_err_count+ " /จากทั้งหมด "+ ct_tl_active_friends_count+ " "+window.lang.translate("Person");
			//document.getElementById("rzf").innerHTML = "คนที่ "+loop+" /จาก "+ct_tl_active_friends_count+ " /failed "+ ct_tl_send_txt_err_count +" คน";
			document.getElementById("send_next_gr_alert").innerHTML=window.lang.translate("Sending")+ " " + document.getElementById("xyz").innerHTML;
			
			if (width <= 100) {
				elem.style.width = width + "%";
				elem.innerHTML = width + "%";
			}
		}
	}
}

function runningAllitemsProgress() {
	if(!$("#footer-summary-container").is(':visible')){return;}
	//console.log("visibled");
	var elem = document.getElementById("myBar");
	if(typeof elem!=="undefined"){
		if(ct_tl_active_friends_count>0){ 
			if (ct_tl_iTableAllItems>0){

				if(ct_tl_iTotalMesageMustSend<1){ct_tl_iTotalMesageMustSend=((ct_tl_cfg_max_recipients-ct_tl_cfg_start_seding_no+1) * ct_tl_iTableAllItems);}
				ct_tl_iProgressAllItemsCount++;
				if (ct_tl_iProgressAllItemsCount>0){
					let width=Math.round((ct_tl_iProgressAllItemsCount/(ct_tl_iTotalMesageMustSend))*100);	//ct_tl_iTotalMesageMustSend	//
					//document.getElementById("rzf").innerHTML = window.lang.translate("Person number")+ " "+ct_tl_iSendFriendsCount+" /"+ window.lang.translate("From")+" "+ct_tl_active_friends_count+ " /failed "+ ct_tl_send_txt_err_count +" "+window.lang.translate("Person");
					document.getElementById("mn").innerHTML = window.lang.translate("Message no.")+" "+ct_tl_iMessNoActive+" /"+window.lang.translate("From")+" " +ct_tl_iTableAllItems + +" "+ window.lang.translate("Message");
					document.getElementById("rsfa").innerHTML = window.lang.translate("Message sent successfully")+" "+(ct_tl_iProgressAllItemsCount-ct_tl_itemsSendErrorCount)+" /"+ window.lang.translate("Unsuccessful")+" " +ct_tl_itemsSendErrorCount + " /"+window.lang.translate("From")+" "+ (ct_tl_iTotalMesageMustSend) +" "+ window.lang.translate("Message");	
					
					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 = window.lang.translate("Send counter");	//"สำเร็จ " + "x" +" /ไม่สำเร็จ " + "y" + " /จากทั้งหมด " + "z" + " คน";
	document.getElementById("rzf").innerHTML = window.lang.translate("The person that")	;//"คนที่ " + "r" + " /จาก " + "z" + " /failed " + "f" + " คน";
			
	document.getElementById("mn").innerHTML = window.lang.translate("Messages of");	//"ข้อความที่ " + "m" + " /จาก " + "n" + " ข้อความ";
	document.getElementById("rsfa").innerHTML = window.lang.translate("Message sent summary");	//"ข้อความส่ง สำเร็จ "+ "s" +" /ไม่สำเร็จ " + "f" + " /จาก " + "a" + " ข้อความ";	
					
	var elem = document.getElementById("myBar");
	if(typeof elem!=="undefined"){
		elem.style.width = 0+"%";
		elem.innerHTML = 0 + "%";
	}
	
	document.getElementById("MsgCircleSend").innerHTML="";
	document.getElementById("MsgCircleSend").backgroundColor="#859e1f";
	document.getElementById("MsgCircleSend").color="#fff";
	ct_tl_MsgCircleSend_counter = 1;
}

if (window.location.href.split('settings/general/#openbroadcast?userinfo').length>0) {
	var token_line=localStorage.getItem('token_line');
	if(token_line==null){
		var x=window.location.href.split('https://chat.line.biz/');
		if(x.length>1){
			token_line=x[1].split('/settings/general/#openbroadcast?userinfo')[0];
			localStorage.setItem('token_line',token_line);
		}
	}
	
}else{
	//console.log('window.location:'+window.location.href);
}

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 getlineaccall(){
	//console.log('getlineaccall()');
	//console.log(localStorage.getItem('_trmccid'));
	var myoaacc = GetQueryStringParams('myoaaccall');
	return myoaacc;
}
function getuserinfo(){
	var userinfo = GetQueryStringParams('userinfo');
	return userinfo;
}
function getlineselectindex(){
	return GetQueryStringParams('myaccindex');
}
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));
}

function populate_line_accs() {
	ct_tl_option = '';
	
	ct_tl_lineCSRF="";
	
	$(".get_line").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);
	}

	let line_all_length = ct_tl_line_alls.length;

	var options = [];
	var dataAcc="";
	
	$.each(ct_tl_line_alls, function (index, data) {
		var name = "";
		if(data.targetedReaches==undefined){
			//name = (index + 1) + '.' + data.name;
			name = (line_all_length-index) + '.' + data.name;
		}else{
			//name = (index + 1) + '.' + data.name + '(' + data.targetedReaches + ')';
			if (data.targetedReaches.trim()!=""){
				name = (line_all_length-index) + '.' + data.name + '(' + data.targetedReaches + ')';
			}else{
				name = (line_all_length-index) + '.' + data.name;
			}
		}
		var id = data.basicSearchId;
		var botId=data.botId;
		//var page_access_token = data.basicSearchId;
		ct_tl_option = '<option value="' + id + '|' + name + '|' + index + '" data-botId="' + botId + '" data-icon="' + data.profileImageUrl + '" title="'+data.profileImageUrl+ '" >' + name + '</option>' + ct_tl_option;

		dataAcc = '<option value="' + id + '|' + name + '|' + index + '" data-botId="' + botId + '" data-icon="' + data.profileImageUrl + '" title="'+data.profileImageUrl+ '" >' + name + '</option>';         
		options.push(dataAcc);
		
	});

	var idaccs=document.getElementById("my_broadcastline_idpage");//.selectedIndex = "2";

	if(options.length>0){
		options.reverse();
	}
	idaccs.innerHTML = options.join('\n'); 

	var idx = null;
	if(typeof idaccs!=="undefined" && idaccs!=null){
		if(idaccs.length>0){
			idaccs.selectedIndex=0;
			let step_acc1 = window.location.href.split('.biz/');
			
			if(step_acc1.length>1){
				let my_broadcastline_accs = window.location.href.split('.biz/')[1].split('/')[0];
				if(my_broadcastline_accs!==null){
					let txt = "";
					let i=0;
					for (i = 0; i < idaccs.length; i++) {	//id = sync_botId
						if(idaccs.options[i].getAttribute('data-botId')!=null){
							if(idaccs.options[i].getAttribute('data-botId').trim() == my_broadcastline_accs){
								idaccs.selectedIndex=i;
							}
						}
					}
				}
				
				if (typeof idaccs!=='undefined' && idaccs!=null){
					if(idaccs.selectedIndex<1){
						if(idaccs.length>1){
							idaccs.selectedIndex=0;
						}
					}
				}
				idx=idaccs.selectedIndex;
			}
		}
	}

	if(idx!=null){
		document.getElementById("my_broadcastline_idpage").selectedIndex = idx;
		var sel=document.getElementById("my_broadcastline_idpage");
		let oaAccountName_img=document.getElementById('oaAccountName_img');
		if(typeof oaAccountName_img !=="undefined" && oaAccountName_img!=null){
			document.getElementById('oaAccountName_img').src=sel.options[sel.selectedIndex].getAttribute('data-icon');
		}
		var opt = sel.options[sel.selectedIndex];
		if(typeof opt!=="undefined" && opt!=null ){
			let oaAccountNameActiveLabel=document.getElementById("oaAccountNameActiveLabel");
			if(typeof oaAccountNameActiveLabel!=="undefined" && oaAccountNameActiveLabel!=null){
				document.getElementById("oaAccountNameActiveLabel").innerHTML=opt.text;
			}
			let oaAccountIdActive=document.getElementById("oaAccountIdActive");
			if(typeof oaAccountIdActive!=="undefined" && oaAccountIdActive!=null){
				document.getElementById("oaAccountIdActive").innerHTML=opt.getAttribute('data-botId');
			}
			let oaAccountNameActive_img=document.getElementById("oaAccountNameActive_img");
			if(typeof oaAccountNameActive_img!=="undefined" && oaAccountNameActive_img!=null){
				document.getElementById("oaAccountNameActive_img").src=sel.options[sel.selectedIndex].getAttribute('data-icon');
			}
			let sync_botId=document.getElementById('sync_botId');
			if(typeof sync_botId!=="undefined" && sync_botId!=null){
				document.getElementById('sync_botId').innerHTML='&nbsp;&nbsp;'+opt.getAttribute('data-botId');
			}
		}
	}

	ct_tl_oHandler = $("#my_broadcastline_idpage").msDropDown().data("dd");
	
	try {
		if(ct_tl_oHandler){
			var botsel = GetQueryStringParams('botid');
			if(typeof botsel!=="undefined" && botsel!=null){
				idaccs.selectedIndex=botsel;
				ct_tl_oHandler.set("selectedIndex", botsel);
			}else{
				idaccs.selectedIndex=0;
				ct_tl_oHandler.set("selectedIndex", 0);
			}
			
		}
	} catch(e) {
		console.log("Error: "+e.message);
	}
	
	try{
		if(localStorage){
			let back_log=localStorage.getItem('back_log');
			//console.log(back_log);
			
			if(typeof back_log!=="undefined" && back_log!=null){
				let json_backlog=JSON.parse(back_log);
				let page_id = json_backlog.page_id;
				
				let sel=document.getElementById("my_broadcastline_idpage");

				for(let sel_len=0;sel_len<sel.length;sel_len++){
					let opt = sel.options[sel_len];
					if(typeof opt!=="undefined" && opt!=null ){
						if(opt.getAttribute('data-botId')==page_id){
							sel.selectedIndex = sel_len;
							idaccs.selectedIndex = sel_len;
							if(ct_tl_oHandler){
								ct_tl_oHandler.set("selectedIndex", sel_len);
							}
							
							ct_tl_my_broadcastline_select_index = sel.selectedIndex;
							ct_tl_my_broadcastline_idpage_token=opt.getAttribute('data-botId');
							
							document.getElementById("cfg_start_seding_no").value = Number(json_backlog.number_send)+1;
								
							break;
						}
					}
				}
				
			}
		}
	}catch(ee){
		console.log(ee)
	}
	
	try{
		let data_page_icon = "";
		try{data_page_icon = $("#my_broadcastline_idpage option:selected").attr("data-icon");}catch(ee){}
		$('#page_image').prop("src", data_page_icon);
		$('#my_header').text(CT_TL_APP_VERSION + ' ระบบกำลังทำงานอยู่');
		try{ct_tl_my_broadcastline_label_name = $("#my_broadcastline_idpage option:selected").text();}catch(ee){}
		document.getElementById("modalGrAlert_OA_Account_name").innerHTML = "&nbsp;&nbsp;"+ct_tl_my_broadcastline_label_name;
	}catch(e){}
	//history.pushState(null, null, "/");
	
}

function populate_card_list(obj,oa_page) {
	console.log(obj);
	let objId=obj.id;
	let options = [];
	let dataCard="";
	
	if (oa_page!="" && ct_tl_card_prev_obj!=""){
		if (ct_tl_card_prev_oa_page==oa_page && ct_tl_card_prev_obj==objId){
			if(ct_tl_card_list.length>0 && obj.options.length>0){
				return;
			}
		}
	}
	//ct_tl_card_list.push({
	//	'cardId': cardId,
	//	'cardTitle': cardTitle,
	//	'cardType': cardType
	//});
	$("#"+objId).empty();
	options.push('<option value="">0-None</option>');
	$.each(ct_tl_card_list, function (index, data) {
		let cardId = data.cardId;
		let cardTitle=data.cardTitle;
		let cardType = data.cardType;
		let cardUpdated=data.cardUpdated;
		let content = (index+1)+'-'+ cardTitle + ' ('+cardUpdated+')';

		dataCard = '<option value="' + cardId + '|' + cardTitle + '|' + cardType + '" title="'+ content +'">' + content + '</option>';
		options.push(dataCard);
		
	});
	let idCard=document.getElementById(objId);//.selectedIndex = "2";
	idCard.innerHTML = options.join('\n'); 
	
	ct_tl_card_prev_oa_page = oa_page;
	ct_tl_card_prev_obj = objId;
	
	/*
	$(".get_line").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);
	}

	let line_all_length = ct_tl_line_alls.length;

	var options = [];
	var dataAcc="";
	
	$.each(ct_tl_line_alls, function (index, data) {
		if(data.targetedReaches==undefined){
			//name = (index + 1) + '.' + data.name;
			name = (line_all_length-index) + '.' + data.name;
		}else{
			//name = (index + 1) + '.' + data.name + '(' + data.targetedReaches + ')';
			if (data.targetedReaches.trim()!=""){
				name = (line_all_length-index) + '.' + data.name + '(' + data.targetedReaches + ')';
			}else{
				name = (line_all_length-index) + '.' + data.name;
			}
		}
		id = data.basicSearchId;
		botId=data.botId;
		page_access_token = data.basicSearchId;
		ct_tl_option = '<option value="' + id + '|' + name + '" data-botId="' + botId + '" data-icon="' + data.profileImageUrl + '" title="'+data.profileImageUrl+ '" >' + name + '</option>' + ct_tl_option;

		dataAcc = '<option value="' + id + '|' + name + '" data-botId="' + botId + '" data-icon="' + data.profileImageUrl + '" title="'+data.profileImageUrl+ '" >' + name + '</option>';         
		options.push(dataAcc);
		
	});

	var idaccs=document.getElementById("my_broadcastline_idpage");//.selectedIndex = "2";

	if(options.length>0){
		options.reverse();
	}
	idaccs.innerHTML = options.join('\n'); 
	*/
	
}
function populate_rich_list(obj,oa_page) {
	console.log(obj);
	let objId=obj.id;
	let options = [];
	let dataRich="";
	if (oa_page!="" && ct_tl_rich_prev_obj!=""){
		if (ct_tl_rich_prev_oa_page==oa_page && ct_tl_rich_prev_obj==objId){
			if(ct_tl_rich_list.length>0 && obj.options.length>0){
				return;
			}
		}
	}

	$("#"+objId).empty();
	options.push('<option value="">0-None</option>');
	$.each(ct_tl_rich_list, function (index, data) {
		let richId = data.richId;
		let richTitle=data.richTitle.replace('"',"");
		richTitle = richTitle.replace("'","");
		let richType = data.richType;
		let created = data.created;
		//let richData = data.richData;
		let content = (index+1)+'-'+ richTitle + ' ('+created+')';
		//dataRich = '<option value="' + richId + '|' + richTitle + '|' + richType+ '|' + index + '" title="'+ content + '">' +content+ '</option>';
		dataRich = '<option value="' + richId + '|' + richTitle + '|' + richType+ '|' + index + '" title="'+ content + '"' + '" index="'+ index + '">' +content+ '</option>';
		//dataRich = '<option value="' + richId + '|' + richTitle + '|' + richType+ '|' + index + '" title="'+ content + '" data="'+ richData +'">' +content+ '</option>';
		options.push(dataRich);
		
	});
	let idRich=document.getElementById(objId);
	idRich.innerHTML = options.join('\n'); 
	
	ct_tl_rich_prev_oa_page = oa_page;
	ct_tl_rich_prev_obj = objId;
	
}

function getLineMeCookie(){
	lineMeCookie={};
    let domain = "line.biz";
	return new Promise(async resolve =>{
		try{
            chrome.cookies.getAll({domain:"line.biz"}, function (cookies) {
                var a = [];
                    console.log("@getCookies. Cookies found " +  cookies.length);
                    cookies.forEach(function(cookie) {
                        console.log("[COOKIE] => " + JSON.stringify(cookie));
                        a.push({
                            name: cookie.name,
                            value: cookie.value,
                            domain: cookie.domain,
                            secure: cookie.secure,
                            path: cookie.path
                        });
                        if(cookie.domain=="chat."+domain && cookie.name=="XSRF-TOKEN"){
                            lineMeCookie.xsrf=cookie.value;
                        }else if(cookie.domain=="."+domain && cookie.name=="ses"){
                            lineMeCookie.ses=cookie.value;
                        }
                    });
					//console.log(lineMeCookie);
                    //console.log(a);
                    resolve(a);
                }
            );
            
            /*
			const all_cookies = await chrome.cookies.getAll({domain:"line.biz"});
			console.log(all_cookies);
			if (all_cookies.length === 0) {
				return "No Line OA's token found.";
			}else{
				let cookie = "";
				var count = all_cookies.length;
				cookie = "{\n";
				for (var i = 0; i < count; i++) {
					if(all_cookies[i].domain=="chat."+domain && all_cookies[i].name=="XSRF-TOKEN"){
						//cookie+=all_cookies[i].name+"="+all_cookies[i].value+";";
						cookie+='"id":"' + all_cookies[i].value+'",\n';
						lineMeCookie.xsrf=all_cookies[i].value;
					}else if(all_cookies[i].domain=="."+domain && all_cookies[i].name=="ses"){
						//cookie+=all_cookies[i].name+"="+all_cookies[i].value+";";
						cookie+='"token":"' + all_cookies[i].value+'",\n';
						lineMeCookie.ses=all_cookies[i].value;
					}
					//console.log(all_cookies[i]);
				}
				cookie += "}\n";
				cookie = cookie.replace(",\n}","\n}");
				//return cookie;
				resolve(cookie);
			}
            */
		} catch (error) {
			resolve(`Unexpected error: ${error.message}`);
			//return `Unexpected error: ${error.message}`;
		}
	});
}

const line_me_admin = "https://chat.line.biz/api/v1/me";
function get_line_me_admin() {
	//{"bizId":"2fb51000-65ea-11eb-abe7-6acde","language":"th","name":"xxx xxx","linePictureUri":"https://profile.line-scdn.net/AkNCPHxBPRblNohCAzFtPxZiTGVuOF0kGSc7NRh1CSx5OF0jTnQ7ax4sXi5","localStorageEncryptionKey":"qmjQloCnp3NT86F-hFzAXG9O1"}

	return new Promise(resolve =>{
		lineMeAdmin = null;
		$("#lineMeAdmin").html('');
		$.getJSON(line_me_admin, function (data) {
			
			if(typeof data !=='undefined'){
				lineMeAdmin = data;
				$("#lineMeAdmin").html('<img src="'+data.linePictureUri+'" alt="me-logo" id="lineMeLogo" style="width: 40px; height: 40px;border-radius:20px;">&nbsp;'+data.name);
			}
			resolve(true);
		})
		.fail(function (e) {
			console.log(e);
			Swal.fire({
				title: window.lang.translate('Line OA not logged in yet'),
				text: window.lang.translate("You have to log in Line OA first"),
				type: 'warning',
				confirmButtonColor: '#3085d6',
				cancelButtonColor: '#d33',
				confirmButtonText: window.lang.translate('OK'),
				cancelButtonText: window.lang.translate('Cancel')
			}).then((result) => {
				if (result.value) {
					window.open('https://account.line.biz/login?redirectUri=https%3A%2F%2Fmanager.line.biz%2F', '_blank');
				}
			})
			resolve(false);
		});
	});
}

const contact_account_url = 'https://chat.line.biz/api/v1/bots';
function get_line_all_accs(url = contact_account_url, num_page = 1) {
	return new Promise(resolve =>{
		if (num_page == 1) {
			ct_tl_line_alls = [];
		}
		
		
		title = window.lang.translate('Retrieve account in LINE OA');
		$.getJSON(url, function (results) {
		//fetch(url).then(function(results) {
			var data = results.list;
			
			var basicSearchId='';
			var profileImageUrl='';
			var name='';
			var brandType='';
			var targetedReaches='';
			var userPermissionType='';
			var planName='';
			var hasNotification='';
			var notificationCount='';
			
			var unreadCount='';
			var region='';
			var botId='';
			var iconHash='';
			var responseMode='';
			
			//console.log(results);
			let next_url = null;
			if(results.next){
				if(typeof results.next!="undefined" && results.next!=null && results.next!=""){
					next_url= contact_account_url + "?next="+ results.next;
				}
			}else if(results.paging){
				if(typeof results.paging!="undefined" && results.paging!=null && results.paging!=""){
					next_url= contact_account_url + "?next="+ results.paging;
				}
			}
			for(let md = 0;md<data.length;md++){
					let datax = data[md];
				//}
				// var paging = results.paging;
				//$.each(data, function (i, datax) {
					basicSearchId='';
					profileImageUrl='';
					name='';
					brandType='';
					targetedReaches='';
					userPermissionType='';
					planName='';
					hasNotification='';
					notificationCount='';
					
					unreadCount='';
					region='';
					botId='';
					iconHash='';
					responseMode='';
					
					if(typeof datax.basicSearchId!=='undefined'){basicSearchId=datax.basicSearchId;}
					if(typeof datax.profileImageUrl!=='undefined'){profileImageUrl=datax.profileImageUrl;}
					if(typeof datax.name!=='undefined'){name=datax.name;}
					if(typeof datax.brandType!=='undefined'){brandType=datax.brandType;}
					if(typeof datax.targetedReaches!=='undefined'){targetedReaches=datax.targetedReaches;}
					if(typeof datax.userPermissionType!=='undefined'){userPermissionType=datax.userPermissionType;}
					if(typeof datax.planName!=='undefined'){planName=datax.planName;}
					if(typeof datax.hasNotification!=='undefined'){hasNotification=datax.hasNotification;}
					if(typeof datax.notificationCount!=='undefined'){notificationCount=datax.notificationCount;}
					
					if(typeof datax.unreadCount!=='undefined'){unreadCount=datax.unreadCount;}
					if(typeof datax.region!=='undefined'){region=datax.region;}
					if(typeof datax.botId!=='undefined'){botId=datax.botId;}
					if(typeof datax.iconHash!=='undefined'){iconHash=datax.iconHash;}
					if(typeof datax.responseMode!=='undefined'){responseMode=datax.responseMode;}
					
					if(typeof datax.iconUrl!=='undefined'){
						profileImageUrl=datax.iconUrl;
					}
					
					
					//https://manager.line.biz/api/bots
					/*
					ct_tl_line_alls.push({
						'basicSearchId': datax.basicSearchId,
						'profileImageUrl': datax.profileImageUrl,
						'name': datax.name,
						'brandType': datax.brandType,
						'userPermissionType': datax.userPermissionType,
						'targetedReaches': datax.targetedReaches,
						'planName': datax.planName,
						'hasNotification': datax.hasNotification,
						'notificationCount': datax.notificationCount
					});
					*/
					////https://chat.line.biz/api/v1/bots/
					/*
					ct_tl_line_alls.push({
						'basicSearchId': datax.basicSearchId,
						'name': datax.name,
						'brandType': datax.brandType,
						'userPermissionType': datax.userPermissionType,
						'profileImageUrl': datax.iconUrl,
						'unreadCount': datax.unreadCount,
						'region': datax.region,
						'botId': datax.botId,
						'iconHash': datax.iconHash,
						'responseMode': datax.responseMode
					});
					*/
					ct_tl_line_alls.push({
						'basicSearchId': basicSearchId,
						'name': name,
						'brandType': brandType,
						'userPermissionType': userPermissionType,
						'profileImageUrl': profileImageUrl,
						'region': region,
						'botId': botId,
						'iconHash': iconHash,
						'unreadCount': unreadCount,
						'responseMode': responseMode,
						'targetedReaches': targetedReaches,
						'planName': planName,
						'hasNotification': hasNotification,
						'notificationCount': notificationCount
					});
				//});
			}
		
			if(next_url!=null){
				get_line_all_accs(next_url,++num_page);
				//return;
			}else{
				if (data.length > 0) {
					{
						message = 'Line Account ' + ct_tl_line_alls.length + ' ';
						
						iziToast.success({
							title: message,
							position: 'topRight',
							timeout: 3000,
							message: '',
						});
						
						populate_line_accs();
					}
				} else {
					message = 'Line Account ' + ct_tl_line_alls.length + ' ';
					
					iziToast.success({
						title: message,
						position: 'topRight',
						timeout: 3000,
						message: '',
					});
					
					ldb.set('line_accounts', JSON.stringify(ct_tl_line_alls));
					populate_line_accs();
				}
			}
			resolve(true);
		})
		.fail(function (e) {
		//.catch(function(e) {
			console.log(e);
			Swal.fire({
				title: window.lang.translate('Line OA not logged in yet'),
				text: window.lang.translate("You have to log in Line OA first"),
				type: 'warning',
				confirmButtonColor: '#3085d6',
				cancelButtonColor: '#d33',
				confirmButtonText: window.lang.translate('OK'),
				cancelButtonText: window.lang.translate('Cancel')
			}).then((result) => {
				if (result.value) {
					window.open('https://account.line.biz/login?redirectUri=https%3A%2F%2Fmanager.line.biz%2F', '_blank');
				}
			})
			resolve(false);
		});
	});
}


function getMsgCardList(url,num_page,obj){
	let sel=document.getElementById("my_broadcastline_idpage");
	let opt = sel.options[sel.selectedIndex];
	if(typeof opt!=="undefined" && opt!=null ){
		ct_tl_my_broadcastline_idpage_token=opt.getAttribute('data-botId');
	}
	url = url.replace("ct_tl_my_broadcastline_idpage_token",ct_tl_my_broadcastline_idpage_token);
	
	return new Promise(resolve =>{
		if (num_page == 1) {
			ct_tl_card_list = [];
		}
		
		title = window.lang.translate('Retrieve card list in LINE OA');
		$.getJSON(url, function (results) {
			var data = results.list;
			
			var cardId='';
			var cardTitle='';
			var cardType='';
			var cardUpdated='';
			var cardIsRich=false;

			//console.log(results);
			let next_url = null;
			if(results.next){
				if(typeof results.next!="undefined" && results.next!=null && results.next!=""){
					next_url= 'https://chat.line.biz/api/v1/bots/'+ ct_tl_my_broadcastline_idpage_token+ "/cardTypeMessages?limit=25&next="+ results.next;
				}
			}else if(results.paging){
				if(typeof results.paging!="undefined" && results.paging!=null && results.paging!=""){
					next_url= 'https://chat.line.biz/api/v1/bots/'+ ct_tl_my_broadcastline_idpage_token+ "/cardTypeMessages?limit=25&next="+ results.paging;
				}
			}
			for(let md = 0;md<data.length;md++){
				let datax = data[md];
				
				cardId='';
				cardTitle='';
				cardType='';
				cardUpdated='';
				cardIsRich=false;

				if(typeof datax.id!=='undefined'){cardId=datax.id;}
				if(typeof datax.title!=='undefined'){cardTitle=datax.title;}
				if(typeof datax.type!=='undefined'){cardType=datax.type;}
				if(typeof datax.updated!=='undefined'){
					cardUpdated=datax.updated;
					let unixTimestamp = datax.updated;
					let date = new Date(unixTimestamp);
					let dt_str = date.toLocaleDateString("en-GB");
					let tt_str = date.toLocaleTimeString("it-IT");	//default
					cardUpdated = dt_str + ' ' + tt_str;
				}

				if(typeof datax.messageObject!=='undefined'){	//not card are discard
					if(typeof datax.messageObject.rich!=='undefined'){
						cardIsRich =datax.messageObject.rich;
					}
				}
				if(typeof datax.contents!=='undefined'){	//not card are discard
					if(typeof datax.contents.rich!=='undefined'){
						cardIsRich =datax.contents.rich;
					}
				}
				if (cardIsRich==false){	//only card
					ct_tl_card_list.push({
						'cardId': cardId,
						'cardTitle': cardTitle,
						'cardType': cardType,
						'cardUpdated':cardUpdated
					});
				}
			}
		
			if(next_url!=null){
				getMsgCardList(next_url,++num_page,obj);
			}else{
				//ct_tl_card_list = [...ct_tl_card_list].reverse();
				populate_card_list(obj,ct_tl_my_broadcastline_idpage_token);
			}
			resolve(true);
		})
		.fail(function (e) {
			console.log(e);
			Swal.fire({
				title: window.lang.translate('Line OA not logged in yet'),
				text: window.lang.translate("You have to log in Line OA first"),
				type: 'warning',
				confirmButtonColor: '#3085d6',
				cancelButtonColor: '#d33',
				confirmButtonText: window.lang.translate('OK'),
				cancelButtonText: window.lang.translate('Cancel')
			}).then((result) => {
				if (result.value) {
					window.open('https://account.line.biz/login?redirectUri=https%3A%2F%2Fmanager.line.biz%2F', '_blank');
				}
			})
			resolve(false);
		});
	});

}
//dataAcc = '<option value="' + id + '|' + name + '" data-botId="' + botId + '" data-icon="' + data.profileImageUrl + '" title="'+data.profileImageUrl+ '" >' + name + '</option>'; 
//https://manager.line.biz/api/bots/@142trbgp/richImage/list?page=1 
//Fecht all rich images
function getMsgRichList(url,num_page,obj){
	console.log(url,num_page);
	let sel=document.getElementById("my_broadcastline_idpage");
	let opt = sel.options[sel.selectedIndex];
	let basicSearchId = "";
	if(typeof opt!=="undefined" && opt!=null ){
		basicSearchId=opt.getAttribute('value');
		if (typeof basicSearchId!="undefined"){
			basicSearchId = basicSearchId.split("|")[0];
		}
	}
	if(typeof opt!=="undefined" && opt!=null ){
		ct_tl_my_broadcastline_idpage_token=opt.getAttribute('data-botId');
	}
	url = url.replace("ct_tl_my_broadcastline_idpage_token",basicSearchId);
	
	return new Promise(resolve =>{
		if (num_page == 1) {
			ct_tl_rich_list = [];
		}
		
		title = window.lang.translate('Retrieve card list in LINE OA');
		$.getJSON(url, function (results) {
			var data = results.list;
			
			var richId='';
			var richTitle='';
			var richType='';
			var pageNumber=1;
			var totalCount=0;
			var rowsPerPage=30;
			var created='';

			//console.log(results);
			let next_url = null;

			if(typeof results.pageNumber!="undefined"){
				pageNumber = results.pageNumber;
			}
			if(typeof results.totalCount!="undefined"){
				totalCount = results.totalCount;
			}
			if(typeof results.rowsPerPage!="undefined"){
				rowsPerPage = results.rowsPerPage;
			}

			if (pageNumber*rowsPerPage<totalCount){
				if(totalCount>0){
					next_url= 'https://manager.line.biz/api/bots/'+ basicSearchId+ "/richImage/list?page="+ (pageNumber+1) + "&sortType=desc";
				}
			}
			for(let md = 0;md<data.length;md++){
				let datax = data[md];
				
				richId='';
				richTitle='';
				richType='';
				created='';

				if(typeof datax.id!=='undefined'){richId=datax.id;}
				if(typeof datax.title!=='undefined'){richTitle=datax.title;}
				if(typeof datax.contentsType!=='undefined'){richType=datax.contentsType;}
				if(typeof datax.created!=='undefined'){
					//created=datax.created;
					let unixTimestamp = datax.created;
					let date = new Date(unixTimestamp * 1000);
					let dt_str = date.toLocaleDateString("en-GB");
					let tt_str = date.toLocaleTimeString("it-IT");	//default
					created = dt_str + ' ' + tt_str;
				}

				ct_tl_rich_list.push({
					'basicSearchId':basicSearchId,
					'richId': richId,
					'richTitle': richTitle,
					'richType': richType,
					'created': created,
					'richData':datax
				});
			}
		
			if(next_url!=null){
				getMsgRichList(next_url,++num_page,obj);
			}else{
				//ct_tl_rich_list = [...ct_tl_rich_list].reverse();	//order date DESC
				populate_rich_list(obj,ct_tl_my_broadcastline_idpage_token);
			}
			resolve(true);
		})
		.fail(function (e) {
			console.log(e);
			Swal.fire({
				title: window.lang.translate('Line OA not logged in yet'),
				text: window.lang.translate("You have to log in Line OA first"),
				type: 'warning',
				confirmButtonColor: '#3085d6',
				cancelButtonColor: '#d33',
				confirmButtonText: window.lang.translate('OK'),
				cancelButtonText: window.lang.translate('Cancel')
			}).then((result) => {
				if (result.value) {
					window.open('https://account.line.biz/login?redirectUri=https%3A%2F%2Fmanager.line.biz%2F', '_blank');
				}
			})
			resolve(false);
		});
	});
}

function getRichId(basicSearchId, objImg, arrImageUpload, arrRichIdStorage, exist_stored_richid, callbackFn) {
	//i = arrRichIdStorage array img id is 129495315, ... or empty array {} if not store in browser storage
	//Send post rich URL:  https://manager.line.biz/api/bots/@142trbgp/cardTypeMessages
	//$headers = array(
	//	"cookie: XSRF-TOKEN=${xsrf_token};ses=${ses};",
	//	"x-xsrf-token: ${xsrf_token}",
	//	"authority: chat.line.biz",
	//	"referer: https://chat.line.biz",
	//	"pragma: no-cache",
	//	"accept: application/json, text/plain, */*",
	//	"Content-Type: application/json",
	//	"checkadmin: ${lineMeAdminBizId}",
	//	);
	debugger;
	if (exist_stored_richid!=""){
		callbackFn(!0,JSON.parse('{"id":'+exist_stored_richid+',"code":1,"message":"success"}'));
		return;
	}

	// u = check exist id in storage
	var s, c, u=false;//u = objImg.id in i,    //u = false or 0 if not found in i else return number rich id
		//f = (s = objImg.title, (c = JSON.stringify(s)).substr(1, c.length - 2)),
		f = (s = objImg.title, (c = JSON.stringify(s)).substring(1, c.length - 2)),
		l = '\n    {\n      "title": "' + f + '",\n      "type": "Image",\n      "actions": [],\n      "contents": {\n        "rich": true,\n        "type": "flex",\n        "altText": "' + f + '",\n        "contents":{CONTENT}\n      },\n      "origin": {}\n    }\n  ',
		d = new XMLHttpRequest;
	//var url = "https://manager.line.biz/api/bots/" + basicSearchId + "/cardTypeMessages" + (u ? "/" + arrRichIdStorage[objImg.id] : "");
	var url = "https://linebroadcast.com/lineme/getRichId.php";

	d.overrideMimeType("application/json");
	d.open("POST", url, !0);
	d.setRequestHeader("content-type", "application/json");
	d.setRequestHeader("checkadmin", lineMeAdmin.bizId);
	d.setRequestHeader("basicSearchId", basicSearchId);
	d.setRequestHeader("authority", "chat.line.biz");
	d.setRequestHeader("xsrfToken", lineMeCookie.xsrf);
	d.setRequestHeader("usrfToken", usrfToken);
	d.setRequestHeader("ses", lineMeCookie.ses);

	d.onreadystatechange = function() {
		if (4 == d.readyState){
			if("200" == d.status){
				debugger;
				if (u){
					callbackFn(!0,{
						id: arrRichIdStorage[objImg.id]
					});
					return;
				}else{
					let resp = JSON.parse(d.responseText);
					if (resp.code !=1 ){
						callbackFn(!1,resp);    //error
					}else{
						callbackFn(!0,resp);    //rich id d.responseText = "{"id" : 5126554}"
					}
					return;
				}
			}else{
				callbackFn(!1, JSON.parse(d.responseText));   //responseText rich id
				return;
			}
		}
	};
	l = prepareRich(objImg,arrImageUpload);
	console.log(l);

	d.send(l);



	//	"cookie: XSRF-TOKEN=${xsrf_token};ses=${ses};",
	/*
	document.cookie = "XSRF-TOKEN="+ lineMeCookie.xsrf + ";ses="+lineMeCookie.ses+";";
	l = prepareRich(objImg,arrImageUpload);
	$.ajax({
		url: url,
		contentType: 'application/json; charset=utf-8',
		dataType: 'json',
		data: JSON.stringify(l),
		method: 'POST',
		//New
		type: 'POST', // For jQuery < 1.9
		beforeSend: function (xhr) {
			xhr.withCredentials = true; //Include this line
			xhr.setRequestHeader('x-xsrf-token', lineMeCookie.xsrf);	//ct_tl_lineCSRF
			xhr.setRequestHeader('XSRF-TOKEN', lineMeCookie.xsrf);
			//xhr.setRequestHeader('cookie', "XSRF-TOKEN="+ lineMeCookie.xsrf + ";ses="+lineMeCookie.ses+";");
			xhr.setRequestHeader('dataType', 'json');
			xhr.setRequestHeader('checkadmin', lineMeAdmin.bizId);
			xhr.setRequestHeader('authority', 'chat.line.biz');
			//xhr.setRequestHeader('referer','https://chat.line.biz');
		},
		crossOrigin: true,
		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
		success: function (data, textStatus, request) {
			callbackFn(!0,JSON.parse(data.responseText)); 
		},
		error: function (XMLHttpRequest, textStatus, errorThrown) {
			console.log(XMLHttpRequest.responseText);
			console.log(textStatus);
			callbackFn(!1, JSON.parse(XMLHttpRequest.responseText));   //responseText rich id
		}
	});
	*/
}

function prepareRich(n,o){
	//let url = 'https://manager.line.biz/api/bots/'+basicSearchId+'/cardTypeMessages';
	debugger;
	let u = `{
		"title": "${n.title}",
		"type": "Image",
		"actions": [],
		"contents": {
			"rich": true,
			"type": "flex",
			"altText": "${n.title}",
			"contents": {CONTENT}
		},
		"origin": {}
	}`;
	

	if (8 == n.contentsType) {
		let u8 = `{
			"type": "bubble",
			"size": "giga",
			"body": {
				"type": "box",
				"layout": "vertical",
				"contents": [
					{
						"type": "box",
						"layout": "horizontal",
						"contents": [
							{
								"type": "image",
								"url": "${o[0].imageUrl}",
								"size": "full",
								"aspectRatio": "1:1.5",{ACTION_A}
								"aspectMode": "cover"
							},
							{
								"type": "image",
								"url": "${o[1].imageUrl}",
								"size": "full",
								"aspectRatio": "1:1.5",{ACTION_B}
								"aspectMode": "cover"
							},
							{
								"type": "image",
								"url": "${o[2].imageUrl}",
								"size": "full",
								"aspectRatio": "1:1.5",{ACTION_C}
								"aspectMode": "cover"
							}
						]
					},
					{
						"type": "box",
						"layout": "horizontal",
						"contents": [
							{
								"type": "image",
								"url": "${o[3].imageUrl}",
								"size": "full",
								"aspectRatio": "1:1.5",{ACTION_D}
								"aspectMode": "cover"
							},
							{
								"type": "image",
								"url": "${o[4].imageUrl}",
								"size": "full",
								"aspectRatio": "1:1.5",{ACTION_E}
								"aspectMode": "cover"
							},
							{
								"type": "image",
								"url": "${o[5].imageUrl}",
								"size": "full",
								"aspectRatio": "1:1.5",{ACTION_F}
								"aspectMode": "cover"
							}
						]
					}
				],
				"paddingAll": "none"
			}
		}`;
		let action = "";
		if (n.contents.A.url  && "" != n.contents.A.url ){
			action = 	`\n						"action": {
											"type": "uri",
											"label": "${substring_label(n.contents.A.text,40)}",
											"uri": "${n.contents.A.url}"
										},`;
		}else{
			action = "";
		}
		u8 = u8.replace("{ACTION_A}",action);

		if (n.contents.B.url  && "" != n.contents.B.url ){
			action = 	`\n						"action": {
											"type": "uri",
											"label": "${substring_label(n.contents.B.text,40)}",
											"uri": "${n.contents.B.url}"
										},`;
		}else{
			action = "";
		}
		u8 = u8.replace("{ACTION_B}",action);

		if (n.contents.C.url  && "" != n.contents.C.url ){
			action = 	`\n						"action": {
											"type": "uri",
											"label": "${substring_label(n.contents.C.text,40)}",
											"uri": "${n.contents.C.url}"
										},`;
		}else{
			action = "";
		}
		u8 = u8.replace("{ACTION_C}",action);

		if (n.contents.D.url  && "" != n.contents.D.url ){
			action = 	`\n						"action": {
											"type": "uri",
											"label": "${substring_label(n.contents.D.text,40)}",
											"uri": "${n.contents.D.url}"
										},`;
		}else{
			action = "";
		}
		u8 = u8.replace("{ACTION_D}",action);

		if (n.contents.E.url  && "" != n.contents.E.url ){
			action = 	`\n						"action": {
											"type": "uri",
											"label": "${substring_label(n.contents.E.text,40)}",
											"uri": "${n.contents.E.url}"
										},`;
		}else{
			action = "";
		}
		u8 = u8.replace("{ACTION_E}",action);

		if (n.contents.F.url  && "" != n.contents.F.url ){
			action = 	`\n						"action": {
											"type": "uri",
											"label": "${substring_label(n.contents.F.text,40)}",
											"uri": "${n.contents.F.url}"
										},`;
		}else{
			action = "";
		}
		u8 = u8.replace("{ACTION_F}",action);
		u = u.replace("{CONTENT}",u8);
	}else if(7 == n.contentsType){
		let u7 = `{
			"type": "bubble",
			"size": "giga",
			"body": {
				"type": "box",
				"layout": "vertical",
				"contents": [
					{
						"type": "box",
						"layout": "vertical",
						"contents": [
							{
								"type": "image",
								"url": "${o[0].imageUrl}",
								"size": "full",
								"aspectRatio": "2:1",{ACTION_C}
								"aspectMode": "cover"
							},
							{
								"type": "image",
								"url": "${o[1].imageUrl}",
								"size": "full",
								"aspectRatio": "4:1",{ACTION_C}
								"aspectMode": "cover"
							},
							{
								"type": "image",
								"url": "${o[2].imageUrl}",
								"size": "full",
								"aspectRatio": "4:1",{ACTION_C}
								"aspectMode": "cover"
							}
						]
					}
				],
				"paddingAll": "0px"
			}
		}`;
		let action = "";
		if (n.contents.A.url  && "" != n.contents.A.url ){
			action = 	`\n						"action": {
											"type": "uri",
											"label": "${substring_label(n.contents.A.text,40)}",
											"uri": "${n.contents.A.url}"
										},`;
		}else{
			action = "";
		}
		u7 = u7.replace("{ACTION_A}",action);

		if (n.contents.B.url  && "" != n.contents.B.url ){
			action = 	`\n						"action": {
											"type": "uri",
											"label": "${substring_label(n.contents.B.text,40)}",
											"uri": "${n.contents.B.url}"
										},`;
		}else{
			action = "";
		}
		u7 = u7.replace("{ACTION_B}",action);

		if (n.contents.C.url  && "" != n.contents.C.url ){
			action = 	`\n						"action": {
											"type": "uri",
											"label": "${substring_label(n.contents.C.text,40)}",
											"uri": "${n.contents.C.url}"
										},`;
		}else{
			action = "";
		}
		u7 = u7.replace("{ACTION_C}",action);
		u = u.replace("{CONTENT}",u7);
	}else if(6 == n.contentsType){
		let u6 = `{
			"type": "bubble",
			"size": "giga",
			"body": {
				"type": "box",
				"layout": "vertical",
				"contents": [
					{
						"type": "box",
						"layout": "vertical",
						"contents": [
							{
								"type": "image",
								"url": "${o[0].imageUrl}",
								"size": "full",
								"aspectRatio": "2:1",{ACTION_A}
								"aspectMode": "cover"
							}
						]
					},
					{
						"type": "box",
						"layout": "horizontal",
						"contents": [
							{
								"type": "image",
								"url": "${o[1].imageUrl}",
								"size": "full",
								"aspectRatio": "1:1",{ACTION_B}
								"aspectMode": "cover"
							},
							{
								"type": "image",
								"url": "${o[2].imageUrl}",
								"size": "full",
								"aspectRatio": "1:1",{ACTION_C}
								"aspectMode": "cover"
							}
						]
					}
				],
				"paddingAll": "0px"
			}
		}`;
		let action = "";
		if (n.contents.A.url  && "" != n.contents.A.url ){
			action = 	`\n						"action": {
											"type": "uri",
											"label": "${substring_label(n.contents.A.text,40)}",
											"uri": "${n.contents.A.url}"
										},`;
		}else{
			action = "";
		}
		u6 = u6.replace("{ACTION_A}",action);

		if (n.contents.B.url  && "" != n.contents.B.url ){
			action = 	`\n						"action": {
											"type": "uri",
											"label": "${substring_label(n.contents.B.text,40)}",
											"uri": "${n.contents.B.url}"
										},`;
		}else{
			action = "";
		}
		u6 = u6.replace("{ACTION_B}",action);

		if (n.contents.C.url  && "" != n.contents.C.url ){
			action = 	`\n						"action": {
											"type": "uri",
											"label": "${substring_label(n.contents.C.text,40)}",
											"uri": "${n.contents.C.url}"
										},`;
		}else{
			action = "";
		}
		u6 = u6.replace("{ACTION_C}",action);
		u = u.replace("{CONTENT}",u6);
	}else if(5 == n.contentsType){
		let u5 = `{
			"type": "bubble",
			"size": "giga",
			"body": {
			  "type": "box",
			  "layout": "vertical",
			  "contents": [
				{
				  "type": "box",
				  "layout": "horizontal",
				  "contents": [
					{
					  "type": "image",
					  "url": "${o[0].imageUrl}",
					  "size": "full",
					  "aspectRatio": "1:1",{ACTION_A}
					  "aspectMode": "cover"
					},
					{
					  "type": "image",
					  "url": "${o[1].imageUrl}",
					  "size": "full",
					  "aspectRatio": "1:1",{ACTION_B}
					  "aspectMode": "cover"
					}
				  ]
				},
				{
				  "type": "box",
				  "layout": "horizontal",
				  "contents": [
					{
					  "type": "image",
					  "url": "${o[2].imageUrl}",
					  "size": "full",
					  "aspectRatio": "1:1",{ACTION_C}
					  "aspectMode": "cover"
					},
					{
					  "type": "image",
					  "url": "${o[3].imageUrl}",
					  "size": "full",
					  "aspectRatio": "1:1",{ACTION_D}
					  "aspectMode": "cover"
					}
				  ]
				}
			  ],
			  "paddingAll": "0px"
			}
		}`;
		let action = "";
		if (n.contents.A.url  && "" != n.contents.A.url ){
			action = 	`\n						"action": {
											"type": "uri",
											"label": "${substring_label(n.contents.A.text,40)}",
											"uri": "${n.contents.A.url}"
										},`;
		}else{
			action = "";
		}
		u5 = u5.replace("{ACTION_A}",action);

		if (n.contents.B.url  && "" != n.contents.B.url ){
			action = 	`\n						"action": {
											"type": "uri",
											"label": "${substring_label(n.contents.B.text,40)}",
											"uri": "${n.contents.B.url}"
										},`;
		}else{
			action = "";
		}
		u5 = u5.replace("{ACTION_B}",action);

		if (n.contents.C.url  && "" != n.contents.C.url ){
			action = 	`\n						"action": {
											"type": "uri",
											"label": "${substring_label(n.contents.C.text,40)}",
											"uri": "${n.contents.C.url}"
										},`;
		}else{
			action = "";
		}
		u5 = u5.replace("{ACTION_C}",action);

		if (n.contents.D.url  && "" != n.contents.D.url ){
			action = 	`\n						"action": {
											"type": "uri",
											"label": "${substring_label(n.contents.D.text,40)}",
											"uri": "${n.contents.D.url}"
										},`;
		}else{
			action = "";
		}
		u5 = u5.replace("{ACTION_D}",action);
		u = u.replace("{CONTENT}",u5);
	}else if(4 == n.contentsType){
		let u4 = `{
			"type": "bubble",
			"size": "giga",
			"body": {
				"type": "box",
				"layout": "vertical",
				"contents": [
					{
						"type": "box",
						"layout": "vertical",
						"contents": [
							{
								"type": "image",
								"url": "${o[0].imageUrl}",
								"size": "full",
								"aspectRatio": "3:1",{ACTION_A}
								"aspectMode": "cover"
							},
							{
								"type": "image",
								"url": "${o[1].imageUrl}",
								"size": "full",
								"aspectRatio": "3:1",{ACTION_B}
								"aspectMode": "cover"
							},
							{
								"type": "image",
								"url": "${o[2].imageUrl}",
								"size": "full",
								"aspectRatio": "3:1",{ACTION_C}
								"aspectMode": "cover"
							}
						]
					}
				],
				"paddingAll": "0px"
			}
		}`;

		let action = "";
		if (n.contents.A.url  && "" != n.contents.A.url ){
			action = 	`\n						"action": {
											"type": "uri",
											"label": "${substring_label(n.contents.A.text,40)}",
											"uri": "${n.contents.A.url}"
										},`;
		}else{
			action = "";
		}
		u4 = u4.replace("{ACTION_A}",action);

		if (n.contents.B.url  && "" != n.contents.B.url ){
			action = 	`\n						"action": {
											"type": "uri",
											"label": "${substring_label(n.contents.B.text,40)}",
											"uri": "${n.contents.B.url}"
										},`;
		}else{
			action = "";
		}
		u4 = u4.replace("{ACTION_B}",action);

		if (n.contents.C.url  && "" != n.contents.C.url ){
			action = 	`\n						"action": {
											"type": "uri",
											"label": "${substring_label(n.contents.C.text,40)}",
											"uri": "${n.contents.C.url}"
										},`;
		}else{
			action = "";
		}
		u4 = u4.replace("{ACTION_C}",action);
		u = u.replace("{CONTENT}",u4);
	}else if(3 == n.contentsType){
		let u3 = `{
			"type": "bubble",
			"size": "giga",
			"body": {
				"type": "box",
				"layout": "vertical",
				"contents": [
					{
						"type": "image",
						"url": "${o[0].imageUrl}",
						"size": "full",
						"aspectRatio": "2:1",{ACTION_A}
						"aspectMode": "cover"
					},
					{
						"type": "image",
						"url": "${o[1].imageUrl}",
						"size": "full",
						"aspectRatio": "2:1",{ACTION_B}
						"aspectMode": "cover"
					}
				],
				"paddingAll": "0px"
			}
		}`;
		let action = "";
		if (n.contents.A.url  && "" != n.contents.A.url ){
			action = 	`\n						"action": {
											"type": "uri",
											"label": "${substring_label(n.contents.A.text,40)}",
											"uri": "${n.contents.A.url}"
										},`;
		}else{
			action = "";
		}
		u3 = u3.replace("{ACTION_A}",action);

		if (n.contents.B.url  && "" != n.contents.B.url ){
			action = 	`\n						"action": {
											"type": "uri",
											"label": "${substring_label(n.contents.B.text,40)}",
											"uri": "${n.contents.B.url}"
										},`;
		}else{
			action = "";
		}
		u3 = u3.replace("{ACTION_B}",action);
		u = u.replace("{CONTENT}",u3);
	}else if(2 == n.contentsType){
		let u2 = `{
			"type": "bubble",
			"size": "giga",
			"body": {
				"type": "box",
				"layout": "horizontal",
				"contents": [
					{
						"type": "image",
						"url": "${o[0].imageUrl}",
						"size": "full",
						"aspectRatio": "1:2",{ACTION_A}
						"aspectMode": "cover"
					},
					{
						"type": "image",
						"url": "${o[1].imageUrl}",
						"size": "full",
						"aspectRatio": "1:2",{ACTION_B}
						"aspectMode": "cover"
					}
				],
				"paddingAll": "0px"
			}
		}`;

		let action = "";
		if (n.contents.A.url  && "" != n.contents.A.url ){
			action = 	`\n						"action": {
											"type": "uri",
											"label": "${substring_label(n.contents.A.text,40)}",
											"uri": "${n.contents.A.url}"
										},`;
		}else{
			action = "";
		}
		u2 = u2.replace("{ACTION_A}",action);

		if (n.contents.B.url  && "" != n.contents.B.url ){
			action = 	`\n						"action": {
											"type": "uri",
											"label": "${substring_label(n.contents.B.text,40)}",
											"uri": "${n.contents.B.url}"
										},`;
		}else{
			action = "";
		}
		u2 = u2.replace("{ACTION_B}",action);
		u = u.replace("{CONTENT}",u2);
	}else{//1 || 9
		let u1 = `{
			"type": "bubble",
			"size": "giga",
			"body": {
				"type": "box",
				"layout": "vertical",
				"contents": [
					{
						"type": "image",
						"url": "${o[0].imageUrl}",
						"size": "full",
						"aspectRatio": "${o[0].ratio}",{ACTION}
						"aspectMode": "cover"
					}
				],
				"paddingAll": "none"
			}
		}`;
		let action = "";
		if (n.contents.A.url  && "" != n.contents.A.url ){
			action = 	`\n						"action": {
											"type": "uri",
											"label": "${substring_label(n.contents.A.text,40)}",
											"uri": "${n.contents.A.url}"
										},`;
		}else{
			//action = `"aspectRatio": "${o[0].ratio}"`;
			action = "";
		}
		u1 = u1.replace("{ACTION}",action);
		u = u.replace("{CONTENT}",u1);
	}
	return u;
}
function drawImageCanvas(basicSearchId, objImg, exist_stored_richid, callbackFn) {
	//objImg = message (image array list)
	debugger;
	if (exist_stored_richid!=""){
		callbackFn(basicSearchId, objImg, []);
		return;
	}
	var i = document.createElement("canvas"),
		a = i.getContext("2d"),
		s = [],
		c = new Image;

		//c.addEventListener('load', (event) => {
		//	console.log('The logo has been loaded');
		//});

	c.crossOrigin = "Anonymous";
	c.onload = function() {
		if (8 == objImg.contentsType) {
			var u = 3,
				f = 2,
				l = c.width / u,
				d = c.height / f;
			i.width = 347, i.height = d, a.drawImage(this, 0, 0, c.width, c.height), s.push(i.toDataURL()), i.width = 346, i.height = d, a.drawImage(this, -348, 0, c.width, c.height), s.push(i.toDataURL()), i.width = 347, i.height = d, a.drawImage(this, -694, 0, c.width, c.height), s.push(i.toDataURL()), i.width = 347, i.height = d, a.drawImage(this, 0, -d, c.width, c.height), s.push(i.toDataURL()), i.width = 346, i.height = d, a.drawImage(this, -348, -d, c.width, c.height), s.push(i.toDataURL()), i.width = 347, i.height = d, a.drawImage(this, -694, -d, c.width, c.height), s.push(i.toDataURL())
		} else if (5 == objImg.contentsType) {
			u = 2, f = 2, l = c.width / u, d = c.height / f;
			i.width = l, i.height = d, a.drawImage(this, 0, 0, c.width, c.height), s.push(i.toDataURL()), i.width = l, i.height = d, a.drawImage(this, -l, 0, c.width, c.height), s.push(i.toDataURL()), i.width = l, i.height = d, a.drawImage(this, 0, -d, c.width, c.height), s.push(i.toDataURL()), i.width = l, i.height = d, a.drawImage(this, -l, -d, c.width, c.height), s.push(i.toDataURL())
		} else if (7 == objImg.contentsType) {
			u = 1, f = 2, l = c.width / u, d = c.height / f;
			i.width = l, i.height = c.height / 2, a.drawImage(this, 0, 0, c.width, c.height), s.push(i.toDataURL()), i.width = l, i.height = d / 2, a.drawImage(this, 0, -d, c.width, c.height), s.push(i.toDataURL()), i.width = l, i.height = d / 2, a.drawImage(this, 0, -d - d / 2, c.width, c.height), s.push(i.toDataURL())
		} else if (4 == objImg.contentsType) {
			u = 1, f = 3, l = c.width / u, d = c.height / f;
			i.width = l, i.height = 347, a.drawImage(this, 0, 0, c.width, c.height), s.push(i.toDataURL()), i.width = l, i.height = 346, a.drawImage(this, 0, -348, c.width, c.height), s.push(i.toDataURL()), i.width = l, i.height = 347, a.drawImage(this, 0, -694, c.width, c.height), s.push(i.toDataURL())
		} else if (6 == objImg.contentsType) {
			u = 1, f = 2, l = c.width / u, d = c.height / f;
			i.width = l, i.height = c.height / 2, a.drawImage(this, 0, 0, c.width, c.height), s.push(i.toDataURL()), i.width = l / 2, i.height = d, a.drawImage(this, 0, -d, c.width, c.height), s.push(i.toDataURL()), i.width = l / 2, i.height = d, a.drawImage(this, -d, -d, c.width, c.height), s.push(i.toDataURL())
		} else if (3 == objImg.contentsType) {
			u = 1, f = 2, l = c.width / u, d = c.height / f;
			i.width = l, i.height = d, a.drawImage(this, 0, 0, c.width, c.height), s.push(i.toDataURL()), i.width = l, i.height = d, a.drawImage(this, 0, -d, c.width, c.height), s.push(i.toDataURL())
		} else if (2 == objImg.contentsType) {
			u = 2, f = 1, l = c.width / u, d = c.height / f;
			i.width = l, i.height = d, a.drawImage(this, 0, 0, c.width, c.height), s.push(i.toDataURL()), i.width = l, i.height = d, a.drawImage(this, -l, 0, c.width, c.height), s.push(i.toDataURL())
		} else 9 != objImg.contentsType && 1 != objImg.contentsType || s.push({
			imageUrl: this.src,
			ratio: img_ratio(this.width, this.height)
		});
		console.log("draw image: ",basicSearchId, objImg, s);
		callbackFn(basicSearchId, objImg, s);   //finish and callback
	}
	c.src = objImg.imageUrl;
}

function substring_label(text, len) {
	var r = !(arguments.length > 2 && void 0 !== arguments[2]) || arguments[2];
	try {
		var n = text.substr(0, len - 1) + (text.length > len ? "…" : "");
		return n = JSON.stringify(n), r ? n.substr(1, n.length - 2) : n
	} catch (e) {
		return text
	}
}
//image ratio
function img_ratio(img_width, img_height) {
	var r = img_width,
		n = img_height;
	if (n > r) {
		var o = r;
		r = n, n = o
	}
	for (; 0 != n;) {
		var i = r % n;
		r = n, n = i
	}
	return img_width / r + ":" + img_height / r
}
//UPLOAD IMAGE
function upload_image(basicSearchId, objImg, objImageUrlAndRatio, arrImgUpload, iretry,exist_stored_richid, callbackFn) {
	//t is basicSearchId @142trbgp
	//e = objMeAdmin
	//r = objImg
	//n = nloop
	//o = objImageUrlAndRatio to upload
	//i = arrImgUpload start from [] Array(0) (length 0)
	//a = retry start from 0
	//s = callback function callbackFn
	
	//$headers = array(
	//	"cookie: XSRF-TOKEN=${xsrf_token};ses=${ses};",
	//	"x-xsrf-token: ${xsrf_token}",
	//	"authority: chat.line.biz",
	//	"referer: https://chat.line.biz",
	//	"pragma: no-cache",
	//	"accept: application/json, text/plain, */*",
	//	"Content-Type: application/json",
	//	"checkadmin: ${lineMeAdminBizId}",
	//	);
	debugger;
	if (exist_stored_richid!=""){
		callbackFn(basicSearchId, objImg, !0, arrImgUpload)
		return;
	}

	var c = objImageUrlAndRatio[0];
	if (1 == objImageUrlAndRatio.length && 0 == arrImgUpload.length) return arrImgUpload.push(c), callbackFn(basicSearchId, objImg, !0, arrImgUpload);
	var u = new XMLHttpRequest;
	//u.open("POST", "https://manager.line.biz/api/bots/" + basicSearchId + "/richImage/upload/image", !0);
	u.open("POST", "https://linebroadcast.com/lineme/uploadImg.php", !0);
	u.setRequestHeader("checkadmin", lineMeAdmin.bizId);
	//u.setRequestHeader("cookie","XSRF-TOKEN="+ lineMeCookie.xsrf + ";ses="+lineMeCookie.ses+";");
	u.setRequestHeader("XSRF-TOKEN",lineMeCookie.xsrf);
	u.setRequestHeader("x-xsrf-token", lineMeCookie.xsrf);
	u.setRequestHeader("authority", "chat.line.biz");
	u.setRequestHeader("basicSearchId",basicSearchId);
	u.setRequestHeader("xsrfToken", lineMeCookie.xsrf);
	u.setRequestHeader("usrfToken", usrfToken);
	u.setRequestHeader("ses", lineMeCookie.ses);
	u.withCredentials = true;
	
	//u.setRequestHeader("referer", "https://chat.line.biz");
	u.onreadystatechange = function() {
		//4 == u.readyState && ("200" == u.status ? (o.shift(), i.push(JSON.parse(u.responseText)), o.length > 0 ? ne(t, e, r, n, o, i, 0, s) : s(t, e, r, n, !0, i)) : (a += 1) >= 3 ? s(t, e, r, n, !1, u.status + "|" + u.responseText) : ne(t, e, r, n, o, i, a, s))
		if (4 == u.readyState){
			if("200" == u.status){
				objImageUrlAndRatio.shift();
				try{
					let res_json = JSON.parse(u.responseText);
					if(res_json.code!=1){
						callbackFn(basicSearchId, objImg, !1, u.status + "|" + u.responseText)  //error callback function
						return;
					}
					arrImgUpload.push(res_json);
				}catch(e){
					callbackFn(basicSearchId, objImg, !1, u.status + "|" + u.responseText)  //error callback function
					return;
				}
				if(objImageUrlAndRatio.length > 0){
					upload_image(basicSearchId, objImg, objImageUrlAndRatio, arrImgUpload, 0, exist_stored_richid, callbackFn)
					return;
				}else{
					callbackFn(basicSearchId, objImg, !0, arrImgUpload)    //callback function finished upload
					return;
				}
			}else{
				if((iretry += 1) >= 3){	//retry
					callbackFn(basicSearchId, objImg, !1, u.status + "|" + u.responseText)  //callback function
					return;
				}else{
					upload_image(basicSearchId, objImg, objImageUrlAndRatio, arrImgUpload, iretry, exist_stored_richid, callbackFn)
					return;
				}
			}
		}
	};
	var f = document.createElement("input");
	f.setAttribute("type", "file"), f.setAttribute("name", "file"), f.files = null;
	var blob = se(c);
	console.log(blob);
	
	var l = new DataTransfer,
		d = new File([blob], "blob", {
			type: c.split("data:")[1].split(";")[0]
		});

	/*	
	var l = new DataTransfer,
		d = new File([se(c)], "blob", {
			type: c.split("data:")[1].split(";")[0]
		});
	*/

	l.items.add(d);
	f.files = l.files;
	var p = new FormData;
	p.append("file", f.files[0]);
	p.append("basicSearchId",basicSearchId);
	p.append("xsrfToken", lineMeCookie.xsrf);
	p.append("checkadmin", lineMeAdmin.bizId);
	p.append("usrfToken", usrfToken);
	p.append("ses", lineMeCookie.ses);
	
	u.send(p);
}
function se(t) {
	for (var e = atob(t.split(",")[1]), r = t.split(",")[0].split(":")[1].split(";")[0], n = new ArrayBuffer(e.length), o = new Uint8Array(n), i = 0; i < e.length; i++) o[i] = e.charCodeAt(i);
	return new Blob([n], {
		type: r
	})
}

async function pause_broadcast(){
	//ct_tl_status_stop_pause = 2;
	//localStorage.setItem('setstop', 2);	//Set pause flag
	Swal.fire({
		title: window.lang.translate('ยืนยันหยุดทำงานชั่วคราว?'),
		text: window.lang.translate('คุณต้องการหยุดการทำงานชั่วคราวหรือไม่?'),
		type: 'warning',
		//footer: footer_swal(),
		showCancelButton: true,
		confirmButtonColor: '#3085d6',
		cancelButtonColor: '#d33',
		confirmButtonText: window.lang.translate('Yes'),
		cancelButtonText: window.lang.translate('Cancel')
	}).then(async (result) => {
		if (result.value) {
			$('#pause_broadcast').text('   pausing');
			$('#stop_broadcast').text('   stop');
			document.getElementById("stop_time").innerHTML="pause waiting";
			$('#radio_schedule *').prop('disabled',false);
			$('#pause_broadcast').prop('disabled',true);
			$('#stop_broadcast').prop('disabled',false);
			$('#modalGrAlert_OA_Status').text('หยุดการทำงาน ชั่วคราว');
			$('#modalGrAlert_OA_Status').css('color','white');
			

			pressPause_Broadcast_Button();

			if(ct_tl_execSetTimeout!=null){
				clearTimeout(ct_tl_execSetTimeout);
			}

			let to_recipient = Number(ct_tl_iSendFriendsCount)+Number(ct_tl_cfg_start_seding_no)-1;
			await setStopJob(to_recipient,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= window.lang.translate("Pause")+" "+esttime_date_format_str;
			ct_tl_status_running=false;
			checkActionStatus();
			//ct_tl_status_stop_pause
			show_msg_report("","","2",window.lang.translate("Ready to pause") + " to recipient:" + to_recipient+1);	
		}
	});

	

}

//localStorage.setItem('setstop', ct_tl_status_stop_pause);	//Clear stop flag
//localStorage.setItem('loops', loop);	//store sending no to local storage

async function continue_broadcast(){
	pressStart_Broadcast_Button();
	
	$('#footer-summary-container').show();
	$('#close-x').show();
	$('#open-o').hide();
	pressContinue_GrAlert_Button();
	
	let set_stop = await getItem('setstop');
	//getAllItemsPromise().then(x => ct_tl_iTableAllItems=x);
	if(set_stop!=null){
		try{set_stop = Number(set_stop);}catch(e){set_stop=2;};
	}else{
		set_stop = 0;
	}
	//localStorage.setItem('setstop', 1);	//Clear stop flag
	//ct_tl_status_stop_pause = 1;
	//console.log("continue broadcast");
	
	if(set_stop!=2){
		show_msg_report("","","2","Pause flag is "+set_stop + " cannot continue please stop and start again");	
		$('#pause_broadcast').text('   pause');
		$('#stop_broadcast').text('   stop');
		$('#pause_broadcast').prop('disabled',false);
		$('#stop_broadcast').prop('disabled',false);
		return;
	}
	

	if(ct_tl_is_finished_get_friends_list==0){	//load friend only
		show_msg_report("","","2","Continue load friend only");	
		sending_my_broadcastline_start(false,true);
	}else if(ct_tl_is_finished_get_friends_list==1){	//load friend and send
		show_msg_report("","","2","Continue load friend and send");	
		sending_my_broadcastline_start(true,true);
	}else{
			
		let to_recipient=localStorage.getItem('loops');	//get sending no to local storage
		show_msg_report("","","2","Get continue from recipient: "+to_recipient);
		if (to_recipient!=null){
			ct_tl_iSendFriendsCount=Number(to_recipient);
		}
		show_msg_report("","","2","Continue send friend from recipient: "+ct_tl_iSendFriendsCount+1);

		setTimeout(function () {
			send_my_broadcastline_continue(ct_tl_iSendFriendsCount);
		}, 2000);
	}
}
function stop_broadcast(){
	Swal.fire({
		title: window.lang.translate('Do you want to stop this the transaction?'),
		text: window.lang.translate('Do you want to stop this the transaction?'),
		type: 'warning',
		//footer: footer_swal(),
		showCancelButton: true,
		confirmButtonColor: '#3085d6',
		cancelButtonColor: '#d33',
		confirmButtonText: window.lang.translate('Yes'),
		cancelButtonText: window.lang.translate('Cancel')
	}).then((result) => {
		if (result.value) {
			//console.log("stop waiting");
			document.getElementById("stop_time").innerHTML=window.lang.translate("Waiting stop");
			localStorage.setItem('setstop', 0);	//Clear stop flag
			localStorage.setItem('loops', 0);	//store sending no to local storage
			ct_tl_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);
			$('#modalGrAlert_OA_Status').text('หยุดการทำงาน');
			$('#modalGrAlert_OA_Status').css('color','white');
			
			if(ct_tl_execSetTimeout!=null){
				clearTimeout(ct_tl_execSetTimeout);
			}

			ct_tl_continue_get_friends_url="";
			ct_tl_is_finished_get_friends_list = 0;
			
			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=window.lang.translate("Stop")+" "+esttime_date_format_str;
			ct_tl_status_running=false;
			checkActionStatus();
		}
	});
}
function start_broadcast(){
	var dnow = new Date();
	var curdate = dnow.toJSON().slice(0,10);
	
	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);
			
			//$('#cfg_start_seding_no').prop('disabled',false);
			
			var my_broadcastline_idpage = $('#my_broadcastline_idpage').val();	//openoa.html account line in select input
			ct_tl_my_broadcastline_delay = $('#cfg_delay').val();//ct_tl_my_broadcastline_delay=3;
			ct_tl_cfg_max_recipients = $('#cfg_max_recipients').val();
			ct_tl_cfg_start_seding_no = $('#cfg_start_seding_no').val();
			
			if (ct_tl_my_broadcastline_delay==''){ct_tl_my_broadcastline_delay=0;}
			if (typeof ct_tl_my_broadcastline_delay=='undefined'){ct_tl_my_broadcastline_delay=0;}
			if(isNaN(ct_tl_my_broadcastline_delay)){ct_tl_my_broadcastline_delay=0;}
			ct_tl_my_broadcastline_delay = Number(ct_tl_my_broadcastline_delay);
			if(ct_tl_my_broadcastline_delay<0){ct_tl_my_broadcastline_delay=0;}
			
			if (my_broadcastline_idpage == '') {	//OA account from select input
				Swal.fire({
					title: window.lang.translate('Something went wrong'),
					type: 'error',
					html: window.lang.translate('You must first select the Line OA account'),
				})
				$('#my_broadcastline_idpage').focus();
				return false;
			}
			if ($('#my_broadcastline_select_type').val() == 2) {	//Tag
				ct_tl_my_broadcastline_label = $('#cfg_recipients_option_tag').val();	//cfg_recipients_option_tag
				let ct_tl_my_broadcastline_label_length = 1;
				if (Array.isArray(ct_tl_my_broadcastline_label)) {
					ct_tl_my_broadcastline_label_length = ct_tl_my_broadcastline_label.length;
				}
				if (ct_tl_my_broadcastline_label == '' || ct_tl_my_broadcastline_label==null || ct_tl_my_broadcastline_label_length==0) {
					if (document.getElementById('recipients_option_tag_msg').innerHTML!==''){
						Swal.fire({
							title: window.lang.translate('Something went wrong'),
							type: 'error',
							html: window.lang.translate('This account cannot find the tag you want to send'),
						})
					}else{
						Swal.fire({
							title: window.lang.translate('Something went wrong'),
							type: 'error',
							html: window.lang.translate('You must first select the Line OA account'),
						})
					}
					$('#cfg_recipients_option_tag').focus();
					return false;
				}
			}
			if ($('#my_broadcastline_select_type').val() == 1) {	//folder
				ct_tl_cfg_recipients_option_folder = $('#cfg_recipients_option_folder').val();
				if (ct_tl_cfg_recipients_option_folder == '' || ct_tl_cfg_recipients_option_folder==null) {
					Swal.fire({
						title: window.lang.translate('Something went wrong'),
						type: 'error',
						html: window.lang.translate('Select the folder you want to send'),
					});
					$('#cfg_recipients_option_folder').focus();
					return false;
				}
			}
			if ((ct_tl_my_broadcastline_delay == '') || (ct_tl_my_broadcastline_delay < 0)) {
				ct_tl_my_broadcastline_delay=0;
			}
			$('#cfg_delay').val(ct_tl_my_broadcastline_delay);
			
			
			if (typeof ct_tl_cfg_max_recipients=='undefined'){ct_tl_cfg_max_recipients=500000;}
			if ((ct_tl_cfg_max_recipients == '') || (ct_tl_cfg_max_recipients < 0)) {
				ct_tl_cfg_max_recipients=500000;
				$('#cfg_max_recipients').val(ct_tl_cfg_max_recipients);
			}
			
			if (typeof ct_tl_cfg_start_seding_no=='undefined'){ct_tl_cfg_start_seding_no=1;}
			if ((ct_tl_cfg_start_seding_no == '') || (ct_tl_cfg_start_seding_no < 0)) {
				ct_tl_cfg_start_seding_no=1;
				$('#cfg_start_seding_no').val(ct_tl_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: window.lang.translate('Something went wrong'),
							type: 'error',
							html: window.lang.translate('You have not specified a valid schedule for broadcasting'),
						});
						
						return false;
					}else{
						if (timestamp< (new Date()).getTime()){
							Swal.fire({
								title: window.lang.translate('Something went wrong'),
								type: 'error',
								html: window.lang.translate('Please specify the time of the schedule that will be broadcast more than the current time'),
							});
							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: window.lang.translate('Something went wrong'),
					type: 'error',
					html: window.lang.translate('You have not entered a message or choosed the file you want to send'),
				});
				$('#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'){
					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')
				{
					if(my_broadcastline_text_check.value!=""){
						bpass=true;
						break;
					}
				}

				let my_broadcastline_card=document.getElementById("edit_"+myOLBroadcastTable_check.rows[irow_check].id+"col3");	//file id file-row1col2
				if (typeof my_broadcastline_card!=='undefined' && my_broadcastline_card!=null && my_broadcastline_card.value != '') {
					my_broadcastline_card = $("#edit_"+myOLBroadcastTable_check.rows[irow_check].id+"col3").val();	//value
					if(typeof my_broadcastline_card!="undefined" && my_broadcastline_card!=null && my_broadcastline_card!=""){
						my_broadcastline_card = my_broadcastline_card.split('|')[0];	//id
					}else{
						my_broadcastline_card="";
					}
				}else{
					my_broadcastline_card="";
				}
				if(typeof my_broadcastline_card=='undefined' || my_broadcastline_card==null){my_broadcastline_card="";}
				my_broadcastline_card=my_broadcastline_card.trim();
				if(my_broadcastline_card!=''){
					bpass=true;
					break;
				}
				
				let my_broadcastline_rich=document.getElementById("edit_"+myOLBroadcastTable_check.rows[irow_check].id+"col4");
				if (typeof my_broadcastline_rich!=='undefined' && my_broadcastline_rich!=null && my_broadcastline_rich.value != '') {
					my_broadcastline_rich = $("#edit_"+myOLBroadcastTable_check.rows[irow_check].id+"col4").val();	//value
					if(typeof my_broadcastline_rich!="undefined" && my_broadcastline_rich!=null && my_broadcastline_rich!=""){
						my_broadcastline_rich = my_broadcastline_rich.split('|')[0];	//id
					}else{
						my_broadcastline_rich="";
					}
				}else{
					my_broadcastline_rich="";
				}
				if(typeof my_broadcastline_rich=='undefined' || my_broadcastline_rich==null){my_broadcastline_rich="";}
				my_broadcastline_rich=my_broadcastline_rich.trim();
				if(my_broadcastline_rich!=''){
					bpass=true;
					break;
				}
				irow_check++;
			}
			 
			
			if(bpass==false){
				Swal.fire({
					title: window.lang.translate('Something went wrong'),
					type: 'error',
					html: window.lang.translate('You have not entered a message or choosed the file you want to send'),
				})
				$('#text_add').focus();
				return false;
			}
			
			///////////////
			///////////////
			ct_tl_send_txt_err_count = 0;
			
			if($('#fanpage_OA_inbox_friend_ids_send_input').val().replace('\n').trim()!='' && permission_extract_member==1){
				//generate input data;
				await generateInputData();
				ct_tl_label_user_all_copy = await uniqueByKey(ct_tl_label_user_all, 'id');
				if (ct_tl_label_user_all_copy.length>0){
					ct_tl_label_user_all_copy[0].accountName = ct_tl_label_user_all[0].accountName;
					ct_tl_label_user_all_copy[0].folder = ct_tl_label_user_all[0].folder;
				}
				ct_tl_label_user_all = ct_tl_label_user_all_copy;

			}else{
				ct_tl_label_user_all = ct_tl_label_user_all_copy;	//copy data from standby to active 
			}
			
			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 ){
					ct_tl_oaAccountIdActiveName=opt.text;
					ct_tl_oaAccountActiveImg = opt.getAttribute('title');
					if(ct_tl_oaAccountActiveImg!=""){
						ct_tl_oaAccountActiveImg='<i style="justify-content:center;"><img src="'+ct_tl_oaAccountActiveImg+'" alt="oaacc-logo" id="oaacc_logo_img" style="width: 48px; height: 48px;"></i>';
					}
				}
			}
			var oaImg="";
			if(ct_tl_oaAccountActiveImg!=""){
				oaImg="<br />"+ct_tl_oaAccountActiveImg;
			}
			Swal.fire({
				title: window.lang.translate('Would you like to send this message?'),
				html: window.lang.translate("Account name")+"<br />"+oaImg+"<h2 style='color:#039639'>'"+ ct_tl_oaAccountIdActiveName +"'</h2>", 
				//type: 'warning',
				//footer: footer_swal(),
				showCancelButton: true,
				confirmButtonColor: '#3085d6',
				cancelButtonColor: '#d33',
				confirmButtonText: window.lang.translate('Yes'),
				cancelButtonText: window.lang.translate('Cancel')
			}).then((result) => {
				if (result.value) {
					
					ct_tl_cfg_start_seding_no=$('#cfg_start_seding_no').val();
					ct_tl_cfg_start_seding_no = Number(ct_tl_cfg_start_seding_no);
					
					ct_tl_cfg_max_recipients=$('#cfg_max_recipients').val();
					ct_tl_cfg_max_recipients=Number(ct_tl_cfg_max_recipients);
					
					if(ct_tl_cfg_start_seding_no>1 && ct_tl_cfg_max_recipients<ct_tl_label_user_all.length){
						Swal.fire({
							title: window.lang.translate('Confirm start broadcast'),
							html: window.lang.translate("Both start and end recipient not default value, are you sure?") +" " + ct_tl_cfg_start_seding_no + " - " + ct_tl_cfg_max_recipients, 
							showCancelButton: true,
							confirmButtonColor: '#3085d6',
							cancelButtonColor: '#d33',
							confirmButtonText: window.lang.translate('Yes'),
							cancelButtonText: window.lang.translate('Cancel')
						}).then((result2) => {
							if (result2.value) {
								runBroadcastTL();
							}else{
								document.getElementById("cfg_start_seding_no").focus();
							}
						});
					}else if(ct_tl_cfg_start_seding_no>1){
						Swal.fire({
							title: window.lang.translate('Confirm start broadcast'),
							html: window.lang.translate("Start recipient not the first, are you sure?") +" " + ct_tl_cfg_start_seding_no, 
							showCancelButton: true,
							confirmButtonColor: '#3085d6',
							cancelButtonColor: '#d33',
							confirmButtonText: window.lang.translate('Yes'),
							cancelButtonText: window.lang.translate('Cancel')
						}).then((result2) => {
							if (result2.value) {
								runBroadcastTL();
							}else{
								document.getElementById("cfg_start_seding_no").focus();
							}
						});
					}else if(ct_tl_cfg_max_recipients<ct_tl_label_user_all.length){
						Swal.fire({
							title: window.lang.translate('Confirm start broadcast'),
							html: window.lang.translate("End recipient less than broadcast data, are you sure?") +" " + ct_tl_cfg_max_recipients + " < "+ ct_tl_label_user_all.length, 
							showCancelButton: true,
							confirmButtonColor: '#3085d6',
							cancelButtonColor: '#d33',
							confirmButtonText: window.lang.translate('Yes'),
							cancelButtonText: window.lang.translate('Cancel')
						}).then((result2) => {
							if (result2.value) {
								runBroadcastTL();
							}else{
								document.getElementById("cfg_max_recipients").focus();
							}
						});
					}else{
						runBroadcastTL();
					}
					
				}
			});
	});
	
}

function runBroadcastTL(){
	showStart_Broadcast_Button();

	$('#footer-summary-container').show();
	$('#close-x').show();
	$('#open-o').hide();
	
	if(document.getElementById('cfg_schedule_later').checked){
		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(true);	//pop.js
		
	}
}


(() => { function fn() {
		var modal = document.getElementById('modalid01');

		window.onclick = function(event) {
			if (event.target == modal) {
				modal.style.display = "none";
			}
		}
		
		showStart_Broadcast_Button();
		
	};  
	if (document.readyState != 'loading') {fn()}
	else {
		document.addEventListener('DOMContentLoaded', fn);
	}
})();

function readyJQuery(){
	console.log("readyJQuery");
				
	$('#dtschedule').on('click', '', function () {
		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 });
	});
	
	$('#save_table').on('click','',function(){
		saveTable(this);
	});
	$('#restore_table').on('click','',function(){
		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();
	});
	$("#header_colp").on("click", function (e) {
		if($("#header_colp").attr('title')=="ย่อส่วนหัว"){
			$("#header_colp").removeClass("fa fa-angle-double-up");
			$("#header_colp").addClass("fa fa-angle-double-down");
			$("#header_colp").attr('title', "ขยายส่วนหัว");
			$("#fixed_header_container").css('height', '30px');
		}else{
			$("#header_colp").removeClass("fa fa-angle-double-down");
			$("#header_colp").addClass("fa fa-angle-double-up");
			$("#header_colp").attr('title', "ย่อส่วนหัว");
			$("#fixed_header_container").css('height', 'auto');
		}
		/*
		chrome.runtime.sendMessage(
			{
				contentScriptQuery: 'fetchUrl',
				applicationcode: 'VALIDAPPLICATIONKEY'
			},
			response => parsePrice(response.text())
		);
		*/
	});
	
	
	$("#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();
	});
	
	//counterchar
	$("#add_new_item").on("click", function (e) {
		e.stopImmediatePropagation();
		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(window.lang.translate("Please specify a message or choose a file to send"));
			return;
		}else{
			if($('#text_add').val()!=""){
				let lengthCount = $('#text_add').val().length; 
				if (lengthCount > ct_tl_maxLimitChar) {
					$('#text_add').val($('#text_add').val().substring(0, ct_tl_maxLimitChar));
					let charactersOver = (lengthCount + 1) - ct_tl_maxLimitChar;
					alert("ข้อความจำกัดอยู่ที่ 2,000 ตัวอักษร ตอนนี้เกินไป "+charactersOver+ "ตัวอักษร โปรแกรมได้ทำการตัดข้อความให้บางส่วนแล้ว ลองตรวจสอบแล้วกดเพิ่มอีกครั้ง");
					return;
				}
			}
			addNewRow(true);
			$("#text_add").title=window.lang.translate("F7");
		}
		return true;
	});
	
	$("#add_to_table").on("click", function (e) {
		e.stopImmediatePropagation();
		addNewRow(false);
	});
	
	$("#file_file_add_container").on("click", function (e) {
		document.getElementById('file-file_add_container').click();
	});
	
	$("#pause_broadcast").on("click", async function (e) {
		e.preventDefault();
		pause_broadcast();
		e.stopImmediatePropagation();
		e.stopPropagation();
	});
	
	$('#start_broadcast').on('click', function (e) {
		e.preventDefault();
		start_broadcast();
		e.stopImmediatePropagation();
		e.stopPropagation();
	});
	
	$("#continue_broadcast").on("click", function (e) {
		e.preventDefault();
		continue_broadcast();
		e.stopImmediatePropagation();
		e.stopPropagation();
	});
	
	$('#stop_broadcast').on('click', function (e) {
		e.preventDefault();
		stop_broadcast();
		e.stopImmediatePropagation();
		e.stopPropagation();
	});
	
	
	$("#pause_broadcast_GrAlert").on("click", async function (e) {
		e.preventDefault();
		pause_broadcast();
		e.stopImmediatePropagation();
		e.stopPropagation();
	});
	$("#continue_broadcast_GrAlert").on("click", async function (e) {
		e.preventDefault();
		continue_broadcast();
		e.stopImmediatePropagation();
		e.stopPropagation();
	});
	$("#stop_broadcast_GrAlert").on("click", async function (e) {
		e.preventDefault();
		stop_broadcast();
		e.stopImmediatePropagation();
		e.stopPropagation();
	});
	
	$("#btn_menu_manual_oa_tl").on("click", function (e) {
		try{
			manual_detail();	//from host customer.js
		}catch(e){
			alert('Error:'+e);
		}
	});
	$("#btn_menu_contact_oa_tl").on("click", function (e) {
		try{
			contact_detail();	//from host customer.js
		}catch(e){
			alert('Error:'+e);
		}
	});
	$("#btn_menu_moreinfo_oa_tl").on("click", function (e) {
		try{
			moreinfo_detail();	//from host customer.js
		}catch(e){
			alert('Error:'+e);
		}
	});
	$("#btn_menu_downloadapp_oa_tl").on("click", function (e) {
		try{
			download_software();	//from host customer.js
		}catch(e){
			alert('Error:'+e);
		}
	});
	
	
}

async function getAllStorage() {
    var archive = [],
        keys = Object.keys(localStorage),
        i = 0, key;
	return new Promise(function (resolve) {
		for (; key = keys[i]; i++) {
			if(key){
				if(key.charAt(0)=="U"){
					archive.push( localStorage.getItem(key) );
				}
			}
		}
		resolve(archive);
	});
}

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(() => {
			resolve(true);
		});
	});
}

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();
	var 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);
		
		document.getElementById("schedule_running").innerHTML = (days).pad() + "d "+(hours).pad() + "h "+(minutes).pad() + "m "+(seconds).pad() + "s ";
		if (timeleft < 0) {
			clearInterval(schTimeLeft);
			document.getElementById("schedule_running").innerHTML = "";
			document.getElementById("end").innerHTML = window.lang.translate("TIME UP!!");
			setTimeout(function () {
				document.getElementById('modalidSchedule').style.display='none';
				send_my_broadcastline_start(true);
			}, 2000);
			
		}
	}, 1000);
}

function setStopJob(loop,isShowContinue,actionFlagStopPauseDone){	//0=stop,1=working,2=pause,3=done
	return new Promise(resolve => {
		ct_tl_status_running=false;
		try{
			if(typeof loop =="undefined"){loop=0;}
			if(loop<0){loop=0;}
			if(typeof actionFlagStopPauseDone =="undefined"){actionFlagStopPauseDone=3;}
			if(isShowContinue){
				ct_tl_status_stop_pause = 2;
			}else{
				if(actionFlagStopPauseDone==0){
					ct_tl_status_stop_pause = 0;
					document.getElementById("modalGrAlert").style.display = "none";
				}else{
					ct_tl_status_stop_pause = 3;	//done
					document.getElementById("modalGrAlert").style.display = "none";
				}
			}
			localStorage.setItem('setstop', ct_tl_status_stop_pause);	//Clear stop flag
			localStorage.setItem('loops', loop);	//store sending no to local storage
			
			setStopClock();
			var dnow = new Date();
			var curdate = dnow.toJSON().slice(0,10);
			curdate = ct_tl_server_date;	//Hack server yyyy-mm-dd

			if(ct_tl_user_type=="ทดลองใช้งาน" && Number(ct_tl_demo_ratelimit)>0){
				ct_tl_demo_usage_ratelimit_left = Number(ct_tl_demo_ratelimit) - Number(ct_tl_demo_usage_ratelimit);
				document.getElementById('plan_package').innerHTML="plan "+ct_tl_user_type+ " "+window.lang.translate("Time left")+" "+ ct_tl_demo_usage_ratelimit_left +" "+window.lang.translate("Messages per day");
				document.getElementById('plan_demo_package').innerHTML=document.getElementById('plan_package').innerHTML
	
				ldb.set('demo_usage_ratelimit_'+ct_tl_user_name, ct_tl_demo_usage_ratelimit+'|'+curdate+'|'+ ct_tl_demo_usage_ratelimit_left+'|'+ct_tl_demo_ratelimit);
			}
			
			showStart_Broadcast_Button();
			
			document.getElementById('clock_status').innerHTML="stopped";	//window.lang.translate("Stop");
			
			if(typeof isShowContinue=="undefined"){isShowContinue=false;}
			if(isShowContinue){
				pressPause_Broadcast_Button();
				
			}else{
				showStart_Broadcast_Button();
				
				document.getElementById("modalGrAlert").style.display = "none";
			}
			
			// if(actionFlagStopPauseDone=3){
			// 	let icount =localStorage.getItem('loops');
			// 	if (icount!=null){
			// 		ct_tl_iSendFriendsCount = Number(icount);
			// 	}
			// 	show_msg_report("","","2",window.lang.translate("Stop")+" "+window.lang.translate("Person number")+' '+ ct_tl_iSendFriendsCount );
			// }
			if(ct_tl_status_stop_pause==0 || ct_tl_status_stop_pause==2 || ct_tl_status_stop_pause==3){
				let done_text = "ยังไม่เสร็จ";
				if(ct_tl_status_stop_pause==0){
					done_text = "หยุดทำงาน";
					$('#get_line_fanpage').show();
					// let icount =localStorage.getItem('loops');
					// if (icount!=null){
					// 	ct_tl_iSendFriendsCount = Number(icount);
					// }
					// show_msg_report("","","2",done_text+" "+window.lang.translate("Person number")+' '+ ct_tl_iSendFriendsCount );
					
				}else if(ct_tl_status_stop_pause==2){
					done_text = "หยุดชั่วคราว";
				}else if(ct_tl_status_stop_pause==3){
					done_text = "สำเร็จ";
					$('#get_line_fanpage').show();
				}
				if(ct_tl_label_user_all.length>0){
					$('#download_oa_fanpage_members').attr("title","Download friends from "+ct_tl_my_broadcastline_label_name+ " " + ct_tl_label_user_all.length + " Persons "+done_text);
					$('#download_oa_fanpage_members').show();
				}else{
					$('#download_oa_fanpage_members').hide();
				}
				if(ct_tl_label_user_all_send_success.length>0){
					$('#download_oa_fanpage_success_members').attr("title","Download friends from "+ct_tl_my_broadcastline_label_name+ " " + ct_tl_label_user_all_send_success.length + " Persons "+done_text);
					$('#download_oa_fanpage_success_members').show();
				}else{
					$('#download_oa_fanpage_success_members').hide();
				}
				if(ct_tl_label_user_all_send_failed.length>0){
					$('#download_oa_fanpage_failed_members').attr("title","Download friends from "+ct_tl_my_broadcastline_label_name+ " " + ct_tl_label_user_all_send_failed.length + " Persons "+done_text);
					$('#download_oa_fanpage_failed_members').show();
				}else{
					$('#download_oa_fanpage_failed_members').hide();
				}
				ct_tl_label_user_all_copy = ct_tl_label_user_all;
			}else{
				$('#download_oa_fanpage_members').hide();
				$('#download_oa_fanpage_success_members').hide();
				$('#download_oa_fanpage_failed_members').hide();
				$('#get_line_fanpage').hide();
			}
		}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";	//window.lang.translate("Stop");
		}
	}
}

function pressPause_GrAlert_Button(){
	//$('#pause_broadcast_GrAlert').prop('disabled',true);
	$('#pause_broadcast_GrAlert').hide();
	$('#stop_broadcast_GrAlert').show();
	$('#continue_broadcast_GrAlert').show();
	$('#pause_broadcast_GrAlert').css('background-color', '#464343');
}
function pressContinue_GrAlert_Button(){
	$('#pause_broadcast_GrAlert').css('background-color', '#464343');
	$('#pause_broadcast_GrAlert').css('cursor', 'pointer');
	$('#pause_broadcast_GrAlert').prop('disabled',false);
	$('#pause_broadcast_GrAlert').show();
	$('#stop_broadcast_GrAlert').show();
	$('#continue_broadcast_GrAlert').hide();
}

function showStart_Broadcast_Button(){
	$('#start_broadcast').show();
	$('#pause_broadcast').hide();			
	$('#stop_broadcast').hide();
	$('#continue_broadcast').hide();
}
function pressStart_Broadcast_Button(){
	$('#start_broadcast').hide();
	$('#continue_broadcast').hide();
	//$('#download_oa_fanpage_members').hide();
	$('#download_oa_fanpage_success_members').hide();
	$('#download_oa_fanpage_failed_members').hide();
	$('#pause_broadcast_GrAlert').css('background-color', '#464343');
	$('#pause_broadcast_GrAlert').css('cursor', 'pointer');
}
function pressPause_Broadcast_Button(){
	$('#start_broadcast').hide();
	$('#pause_broadcast').hide();
	$('#continue_broadcast').hide();
	$('#pause_broadcast_GrAlert').prop('disabled',true);
	$('#pause_broadcast_GrAlert').css('background-color', '#d7c9c9');
	$('#pause_broadcast_GrAlert').css('cursor', 'not-allowed');
	//$('#pause_broadcast_GrAlert').hide();
}


async function checkActionStatus(){
	return new Promise(function (resolve) {
		let actStatus = ct_tl_status_stop_pause;
		//if (typeof actStatus=="undefined" || actStatus==""){
		//	actStatus=1;
		//}
		
		try{
			actStatus=parseInt(actStatus);
		}catch(e){
			actStatus=1;
		}

		if (actStatus == 3) {	//job done
			
			setStopClock();
			iziToast.info({
				title: window.lang.translate('Job completed'),
				position: 'topLeft',
				timeout: 5000,
				message: '',
			});
			
			showStart_Broadcast_Button();
			
			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 = window.lang.translate("Completed")+" " + esttime_date_format_str;
			document.getElementById("clock").innerHTML = window.lang.translate("Completed")+" " + esttime_date_format_str;
			ct_tl_status_running=false;
			
			resolve(0);
		}else if (actStatus == 0) {	//press stop button
			setStopClock();
			iziToast.info({
				title: window.lang.translate('Has stopped working successfully'),
				position: 'topLeft',
				timeout: 5000,
				message: '',
			});
			
			showStart_Broadcast_Button();
			
			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 = window.lang.translate("Stop")+" " + esttime_date_format_str;
			document.getElementById("clock").innerHTML = window.lang.translate("Stop")+" " + esttime_date_format_str;
			ct_tl_status_running=false;
			
			//return 0;
			resolve(0);
		}else if (actStatus == 2) {	//press pause button
			
			setStopClock();
			
			iziToast.info({
				title: window.lang.translate('Pause'),
				position: 'topLeft',
				timeout: 5000,
				message: '',
			});
			
			pressPause_Broadcast_Button();
			//pressPause_GrAlert_Button();
			
			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=window.lang.translate('Pause')+" " + esttime_date_format_str;
			ct_tl_status_running=false;
			
			resolve(2);
		}else{
			resolve(1);
		}
	});
}

///////////////////////////////////////
////// SEND Message Here /////////////
function send_my_broadcastline_start(iswith_sendmsg) {
	ct_tl_status_running=false;
	if ($('#my_broadcastline_select_type').val() == 2) {	//Tag
		ct_tl_my_broadcastline_label = $('#cfg_recipients_option_tag').val();	//cfg_recipients_option_tag
		let ct_tl_my_broadcastline_label_length = 1;
		if (Array.isArray(ct_tl_my_broadcastline_label)) {
			ct_tl_my_broadcastline_label_length = ct_tl_my_broadcastline_label.length;
		}
		if (ct_tl_my_broadcastline_label == '' || ct_tl_my_broadcastline_label==null || ct_tl_my_broadcastline_label_length==0) {
			if (document.getElementById('recipients_option_tag_msg').innerHTML!==''){
				Swal.fire({
					title: window.lang.translate('Something went wrong'),
					type: 'error',
					html: window.lang.translate('This account cannot find the tag you want to send'),
				})
			}else{
				Swal.fire({
					title: window.lang.translate('Something went wrong'),
					type: 'error',
					html: window.lang.translate('You must first select the Line OA account'),
				})
			}
			$('#cfg_recipients_option_tag').focus();
			return false;
		}
	}
	check_net().then((data) =>{
		try{
			lockedScreen();
		}catch(ex){
		}
		sending_my_broadcastline_start(iswith_sendmsg);
	}).catch((error) =>{
		console.log(error);
		
		pressStart_Broadcast_Button();
		
		$('#close-x').hide();
		$('#open-o').show();
		
		setStopJob(0,false,0);

		$('#error_x_report').hide();
		$('#error_report').show();
		$('#txt_error_report').hide();
		
		show_msg_report("","","1",window.lang.translate("Unabled to communicate with LINE OA"));
		
		alert(window.lang.translate("Unabled to communicate with LINE OA"));
		
		return
	});
	//////////////////////////////////////
}

////GET FRIENDS INSIDE THIS FUNCTION ////
function sending_my_broadcastline_start(iswith_sendmsg,is_continue_get_friends){
	ct_tl_status_running=false;
	localStorage.setItem('setstop', 1);	//Clear stop flag
	ct_tl_status_stop_pause = 1;
	
	pressStart_Broadcast_Button();
	
	/*
	ct_tl_iProgressAllItemsCount=0;
	ct_tl_itemsSendErrorCount=0;
	ct_tl_iTableAllItems=0;
	ct_tl_prev_friend_loop=-1;
	ct_tl_send_txt_err_count=0;
	ct_tl_iMessNoActive=0;
	ct_tl_iTotalMesageMustSend=0;
	ct_tl_iSendFriendsCount=0;
	ct_tl_iCountAgv=0;
	
	ct_tl_label_user_all_send_success = [];
	ct_tl_label_user_all_send_failed = [];
	ct_tl_lable_user_all_send_skip = [];
	*/
	
	ct_tl_MsgCircleSend_counter = 1;
	ct_tl_my_broadcastline_label_name="";
	ct_tl_my_broadcastline_select_index=0;
	
	ct_tl_tag_list=[];
	
	removeDownloadSuccessLink();
	removeDownloadFailedLink();
	
	let data_page_icon = "";
	try{data_page_icon = $("#my_broadcastline_idpage option:selected").attr("data-icon");}catch(ee){}
	
	var page_count=0;
	var elem = document.getElementById("myProgress");
	if(typeof elem!=="undefined" && elem!=null){
		elem.style.display="block";
	}

	count_my_broadcastline_success = 0;
	ct_tl_iTableAllItems=0; 
	getAllItemsPromise().then(x => ct_tl_iTableAllItems=x);
	
	var line_biz=window.location.href.split('.biz/');
	if(typeof line_biz!=="undefined" && line_biz!=null && line_biz.length>1){
		ct_tl_my_broadcastline_idpage_token = window.location.href.split('.biz/')[1].split('/')[0];
	}
	
	let sel=document.getElementById("my_broadcastline_idpage");
	let opt = sel.options[sel.selectedIndex];
	ct_tl_my_broadcastline_select_index = sel.selectedIndex;
	
	if(typeof opt!=="undefined" && opt!=null ){
		ct_tl_my_broadcastline_idpage_token=opt.getAttribute('data-botId');
	}
	ct_tl_my_broadcastline_label_name = $('#my_broadcastline_idpage').val();	//name
	if(typeof ct_tl_my_broadcastline_label_name!="undefined" && ct_tl_my_broadcastline_label_name!=null && ct_tl_my_broadcastline_label_name!=""){
		ct_tl_my_broadcastline_label_name = $('#my_broadcastline_idpage').val().split('|')[1];	//name
	}

	ct_tl_my_broadcastline_label = $('#cfg_recipients_option_folder').val().split('|')[0];
	ct_tl_my_broadcastline_name = $('#cfg_recipients_option_folder').val().split('|')[1];
	try{ct_tl_my_broadcastline_name = $( "#cfg_recipients_option_folder option:selected" ).text();}catch(e){}
	
	try{
		ct_tl_cfg_max_recipients = $('#cfg_max_recipients').val();
		ct_tl_cfg_max_recipients = Number(ct_tl_cfg_max_recipients);
		if(ct_tl_cfg_max_recipients<1){
			ct_tl_cfg_max_recipients=500000;
			$('#cfg_max_recipients').val(ct_tl_cfg_max_recipients);
		}
		ct_tl_cfg_max_recipients = parseInt(ct_tl_cfg_max_recipients);
	}catch(e){
		ct_tl_cfg_max_recipients=500000;
		$('#cfg_max_recipients').val(ct_tl_cfg_max_recipients);
	}
	
	var url="";
	var url2="";
	
	//https://chat.line.biz/U97028224c1aae20d338854c5273f9ef3/contact
	if ($('#my_broadcastline_select_type').val() == 1) {	//folder
		url = 'https://chat.line.biz/api/v2/bots/' + ct_tl_my_broadcastline_idpage_token + '/chats?' + ct_tl_my_broadcastline_label + '&tagIds=&autoTagIds=&limit=25&prioritizePinnedChat=true';
		//url = 'https://chat.line.biz/api/v1/bots/' + ct_tl_my_broadcastline_idpage_token + '/chats?' + ct_tl_my_broadcastline_label + '&tagIds=&limit=25';
		//url2 = 'https://chat.line.biz/api/v1/bots/' + ct_tl_my_broadcastline_idpage_token + '/chats?' + ct_tl_my_broadcastline_label + '&tagIds=&autoTagIds=&limit=25&next=';
		url2 = 'https://chat.line.biz/api/v2/bots/' + ct_tl_my_broadcastline_idpage_token + '/chats?' + ct_tl_my_broadcastline_label + '&tagIds=&autoTagIds=&limit=25&next=';
	} else {	//tag
	
		cfg_recipients_option_tag = $('#cfg_recipients_option_tag').val();
		$('#cfg_recipients_option_tag :selected').each(function(i, value){
			cfg_recipients_option_tag = value.value;
			let urlStart = 'https://chat.line.biz/api/v2/bots/' + ct_tl_my_broadcastline_idpage_token + '/chats?' + ct_tl_my_broadcastline_label + '&tagIds=' + cfg_recipients_option_tag + '&autoTagIds=&limit=25';
			//let urlStart = 'https://chat.line.biz/api/v1/bots/' + ct_tl_my_broadcastline_idpage_token + '/chats?' + ct_tl_my_broadcastline_label + '&tagIds=' + cfg_recipients_option_tag + '&limit=25';
			//let urlNext = 'https://chat.line.biz/api/v1/bots/' + ct_tl_my_broadcastline_idpage_token + '/chats?' + ct_tl_my_broadcastline_label + '&tagIds=' + cfg_recipients_option_tag + '&autoTagIds=&limit=25&next=';
			let urlNext = 'https://chat.line.biz/api/v2/bots/' + ct_tl_my_broadcastline_idpage_token + '/chats?' + ct_tl_my_broadcastline_label + '&tagIds=' + cfg_recipients_option_tag + '&autoTagIds=&limit=25&next=';
			ct_tl_tag_list.push({id:value.value,label:value.text,url:urlStart,urlNext:urlNext});
		});
		if(ct_tl_tag_list.length>0){
			cfg_recipients_option_tag = ct_tl_tag_list[0].id;	//start index 0
			url = ct_tl_tag_list[0].url;
			url2 = ct_tl_tag_list[0].urlNext;
		}
		
		//url = 'https://chat.line.biz/api/v1/bots/' + ct_tl_my_broadcastline_idpage_token + '/chats?' + ct_tl_my_broadcastline_label + '&tagIds=' + cfg_recipients_option_tag + '&limit=25';
		//url2 = 'https://chat.line.biz/api/v1/bots/' + ct_tl_my_broadcastline_idpage_token + '/chats?' + ct_tl_my_broadcastline_label + '&tagIds=' + cfg_recipients_option_tag + '&limit=25&next=';
	}
	
	pressContinue_GrAlert_Button();
	if(typeof is_continue_get_friends!=="undefined" && is_continue_get_friends!=null && is_continue_get_friends==true && ct_tl_continue_get_friends_url!=""){
		get_start_line_oa_friends_list(ct_tl_continue_get_friends_url);
	}else{
		$('#txt_error_report').html("");
		document.getElementById("txt_error_report").value="";

		$('#error_x_report').hide();
		$('#error_report').show();
		$('#txt_error_report').hide();
		
		clearSummary();
		
		if(ct_tl_lineCSRF==""){
			getLineCSRF();
		}else{
			get_start_line_oa_friends_list(url);
		}
	}
	
	function getLineCSRF(){
		try{
			//const UNSENT = 0; // initial state
			//const OPENED = 1; // open called
			//const HEADERS_RECEIVED = 2; // response headers received
			//const LOADING = 3; // response is loading (a data packed is received)
			//const DONE = 4; // request complete
			//const ASYNC = false;
			//const ASYNC = true;
			
			$.getJSON("https://chat.line.biz/api/v1/csrfToken", function (results) {
				try{
					ct_tl_lineCSRF="";
					if (results) {
						ct_tl_lineCSRF = results.token;
						if(typeof ct_tl_lineCSRF=="undefined"){ct_tl_lineCSRF="";}
						if(ct_tl_lineCSRF!==""){
							get_start_line_oa_friends_list(url);
						}else{
							iziToast.error({
								title: window.lang.translate("User token could not be loaded, please try again"),
								position: 'topRight',
								timeout: 3000,
								message: '',
							});
							setStopJob(0,false,0);
							alert(window.lang.translate('User token could not be loaded'));
							ct_tl_status_running=false;
							return;
						}
					}else{
						iziToast.error({
							title: window.lang.translate("User token could not be loaded, please try again"),
							position: 'topRight',
							timeout: 3000,
							message: '',
						});
						setStopJob(0,false,0);
						alert(window.lang.translate('User token could not be loaded'));
						ct_tl_status_running=false;
						return;
					}
					
				}catch(error){
					console.log(error);
					iziToast.error({
						title: window.lang.translate("User token could not be loaded, please try again"),
						position: 'topRight',
						timeout: 3000,
						message: '',
					});
					setStopJob(0,false,0);
					alert(window.lang.translate('User token could not be loaded')+' ' +error.message);
					
					return;
				}
			})
			.fail(function(err) {
				console.log(err);
				iziToast.error({
					title: window.lang.translate("User token could not be loaded, please try again"),
					position: 'topRight',
					timeout: 3000,
					message: '',
				});
				setStopJob(0,false,0);
				alert(window.lang.translate('User token could not be loaded')+' ' +err.message);
				return;
			});
			
		}catch(err){
			iziToast.error({
				title: window.lang.translate("User token could not be loaded, please try again"),
				position: 'topRight',
				timeout: 3000,
				message: '',
			});
			setStopJob(0,false,0);
			alert (window.lang.translate("Gathering people to send trouble")+' '+err.message);
			ct_tl_status_running=false;
			return;
		}
	}
		
	function get_start_line_oa_friends_list(url){
		ct_tl_my_broadcastline_label = $('#cfg_recipients_option_folder').val().split('|')[0];
		ct_tl_my_broadcastline_name = $('#cfg_recipients_option_folder').val().split('|')[1];
		try{ct_tl_my_broadcastline_name = $( "#cfg_recipients_option_folder option:selected" ).text();}catch(e){}
		ct_tl_cfg_recipients_option_folder_selectedIndex=document.getElementById("cfg_recipients_option_folder").selectedIndex;	//except tag
		ct_tl_txt_error_report=document.getElementById('txt_error_report');
		let my_broadcastline_select_type_val = $('#my_broadcastline_select_type').val();
		let my_recipients_option_tag = $('#cfg_recipients_option_tag').val();
		let texts = "";
		$('#cfg_recipients_option_tag :selected').each(function(i, value){
			if(texts!=""){
				texts += ','+value.value;
			}else{
				texts += value.value;
			}
		});
		my_recipients_option_tag = texts;
		
		//cfg_recipients_option_tag
		if( (
				(ct_tl_my_prev_broadcastline_idpage_token!=ct_tl_my_broadcastline_idpage_token || ct_tl_cfg_prev_recipients_option_folder!=ct_tl_my_broadcastline_label) 
				|| ct_tl_label_user_all.length==0 
				|| my_broadcastline_select_type_val!=ct_tl_my_prev_broadcastline_select_type
				|| ct_tl_my_prev_cfg_recipients_option_tag!=my_recipients_option_tag
				|| ct_tl_is_finished_get_friends_list<2
			)	&& (!(iswith_sendmsg==true && $('#fanpage_OA_inbox_friend_ids_send_input').val().replace('\n').trim()!='') )
		){
			if(ct_tl_is_finished_get_friends_list<2 && ct_tl_continue_get_friends_url!=""){
			}else{
				ct_tl_acc_all_count=0;
				ct_tl_inactive_friends_count=0;
				ct_tl_problem_userId_count=0;
				ct_tl_active_friends_count=0;
				
				ct_tl_iProgressAllItemsCount=0;
				ct_tl_itemsSendErrorCount=0;
				//ct_tl_iTableAllItems=0; 
				ct_tl_prev_friend_loop=-1;
				ct_tl_send_txt_err_count=0;
				ct_tl_iMessNoActive=0;
				ct_tl_iTotalMesageMustSend=0;
				ct_tl_iSendFriendsCount=0;
				ct_tl_iCountAgv=0;
				
				ct_tl_label_user_all = [];
				ct_tl_label_user_inactive = [];
				ct_tl_label_user_id_problem = [];
				ct_tl_label_user_all_send_success = [];
				ct_tl_label_user_all_send_failed = [];
				//ct_tl_lable_user_all_send_skip = [];
				ct_tl_label_user_all_copy = [];
			}
			
			ct_tl_my_prev_broadcastline_idpage_token = ct_tl_my_broadcastline_idpage_token;
			ct_tl_cfg_prev_recipients_option_folder = ct_tl_my_broadcastline_label;
			ct_tl_my_prev_broadcastline_select_type = my_broadcastline_select_type_val;
			ct_tl_my_prev_cfg_recipients_option_tag = my_recipients_option_tag;
			
			var modalGrAlert = document.getElementById("modalGrAlert");
			modalGrAlert.style.display = "flex";	//"block";
			$('#page_image').prop("src", data_page_icon);
			$('#my_header').text(CT_TL_APP_VERSION + ' ระบบกำลังทำงานอยู่');
			document.getElementById("modalGrAlert_OA_Account_name").innerHTML = "&nbsp;&nbsp;"+ct_tl_my_broadcastline_label_name;
			
			if(ct_tl_tag_list.length>0){
				ct_tl_tag_list.splice(0, 1);	//remove index 0
			}
		
			get_line_oa_friends_list(url,iswith_sendmsg,1);
			
		}else{
			send_init_my_broadcastline_and_begin_send(iswith_sendmsg);
		}
	}
	

	async function get_line_oa_friends_list(url,iswith_sendmsg,pagingNo=1) {
		let xfinished = 1;
		if(iswith_sendmsg==true){xfinished=1;}else{xfinished=0;}
		ct_tl_is_finished_get_friends_list = xfinished;	//0=false,false,1=false,true,2=true,false,3=true,true
		if(pagingNo==1){
			$('#fanpage_OA_inbox_friend_ids_send_input').val("");
		}
		
		console.log("ct_tl_status_stop_pause:"+ct_tl_status_stop_pause);
		
		if (ct_tl_status_stop_pause == 0) {	
			//stop
			ct_tl_continue_get_friends_url = url;
			iziToast.info({
				title: window.lang.translate('Can gather people') + " " + (ct_tl_label_user_all.length)+" /Blocked "+ct_tl_inactive_friends_count+ " /Problem "+ ct_tl_problem_userId_count+ " /Total "+ ct_tl_acc_all_count + ' '+ window.lang.translate('Ready to stop working'),
				position: 'topRight',
				timeout: 5000,
				message: '',
			});
			
			showStart_Broadcast_Button();
			setStopClock();
			ct_tl_status_running=false;
			show_msg_report("","","2",window.lang.translate("Can gather people from") + " "+ct_tl_my_broadcastline_name +" -> "+ct_tl_my_broadcastline_label_name+" Active: "+ct_tl_label_user_all.length+" /Blocked "+ct_tl_inactive_friends_count+ " /Problem "+ ct_tl_problem_userId_count+ " /Total "+ ct_tl_acc_all_count + ' '+ window.lang.translate('Ready to stop working'));
			
			return
		}else if(ct_tl_status_stop_pause == 2)	{	//pause
			ct_tl_continue_get_friends_url = url;
			iziToast.info({
				title: window.lang.translate('Can gather people') + " " + (ct_tl_label_user_all.length) +" /Blocked "+ct_tl_inactive_friends_count+ " /Problem "+ ct_tl_problem_userId_count+ " /Total "+ ct_tl_acc_all_count + ' '+ window.lang.translate("Ready to pause"),
				position: 'topRight',
				timeout: 5000,
				message: '',
			});
			
			pressPause_Broadcast_Button();
			setStopClock();
			ct_tl_status_running=false;
			show_msg_report("","","2",window.lang.translate("Can gather people from") + " "+ct_tl_my_broadcastline_name +" -> "+ct_tl_my_broadcastline_label_name+" Active: "+ct_tl_label_user_all.length+" /Blocked "+ct_tl_inactive_friends_count+ " /Problem "+ ct_tl_problem_userId_count+ " /Total "+ ct_tl_acc_all_count + ' '+ window.lang.translate('Ready to stop working'));
			
			return;
		}
		
		removeDownloadLink();
		
		//// Load friends ////
		try{
			let folder = "";
			let accountName = "";
			if(ct_tl_label_user_all.length==0){
				accountName = ct_tl_my_broadcastline_label_name;
				//folder = ct_tl_my_broadcastline_label;
				folder = await get_folder_label_tag();
			}
			$.getJSON(url, async function (results) {
				var data = results.list;
				var paging = results.next;
				let ids = "";
				$.each(data, async function (i, data) {
					var profile_userId="";
					var profile_name="";
					var profile_iconHash="";
					var lastActivityExpiresAt=(Date.now())+1000000;
					var friend=true;
					var chatType="";
					var profile_nickname = "";
					
					profile_userId="undefined"!==typeof data.profile.userId?data.profile.userId:"";
					profile_name="undefined"!==typeof data.profile.name?data.profile.name:"";
					profile_iconHash="undefined"!==typeof data.profile.iconHash?data.profile.iconHash:"";
					lastActivityExpiresAt="undefined"!==typeof data.profile.lastActivityExpiresAt?data.profile.lastActivityExpiresAt:(Date.now())+1000000;
					lastActivityExpiresAt=null!==lastActivityExpiresAt?lastActivityExpiresAt:(Date.now())+1000000;
					friend="undefined"!==typeof data.profile.friend?data.profile.friend:false;
					chatType="undefined"!==typeof data.chatType?data.chatType:"";
					
					profile_nickname="undefined"!==typeof data.profile.nickname?data.profile.nickname:"";
					
					if(typeof data.profile.userId=="undefined"){//ROOM or Group
						let friends_in_group_count = "undefined"!==typeof data.profile.count?data.profile.count:0;
						profile_userId = data.chatId;
						profile_name="undefined"!==typeof data.name?data.name:chatType;
						if(chatType=="ROOM"){
							profile_iconHash="undefined"!==typeof data.iconHash?data.iconHash:"app-assets/img/lineroom.png";
						}else{
							profile_iconHash="undefined"!==typeof data.iconHash?data.iconHash:"app-assets/img/linegroup.jpg";
						}
						friend = true;
					}
					
					if(typeof profile_nickname!="undefined"){
						if(profile_nickname!=""){
							profile_name = profile_nickname;
						}
					}
					
					ct_tl_acc_all_count++;
					//if ("active" == data.status && null != data.profile && (data.profile.friend || null == data.profile.lastActivityExpiresAt || !data.profile.friend && data.profile.lastActivityExpiresAt > Date.now())) {
					//if(profile_userId!="" && lastActivityExpiresAt > Date.now()){
					if(profile_userId!=""){
						if (data.status == 'active') {
								//
								if(ct_tl_cfg_recipients_option_folder_selectedIndex==3){
									if(data.read==true){
										//message read (already read)
										ids+=profile_userId+"\r\n";
										ct_tl_label_user_all.push({
											'id': profile_userId,
											'name': profile_name,
											'iconHash': profile_iconHash,
											'accountName':accountName,
											'folder':folder,
											'chatType':chatType
										});
									}else{
										ct_tl_acc_all_count--;
									}
								}else if(ct_tl_cfg_recipients_option_folder_selectedIndex==5){
									if(data.tagIds.length==0){
										//not member any tag
										ids+=profile_userId+"\r\n";
										ct_tl_label_user_all.push({
											'id': profile_userId,
											'name': profile_name,
											'iconHash': profile_iconHash,
											'accountName':accountName,
											'folder':folder,
											'chatType':chatType
										});
									}else{
										ct_tl_acc_all_count--;
									}
								}else{
									ids+=profile_userId+"\r\n";
									ct_tl_label_user_all.push({
										'id': profile_userId,
										'name': profile_name,
										'iconHash': profile_iconHash,
										'accountName':accountName,
										'folder':folder,
										'chatType':chatType
									});
								}
								
						}else{
							//count inactive friends
							let accountName = "";
							let folder = "";
							if(ct_tl_label_user_inactive.length==0){
								accountName = ct_tl_my_broadcastline_label_name;
								folder = ct_tl_my_broadcastline_label;
							}
							ct_tl_inactive_friends_count++;
							ct_tl_label_user_inactive.push({
								'id': profile_userId,
								'name': profile_name,
								'iconHash': profile_iconHash,
								'accountName':accountName,
								'folder':folder
							});
						}
					}else{
						ct_tl_problem_userId_count++;
						var chatType="undefined"!==typeof data.chatType?data.chatType:"";
						profile_userId="undefined"!==typeof data.chatId?data.chatId:"";
						
						if(profile_name!=""){
							let accountName = "";
							let folder = "";
							if(ct_tl_label_user_id_problem.length==0){
								accountName = ct_tl_my_broadcastline_label_name;
								folder = ct_tl_my_broadcastline_label;
							}
							
							ct_tl_label_user_id_problem.push({
								'id': profile_userId,
								'name': profile_name,
								'iconHash': profile_iconHash,
								'accountName':accountName,
								'folder':folder
							});
							if(chatType.toLowerCase() !="user"){
								show_msg_report(profile_userId,profile_name,"1","chatType:"+chatType +" " + window.lang.translate("This type of transmission is not yet supported"));
							}else{
								show_msg_report(profile_userId,profile_name,"1","chatType:"+chatType +", lastActivityExpiresAt:"+getNow(lastActivityExpiresAt) + " " + window.lang.translate("Expired or not existed"));
							}
						}
					}
					
				});

				/////////////////////////////////////
				page_count++;

				if (typeof paging != 'undefined') {
					
					if(ct_tl_label_user_all.length>(ct_tl_cfg_max_recipients)){
						//success limit by max_recipients
						title = window.lang.translate("Can gather people from")+' "' +ct_tl_my_broadcastline_name +' -> '+ ct_tl_my_broadcastline_label_name + '" ' + ct_tl_label_user_all.length+"/"+ct_tl_acc_all_count+ " Blocked:"+ct_tl_inactive_friends_count + ' page no:'+page_count + " limit:"+ct_tl_cfg_max_recipients +" Persons";
						try{
							iziToast.info({
								title: '',
								position: 'topRight',
								timeout: 1000,
								message: title,
							});
						}catch(exc){}
						
						show_msg_report("","","2",window.lang.translate("Can gather people from") + " "+ct_tl_my_broadcastline_name +" -> "+ct_tl_my_broadcastline_label_name+" Active: "+ct_tl_label_user_all.length+" /Blocked "+ct_tl_inactive_friends_count+ " /Problem "+ ct_tl_problem_userId_count+ " /Total "+ ct_tl_acc_all_count + ' '+ window.lang.translate('Send limited messages to')+ ' '+ct_tl_cfg_max_recipients);
						
						$('#download_oa_fanpage_members').attr("title","Download friends from "+ct_tl_my_broadcastline_label_name + " limit:"+ct_tl_cfg_max_recipients);
						$('#download_oa_fanpage_members').show();
						$('#download_oa_fanpage_success_members').hide();
						$('#download_oa_fanpage_failed_members').hide();
						
						ct_tl_label_user_all_copy = await uniqueByKey(ct_tl_label_user_all, 'id');
						if (ct_tl_label_user_all_copy.length>0){
							ct_tl_label_user_all_copy[0].accountName = ct_tl_label_user_all[0].accountName;
							ct_tl_label_user_all_copy[0].folder = ct_tl_label_user_all[0].folder;
						}
						ct_tl_label_user_all = ct_tl_label_user_all_copy;
						//ct_tl_label_user_all_copy = ct_tl_label_user_all;	//copy data to new one
						send_init_my_broadcastline_and_begin_send(iswith_sendmsg);
						
					}else{
						title = window.lang.translate("Can gather people from")+' "' +ct_tl_my_broadcastline_name +' -> '+ ct_tl_my_broadcastline_label_name + '" ' + ct_tl_label_user_all.length+"/"+ct_tl_acc_all_count+ " Blocked:"+ct_tl_inactive_friends_count + ' page no:'+page_count;
						try{
							iziToast.info({
								title: '',
								position: 'topRight',
								timeout: 1000,
								message: title,
							});
						}catch(exc){}
						setTimeout(function () {
							pagingNo++;
							//https://chat.line.biz/api/v2/bots/U97028224c1aae20d338854c5273f9ef3/chats?folderType=ALL&tagIds=&autoTagIds=&limit=25&next=v2.XcrvRpLEyJJr0QbhKzw_eg.k4wcY1jKCTCN5KqwoqMoOPy3MUiT7NECy_jPs0aMFOvx94QYJe-XTRY89lzme8gtsTViUAqus-e9f5ts4cfVhzGJx292prbHOjCzoznIzJxEmME1hA-F47nlGxsC&prioritizePinnedChat=true
							get_line_oa_friends_list(url2 + '' + paging+ '&prioritizePinnedChat=true',iswith_sendmsg,pagingNo);
						}, 100);
					}
				} else {
					//Load friends success
					if(ct_tl_tag_list.length>0 && $('#my_broadcastline_select_type').val() == 2 && ct_tl_label_user_all.length<ct_tl_cfg_max_recipients){	//TAG
						url=ct_tl_tag_list[0].url;
						url2=ct_tl_tag_list[0].urlNext;
						ct_tl_tag_list.splice(0, 1);	//remove index 0
						pagingNo++;
						get_line_oa_friends_list(url,iswith_sendmsg,pagingNo);
					}else{
						if(ct_tl_label_user_all.length>(ct_tl_cfg_max_recipients)){
							//success limit by max_recipients
							title = window.lang.translate("Can gather people from")+' "' +ct_tl_my_broadcastline_name +' -> '+ ct_tl_my_broadcastline_label_name + '" ' + ct_tl_label_user_all.length+"/"+ct_tl_acc_all_count+ " Blocked:"+ct_tl_inactive_friends_count + ' page no:'+page_count + " limit:"+ct_tl_cfg_max_recipients +" Persons";
							try{
								iziToast.info({
									title: '',
									position: 'topRight',
									timeout: 1000,
									message: title,
								});
							}catch(exc){}
							
							show_msg_report("","","2",window.lang.translate("Can gather people from") + " "+ct_tl_my_broadcastline_name +" -> "+ct_tl_my_broadcastline_label_name+" Active: "+ct_tl_label_user_all.length+" /Blocked "+ct_tl_inactive_friends_count+ " /Problem "+ ct_tl_problem_userId_count+ " /Total "+ ct_tl_acc_all_count + ' '+ window.lang.translate('Send limited messages to')+ ' '+ct_tl_cfg_max_recipients);
							$('#download_oa_fanpage_members').attr("title","Download friends from "+ct_tl_my_broadcastline_label_name + " Limit: " + ct_tl_label_user_all.length);
						}else{
							$('#download_oa_fanpage_members').attr("title","Download friends from "+ct_tl_my_broadcastline_label_name + " Done: " +ct_tl_label_user_all.length);
						}
						
						$('#download_oa_fanpage_members').show();
						$('#download_oa_fanpage_success_members').hide();
						$('#download_oa_fanpage_failed_members').hide();
						ct_tl_label_user_all_copy = await uniqueByKey(ct_tl_label_user_all, 'id');
						if (ct_tl_label_user_all_copy.length>0){
							ct_tl_label_user_all_copy[0].accountName = ct_tl_label_user_all[0].accountName;
							ct_tl_label_user_all_copy[0].folder = ct_tl_label_user_all[0].folder;
						}
						ct_tl_label_user_all = ct_tl_label_user_all_copy;
						//ct_tl_label_user_all_copy = ct_tl_label_user_all;	//copy data to new one
						send_init_my_broadcastline_and_begin_send(iswith_sendmsg);
					}
				}
				
			}).fail(function(err) {
				console.log(err);
				iziToast.error({
					title: window.lang.translate("Gathering people to send trouble"),
					position: 'topRight',
					timeout: 3000,
					message: '',
				});
				setStopJob(0,false,0);
				try{
					show_msg_report("","","1",window.lang.translate("Gathering people to send trouble") + " Status:"+err.status +" " + err.responseJSON);
				}catch(ee){}
				alert (window.lang.translate("Gathering people to send trouble")+' '+ err.status +":"+ err.responseJSON+ ":"+err.message);
				ct_tl_status_running=false;
				return;
			});
			
		}catch(error){
			console.log(error);
			setStopJob(0,false,0);
			if (chrome.runtime.lastError){
				alert (chrome.runtime.lastError);
			}else{
				alert(error);
			}
			ct_tl_status_running=false;
			return;
		}
		
	}
	
	
	//////////////////////////////////
	//// INIT SEND BROADCAST ////
	async function send_init_my_broadcastline_and_begin_send(iswith_sendmsg){

		let xfinished = 3;
		if(iswith_sendmsg==true){xfinished=3;}else{xfinished=2;}
		ct_tl_is_finished_get_friends_list = xfinished;	//0=false,false,1=false,true,2=true,false,3=true,true
		ct_tl_continue_get_friends_url = "";
		
		/*
		if($('#fanpage_OA_inbox_friend_ids_send_input').val().replace('\n').trim()!='' && iswith_sendmsg==true && permission_extract_member==1){
			//generate input data;
			await generateInputData();
		}else{
			label_user_all = label_user_all_copy;	//copy data from standby to active 
		}
		*/
		
		ct_tl_active_friends_count=ct_tl_label_user_all.length;
		ct_tl_iTotalMesageMustSend=ct_tl_active_friends_count*ct_tl_iTableAllItems;
		
		ct_tl_acc_all_count = ct_tl_active_friends_count + ct_tl_inactive_friends_count + ct_tl_problem_userId_count;

		ct_tl_cfg_max_recipients = $('#cfg_max_recipients').val();
		ct_tl_cfg_max_recipients = Number(ct_tl_cfg_max_recipients);
		if(ct_tl_cfg_max_recipients>ct_tl_active_friends_count || ct_tl_cfg_max_recipients<1){
			ct_tl_cfg_max_recipients=ct_tl_active_friends_count;
		}
		ct_tl_cfg_max_recipients = parseInt(ct_tl_cfg_max_recipients);
		
		ct_tl_cfg_start_seding_no=$('#cfg_start_seding_no').val();
		ct_tl_cfg_start_seding_no = Number(ct_tl_cfg_start_seding_no);
		if(ct_tl_cfg_start_seding_no>ct_tl_cfg_max_recipients){ct_tl_cfg_start_seding_no=ct_tl_cfg_max_recipients;}
		if(ct_tl_cfg_start_seding_no<1){ct_tl_cfg_start_seding_no=1;}
		ct_tl_cfg_start_seding_no = Number(ct_tl_cfg_start_seding_no);
		
		ct_tl_iTotalMesageMustSend=(ct_tl_cfg_max_recipients-ct_tl_cfg_start_seding_no+1)*ct_tl_iTableAllItems;
		
		//////////////////////////////////////
		let loop_extract = "";
		if(page_count=="0"){
		}else{
			loop_extract = window.lang.translate("All pages")+': '+page_count +' '+window.lang.translate("Times");
		}
		message = window.lang.translate("Can gather people from")+' "' +ct_tl_my_broadcastline_name +' -> '+ ct_tl_my_broadcastline_label_name + '" Active: ' + ct_tl_active_friends_count +"/"+ct_tl_acc_all_count+ " Blocked: "+ct_tl_inactive_friends_count + " Problem: "+ ct_tl_problem_userId_count +" "+ window.lang.translate('Person')+' '+ loop_extract + ' '+window.lang.translate('Completed');
		
		if (typeof iziToast != 'undefined') {
			iziToast.success({
				title: message,
				position: 'topRight',
				timeout: 7000,
				message: '',
			});
		}
		
		document.getElementById("abpc").innerHTML = "Active "+ct_tl_active_friends_count+" /Blocked "+ct_tl_inactive_friends_count+ " /Problem "+ ct_tl_problem_userId_count+ " /Total "+ ct_tl_acc_all_count + " "+window.lang.translate('Person');
		
		if($('#fanpage_OA_inbox_friend_ids_send_input').val().replace('\n').trim()!='' && permission_extract_member==1 && iswith_sendmsg==true){
			show_msg_report("","","2",window.lang.translate("Send friends in manual list"));
		}
		
		show_msg_report("","","2",window.lang.translate("Can gather people from")+" "+ct_tl_my_broadcastline_name +" -> "+ct_tl_my_broadcastline_label_name+" Active: "+ct_tl_active_friends_count+" /Blocked "+ct_tl_inactive_friends_count+ " /Problem "+ ct_tl_problem_userId_count+ " /Total "+ ct_tl_acc_all_count +" "+window.lang.translate('Person')+ " " +" "+window.lang.translate('Completed'));
		
		var modalGrAlert = document.getElementById("modalGrAlert");
		
		if(iswith_sendmsg==false){
			//Load friends only
			document.getElementById("start_broadcast").style.display = "inline-block";
			modalGrAlert.style.display = "none";
			if(ct_tl_label_user_all.length>0){
				$('#download_oa_fanpage_members').show();
			}
			ct_tl_status_stop_pause=3;
			setStopJob();
			return;
		}
		
		modalGrAlert.style.display = "flex";	//"block";
		$('#page_image').prop("src", data_page_icon);
		document.getElementById("modalGrAlert_OA_Account_name").innerHTML = "&nbsp;&nbsp;"+ct_tl_my_broadcastline_label_name;
		$('#my_header').text(CT_TL_APP_VERSION + ' ระบบกำลังทำงานอยู่');
		$('#my_header_detail').text($('#user_name').text()+ " / "+ct_tl_user_type);
		//document.getElementById("my_header_detail").innerHTML = CT_TL_APP_VERSION + " / " + $('#user_name').html();

		show_msg_report("","","2",window.lang.translate("Start sending people")+" : "+ct_tl_cfg_start_seding_no);
		show_msg_report("","","2",window.lang.translate("To send to people")+" : "+ct_tl_cfg_max_recipients);
		show_msg_report("","","2",window.lang.translate("Total messages that must be delivered")+" : "+ct_tl_iTotalMesageMustSend +" "+window.lang.translate("Message"));
		
		$('#modalGrAlert_OA_Status').text('กำลังดึงข้อมูลรายชื่อ กรุณารอสักครู่ ...');
		$('#modalGrAlert_OA_Status').css('color','white');
		
		if(ct_tl_label_user_all.length>0){
			let elem = document.getElementById("myProgress");
			if(typeof elem!="undefined"){
				if (elem!==null){
					elem.style.display="block";
				}
			}
			
			let clock = document.getElementById('clock');
			if(typeof clock!="undefined"){
				if (clock!==null){
					document.getElementById('clock_status').innerHTML="";
					clock.style.display="block";
					startTime();
				}
			}
			
			send_my_broadcastline_loop(ct_tl_cfg_start_seding_no-1);
			
		}else{
			iziToast.error({
				title: window.lang.translate("Unable to load the friends"),
				position: 'topRight',
				timeout: 3000,
				message: '',
			});
			let elem = document.getElementById("myProgress");
			if(typeof elem!=="undefined"){
				if (elem!==null){
					elem.style.display="none";
				}
			}
			setStopJob(0,false,0);
			ct_tl_status_running=false;
			return;
		}
	}
	
}


function send_my_broadcastline_continue(loop) {
	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="continue "+ (loop+1) +" "+esttime_date_format_str;
		localStorage.setItem('setstop', 1);	//Clear stop flag
		ct_tl_status_stop_pause = 1;
		
		let clock = document.getElementById('clock');
		if(typeof clock!="undefined"){
			if (clock!==null){
				document.getElementById('clock_status').innerHTML="";
				clock.style.display="block";
				startTime();
			}
		}
		
		send_my_broadcastline_loop(loop);
	}).catch((error) =>{
		ct_tl_status_running=false;
		console.log(error);
		
		pressStart_Broadcast_Button();
		
		
		$('#footer-summary-container').hide();
		$('#close-x').hide();
		$('#open-o').show();
		setStopJob(0,false,0);
		alert (window.lang.translate("Unabled to communicate with LINE OA"));
		return
	});
}

////// EVERY THINGS IN HERE //////
//// SEND TEXTS OR FILES IN HERE
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
	
	var line_biz=window.location.href.split('.biz/');
	if(typeof line_biz!=="undefined" && line_biz!=null && line_biz.length>1){
		ct_tl_my_broadcastline_idpage_token = window.location.href.split('.biz/')[1].split('/')[0];
	}
	
	if(ct_tl_my_broadcastline_idpage_token == ""){
		let sel=document.getElementById("my_broadcastline_idpage");
		let opt = sel.options[sel.selectedIndex];
		if(typeof opt!=="undefined" && opt!=null ){
			ct_tl_my_broadcastline_idpage_token=opt.getAttribute('data-botId');
		}
	}
	
	if (ct_tl_status_stop_pause == 0) {	//stop
		iziToast.info({
			title: window.lang.translate('To send to people')+ ' ' + (loop+1)+'/'+ct_tl_active_friends_count  +' '+ window.lang.translate('Successfully')+' '+ window.lang.translate("Ready to stop working"),
			position: 'topRight',
			timeout: 5000,
			message: '',
		});
		
		showStart_Broadcast_Button();

		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=window.lang.translate("Stop")+" "+loop+" "+esttime_date_format_str;
		ct_tl_status_running=false;
		runningProgress(loop);	//loop in friends
		return
	}else if(ct_tl_status_stop_pause==2)	{	//pause
		iziToast.info({
			title: window.lang.translate("To send to people")+' ' + (loop+1)+"/"+ct_tl_active_friends_count +" "+ window.lang.translate("Successfully")+' '+ window.lang.translate("Ready to pause"),
			position: 'topRight',
			timeout: 5000,
			message: '',
		});
		
		pressPause_Broadcast_Button();

		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="paused "+loop+" "+esttime_date_format_str;
		ct_tl_status_running=false;
		runningProgress(loop);	//loop in friends
		return;
	}
	
	checkPackagePromise()
	.then(x => {
		if(x==0){return false;}
	}).then(function(result){
	
		if(result==false){return;}
			
			var MsgCircleSend = document.getElementById("MsgCircleSend");
			let my_broadcastline_oldtonew = $('#my_broadcastline_oldtonew').prop("checked");
			if(typeof my_broadcastline_oldtonew=='undefined'){my_broadcastline_oldtonew=false;}
			
			var tl_send_last_to_first = document.getElementById("tl_send_last_to_first");
			var my_broadcastline_data = [];
			
			if(tl_send_last_to_first){
				if(tl_send_last_to_first.checked == true){
					my_broadcastline_data = ct_tl_label_user_all.slice().reverse();
					/*
					for (var ii = ct_tl_label_user_all.length - 1; ii >= 0; ii--) {
						my_broadcastline_data.push(ct_tl_label_user_all[ii]);
					}
					*/
				}else{
					my_broadcastline_data = ct_tl_label_user_all;
				}
			}else{
				my_broadcastline_data = ct_tl_label_user_all;
			}
			
			ct_tl_label_user_all_send_failed = [];

			ct_tl_active_friends_count=ct_tl_label_user_all.length;
			
			ct_tl_iTotalMesageMustSend=ct_tl_active_friends_count*ct_tl_iTableAllItems;
			
			ct_tl_cfg_max_recipients = $('#cfg_max_recipients').val();
			ct_tl_cfg_max_recipients = Number(ct_tl_cfg_max_recipients);
			if(ct_tl_cfg_max_recipients>ct_tl_active_friends_count || ct_tl_cfg_max_recipients<1){
				ct_tl_cfg_max_recipients=ct_tl_active_friends_count;
			}
			ct_tl_cfg_max_recipients = parseInt(ct_tl_cfg_max_recipients);
			
			ct_tl_cfg_start_seding_no=$('#cfg_start_seding_no').val();
			ct_tl_cfg_start_seding_no = Number(ct_tl_cfg_start_seding_no);
			if(ct_tl_cfg_start_seding_no>ct_tl_cfg_max_recipients){ct_tl_cfg_start_seding_no=ct_tl_cfg_max_recipients;}
			if(ct_tl_cfg_start_seding_no<1){ct_tl_cfg_start_seding_no=1;}
			ct_tl_cfg_start_seding_no = Number(ct_tl_cfg_start_seding_no);
			
			ct_tl_iTotalMesageMustSend=(ct_tl_cfg_max_recipients-ct_tl_cfg_start_seding_no+1)*ct_tl_iTableAllItems;
			
			if(loop<1){
				loop = ct_tl_cfg_start_seding_no - 1;
				if(loop<0){loop=0;}
				
				MsgCircleSend.style.backgroundColor = "#ffc107";
			}
			
			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: window.lang.translate("Something went wrong"),
					type: 'error',
					html: window.lang.translate('Enter your message or choose the folder you want to send first'),
				});
				ct_tl_status_running=false;
				return;
			}
			
			//Start Sending
			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 = window.lang.translate("Start time")+" "+starttime_date_format_str;
			
			show_msg_report("","","2",window.lang.translate("Start messaging people with")+" : "+(loop+1));
			
			let rateLimitedMaxPerMin_user = ct_tl_rateLimitedMaxPerMin;
			try{
				try{
					rateLimitedMaxPerMin_user = Number(document.getElementById("cfg_msg_rate_limit_per_min").value);
				}catch(err){}
				
				if (typeof CT_TL_SEND_MSG_RATE_LIMIT_MAX_PER_MIN !== 'undefined') {
					if( (rateLimitedMaxPerMin_user<1 || rateLimitedMaxPerMin_user>CT_TL_SEND_MSG_RATE_LIMIT_MAX_PER_MIN) && CT_TL_SEND_MSG_RATE_LIMIT_MAX_PER_MIN>0 ){rateLimitedMaxPerMin_user=CT_TL_SEND_MSG_RATE_LIMIT_MAX_PER_MIN;}
					
				}
				ct_tl_rateLimitedMaxPerMin=rateLimitedMaxPerMin_user;
			
				document.getElementById("cfg_msg_rate_limit_per_min").value = ct_tl_rateLimitedMaxPerMin;
			
			}catch(err){}
			
			if(ct_tl_status_running){
				show_msg_report("","","2",window.lang.translate("The program was already running previously")+" "+(loop+1));
				return;
			}
			
			
			//var richMessageData = null;

			$('#modalGrAlert_OA_Status').text('กำลังส่งข้อมูล กรุณารอสักครู่ ...');
			$('#modalGrAlert_OA_Status').css('color','blue');
			
			///// START SEND HERE ////
			ct_tl_send_msg_limit_person_before_delay_counter=0;
			var start_send_msg_time=new Date();

			send_Oa_accs_loop(loop);
			
			async function send_Oa_accs_loop(loop){
				var is_can_send_somthing_success=false;
				//var is_send_somthing_failed=false;
				//loop in friends

				loop = parseInt(loop);	//start sending no.
				
				if(ct_tl_status_stop_pause==0){	//stop
					localStorage.setItem('loops', (loop));	//store sending no to local storage
					
					show_msg_report("","","2",window.lang.translate("Stop")+" "+window.lang.translate("Person number")+' '+(loop) + "/"+ ct_tl_active_friends_count );
					
					iziToast.info({
						title: window.lang.translate("Person number")+' ' + (loop+1)+"/"+ct_tl_active_friends_count + ' '+ window.lang.translate("Successfully")+ ' '+window.lang.translate("Ready to stop working"),
						position: 'topRight',
						timeout: 5000,
						message: '',
					});
					
					showStart_Broadcast_Button();
					
					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=window.lang.translate("Stop")+" "+loop+" "+esttime_date_format_str;
					ct_tl_status_running=false;
					runningProgress(loop);	//loop in friends
					return;
				}else if(ct_tl_status_stop_pause==2){	//pause
					localStorage.setItem('loops', (loop));	//store sending no to local storage
					show_msg_report("","","2",window.lang.translate("Pause")+" "+window.lang.translate("Person number")+' '+(loop+1) + "/"+ ct_tl_active_friends_count );
					
					iziToast.info({
						title: window.lang.translate("Person number")+' ' + (loop+1)+"/"+ct_tl_active_friends_count  + ' '+ window.lang.translate("Successfully")+ ' '+window.lang.translate("Ready to pause"),
						position: 'topRight',
						timeout: 5000,
						message: '',
					});
					
					pressPause_Broadcast_Button();
					pressPause_GrAlert_Button();
					
					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=window.lang.translate("Pause")+" "+loop+" "+esttime_date_format_str;
					ct_tl_status_running=false;
					runningProgress(loop);	//loop in friends
					return;
				}
				
				
				//dtschepause_chk
				let dtschepause_chk = document.getElementById('dtschepause_chk');
				if(dtschepause_chk.checked == true){
					let dtschepause = document.getElementById('dtschepause');
					if(typeof dtschepause!=='undefined'){
						let timetopause = Date.parse(dtschepause.value);
						if (isNaN(timetopause)) {
							
						}else{
							if (timetopause< (new Date()).getTime()){
								//expired
								pause_broadcast();
								show_msg_report("","","3",window.lang.translate("It time to stop")+" : "+(loop+1));
								return false;
							}
						}
					}
				}
				
				
				var irow=-1;
				
				ct_tl_status_running=true;
				runningProgress(loop);	//loop in friends
				
				ct_tl_iCountAgv++;
				if(ct_tl_iCountAgv>50){
					var timeused=new Date().getTime()-ct_tl_dtStartTime.getTime();
					var avg=timeused/ct_tl_iCountAgv;
					var esttime = new Date().getTime()+Math.ceil((ct_tl_active_friends_count-loop+1)*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 = window.lang.translate("Estimate")+" "+esttime_date_format_str;
					ct_tl_dtStartTime=new Date();
					ct_tl_iCountAgv=0;
				}
				
				///////////////////////////////////
				//////////////////////////////////
				//// SEND TEXTS OR FILES CARD RICH IN HERE
				/////////////////////////////////
				////////////////////////////////
				if (typeof my_broadcastline_data[loop] != 'undefined' || loop<my_broadcastline_data.length) {
					if ((loop + 1) <= ct_tl_cfg_max_recipients && loop<ct_tl_label_user_all.length) {	//loop for next recipients
						var target_id = my_broadcastline_data[loop].id;
						var target_name=my_broadcastline_data[loop].name;
						var iconhash=my_broadcastline_data[loop].iconHash;
						var chatType=my_broadcastline_data[loop].chatType;
						
						
						ct_tl_txt_error_report=document.getElementById('txt_error_report');
						
						if(typeof target_id=='undefined'){target_id="";}
						if(typeof target_name=='undefined'){target_name="";}
						if(typeof iconhash=='undefined'){iconhash=" ";}
						
						var imageUrl='https://profile.line-scdn.net/' + iconhash + '/preview';
						
						////////////////////////////////////////////////////
						///////////////////////////// SEND /////////////////
						////////////////////////////////////////////////////
						
						ct_tl_send_msg_limit_person_before_delay_counter++;
						if (ct_tl_send_msg_next_time_gettime< 1) {
							ct_tl_send_msg_next_time_gettime = new Date().getTime();
						}
						show_msg_report("","","2","Latest send time "+ ct_tl_send_msg_next_time_gettime + " -> " + getDateTime(new Date(ct_tl_send_msg_next_time_gettime)) + " Count: " + ct_tl_send_msg_limit_person_before_delay_counter + "/" + (loop+1));

						document.getElementById("send_next_gr_alert").innerHTML="Latest send time "+getDateTime(new Date(ct_tl_send_msg_next_time_gettime)) + " Count: " + ct_tl_send_msg_limit_person_before_delay_counter + "/" + (loop+1) + " ใน 24 ชม. ส่งได้ไม่เกิน 200 คน";

						if (CT_TL_SEND_MSG_LIMIT_PERSON_BEFORE_DELAY>0 && CT_TL_SEND_MSG_PERSON_DELAY_TIME_MIN>0 
							&& ct_tl_send_msg_limit_person_before_delay_counter>=CT_TL_SEND_MSG_LIMIT_PERSON_BEFORE_DELAY){	//in tp_tl_customer_v4.js
								var now = new Date();

								let laspe_send_msg_time_sec=Math.ceil(((new Date().getTime() - (start_send_msg_time.getTime()) )/1000));	//1 hour = 3600000 milliseconds

								//
								if(laspe_send_msg_time_sec>3960){	//1 hrs. 10 mins ถ้าเวลาปัจจุบัน ลบ เวลาเริ่มต้นเกิน 3960 วินาที หรือ 1 ชม. 10 นาที แสดงว่าเคลียร์โควต้า 200 คนได้
									ct_tl_send_msg_next_time_gettime = now.getTime()+(60*1000);	//plus 1 mins ให้มี Delay อีกสัก 1 นาที
									document.getElementById("stop_time").innerHTML=window.lang.translate("Wait for next send time") +" " + getDateTime(new Date(ct_tl_send_msg_next_time_gettime));
									document.getElementById("send_next_gr_alert").innerHTML=document.getElementById("stop_time").innerHTML + "  /" + ct_tl_send_msg_limit_person_before_delay_counter + "/" + (loop+1) + " DELAY " + 1 + " Minutes every 200 Persons";
									document.getElementById("send_next_gr_alert").style.color="red";
									await sleep(60*1000);	//1 minute
								}else{	// ถ้ายังอยู่ในช่วงจำกัดส่ง 200 คนต่อ ชม.
									ct_tl_send_msg_next_time_gettime = now.getTime()+(((3960-laspe_send_msg_time_sec))*1000);	//1 hr = 3600 sec plus 10 mins หรือ 1 ชม. 10 นาที
									document.getElementById("stop_time").innerHTML=window.lang.translate("Wait for next send time") +" " + getDateTime(new Date(ct_tl_send_msg_next_time_gettime));
									document.getElementById("send_next_gr_alert").innerHTML=document.getElementById("stop_time").innerHTML + "  /" + ct_tl_send_msg_limit_person_before_delay_counter + "/" + (loop+1) + " DELAY " + Math.ceil((3960-laspe_send_msg_time_sec)/60) + " Minutes every 200 Persons";
									document.getElementById("send_next_gr_alert").style.color="red";
									await sleep((3960-laspe_send_msg_time_sec)*1000);
								}
								ct_tl_send_msg_limit_person_before_delay_counter=1;
								start_send_msg_time = new Date();
								document.getElementById("send_next_gr_alert").style.color="black";
								//
						}
						
						//ct_tl_send_msg_limit_person_before_delay_counter=CT_TL_SEND_MSG_LIMIT_PERSON_BEFORE_DELAY;
						
						let delayBuble = 1.5;
						let delayDefault = delayBuble;
						
						let xxxxxxxxxx = 0;
						timest = new Date(); 
						
						//$('#modalGrAlert_OA_Status').text('กำลังส่งข้อมูล กรุณารอสักครู่ ...');
						$('#modalGrAlert_OA_Status').css('color','blue');
			
						broadcastDataInTable();	//send all lines in table then go to next friends.
						
						async function broadcastDataInTable(){
							if (irow < num_rows) {
								
								irow++;
								
								//////// begin for test //////
								//irow=0;
								//xxxxxxxxxx++;
								//document.getElementById("text_"+myOLBroadcastTable.rows[irow].id+"col1").value = getFormattedDate()+ " : " + xxxxxxxxxx;
								//if(xxxxxxxxxx>95){
								//	irow=num_rows;
								//}
								////// end test //////
								//$('#modalGrAlert_OA_Status').text('กำลังส่งข้อมูล กรุณารอสักครู่ ...');
								//$('#modalGrAlert_OA_Status').css('color','blue');
								
								 //document.getElementById("xyz").innerHTML = window.lang.translate("Sending")+" " + window.lang.translate("Completed")+" "+(loop - ct_tl_send_txt_err_count)+" /"+window.lang.translate("Unsuccessful")+ " "+ct_tl_send_txt_err_count+ " /"+window.lang.translate("All")+ " "+ actual_friends_must_send+ " "+window.lang.translate("Person");
								//document.getElementById("send_next_gr_alert").innerHTML=window.lang.translate("Sending");
								broadcast_text(0);	//send data all rows in table start at row 1 (index 0)
								
							}
							
							if(irow>=num_rows){	//after finished send all rows in table go to next friends
								ct_tl_iMessNoActive=0;
								if(typeof my_broadcastline_data[loop].iconHash!="undefined"){
									iconhash=my_broadcastline_data[loop].iconHash; 
								}else{
									iconhash=="";
								}
								
								if(typeof iconhash=='undefined'){iconhash=" ";}
								if(chatType=="ROOM" || chatType=="GROUP"){
									imageUrl = iconhash;
								}
								
								
								if(typeof iziToast!=="undefined"){
									if(is_can_send_somthing_success==false){
										iziToast.error({
											title: window.lang.translate("Person number")+' : ' + (loop+1)+ ' '+ target_name + ' '+window.lang.translate("Unsuccessful") +' <br />' +  g_err_msg,
											position: 'topRight',
											timeout: 3000,
											image: imageUrl,	//'https://profile.line-scdn.net/' + iconhash + '/preview',
											imageWidth: 50,
											message: '',
										});
									}else{
										iziToast.success({
											title: window.lang.translate("Person number")+' : ' + (loop+1)+ ' '+ target_name + ' '+window.lang.translate("Completed") +' <br />',
											position: 'topRight',
											timeout: 3000,
											image: imageUrl,	//'https://profile.line-scdn.net/' + iconhash + '/preview',
											imageWidth: 50,
											message: '',
										});
									}
									g_err_msg="";
								}
								
								
								if(typeof completed_counter !='undefined'){
									if(completed_counter!=null){
										completed_counter.innerHTML=(loop+1)+'/'+my_broadcastline_data.length;
									}
								}
								
								//Send to next friend
								setTimeout(function () {
									if (loop<ct_tl_label_user_all.length){
										if(is_can_send_somthing_success==true){
											//keep success user
											if(ct_tl_label_user_all_send_success.length==0){
												ct_tl_label_user_all_send_success.push({
													'id': ct_tl_label_user_all[loop].id,
													'name': ct_tl_label_user_all[loop].name,
													'iconHash': ct_tl_label_user_all[loop].iconHash,
													'accountName':ct_tl_label_user_all[0].accountName,
													'folder':ct_tl_label_user_all[0].folder
												});
											}else{
												ct_tl_label_user_all_send_success.push({
													'id': ct_tl_label_user_all[loop].id,
													'name': ct_tl_label_user_all[loop].name,
													'iconHash': ct_tl_label_user_all[loop].iconHash,
													'accountName':'',
													'folder':''
												});
											}
										}else{
											if(ct_tl_label_user_all_send_failed.length==0){
												ct_tl_label_user_all_send_failed.push({
													'id': ct_tl_label_user_all[loop].id,
													'name': ct_tl_label_user_all[loop].name,
													'iconHash': ct_tl_label_user_all[loop].iconHash,
													'accountName':ct_tl_label_user_all[0].accountName,
													'folder':ct_tl_label_user_all[0].folder
												});
											}else{
												ct_tl_label_user_all_send_failed.push({
													'id': ct_tl_label_user_all[loop].id,
													'name': ct_tl_label_user_all[loop].name,
													'iconHash': ct_tl_label_user_all[loop].iconHash,
													'accountName':'',
													'folder':''
												});
											}
										}
									}
									
									ct_tl_prev_friend_loop=loop;
									loop=loop + 1;
									
									try{
										if(localStorage){
											let status_log = "unknown";
											if(ct_tl_status_stop_pause==0){
												status_log ="stop";
											}else if(ct_tl_status_stop_pause==2){
												status_log = "pause";
											}
											let back_log = JSON.stringify({"date_time":getNow(),"page_index":ct_tl_my_broadcastline_select_index,"page_id":ct_tl_my_broadcastline_idpage_token,"page_name":ct_tl_my_broadcastline_label_name,"target_id":target_id,"target_name":target_name,"number_send":loop,"status":status_log});
											localStorage.setItem("back_log", back_log );
											localStorage.setItem(ct_tl_my_broadcastline_idpage_token, back_log );
										}
									}catch(exc){}
									
									ct_tl_iSendFriendsCount = loop;
									//ct_tl_iSendFriendsCount++;
									
									send_Oa_accs_loop(loop);	//next friends
									
								}, $('#cfg_delay').val() * 1000);	//delay secs in config for next friend
								return;
								
							}
						}
						
						//////////////////////////////////
						////// Broadcast rich message/////
						/////////////////////////////////
						async function broadcast_rich(num,retry_send,retry429) {
							if(typeof num !="undefined"){
								if(num>0){
									// if(ct_tl_delay_per_msg_ms>0){
									// 	console.log("Start file: "+getNow());
									// 	await sleep(ct_tl_delay_per_msg_ms);
									// 	console.log("End file: "+getNow());
									// }
								}
							}else{
								num = 0;
							}
							if(typeof retry_send =="undefined"){
								retry_send=0;
							}
							let rowid = null;
							let my_broadcastline_rich = null;
							let my_broadcastline_rich_index = null;
							let richMessageData = null;

							if(typeof retry429=="undefined"){retry429=0;}
							if(typeof myOLBroadcastTable.rows[irow]=="undefined" || myOLBroadcastTable.rows[irow]==null){return;}
							
							rowid=myOLBroadcastTable.rows[irow].id;
							if(typeof rowid=='undefined' || rowid==null){return;}
							
							my_broadcastline_rich=document.getElementById("edit_"+rowid+"col4");	//file id file-row1col4
							if (typeof my_broadcastline_rich!=='undefined' && my_broadcastline_rich!=null && my_broadcastline_rich.value != '') {
								my_broadcastline_rich = $("#edit_"+rowid+"col4").val();	//value
								if(typeof my_broadcastline_rich!="undefined" && my_broadcastline_rich!=null && my_broadcastline_rich!=""){
									try{
										my_broadcastline_rich_index = my_broadcastline_rich.split('|')[3];	//rich index
										if (typeof my_broadcastline_rich_index=="undefined"){
											let opt_select = document.querySelector("#edit_"+rowid+"col4"+' option:checked');
											if (typeof opt_select !="undefined"){
												my_broadcastline_rich_index = opt_select.index;
											}
										}
									}catch(e){}
									my_broadcastline_rich = my_broadcastline_rich.split('|')[0];	//rich id
								}else{
									my_broadcastline_rich="";
								}
							}else{
								my_broadcastline_rich="";
							}
							
							if(typeof my_broadcastline_rich=='undefined' || my_broadcastline_rich==null){my_broadcastline_rich="";}
							my_broadcastline_rich=my_broadcastline_rich.trim();
							if(my_broadcastline_rich==''){
								broadcastDataInTable();	//next row
								return;
							}
							
							//get rich data to variable
							try{
								//if (!richMessageData){
									if(typeof my_broadcastline_rich_index=='undefined' || my_broadcastline_rich_index==null){my_broadcastline_rich_index="";}
									if (isNaN(my_broadcastline_rich_index)){
										broadcastDataInTable();	//next row
										return;
									}
									my_broadcastline_rich_index = Number(my_broadcastline_rich_index);
									richMessageData = ct_tl_rich_list[my_broadcastline_rich_index];
									if(!richMessageData){
										broadcastDataInTable();	//next row
										return;
									}
								//}
							}catch(e){
								broadcastDataInTable();	//next row
								return;
							}
							/*
							{
								"basicSearchId": "@142trbgp",
								"richId": 131161752,
								"richTitle": "Rich Col 6",
								"richType": 8,
								"created": "15/11/2022 11:08:06",
								"richData": {
									"id": 131161752,
									"imageThumbUrl": "https://obs.line-scdn.net/h9iQC7shQZkZ0OhBkFQx0eld5JiQaCyBANhVwdS9veCQecWlvUjtsWxZGMCYeeiBrDzwhcgFROBckfiNFNTtvdRUyeyYKdWNsJSx1cCw7cCYH/300",
									"imageUrl": "https://obs.line-scdn.net/h9iQC7shQZkZ0OhBkFQx0eld5JiQaCyBANhVwdS9veCQecWlvUjtsWxZGMCYeeiBrDzwhcgFROBckfiNFNTtvdRUyeyYKdWNsJSx1cCw7cCYH",
									"imageKey": null,
									"imageId": "cj00aWxhdWdqcnJyN3VtJnM9anA0JnQ9cyZ1PTE3dTVwdm9razNsMDAmaT0yaw",
									"title": "Rich Col 6",
									"contentsType": 8,
									"contents": {
										"A": {
											"linkType": "URL",
											"url": "https://google.com",
											"text": "https://google.com A",
											"contentsId": null
										},
										"B": {
											"linkType": "URL",
											"url": "https://linebroadcast.com",
											"text": "https://linebroadcast.com B",
											"contentsId": null
										},
										"C": {
											"linkType": "URL",
											"url": "https://cactusmarketing.biz",
											"text": "https://cactusmarketing.biz C",
											"contentsId": null
										},
										"D": {
											"linkType": "URL",
											"url": "https://youtube.com",
											"text": "https://youtube.com D",
											"contentsId": null
										},
										"E": {
											"linkType": "URL",
											"url": "https://gmail.com",
											"text": "https://gmail.com E",
											"contentsId": null
										},
										"F": {
											"linkType": "URL",
											"url": "https://pantip.com",
											"text": "https://pantip.com F",
											"contentsId": null
										}
									},
									"created": 1668485286
								}
							}
							*/
							var v = [];
							let exist_stored_richid = "";
							if (isEmpty(ct_tl_richId_stored_list)){
								//const str = sessionStorage.getItem(richMessageData.basicSearchId);
								const str = localStorage.getItem(richMessageData.basicSearchId);
								// convert JSON string to valid object
								if (str){
									ct_tl_richId_stored_list = JSON.parse(str);
								}
							}
							if (typeof ct_tl_richId_stored_list[richMessageData.richId] != 'undefined'){
								if (ct_tl_richId_stored_list[richMessageData.richId] != ""){
									exist_stored_richid = ct_tl_richId_stored_list[richMessageData.richId];
								}
							}

							debugger;
							drawImageCanvas(richMessageData.basicSearchId, richMessageData.richData,exist_stored_richid, function(basicSearchId, objImg, objImageUrlAndRatio) {
								debugger;
								upload_image(basicSearchId, objImg, objImageUrlAndRatio, [], 0,exist_stored_richid, function(basicSearchId, objImg, flagUploadSuccess, arrImgUpload) {
									debugger;
									if (flagUploadSuccess){
										debugger;
										getRichId(basicSearchId, objImg, arrImgUpload, [],exist_stored_richid, async function(isGetRichIdSuccess, objRichId) {
											debugger;
											if (isGetRichIdSuccess){
												if (typeof objRichId.id == "undefined"){
													isGetRichIdSuccess = false;
												}
											}
											if (isGetRichIdSuccess){
												console.log(objRichId);
												//r[n.id] = objRichId.id;
												//f.messages[nloop].type = "card";
												//f.messages[nloop].value = objRichId;
												//h++; 
												
												if (exist_stored_richid==""){
													//ct_tl_richId_stored_list
													ct_tl_richId_stored_list[richMessageData.richId] = objRichId.id;	//add richid to json object

													const jsonObject = JSON.stringify(ct_tl_richId_stored_list);
													// save to localStorage
													//sessionStorage.setItem(basicSearchId, jsonObject);

													localStorage.setItem(basicSearchId, jsonObject);	//Clear stop flag

													//// get the JSON string from sessionStorage
													//const str = sessionStorage.getItem(basicSearchId);
													//// convert JSON string to valid object
													//const parsedObject = JSON.parse(str);
													//console.log(parsedObject);
												}

												if (retry_send==0){
													ct_tl_iMessNoActive++; 
												}
												
												let parms = {
													  "type": "cardType",
													  "cardTypeMessageId": objRichId.id,
													  "sendId": target_id+ '_' + Math.floor(Date.now()) + '_' + Math.floor(10000000 + Math.random() * 90000000)
													};
												
												///// 2022-04-20 ////
												//if(ct_tl_my_broadcastline_delay>0){
												//	await sleep(ct_tl_my_broadcastline_delay*1000);
												//}

												//Work for 20200925
												let url_line_txt = "https://chat.line.biz/api/v1/bots/" + ct_tl_my_broadcastline_idpage_token + "/messages/" + target_id + "/send";
												rateLimitedCounter++;
												if(ct_tl_delay_per_msg_ms>0 && is_use_avg_time_send){
													await sleep(ct_tl_delay_per_msg_ms);
												}
												$.ajax({
													url: url_line_txt,
													contentType: 'application/json; charset=utf-8',
													dataType: 'json',
													data: JSON.stringify(parms),
													method: 'POST',
													//New
													type: 'POST', // For jQuery < 1.9
													beforeSend: function (xhr) {
														xhr.withCredentials = true; //Include this line
														xhr.setRequestHeader('Accept', 'application/json, text/plain, */*');
														xhr.setRequestHeader('x-xsrf-token', ct_tl_lineCSRF);
														xhr.setRequestHeader('dataType', 'json');
													},
													crossOrigin: true,
													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
													success: function (data, textStatus, request) {
					
														is_can_send_somthing_success=true;
														runningAllitemsProgress();
														show_msg_report(target_id,target_name,"0",window.lang.translate("Send message to friend #no.")+' '+(loop+1) + ' row ' + irow+' '+window.lang.translate("Completed") + " msgs. " + ct_tl_iProgressAllItemsCount );
					
														ct_tl_demo_usage_ratelimit++;
														if(ct_tl_user_type=="ทดลองใช้งาน" && Number(ct_tl_demo_ratelimit)>0){
															ct_tl_demo_usage_ratelimit_left = Number(ct_tl_demo_ratelimit) - Number(ct_tl_demo_usage_ratelimit);
															document.getElementById('plan_package').innerHTML="plan "+ct_tl_user_type+ " "+ window.lang.translate("Time left") +" "+ ct_tl_demo_usage_ratelimit_left +" "+ window.lang.translate("Messages per day");
															document.getElementById('plan_demo_package').innerHTML=document.getElementById('plan_package').innerHTML
															
															if(Number(ct_tl_demo_usage_ratelimit) > Number(ct_tl_demo_ratelimit)){
																Swal.fire({
																	title: window.lang.translate('Cannot do the transaction'),
																	html: window.lang.translate("You have sent the full amount of messages per day")+"<br /><a href='" + LINE_URL_QRCODE + "'>Line : " + LINE_AT_ID + "</a>",
																	type: 'warning',
																	footer: footer_swal(),
																	showCancelButton: true,
																	confirmButtonColor: '#3085d6',
																	cancelButtonColor: '#d33',
																	confirmButtonText: window.lang.translate('Yes'),
																	cancelButtonText: window.lang.translate('Cancel')
																}).then((result) => {
																	if (result.value) {
																		var mywinUrl = window.open(LINE_URL_QRCODE, '_blank');
																		mywinUrl.focus();
																	}
																});
																setStopJob(0,false,0);
																return;
															}
														}
														
														//////////////////// Solution 1 /////////////////////
														//rateLimitedCounter++;
														//MsgCircleSend.innerHTML = rateLimitedCounter + "/" + ct_tl_MsgCircleSend_counter;
														MsgCircleSend.innerHTML = rateLimitedCounter + "/" + ct_tl_MsgCircleSend_counter + "/" + ct_tl_send_msg_limit_person_before_delay_counter;

														if(rateLimitedPrevStamp==null){
															rateLimitedPrevStamp=new Date();
														}
														
														if (!is_use_avg_time_send){
															let timeLapse=Math.ceil(((new Date().getTime() - rateLimitedPrevStamp.getTime())/1000));							
															if( rateLimitedCounter>=ct_tl_rateLimitedMaxPerMin || timeLapse>60){
																delayDefault = timeLapse - 1;
						
																if(delayDefault>60){	//more than 1 minutes
																	//delayDefault = 15;//0.2;
																	delayDefault = 0.2;
																}else{
																	delayDefault = 60-delayDefault+10;	//plus 10 sec
																	if(delayDefault<0){
																		//delayDefault = 15;//0.2;
																		delayDefault = 0.2;
																	}
																}
																//delayDefault = 65;
																
																show_msg_report(target_id,target_name,"2"," Delay: "+delayDefault + " rate limited count: "+rateLimitedCounter );
																rateLimitedCounter=0;
																rateLimitedPrevStamp=null;
																const now = new Date();
																
																ct_tl_send_msg_next_time_gettime = now.getTime()+(delayDefault*1000);
																document.getElementById("stop_time").innerHTML=window.lang.translate("Wait for next send time") +" " + getDateTime(new Date(ct_tl_send_msg_next_time_gettime));
																document.getElementById("send_next_gr_alert").innerHTML=document.getElementById("stop_time").innerHTML + "  /" + ct_tl_send_msg_limit_person_before_delay_counter + "/" + (loop+1) + " DELAY " + CT_TL_SEND_MSG_PERSON_DELAY_TIME_MIN + " Minutes every 200 Persons";
																ct_tl_execSetTimeout = setTimeout(function () {
																	ct_tl_MsgCircleSend_counter++;
																	let msg_circle_bg_color = ["#ffc107","#007bff","#00b900","#eb4e3d","#6c757d"];	//#ae4cae
																	MsgCircleSend.style.backgroundColor = msg_circle_bg_color[(ct_tl_MsgCircleSend_counter%5)];
																	MsgCircleSend.style.color = "#000";
																	broadcastDataInTable();	//next row
																	return;
																}, delayDefault*1000);	//wait 61 secs and resend
															}else{
																broadcastDataInTable();	//next row
																return;
															}
														}else{
															broadcastDataInTable();	//next row
															return;
														}

													},
													error: function (XMLHttpRequest, textStatus, errorThrown) {
														let responseText = XMLHttpRequest.responseText;
														if(typeof responseText!=="undefined" && responseText!=null && responseText!=""){
															try{
																//{"details":[{"message":"length must be between 0 and 2000","property":"text"}]}
																responseText = responeText.details[0].message;
															}catch(e){}
														}
														
														if(XMLHttpRequest.statusText!=""){
															responseText = XMLHttpRequest.statusText + " " + responseText;
														}
														
														try{
															if(XMLHttpRequest.status==400 && responseText=="length must be between 0 and 2000"){
															}else{
																iziToast.error({
																	title: window.lang.translate("Person number")+' : ' + (loop+1) + ' '+ target_name  + ' row:'+irow +' STATUS:('+ XMLHttpRequest.status + ') '+window.lang.translate("Unable to send messages")+'<br />' +XMLHttpRequest.responseText,
																	position: 'topRight',
																	timeout: 5000,
																	image: imageUrl,	//'https://profile.line-scdn.net/' + iconhash + '/preview',
																	imageWidth: 50,
																	message: "",
																});
															}
														}catch(e){}
														
														if(XMLHttpRequest.status==401 && XMLHttpRequest.responseJSON.code=="not_login"){
															setStopJob(0,false,0);
															show_msg_report(target_id,target_name,"1",window.lang.translate("Stop")+" : "+(loop+1) + ' row ' + irow+ " " +window.lang.translate("Message no.")+ " : "+ct_tl_iMessNoActive + " msgs. " + ct_tl_iProgressAllItemsCount);
															ct_tl_status_running=false;
															Swal.fire({
																title: window.lang.translate('Stop'),
																type: 'danger',	//    icon: "warning",
																html: window.lang.translate("Stop")+' please login line manager and re-open TL<br>กรุณา Login ไลน์แมนเนเจอร์ใหม่อีกครั้งแล้วให้ทำการปิดแล้วเปิดโปรกรมขึ้นมาทำงานใหม่อีกรอบ',
															});
														}
														
														if(XMLHttpRequest.status==0){	//internet failed
															check_net()
															.then((data) => {
																broadcast_rich(num,1);
															}).catch((error) => {
																//console.log(error);
																show_msg_report(target_id,target_name,"1",window.lang.translate("Communicating with LINE OA problem")+" : "+(loop+1) + ' row ' + irow+ " " +window.lang.translate("Message no.")+ " : "+ct_tl_iMessNoActive + " msgs. " + ct_tl_iProgressAllItemsCount);
																ct_tl_status_running=false;
																wait_net_online(loop,target_name,target_id);
																return;
															});
														}else{
															if(typeof retry429=="undefined"){retry429=0;}
															if(XMLHttpRequest.status==429 && retry429<12){	//To many request (rate limit)
																retry429++;
																var delay429 = 90;
																//const delay429 = 6;	//	30;
																var now = new Date();
																if (retry429>1){
																	ct_tl_send_msg_limit_person_before_delay_counter=CT_TL_SEND_MSG_LIMIT_PERSON_BEFORE_DELAY;
																	delay429=CT_TL_SEND_MSG_PERSON_DELAY_TIME_MIN*60;
																}
																ct_tl_send_msg_next_time_gettime = now.getTime()+(delay429*1000);
																show_msg_report(target_id,target_name,"1",window.lang.translate("Send a message to a friend #no.") + ' row ' + irow+' '+(loop+1)+' '+window.lang.translate("Unsuccessful")+' -> status:429 ' +window.lang.translate("Speed ​​limit") + " Next:"+getDateTime(new Date(ct_tl_send_msg_next_time_gettime)) + " msgs. " + ct_tl_iProgressAllItemsCount);
																
																document.getElementById("stop_time").innerHTML=window.lang.translate("Wait for next send time")+" " + getDateTime(new Date(ct_tl_send_msg_next_time_gettime));
																document.getElementById("send_next_gr_alert").innerHTML=document.getElementById("stop_time").innerHTML + "  /" + ct_tl_send_msg_limit_person_before_delay_counter + "/" + (loop+1) + " DELAY " + CT_TL_SEND_MSG_PERSON_DELAY_TIME_MIN + " Minutes every 200 Persons";
																document.getElementById("send_next_gr_alert").style.color="red";
																ct_tl_execSetTimeout = setTimeout(function () {
																	rateLimitedCounter=0;
																	rateLimitedPrevStamp=null;
																	document.getElementById("send_next_gr_alert").style.color="black";
																	broadcast_rich(num,0,retry429);
																}, delay429*1000);	//wait 61 secs and resend
															
															}else {
																try{
																	//check error send in each friends
																	if(ct_tl_prev_friend_loop!=loop && is_can_send_somthing_success==false){
																		ct_tl_prev_friend_loop=loop;
																		ct_tl_send_txt_err_count++;
																	}
																	
																	//rateLimitedCounter++;
																	if(XMLHttpRequest.status==400){
																		show_msg_report(target_id,target_name,"1",window.lang.translate("Send message got a problem. Send to someone #no.")+" : "+(loop+1) + ' row ' + irow+ ' '+ window.lang.translate("Message no.")+" : "+ct_tl_iMessNoActive+" -> status: "+XMLHttpRequest.status+ ' ' + responseText + ' '+window.lang.translate("Or you have turned on AI mode") + " msgs. " + ct_tl_iProgressAllItemsCount);
																	}else{
																		show_msg_report(target_id,target_name,"1",window.lang.translate("Send message got a problem. Send to someone #no.")+" : "+(loop+1) + ' row ' + irow+' '+ window.lang.translate("Message no.")+" : "+ct_tl_iMessNoActive+" -> status: "+XMLHttpRequest.status+ ' ' + responseText + " msgs. " + ct_tl_iProgressAllItemsCount);
																	}
																	ct_tl_itemsSendErrorCount++;
																	runningAllitemsProgress();
																	
																	///////////////////////////
																	//////////////////////////
																	//////////////////// Solution 1 /////////////////////
																	//rateLimitedCounter++;
																	//MsgCircleSend.innerHTML = rateLimitedCounter + "/" + ct_tl_MsgCircleSend_counter;
																	MsgCircleSend.innerHTML = rateLimitedCounter + "/" + ct_tl_MsgCircleSend_counter + "/" + ct_tl_send_msg_limit_person_before_delay_counter;

																	if(rateLimitedPrevStamp==null){
																		rateLimitedPrevStamp=new Date();
																	}
																	
																	let timeLapse=Math.ceil(((new Date().getTime() - rateLimitedPrevStamp.getTime())/1000));							
																	if( rateLimitedCounter>=ct_tl_rateLimitedMaxPerMin || timeLapse>60){
																		delayDefault = timeLapse - 1;
					
																		if(delayDefault>60){	//more than 1 minutes
																			//delayDefault = 15;//0.1;
																			delayDefault = 0.1;
																		}else{
																			delayDefault = 60-delayDefault+10;	//plus 10 sec;
																			if(delayDefault<0){
																				//delayDefault = 15;//0.1;
																				delayDefault = 0.1;
																			}
																		}
																		//delayDefault = 65;
																		
																		show_msg_report(target_id,target_name,"2"," Delay: "+delayDefault + " rate limited count: "+rateLimitedCounter );
																		rateLimitedCounter=0;
																		rateLimitedPrevStamp=null;
																		const now = new Date();
																		
																		ct_tl_send_msg_next_time_gettime = now.getTime()+(delayDefault*1000);
																		document.getElementById("stop_time").innerHTML=window.lang.translate("Wait for next send time") +" " + getDateTime(new Date(ct_tl_send_msg_next_time_gettime));
																		document.getElementById("send_next_gr_alert").innerHTML=document.getElementById("stop_time").innerHTML + "  /" + ct_tl_send_msg_limit_person_before_delay_counter + "/" + (loop+1) + " DELAY " + CT_TL_SEND_MSG_PERSON_DELAY_TIME_MIN + " Minutes every 200 Persons";
																		document.getElementById("send_next_gr_alert").style.color="red";
																		ct_tl_execSetTimeout = setTimeout(function () {
																			ct_tl_MsgCircleSend_counter++;
																			let msg_circle_bg_color = ["#ffc107","#007bff","#00b900","#eb4e3d","#6c757d"];	//#ae4cae
																			MsgCircleSend.style.backgroundColor = msg_circle_bg_color[(ct_tl_MsgCircleSend_counter%5)];
																			MsgCircleSend.style.color = "#000";
																			document.getElementById("send_next_gr_alert").style.color="black";
																			broadcastDataInTable();	//next row
																		}, delayDefault*1000);	//wait 61 secs and resend
																	}else{
																		broadcastDataInTable();	//next row
																	}
																	//////////////////////////
																	//////////////////////////
																	
																}catch(e){
																	broadcastDataInTable();	//next row
																}
																//broadcastDataInTable();	//next row
																return;
															}
														}
														
													}
												});
											}else{
												//g++;
												console.log("Error get rich id:",objRichId);
												iziToast.error({
													title: window.lang.translate("Error get rich id "+objRichId),
													position: 'topRight',
													timeout: 3000,
													message: '',
												});
												broadcastDataInTable();	//next row
											}
										}) 
									}else{
										console.log("upload_rich");
										//v.push({
										//	source: "upload_rich",
										//		data: arrImgUpload
										//});
										iziToast.error({
											title: window.lang.translate("Error upload rich image "+arrImgUpload),
											position: 'topRight',
											timeout: 3000,
											message: '',
										});
										broadcastDataInTable();	//next row
										//g++;
									}
								});
							});
						}

						//////////////////////////////////
						////// Broadcast card message/////
						/////////////////////////////////
						async function broadcast_card(num,retry_send,retry429) {
							if(typeof num !="undefined"){
								if(num>0){
									// if(ct_tl_delay_per_msg_ms>0){
									// 	console.log("Start file: "+getNow());
									// 	await sleep(ct_tl_delay_per_msg_ms);
									// 	console.log("End file: "+getNow());
									// }
								}
							}else{
								num = 0;
							}
							if(typeof retry_send =="undefined"){
								retry_send=0;
							}

							let rowid = null;
							let my_broadcastline_card = null;
							if(typeof retry429=="undefined"){retry429=0;}
							if(typeof myOLBroadcastTable.rows[irow]=="undefined" || myOLBroadcastTable.rows[irow]==null){return;}
							
							rowid=myOLBroadcastTable.rows[irow].id;
							if(typeof rowid=='undefined' || rowid==null){return;}
							
							my_broadcastline_card=document.getElementById("edit_"+rowid+"col3");	//file id file-row1col3
							if (typeof my_broadcastline_card!=='undefined' && my_broadcastline_card!=null && my_broadcastline_card.value != '') {
								my_broadcastline_card = $("#edit_"+rowid+"col3").val();	//value
								if(typeof my_broadcastline_card!="undefined" && my_broadcastline_card!=null && my_broadcastline_card!=""){
									my_broadcastline_card = my_broadcastline_card.split('|')[0];	//id
								}else{
									my_broadcastline_card="";
								}
							}else{
								my_broadcastline_card="";
							}
							
							if(typeof my_broadcastline_card=='undefined' || my_broadcastline_card==null){my_broadcastline_card="";}
							my_broadcastline_card=my_broadcastline_card.trim();
							if(my_broadcastline_card==''){
								broadcast_rich();	//next rich
								return;
							}
							
							if (retry_send==0){
								ct_tl_iMessNoActive++; 
							}
							
							let parms = {
								  "type": "cardType",
								  "cardTypeMessageId": my_broadcastline_card,
								  "sendId": target_id+ '_' + Math.floor(Date.now()) + '_' + Math.floor(10000000 + Math.random() * 90000000)
								};
							
							///// 2022-04-20 ////
							// if(ct_tl_my_broadcastline_delay>0){
							// 	await sleep(ct_tl_my_broadcastline_delay*1000);
							// }
							
							//Work for 20200925
							let url_line_txt = "https://chat.line.biz/api/v1/bots/" + ct_tl_my_broadcastline_idpage_token + "/messages/" + target_id + "/send";
							rateLimitedCounter++;
							if(ct_tl_delay_per_msg_ms>0 && is_use_avg_time_send){
								await sleep(ct_tl_delay_per_msg_ms);
							}

							$.ajax({
								url: url_line_txt,
								contentType: 'application/json; charset=utf-8',
								dataType: 'json',
								data: JSON.stringify(parms),
								method: 'POST',
								//New
								type: 'POST', // For jQuery < 1.9
								beforeSend: function (xhr) {
									xhr.withCredentials = true; //Include this line
									xhr.setRequestHeader('Accept', 'application/json, text/plain, */*');
									xhr.setRequestHeader('x-xsrf-token', ct_tl_lineCSRF);
									xhr.setRequestHeader('dataType', 'json');
								},
								crossOrigin: true,
								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
								success: function (data, textStatus, request) {

									is_can_send_somthing_success=true;
									runningAllitemsProgress();
									show_msg_report(target_id,target_name,"0",window.lang.translate("Send message to friend #no.")+' '+(loop+1) + ' row ' + irow+' '+window.lang.translate("Completed") + " msgs. " + ct_tl_iProgressAllItemsCount );

									ct_tl_demo_usage_ratelimit++;
									if(ct_tl_user_type=="ทดลองใช้งาน" && Number(ct_tl_demo_ratelimit)>0){
										ct_tl_demo_usage_ratelimit_left = Number(ct_tl_demo_ratelimit) - Number(ct_tl_demo_usage_ratelimit);
										document.getElementById('plan_package').innerHTML="plan "+ct_tl_user_type+ " "+ window.lang.translate("Time left") +" "+ ct_tl_demo_usage_ratelimit_left +" "+ window.lang.translate("Messages per day");
										document.getElementById('plan_demo_package').innerHTML=document.getElementById('plan_package').innerHTML
										
										if(Number(ct_tl_demo_usage_ratelimit) > Number(ct_tl_demo_ratelimit)){
											Swal.fire({
												title: window.lang.translate('Cannot do the transaction'),
												html: window.lang.translate("You have sent the full amount of messages per day")+"<br /><a href='" + LINE_URL_QRCODE + "'>Line : " + LINE_AT_ID + "</a>",
												type: 'warning',
												footer: footer_swal(),
												showCancelButton: true,
												confirmButtonColor: '#3085d6',
												cancelButtonColor: '#d33',
												confirmButtonText: window.lang.translate('Yes'),
												cancelButtonText: window.lang.translate('Cancel')
											}).then((result) => {
												if (result.value) {
													var mywinUrl = window.open(LINE_URL_QRCODE, '_blank');
													mywinUrl.focus();
												}
											});
											setStopJob(0,false,0);
											return;
										}
									}
									
									//////////////////// Solution 1 /////////////////////
									//rateLimitedCounter++;
									//MsgCircleSend.innerHTML = rateLimitedCounter + "/" + ct_tl_MsgCircleSend_counter;
									MsgCircleSend.innerHTML = rateLimitedCounter + "/" + ct_tl_MsgCircleSend_counter + "/" + ct_tl_send_msg_limit_person_before_delay_counter;

									if(rateLimitedPrevStamp==null){
										rateLimitedPrevStamp=new Date();
									}
									
									if (!is_use_avg_time_send){
										let timeLapse=Math.ceil(((new Date().getTime() - rateLimitedPrevStamp.getTime())/1000));							
										if( rateLimitedCounter>=ct_tl_rateLimitedMaxPerMin || timeLapse>60){
											delayDefault = timeLapse - 1;

											if(delayDefault>60){	//more than 1 minutes
												//delayDefault = 15;//0.1;
												delayDefault = 0.1;
											}else{
												delayDefault = 60-delayDefault+10;	//plus 10 sec;
												if(delayDefault<0){
													//delayDefault = 15;//0.1;
													delayDefault = 0.1;
												}
											}
											//delayDefault = 65;
											
											show_msg_report(target_id,target_name,"2"," Delay: "+delayDefault + " rate limited count: "+rateLimitedCounter );
											rateLimitedCounter=0;
											rateLimitedPrevStamp=null;
											const now = new Date();
											
											ct_tl_send_msg_next_time_gettime = now.getTime()+(delayDefault*1000);
											document.getElementById("stop_time").innerHTML=window.lang.translate("Wait for next send time") +" " + getDateTime(new Date(ct_tl_send_msg_next_time_gettime));
											document.getElementById("send_next_gr_alert").innerHTML=document.getElementById("stop_time").innerHTML + "  /" + ct_tl_send_msg_limit_person_before_delay_counter + "/" + (loop+1) + " DELAY " + CT_TL_SEND_MSG_PERSON_DELAY_TIME_MIN + " Minutes every 200 Persons";
											document.getElementById("send_next_gr_alert").style.color="red";
											ct_tl_execSetTimeout = setTimeout(function () {
												ct_tl_MsgCircleSend_counter++;
												let msg_circle_bg_color = ["#ffc107","#007bff","#00b900","#eb4e3d","#6c757d"];	//#ae4cae
												MsgCircleSend.style.backgroundColor = msg_circle_bg_color[(ct_tl_MsgCircleSend_counter%5)];
												MsgCircleSend.style.color = "#000";
												document.getElementById("send_next_gr_alert").style.color="black";
												broadcast_rich();	//next rich
												return;
											}, delayDefault*1000);	//wait 61 secs and resend
										}else{
											broadcast_rich();	//next rich
											return;
										}
									}else{
										broadcast_rich();	//next rich
										return;
									}
								},
								error: function (XMLHttpRequest, textStatus, errorThrown) {
									//May need to show report unsend
									//console.log(XMLHttpRequest);
									//XMLHttpRequest.status=400;
									//XMLHttpRequest.statusText=="error";
									//XMLHttpRequest.responseText== code smart_response_enabled
									//XMLHttpRequest.responseJSON.code=="smart_response_enabled";
									let responseText = XMLHttpRequest.responseText;
									if(typeof responseText!=="undefined" && responseText!=null && responseText!=""){
										try{
											//{"details":[{"message":"length must be between 0 and 2000","property":"text"}]}
											responseText = responeText.details[0].message;
										}catch(e){}
									}
									
									if(XMLHttpRequest.statusText!=""){
										responseText = XMLHttpRequest.statusText + " " + responseText;
									}
									
									try{
										if(XMLHttpRequest.status==400 && responseText=="length must be between 0 and 2000"){
										}else{
											iziToast.error({
												title: window.lang.translate("Person number")+' : ' + (loop+1) + ' '+ target_name  + ' row:'+irow +' STATUS:('+ XMLHttpRequest.status + ') '+window.lang.translate("Unable to send messages")+'<br />' +XMLHttpRequest.responseText,
												position: 'topRight',
												timeout: 5000,
												image: imageUrl,	//'https://profile.line-scdn.net/' + iconhash + '/preview',
												imageWidth: 50,
												message: "",
											});
										}
									}catch(e){}
									
									if(XMLHttpRequest.status==401 && XMLHttpRequest.responseJSON.code=="not_login"){
										setStopJob(0,false,0);
										show_msg_report(target_id,target_name,"1",window.lang.translate("Stop")+" : "+(loop+1) + ' row ' + irow+ " " +window.lang.translate("Message no.")+ " : "+ct_tl_iMessNoActive + " msgs. " + ct_tl_iProgressAllItemsCount);
										ct_tl_status_running=false;
										Swal.fire({
											title: window.lang.translate('Stop'),
											type: 'danger',	//    icon: "warning",
											html: window.lang.translate("Stop")+' please login line manager and re-open TL<br>กรุณา Login ไลน์แมนเนเจอร์ใหม่อีกครั้งแล้วให้ทำการปิดแล้วเปิดโปรกรมขึ้นมาทำงานใหม่อีกรอบ',
										});
									}
									
									if(XMLHttpRequest.status==0){	//internet failed
										check_net()
										.then((data) => {
											broadcast_card(num,1);
										}).catch((error) => {
											//console.log(error);
											show_msg_report(target_id,target_name,"1",window.lang.translate("Communicating with LINE OA problem")+" : "+(loop+1) + ' row ' + irow+ " " +window.lang.translate("Message no.")+ " : "+ct_tl_iMessNoActive + " msgs. " + ct_tl_iProgressAllItemsCount);
											ct_tl_status_running=false;
											wait_net_online(loop,target_name,target_id);
											return;
										});
									}else{
										if(typeof retry429=="undefined"){retry429=0;}
										if(XMLHttpRequest.status==429 && retry429<12){	//To many request (rate limit)
											retry429++;
											var delay429 = 90;
											//const delay429 = 6;	//	30;
											var now = new Date();
											if (retry429>1){
												ct_tl_send_msg_limit_person_before_delay_counter=CT_TL_SEND_MSG_LIMIT_PERSON_BEFORE_DELAY;
												delay429=CT_TL_SEND_MSG_PERSON_DELAY_TIME_MIN*60;
											}
											ct_tl_send_msg_next_time_gettime = now.getTime()+(delay429*1000);
											show_msg_report(target_id,target_name,"1",window.lang.translate("Send a message to a friend #no.") + ' row ' + irow+' '+(loop+1)+' '+window.lang.translate("Unsuccessful")+' -> status:429 ' +window.lang.translate("Speed ​​limit") + " Next:"+getDateTime(new Date(ct_tl_send_msg_next_time_gettime)) + " msgs. " + ct_tl_iProgressAllItemsCount);
											
											document.getElementById("stop_time").innerHTML=window.lang.translate("Wait for next send time")+" " + getDateTime(new Date(ct_tl_send_msg_next_time_gettime));
											document.getElementById("send_next_gr_alert").innerHTML=document.getElementById("stop_time").innerHTML + "  /" + ct_tl_send_msg_limit_person_before_delay_counter + "/" + (loop+1) + " DELAY " + CT_TL_SEND_MSG_PERSON_DELAY_TIME_MIN + " Minutes every 200 Persons";
											document.getElementById("send_next_gr_alert").style.color="red";
											ct_tl_execSetTimeout = setTimeout(function () {
												rateLimitedCounter=0;
												rateLimitedPrevStamp=null;
												document.getElementById("send_next_gr_alert").style.color="black";
												broadcast_card(num,0,retry429);
											}, delay429*1000);	//wait 61 secs and resend
										
										}else {
											try{
												//check error send in each friends
												if(ct_tl_prev_friend_loop!=loop && is_can_send_somthing_success==false){
													ct_tl_prev_friend_loop=loop;
													ct_tl_send_txt_err_count++;
												}
												
												//rateLimitedCounter++;
												if(XMLHttpRequest.status==400){
													show_msg_report(target_id,target_name,"1",window.lang.translate("Send message got a problem. Send to someone #no.")+" : "+(loop+1) + ' row ' + irow+ ' '+ window.lang.translate("Message no.")+" : "+ct_tl_iMessNoActive+" -> status: "+XMLHttpRequest.status+ ' ' + responseText + ' '+window.lang.translate("Or you have turned on AI mode") + " msgs. " + ct_tl_iProgressAllItemsCount);
												}else{
													show_msg_report(target_id,target_name,"1",window.lang.translate("Send message got a problem. Send to someone #no.")+" : "+(loop+1) + ' row ' + irow+' '+ window.lang.translate("Message no.")+" : "+ct_tl_iMessNoActive+" -> status: "+XMLHttpRequest.status+ ' ' + responseText + " msgs. " + ct_tl_iProgressAllItemsCount);
												}
												ct_tl_itemsSendErrorCount++;
												runningAllitemsProgress();
												
												///////////////////////////
												//////////////////////////
												//////////////////// Solution 1 /////////////////////
												//rateLimitedCounter++;
												//MsgCircleSend.innerHTML = rateLimitedCounter + "/" + ct_tl_MsgCircleSend_counter;
												MsgCircleSend.innerHTML = rateLimitedCounter + "/" + ct_tl_MsgCircleSend_counter + "/" + ct_tl_send_msg_limit_person_before_delay_counter;

												if(rateLimitedPrevStamp==null){
													rateLimitedPrevStamp=new Date();
												}
												if (!is_use_avg_time_send){
													let timeLapse=Math.ceil(((new Date().getTime() - rateLimitedPrevStamp.getTime())/1000));							
													if( rateLimitedCounter>=ct_tl_rateLimitedMaxPerMin || timeLapse>60){
														delayDefault = timeLapse - 1;

														if(delayDefault>60){	//more than 1 minutes
															//delayDefault = 15;//0.1;
															delayDefault = 0.1;
														}else{
															delayDefault = 60-delayDefault+10;	//plus 10 sec;
															if(delayDefault<0){
																//delayDefault = 15;//0.1;
																delayDefault = 0.1;
															}
														}
														//delayDefault = 65;
														
														show_msg_report(target_id,target_name,"2"," Delay: "+delayDefault + " rate limited count: "+rateLimitedCounter );
														rateLimitedCounter=0;
														rateLimitedPrevStamp=null;
														const now = new Date();
														
														ct_tl_send_msg_next_time_gettime = now.getTime()+(delayDefault*1000);
														document.getElementById("stop_time").innerHTML=window.lang.translate("Wait for next send time") +" " + getDateTime(new Date(ct_tl_send_msg_next_time_gettime));
														document.getElementById("send_next_gr_alert").innerHTML=document.getElementById("stop_time").innerHTML + "  /" + ct_tl_send_msg_limit_person_before_delay_counter + "/" + (loop+1) + " DELAY " + CT_TL_SEND_MSG_PERSON_DELAY_TIME_MIN + " Minutes every 200 Persons";
														document.getElementById("send_next_gr_alert").style.color="red";
														ct_tl_execSetTimeout = setTimeout(function () {
															ct_tl_MsgCircleSend_counter++;
															let msg_circle_bg_color = ["#ffc107","#007bff","#00b900","#eb4e3d","#6c757d"];	//#ae4cae
															MsgCircleSend.style.backgroundColor = msg_circle_bg_color[(ct_tl_MsgCircleSend_counter%5)];
															MsgCircleSend.style.color = "#000";
															document.getElementById("send_next_gr_alert").style.color="black";
															broadcast_rich();	//next rich
														}, delayDefault*1000);	//wait 61 secs and resend
													}else{
														broadcast_rich();	//next rich
														return;
													}
												}else{
													broadcast_rich();	//next rich
													return;
												}
											}catch(e){
												broadcast_rich();	//next rich
											}
											return;
										}
									}
									
								}
							});

						}
						
						///////////////////////////////////
						//////////////////////////////////
						////// Broadcast file message/////
						/////////////////////////////////
						async function broadcast_file(num,retry_send,retry429) {
							if(typeof num !="undefined"){
								if(num>0){
									// if(ct_tl_delay_per_msg_ms>0){
									// 	console.log("Start file: "+getNow());
									// 	await sleep(ct_tl_delay_per_msg_ms);
									// 	console.log("End file: "+getNow());
									// }
								}
							}else{
								num = 0;
							}
							if(typeof retry_send =="undefined"){
								retry_send=0;
							}

							let rowid = null;
							let my_broadcastline_file = null;
							if(typeof retry429=="undefined"){retry429=0;}
							if(typeof myOLBroadcastTable.rows[irow]=="undefined" || myOLBroadcastTable.rows[irow]==null){return;}
							
							rowid=myOLBroadcastTable.rows[irow].id;
							if(typeof rowid=='undefined' || rowid==null){return;}
							
							my_broadcastline_file=document.getElementById("file-"+rowid+"col2");	//file id file-row1col2
							
							
							if (typeof my_broadcastline_file!=='undefined' && my_broadcastline_file!=null && my_broadcastline_file.value != '') {	//'$('#file1').val()
								var data = new FormData();
								var jQFile=jQuery('#'+my_broadcastline_file.id)[0];
								if (num < jQFile.files.length) {
									data = new FormData();
									sendid_rnd_id = target_id + '_' + Math.floor(Date.now()) + '_' + Math.floor(10000000 + Math.random() * 90000000);
									data.append('file', jQFile.files[num]);
									data.append('sendId', sendid_rnd_id);
									
									if (retry_send==0){
										ct_tl_iMessNoActive++;
									}

									//Rate limits
									//Developer Trial requests	1,000/min
									//The following status codes are returned by the Messaging API.
									//Status code	Description
									//200 OK	Request successful
									//400 Bad Request	Problem with the request
									//401 Unauthorized	Valid channel access token is not specified
									//403 Forbidden	Not authorized to access the resource. Confirm that your account or plan is authorized to access the resource.
									//429 Too Many Requests	
									//Exceeded the rate limit for requests.
									//Exceeded your monthly message limit. You can check the limit for your account in the LINE Official Account Manager.
									//500 Internal Server Error	Error on the internal server
									///
									
									///// 2022-04-20 ////
									// if(ct_tl_my_broadcastline_delay>0){
									// 	await sleep(ct_tl_my_broadcastline_delay*1000);
									// }
									
									////////////////////////////////
									//`/bots/${this.botId}/users`
									//Work modify on 20200925
									//jQuery.ajax({

									//let url_line_file = 'https://chat.line.biz/api/v1/bots/' + ct_tl_my_broadcastline_idpage_token + '/messages/' + target_id + '/sendFile';	v3.2
									//let url_line_file = 'https://chat.line.biz/api/v1/bots/' + ct_tl_my_broadcastline_idpage_token + '/messages/' + target_id + '/uploadFile';	//v3.3
									let url_line_file = 'https://chat.line.biz/api/v1/bots/' + ct_tl_my_broadcastline_idpage_token + '/messages/' + target_id + '/uploadFile';	//v3.3


									rateLimitedCounter++;
									if(ct_tl_delay_per_msg_ms>0 && is_use_avg_time_send){
										await sleep(ct_tl_delay_per_msg_ms);
									}
									

									//url: 'https://chat.line.biz/api/v1/bots/' + adverra_premium_broadcastline_new_idpage_token + '/messages/' + target_id + '/uploadFile',
									//data: data,
									//contentType: false,
									//processData: false,
									//headers: {
									//	"x-xsrf-token": localStorage.getItem('xsrfToken_line_all'),
									//},
									//method: 'POST',


									$.ajax({
										url: url_line_file,
										data: data,
										cache: false,
										contentType: false,
										processData: false,
										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', ct_tl_lineCSRF);
											//xhr.setRequestHeader('X-Line-Retry-Key', '123e4567-e89b-12d3-a456-426614174000');
											xhr.setRequestHeader('DataType', 'json');
											//xhr.setRequestHeader('Content-Type', 'multipart/form-data; boundary=----WebKitFormBoundaryWyuc01mIimgL5UtG');
											xhr.setRequestHeader('X-Oa-Chat-Client-Version','20240513144702');
											//xhr.setRequestHeader('Accept-Encoding','gzip, deflate, br, zstd');
											//xhr.setRequestHeader('Cookie','_trmccid=c43b8d6447bba31b; _uts_cid_719894379=be16f864-d48d-4ae2-80bf-4bf9c0d90c82; chat-device-group=495; ses=fzKsbXRjPjJyJjxjeImxJkpjTmeVJjxjZXyoJkpjSWNzOUZjgR.fzKaeXJjPjKRAUilUlKqWaV2AmdxA1O6XEWDZWKJcYN4SX11eIGSVGJ2eUCXUYhxWIebNlmJXIh5A3iUOl9YcEONAaiSUkAEcTJtJnG1ADJ6JnymA2GkfTJtJnW4dDJ6NUd1OkN1OEZaOo0.nyDa6TEgAYxUxvTQ2iVfMBdBaOcKrhXcFYJFWgqeOkzNugey21RJRGQMqUr589eZOjDYVLlGXFx4W4YMrKGwZh; __Host-chat-ses=fzKsbXRjPjJyJjxjeImxJkpjTmeVJjxjZXyoJkpjSWNzOUZjgR.fzKaeXJjPjKRAUilUlKqWaV2AmdxA1O6XEWDZWKJcYN4SX11eIGSVGJ2eUCXUYhxWIebNlmJXIh5A3iUOl9YcEONAaiSUkAEcTJtJnG1ADJ6JkljMDKmfIBjPkF3OUZaOUhzNaA9.fvgSbr2Na1cTCrN1L6eQxOTtST_8T-ZkQbZi1OBrDj-BCi7OzYFSuiDZ6WBsatnpytULPPXhq-tMFM4sli7Rzh; _trmcdisabled2=-1; _trmcuser={"id":""}; _trmcsession={"id":"cbacb6a836125ab8","path":"/U97028224c1aae20d338854c5273f9ef3","query":"","params":{},"time":1756268246261}; XSRF-TOKEN=8803affc-6b03-4378-8b80-3359b2504521; __try__=1756269438501; _trmcpage=/pc/hashBotId/chat/hashChatId; _uts_cs_719894379={"sid":"03153a54-7629-4671-9e4d-acdf4650371e","sq":45,"expiredAt":1756274406546}');
										},
										mode: 'cors',
										credentials: 'same-origin', // include, same-origin, omit
										
										success: async function (data) {
											is_can_send_somthing_success=true;
											var sendidxx = target_id + '_' + Math.floor(Date.now()) + '_' + Math.floor(10000000 + Math.random() * 90000000);
											var parms = { "items": [{ "sendId": sendidxx, "contentMessageToken": data.contentMessageToken }] };
											$.ajax({
												//url: 'https://chat.line.biz/api/v1/bots/' + ct_tl_my_broadcastline_idpage_token + '/messages/' + target_id + '/bulkSendFiles',	//v3.3.2
												url: 'https://chat.line.biz/api/v1/bots/' + ct_tl_my_broadcastline_idpage_token + '/chats/' + target_id + '/messages/bulkSendFiles',	//v3.3.3
												contentType: 'application/json',
												data: JSON.stringify(parms),
												//type: 'POST',
												method: "POST",
												cache: false,
												contentType: false,
												processData: false,
												beforeSend: function (xhr) {
													xhr.withCredentials = true; //Include this line
													xhr.setRequestHeader('Accept', 'application/json, text/plain, */*');
													xhr.setRequestHeader('X-Oa-Chat-Client-Version','20240513144702');
													xhr.setRequestHeader('Content-Type','application/json');
													xhr.setRequestHeader('X-Xsrf-Token', ct_tl_lineCSRF);
												},
												mode: 'cors',
												credentials: 'same-origin', // include, same-origin, omit
												//headers: {
												//	"X-Xsrf-Token": ct_tl_lineCSRF,
												//},

												success: function(data1) {
													//uploadfile_line1(num + 1);
													runningAllitemsProgress();
													is_can_send_somthing_success=true;
													show_msg_report(target_id,target_name,"0",window.lang.translate("Send file to friend #no.")+' '+(loop+1) + ' row ' + irow+' '+ window.lang.translate("File no.")+ " : "+ (num+1) + ' '+window.lang.translate("Completed") + " msgs. " + ct_tl_iProgressAllItemsCount );
												}
												,
												error: function(XMLHttpRequest, textStatus, errorThrown) {
													//uploadfile_line1(num + 1);
													is_can_send_somthing_success=false;
													var responseText = XMLHttpRequest.responseText;
													runningAllitemsProgress();
													is_can_send_somthing_success=false;
													if(XMLHttpRequest.status==400){
														show_msg_report(target_id,target_name,"1",window.lang.translate("Unable to send files")+" "+ window.lang.translate("Person number")+" : "+(loop+1) + ' row ' + irow+" "+window.lang.translate("File no.")+ " : "+(num+1)+" -> status: "+XMLHttpRequest.status+ ' ' + responseText + ' '+window.lang.translate("Or you have turned on AI mode") + " msgs. " + ct_tl_iProgressAllItemsCount);
													}else{
														show_msg_report(target_id,target_name,"1",window.lang.translate("Unable to send files")+" "+ window.lang.translate("Person number")+" : "+(loop+1) + ' row ' + irow+" "+window.lang.translate("File no.")+ " : "+(num+1)+" -> status: "+XMLHttpRequest.status+ ' ' + responseText  + " msgs. " + ct_tl_iProgressAllItemsCount);
													}
													ct_tl_itemsSendErrorCount++;
													g_err_msg = XMLHttpRequest.status+ ' ' + responseText;
													broadcast_file((num + 1),0);	//send next file
													return;
												}
									
											});
											

											//runningAllitemsProgress();
											//show_msg_report(target_id,target_name,"0",window.lang.translate("Send file to friend #no.")+' '+(loop+1) + ' row ' + irow+' '+ window.lang.translate("File no.")+ " : "+ (num+1) + ' '+window.lang.translate("Completed") + " msgs. " + ct_tl_iProgressAllItemsCount );

											ct_tl_demo_usage_ratelimit++;
											
											if(ct_tl_user_type=="ทดลองใช้งาน" && Number(ct_tl_demo_ratelimit)>0){
												ct_tl_demo_usage_ratelimit_left = Number(ct_tl_demo_ratelimit) - Number(ct_tl_demo_usage_ratelimit);
												document.getElementById('plan_package').innerHTML="plan "+window.lang.translate("Trial")+ " " + window.lang.translate("Time left")+ " " + ct_tl_demo_usage_ratelimit_left +" "+window.lang.translate("Messages per day");
												document.getElementById('plan_demo_package').innerHTML=document.getElementById('plan_package').innerHTML
	
												if(Number(ct_tl_demo_usage_ratelimit) > Number(ct_tl_demo_ratelimit)){
													Swal.fire({
														title: window.lang.translate('Cannot do the transaction'),
														html: window.lang.translate("You have sent the full amount of messages per day")+"<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);
													return;
												}
											}

											////////// Solution 1 ///////////
											//rateLimitedCounter++;
											//MsgCircleSend.innerHTML = rateLimitedCounter + "/" + ct_tl_MsgCircleSend_counter;
											MsgCircleSend.innerHTML = rateLimitedCounter + "/" + ct_tl_MsgCircleSend_counter + "/" + ct_tl_send_msg_limit_person_before_delay_counter;

											if(rateLimitedPrevStamp==null){
												rateLimitedPrevStamp=new Date();
											}
											
											await sleep(1000);
											if (!is_use_avg_time_send){
												let timeLapse=Math.ceil(((new Date().getTime() - rateLimitedPrevStamp.getTime())/1000));
												if( rateLimitedCounter>=ct_tl_rateLimitedMaxPerMin || timeLapse>60){
													delayDefault = timeLapse - 1;	//

													if(delayDefault>60){	//more than 1 minutes
														//delayDefault = 15;//0.1;
														delayDefault = 0.1;
													}else{
														delayDefault = 60-delayDefault+10;	//plus 10 sec;
														if(delayDefault<0){
															//delayDefault = 15;//0.1;
															delayDefault = 0.1;
														}
													}
													//delayDefault = 65;
													
													show_msg_report(target_id,target_name,"2"," Delay: "+delayDefault + " rate limited count: "+rateLimitedCounter );
													rateLimitedCounter=0;
													rateLimitedPrevStamp=null;
													const now = new Date();
													
													ct_tl_send_msg_next_time_gettime = now.getTime()+(delayDefault*1000);
													document.getElementById("stop_time").innerHTML=window.lang.translate("Wait for next send time") +" "+ getDateTime(new Date(ct_tl_send_msg_next_time_gettime));
													document.getElementById("send_next_gr_alert").innerHTML=document.getElementById("stop_time").innerHTML + "  /" + ct_tl_send_msg_limit_person_before_delay_counter + "/" + (loop+1) + " DELAY " + CT_TL_SEND_MSG_PERSON_DELAY_TIME_MIN + " Minutes every 200 Persons";
													document.getElementById("send_next_gr_alert").style.color="red";
													ct_tl_execSetTimeout = setTimeout(function () {
														ct_tl_MsgCircleSend_counter++;
														let msg_circle_bg_color = ["#ffc107","#007bff","#00b900","#eb4e3d","#6c757d"];	//#ae4cae
														MsgCircleSend.style.backgroundColor = msg_circle_bg_color[(ct_tl_MsgCircleSend_counter%5)];
														MsgCircleSend.style.color = "#000";
														document.getElementById("send_next_gr_alert").style.color="black";
														broadcast_file((num + 1),0);	//continue next file
													}, delayDefault*1000);	//wait 61 secs and resend
												}else{
													broadcast_file((num + 1),0);	//continue next file
													return;
												}
											}else{
												broadcast_file((num + 1),0);	//continue next file
												return;
											}
										},
										error: function (XMLHttpRequest, textStatus, errorThrown) {
											//var errResTxt = XMLHttpRequest.responseText;
											var responseText = XMLHttpRequest.responseText;
											if(typeof responseText!=="undefined" && responseText!=null && responseText!=""){
												try{
													//{"details":[{"message":"length must be between 0 and 2000","property":"text"}]}
													responseText = responeText.details[0].message;
												}catch(e){}
											}
											if(XMLHttpRequest.statusText!=""){
												responseText = XMLHttpRequest.statusText + " " + responseText;
											}
											
											g_err_msg = XMLHttpRequest.status+ ' ' + responseText;

											try{
												if(XMLHttpRequest.status==400 && responseText=="length must be between 0 and 2000"){
												}else{
													show_msg_report(target_id,target_name,"1",window.lang.translate("Files")+' #no. '+ (num+1) + ' '+ window.lang.translate("Person number") +' '+(loop+1)+' '+window.lang.translate("Unsuccessful")+' -> status: '+XMLHttpRequest.status + ' -> '+ XMLHttpRequest.responseText );
													iziToast.error({
														title: window.lang.translate("Person number")+' : ' + (loop+1) + ' '+ target_name + ' row:'+irow +' STATUS:('+ XMLHttpRequest.status + ') '+window.lang.translate("Unable to send files")+' <br />' +XMLHttpRequest.responseText,
														position: 'topRight',
														timeout: 5000,
														image: imageUrl	,//'https://profile.line-scdn.net/' + iconhash + '/preview',
														imageWidth: 50,
														message: "",
													});
												}
												if(XMLHttpRequest.status==401 && XMLHttpRequest.responseJSON.code=="not_login"){
													setStopJob(0,false,0);
													show_msg_report(target_id,target_name,"1",window.lang.translate("Stop")+" : "+(loop+1) + ' row ' + irow+ " " +window.lang.translate("Message no.")+ " : "+ct_tl_iMessNoActive + " msgs. " + ct_tl_iProgressAllItemsCount);
													ct_tl_status_running=false;
													Swal.fire({
														title: window.lang.translate('Stop'),
														type: 'danger',	//    icon: "warning",
														html: window.lang.translate("Stop")+' please login line manager and re-open TL<br>กรุณา Login ไลน์แมนเนเจอร์ใหม่อีกครั้งแล้วให้ทำการปิดแล้วเปิดโปรกรมขึ้นมาทำงานใหม่อีกรอบ',
													});
												}
											}catch(e){}


											if(XMLHttpRequest.status==0){	//internet failed
												check_net()
												.then((data) => {
													show_msg_report(target_id,target_name,"2",window.lang.translate("Communication with LINE OA is resumed")+" "+window.lang.translate("Person number")+" : "+(loop+1) + ' row ' + irow+ " " + window.lang.translate("File no.")+ " : "+ (num+1)+ " msgs. " + ct_tl_iProgressAllItemsCount);
													broadcast_file(num,1);
												}).catch((error) => {
													//console.log(error);
													show_msg_report(target_id,target_name,"1",window.lang.translate("Line OA communication interruption At the moment")+" "+window.lang.translate("Person number")+" : "+(loop+1) + ' row ' + irow+ " " + window.lang.translate("File no.")+ " : "+ (num+1) + " msgs. " + ct_tl_iProgressAllItemsCount);
													ct_tl_status_running=false;
													wait_net_online(loop,target_name,target_id);
													return;
												});
											}else{
												if(typeof retry429=="undefined"){retry429=0;}
												if(XMLHttpRequest.status==429 && retry429<12){	//To many request (rate limit)
													retry429++;
													var delay429 = 90;
													var now = new Date();
													if (retry429>1){
														ct_tl_send_msg_limit_person_before_delay_counter=CT_TL_SEND_MSG_LIMIT_PERSON_BEFORE_DELAY;
														delay429=CT_TL_SEND_MSG_PERSON_DELAY_TIME_MIN*60;
													}
													ct_tl_send_msg_next_time_gettime = now.getTime()+(delay429*1000);
													show_msg_report(target_id,target_name,"1",window.lang.translate("Files")+' #no. '+ (num+1) + ' '+ window.lang.translate("Person number") +' '+(loop+1) + ' row ' + irow+' '+window.lang.translate("Unsuccessful")+' -> status:429 '+ window.lang.translate("Speed ​​limit") + " Next:"+getDateTime(new Date(ct_tl_send_msg_next_time_gettime)) + " msgs. " + ct_tl_iProgressAllItemsCount );
													
													document.getElementById("stop_time").innerHTML=window.lang.translate("Wait for next send time") +" "+ getDateTime(new Date(ct_tl_send_msg_next_time_gettime));
													document.getElementById("send_next_gr_alert").innerHTML=document.getElementById("stop_time").innerHTML + "  /" + ct_tl_send_msg_limit_person_before_delay_counter + "/" + (loop+1) + " DELAY " + CT_TL_SEND_MSG_PERSON_DELAY_TIME_MIN + " Minutes every 200 Persons";
													document.getElementById("send_next_gr_alert").style.color="red";
													ct_tl_execSetTimeout = setTimeout(function () {
														rateLimitedCounter=0;
														rateLimitedPrevStamp=null;
														document.getElementById("send_next_gr_alert").style.color="black";
														broadcast_file((num),0,retry429);
													}, delay429*1000);	//wait 61 secs and resend
												}else{
														try{
															//check error send in each friends
															if(ct_tl_prev_friend_loop!=loop && is_can_send_somthing_success==false){
																ct_tl_prev_friend_loop=loop;
																ct_tl_send_txt_err_count++;
															}
															
															//rateLimitedCounter++;
															
															if(XMLHttpRequest.status==400){
																show_msg_report(target_id,target_name,"1",window.lang.translate("Unable to send files")+" "+ window.lang.translate("Person number")+" : "+(loop+1) + ' row ' + irow+" "+window.lang.translate("File no.")+ " : "+(num+1)+" -> status: "+XMLHttpRequest.status+ ' ' + responseText + ' '+window.lang.translate("Or you have turned on AI mode") + " msgs. " + ct_tl_iProgressAllItemsCount);
															}else{
																show_msg_report(target_id,target_name,"1",window.lang.translate("Unable to send files")+" "+ window.lang.translate("Person number")+" : "+(loop+1) + ' row ' + irow+" "+window.lang.translate("File no.")+ " : "+(num+1)+" -> status: "+XMLHttpRequest.status+ ' ' + responseText  + " msgs. " + ct_tl_iProgressAllItemsCount);
															}
															ct_tl_itemsSendErrorCount++;
															runningAllitemsProgress();
															
															///////////////////////////
															//////////////////////////
															//////////////////// Solution 1 /////////////////////
															//rateLimitedCounter++;
															//MsgCircleSend.innerHTML = rateLimitedCounter + "/" + ct_tl_MsgCircleSend_counter;
															MsgCircleSend.innerHTML = rateLimitedCounter + "/" + ct_tl_MsgCircleSend_counter + "/" + ct_tl_send_msg_limit_person_before_delay_counter;


															if(rateLimitedPrevStamp==null){
																rateLimitedPrevStamp=new Date();
															}

															if (!is_use_avg_time_send){
																let timeLapse=Math.ceil(((new Date().getTime() - rateLimitedPrevStamp.getTime())/1000));							
																if( rateLimitedCounter>=ct_tl_rateLimitedMaxPerMin || timeLapse>60){
																	delayDefault = timeLapse - 1;

																	if(delayDefault>60){	//more than 1 minutes
																		//delayDefault = 15;//0.1;
																		delayDefault = 0.1;
																	}else{
																		delayDefault = 60-delayDefault+10;	//plus 10 sec;
																		if(delayDefault<0){
																			//delayDefault = 15;//0.1;
																			delayDefault = 0.1;
																		}
																	}
																	//delayDefault = 65;
																	
																	show_msg_report(target_id,target_name,"2"," Delay: "+delayDefault + " rate limited count: "+rateLimitedCounter );
																	rateLimitedCounter=0;
																	rateLimitedPrevStamp=null;
																	const now = new Date();
																	
																	ct_tl_send_msg_next_time_gettime = now.getTime()+(delayDefault*1000);
																	document.getElementById("stop_time").innerHTML=window.lang.translate("Wait for next send time") +" " + getDateTime(new Date(ct_tl_send_msg_next_time_gettime));
																	document.getElementById("send_next_gr_alert").innerHTML=document.getElementById("stop_time").innerHTML + "  /" + ct_tl_send_msg_limit_person_before_delay_counter + "/" + (loop+1) + " DELAY " + CT_TL_SEND_MSG_PERSON_DELAY_TIME_MIN + " Minutes every 200 Persons";
																	document.getElementById("send_next_gr_alert").style.color="red";
																	ct_tl_execSetTimeout = setTimeout(function () {
																		ct_tl_MsgCircleSend_counter++;
																		let msg_circle_bg_color = ["#ffc107","#007bff","#00b900","#eb4e3d","#6c757d"];	//#ae4cae
																		MsgCircleSend.style.backgroundColor = msg_circle_bg_color[(ct_tl_MsgCircleSend_counter%5)];
																		MsgCircleSend.style.color = "#000";
																		document.getElementById("send_next_gr_alert").style.color="black";
																		broadcast_file((num + 1),0);	//send next file
																	}, delayDefault*1000);	//wait 61 secs and resend
																}else{
																	broadcast_file((num + 1),0);	//send next file
																	return;
																}
															}else{
																broadcast_file((num + 1),0);	//send next file
																return;
															}
															
														}catch(e){
															broadcast_file((num + 1),0);	//send next file
														}
														return;
												}
											}
										}
									});
									await sleep(1000);
								} else {
									broadcast_card(0,0);	//continue column send card
									return;
								}
							} else {
								broadcast_card(0,0);	//continue column send card
								return;
							}
						}
						
						
						//////////////////////////////////
						////// Broadcast text message/////
						/////////////////////////////////
						async function broadcast_text(retry_send,retry429) {
							// if(ct_tl_delay_per_msg_ms>0){
							// 	console.log("Start text: "+getNow());
							// 	await sleep(ct_tl_delay_per_msg_ms);
							// 	console.log("End text: "+getNow());
							// }
							if(typeof retry_send =="undefined"){
								retry_send=0;
							}

							if(typeof retry429=="undefined"){retry429=0;}
							var my_broadcastline_row_text_id=myOLBroadcastTable.rows[irow];
							if(typeof my_broadcastline_row_text_id=='undefined'){return;}	//end of row 
							
							var my_broadcastline_text=document.getElementById("text_"+my_broadcastline_row_text_id.id+"col1").value;	//message id text_row1col1
							if(typeof my_broadcastline_text=='undefined'){my_broadcastline_text="";}

							my_broadcastline_text=my_broadcastline_text.trim();
							if(my_broadcastline_text==''){
								broadcast_file(0,0);	//continue column send file
								return;
							}
							if (retry_send==0){
								ct_tl_iMessNoActive++; 
							}
							
							//my_broadcastline_text = replaceAll(my_broadcastline_text,'@name',target_name);
							/*
							if(target_name=="ROOM" || target_name=="GROUP"){
								//my_broadcastline_text = my_broadcastline_text.replace(/@name/gi, '');	//g=global,i=case-insensitive
								//https://api.line.me/v2/bot/group/{groupId}/summary
								//https://api.line.me/v2/bot/room/{roomId}/summary
								var room_group_url = "https://chat.line.biz/api/v1/bots/" + ct_tl_my_broadcastline_idpage_token + "/group/" + target_id + "/summary";
								if (target_name=="ROOM"){
									//room_group_url = 'https://api.line.me/v2/bot/room/'+target_id+'/summary';
									room_group_url = "https://chat.line.biz/api/v1/bots/" + ct_tl_my_broadcastline_idpage_token + "/room/" + target_id + "/summary";

								}
								$.ajax({
									url: room_group_url,
									type: 'GET',
									dataType: 'json',
									//headers: {
									//	'Authorization': 'Bearer '+ct_tl_my_broadcastline_idpage_token,
									//},
									contentType: 'application/json; charset=utf-8',
									success: function (data) {
									   try{
											if(data.groupName){
												my_broadcastline_text = my_broadcastline_text.replace(/@name/gi, data.groupName);	//g=global,i=case-insensitive
											}else{
												my_broadcastline_text = my_broadcastline_text.replace(/@name/gi, target_name);	//g=global,i=case-insensitive
											}
										}catch(ex){my_broadcastline_text = my_broadcastline_text.replace(/@name/gi, target_name)};	//g=global,i=case-insensitive}
									
									},
									error: function (error) {
										console.log(error);
									}
								});

							}else{
								my_broadcastline_text = my_broadcastline_text.replace(/@name/gi, target_name);	//g=global,i=case-insensitive
							}
							*/
							
							my_broadcastline_text = my_broadcastline_text.replace(/@name/gi, target_name);	//g=global,i=case-insensitive
							sendidx = target_id + '_' + Math.floor(Date.now()) + '_' + Math.floor(10000000 + Math.random() * 90000000);
							//my_broadcastline_text = " ";
							
							var parms = {
								"id": "",
								"quoteToken": "",
								"text": my_broadcastline_text,
								"sendId": sendidx,
								"type": "textV2"
							};
							
							///// 2022-04-20 ////
							if(ct_tl_my_broadcastline_delay>0){
								await sleep(ct_tl_my_broadcastline_delay*1000);
							}
							
							/*
								$headers = array(
								   'cookie: XSRF-TOKEN=9f370b55-8877-40ce-9211-55e40eb5f5c5;ses=C3oG9e7mk7viF9tIIAiA38mPlfoUYxyEeu2PW05+PSa1GHiZAYdLXPDfT/B6SB2VQFWDXUIhI+HMUJm177xSqLISWCZWL/Dccd4sdgaRXWF57McHq2hcG4zj+Y+lr4PWOr3bvWUQUikC5I2jsUUyxoBif0uq7nV+QcPtNGXC8Vlm9Qzq9tgDIWsArFLDtSnET9PlLOR7Dy9f7gFp7fMAMCOF215t23rH7FJmrDT4FOXgAmt73Y7ugg0o2PHBS3wL6i4oFfti5h+G0iHvO9M3/NWaqZdag+SA77ddMlMS8/pguiWIWc8DljaXyUKa3Xq+bXNlYXwU3tuRJy01DOtd3as2geLzrGhBse/3qScIY7lWtOXLDUrGCWNtKg2lo7wg52kZysXtXc6jM+B63WyBMc+9YKA0LDAxhRLgTsLxSdJ/Wla2gIdb7V64CTv02itRod38ndPlPv4MBfucI3w+JmHuKM8mrO7dtld+H2Wayho=;',
								   "x-xsrf-token: 9f370b55-8877-40ce-9211-55e40eb5f5c5",
								   "authority: chat.line.biz",
								   "referer: https://chat.line.biz",
								   "pragma: no-cache",
								   "accept: application/json, text/plain",
								   "Content-Type: application/json",
								);
							*/
							/*
							chrome.runtime.sendMessage(
								{
									contentScriptQuery: 'fetchUrl',
									applicationcode: 'VALIDAPPLICATIONKEY'
								},
								response => console.log(response.text())
							);
							*/
							
							//Work for 20200925
							//https://api.line.me/v2/bot/message/push
							//let url_line_txt = "https://chat.line.biz/api/v1/bots/" + ct_tl_my_broadcastline_idpage_token + "/messages/" + target_id + "/send";
							//let url_line_txt = "https://chat.line.biz/api/v1/bots/" + ct_tl_my_broadcastline_idpage_token + "/messages/" + target_id + "/send";	//v3.3.2
							let url_line_txt = "https://chat.line.biz/api/v1/bots/" + ct_tl_my_broadcastline_idpage_token + "/chats/" + target_id + "/messages/send";
							//https://chat.line.biz/api/v1/bots/U092187d5351e1c5e29b00334f1e5c6ae/messages/U51236550628ec843757a7ef714473460/send
							rateLimitedCounter++;
							if(ct_tl_delay_per_msg_ms>0 && is_use_avg_time_send){
								await sleep(ct_tl_delay_per_msg_ms);
							}
							$.ajax({
								url: url_line_txt,
								contentType: 'application/json; charset=utf-8',
								dataType: 'json',
								data: JSON.stringify(parms),
								method: 'POST',
								//New
								type: 'POST', // For jQuery < 1.9
								beforeSend: function (xhr) {
									xhr.withCredentials = true; //Include this line
									xhr.setRequestHeader('Accept', 'application/json, text/plain, */*');
									//xhr.setRequestHeader('XSRF-TOKEN', ct_tl_lineCSRF);
									xhr.setRequestHeader('x-xsrf-token', ct_tl_lineCSRF);
									xhr.setRequestHeader('dataType', 'json');
									//xhr.setRequestHeader('authority', 'chat.line.biz');
									//xhr.setRequestHeader('authority', 'chat.line.biz');
								},
								crossOrigin: true,
								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
								success: function (data, textStatus, request) {

									is_can_send_somthing_success=true;
									runningAllitemsProgress();
									show_msg_report(target_id,target_name,"0",window.lang.translate("Send message to friend #no.")+' '+(loop+1) + ' row ' + irow+' '+window.lang.translate("Completed") + " msgs. " + ct_tl_iProgressAllItemsCount );

									ct_tl_demo_usage_ratelimit++;
									if(ct_tl_user_type=="ทดลองใช้งาน" && Number(ct_tl_demo_ratelimit)>0){
										ct_tl_demo_usage_ratelimit_left = Number(ct_tl_demo_ratelimit) - Number(ct_tl_demo_usage_ratelimit);
										document.getElementById('plan_package').innerHTML="plan "+ct_tl_user_type+ " "+ window.lang.translate("Time left") +" "+ ct_tl_demo_usage_ratelimit_left +" "+ window.lang.translate("Messages per day");
										document.getElementById('plan_demo_package').innerHTML=document.getElementById('plan_package').innerHTML
										
										if(Number(ct_tl_demo_usage_ratelimit) > Number(ct_tl_demo_ratelimit)){
											Swal.fire({
												title: window.lang.translate('Cannot do the transaction'),
												html: window.lang.translate("You have sent the full amount of messages per day")+"<br /><a href='" + LINE_URL_QRCODE + "'>Line : " + LINE_AT_ID + "</a>",
												type: 'warning',
												footer: footer_swal(),
												showCancelButton: true,
												confirmButtonColor: '#3085d6',
												cancelButtonColor: '#d33',
												confirmButtonText: window.lang.translate('Yes'),
												cancelButtonText: window.lang.translate('Cancel')
											}).then((result) => {
												if (result.value) {
													var mywinUrl = window.open(LINE_URL_QRCODE, '_blank');
													mywinUrl.focus();
												}
											});
											setStopJob(0,false,0);
											return;
										}
									}
									
									//////////////////// Solution 1 /////////////////////
									//rateLimitedCounter++;
									//MsgCircleSend.innerHTML = rateLimitedCounter + "/" + ct_tl_MsgCircleSend_counter;
									MsgCircleSend.innerHTML = rateLimitedCounter + "/" + ct_tl_MsgCircleSend_counter + "/" + ct_tl_send_msg_limit_person_before_delay_counter;

									if(rateLimitedPrevStamp==null){
										rateLimitedPrevStamp=new Date();
									}
									
									if (!is_use_avg_time_send){
										let timeLapse=Math.ceil(((new Date().getTime() - rateLimitedPrevStamp.getTime())/1000));							
										if( rateLimitedCounter>=ct_tl_rateLimitedMaxPerMin || timeLapse>60){
											delayDefault = timeLapse - 1;

											if(delayDefault>60){	//more than 1 minutes
												//delayDefault = 15;//0.1;
												delayDefault = 0.1;
											}else{
												delayDefault = 60-delayDefault+10;	//plus 10 sec;
												if(delayDefault<0){
													//delayDefault = 15;//0.1;
													delayDefault = 0.1;
												}
											}
											//delayDefault = 65;
											
											show_msg_report(target_id,target_name,"2"," Delay: "+delayDefault + " rate limited count: "+rateLimitedCounter );
											rateLimitedCounter=0;
											rateLimitedPrevStamp=null;
											const now = new Date();
											
											ct_tl_send_msg_next_time_gettime = now.getTime()+(delayDefault*1000);
											document.getElementById("stop_time").innerHTML=window.lang.translate("Wait for next send time") +" " + getDateTime(new Date(ct_tl_send_msg_next_time_gettime));
											document.getElementById("send_next_gr_alert").innerHTML=document.getElementById("stop_time").innerHTML + "  /" + ct_tl_send_msg_limit_person_before_delay_counter + "/" + (loop+1) + " DELAY " + CT_TL_SEND_MSG_PERSON_DELAY_TIME_MIN + " Minutes every 200 Persons";
											document.getElementById("send_next_gr_alert").style.color="red";
											ct_tl_execSetTimeout = setTimeout(function () {
												ct_tl_MsgCircleSend_counter++;
												let msg_circle_bg_color = ["#ffc107","#007bff","#00b900","#eb4e3d","#6c757d"];	//#ae4cae
												MsgCircleSend.style.backgroundColor = msg_circle_bg_color[(ct_tl_MsgCircleSend_counter%5)];
												MsgCircleSend.style.color = "#000";
												document.getElementById("send_next_gr_alert").style.color="black";
												broadcast_file(0,0);	//continue column send file
											}, delayDefault*1000);	//wait 61 secs and resend
										}else{
											broadcast_file(0,0);	//continue column send file
											return;
										}
									}else{
										broadcast_file(0,0);	//continue column send file
										return;
									}
								},
								error: function (XMLHttpRequest, textStatus, errorThrown) {
									//May need to show report unsend
									//console.log(XMLHttpRequest);
									//XMLHttpRequest.status=400;
									//XMLHttpRequest.statusText=="error";
									//XMLHttpRequest.responseText== code smart_response_enabled
									//XMLHttpRequest.responseJSON.code=="not_login"; 401
									let responseText = XMLHttpRequest.responseText;
									if(typeof responseText!=="undefined" && responseText!=null && responseText!=""){
										try{
											//{"details":[{"message":"length must be between 0 and 2000","property":"text"}]}
											responseText = responeText.details[0].message;
										}catch(e){}
									}
									
									if(XMLHttpRequest.statusText!=""){
										responseText = XMLHttpRequest.statusText + " " + responseText;
									}
									
									try{
										if(XMLHttpRequest.status==400 && responseText=="length must be between 0 and 2000"){
										}else{
											iziToast.error({
												title: window.lang.translate("Person number")+' : ' + (loop+1) + ' '+ target_name  + ' row:'+irow +' STATUS:('+ XMLHttpRequest.status + ') '+window.lang.translate("Unable to send messages")+'<br />' +XMLHttpRequest.responseText,
												position: 'topRight',
												timeout: 5000,
												image: imageUrl,	//'https://profile.line-scdn.net/' + iconhash + '/preview',
												imageWidth: 50,
												message: "",
											});
										}
										if(XMLHttpRequest.status==401 && XMLHttpRequest.responseJSON.code=="not_login"){
											setStopJob(0,false,0);
											show_msg_report(target_id,target_name,"1",window.lang.translate("Stop")+" : "+(loop+1) + ' row ' + irow+ " " +window.lang.translate("Message no.")+ " : "+ct_tl_iMessNoActive + " msgs. " + ct_tl_iProgressAllItemsCount);
											ct_tl_status_running=false;
											Swal.fire({
												title: window.lang.translate('Stop'),
												type: 'danger',	//    icon: "warning",
												html: window.lang.translate("Stop")+' please login line manager and re-open TL<br>กรุณา Login ไลน์แมนเนเจอร์ใหม่อีกครั้งแล้วให้ทำการปิดแล้วเปิดโปรกรมขึ้นมาทำงานใหม่อีกรอบ',
											});
										}
									}catch(e){}
									
									
									if(XMLHttpRequest.status==0){	//internet failed
										check_net()
										.then((data) => {
											broadcast_text(1);
											//broadcast_file(0,0);	//continue column send file 
										}).catch((error) => {
											//console.log(error);
											show_msg_report(target_id,target_name,"1",window.lang.translate("Communicating with LINE OA problem")+" : "+(loop+1) + ' row ' + irow+ " " +window.lang.translate("Message no.")+ " : "+ct_tl_iMessNoActive + " msgs. " + ct_tl_iProgressAllItemsCount);
											ct_tl_status_running=false;
											wait_net_online(loop,target_name,target_id);
											return;
										});
									}else{
										if(typeof retry429=="undefined"){retry429=0;}
										if(XMLHttpRequest.status==429 && retry429<12){	//To many request (rate limit)
											retry429++;
											var delay429 = 90; //secs
											//const delay429 = 6;	//	30;
											var now = new Date();
											if (retry429>1){
												ct_tl_send_msg_limit_person_before_delay_counter=CT_TL_SEND_MSG_LIMIT_PERSON_BEFORE_DELAY;
												delay429=CT_TL_SEND_MSG_PERSON_DELAY_TIME_MIN*60;
											}
											ct_tl_send_msg_next_time_gettime = now.getTime()+(delay429*1000);
											show_msg_report(target_id,target_name,"1",window.lang.translate("Send a message to a friend #no.") + ' row ' + irow+' '+(loop+1)+' '+window.lang.translate("Unsuccessful")+' -> status:429 ' +window.lang.translate("Speed ​​limit") + " Next:"+getDateTime(new Date(ct_tl_send_msg_next_time_gettime)) + " msgs. " + ct_tl_iProgressAllItemsCount);
											
											document.getElementById("stop_time").innerHTML=window.lang.translate("Wait for next send time")+" " + getDateTime(new Date(ct_tl_send_msg_next_time_gettime));
											document.getElementById("send_next_gr_alert").innerHTML=document.getElementById("stop_time").innerHTML + "  /" + ct_tl_send_msg_limit_person_before_delay_counter + "/" + (loop+1) + " DELAY " + CT_TL_SEND_MSG_PERSON_DELAY_TIME_MIN + " Minutes every 200 Persons";
											document.getElementById("send_next_gr_alert").style.color="red";
											ct_tl_execSetTimeout = setTimeout(function () {
												rateLimitedCounter=0;
												rateLimitedPrevStamp=null;
												document.getElementById("send_next_gr_alert").style.color="black";
												broadcast_text(0,retry429);
											}, delay429*1000);	//wait 62 secs and resend
										
										}else {
											try{
												//check error send in each friends
												if(ct_tl_prev_friend_loop!=loop && is_can_send_somthing_success==false){
													ct_tl_prev_friend_loop=loop;
													ct_tl_send_txt_err_count++;
												}
												
												//rateLimitedCounter++;
												if(XMLHttpRequest.status==400){
													show_msg_report(target_id,target_name,"1",window.lang.translate("Send message got a problem. Send to someone #no.")+" : "+(loop+1) + ' row ' + irow+ ' '+ window.lang.translate("Message no.")+" : "+ct_tl_iMessNoActive+" -> status: "+XMLHttpRequest.status+ ' ' + responseText + ' '+window.lang.translate("Or you have turned on AI mode") + " msgs. " + ct_tl_iProgressAllItemsCount);
												}else{
													show_msg_report(target_id,target_name,"1",window.lang.translate("Send message got a problem. Send to someone #no.")+" : "+(loop+1) + ' row ' + irow+' '+ window.lang.translate("Message no.")+" : "+ct_tl_iMessNoActive+" -> status: "+XMLHttpRequest.status+ ' ' + responseText + " msgs. " + ct_tl_iProgressAllItemsCount);
												}
												ct_tl_itemsSendErrorCount++;
												runningAllitemsProgress();
												
												///////////////////////////
												//////////////////////////
												//////////////////// Solution 1 /////////////////////
												//rateLimitedCounter++;
												//MsgCircleSend.innerHTML = rateLimitedCounter + "/" + ct_tl_MsgCircleSend_counter;
												MsgCircleSend.innerHTML = rateLimitedCounter + "/" + ct_tl_MsgCircleSend_counter + "/" + ct_tl_send_msg_limit_person_before_delay_counter;

												if(rateLimitedPrevStamp==null){
													rateLimitedPrevStamp=new Date();
												}
												
												if (!is_use_avg_time_send){
													let timeLapse=Math.ceil(((new Date().getTime() - rateLimitedPrevStamp.getTime())/1000));							
													if( rateLimitedCounter>=ct_tl_rateLimitedMaxPerMin || timeLapse>60){
														delayDefault = timeLapse - 1;

														if(delayDefault>60){	//more than 1 minutes
															//delayDefault = 15;//0.1;
															delayDefault = 0.1;
														}else{
															delayDefault = 60-delayDefault+10;	//plus 10 sec;
															if(delayDefault<0){
																//delayDefault = 15;//0.1;
																delayDefault = 0.1;
															}
														}
														//delayDefault = 65;
														
														show_msg_report(target_id,target_name,"2"," Delay: "+delayDefault + " rate limited count: "+rateLimitedCounter );
														rateLimitedCounter=0;
														rateLimitedPrevStamp=null;
														const now = new Date();
														
														ct_tl_send_msg_next_time_gettime = now.getTime()+(delayDefault*1000);
														document.getElementById("stop_time").innerHTML=window.lang.translate("Wait for next send time") +" " + getDateTime(new Date(ct_tl_send_msg_next_time_gettime));
														document.getElementById("send_next_gr_alert").innerHTML=document.getElementById("stop_time").innerHTML + "  /" + ct_tl_send_msg_limit_person_before_delay_counter + "/" + (loop+1) + " DELAY " + CT_TL_SEND_MSG_PERSON_DELAY_TIME_MIN + " Minutes every 200 Persons";
														document.getElementById("send_next_gr_alert").style.color="red";
														ct_tl_execSetTimeout = setTimeout(function () {
															ct_tl_MsgCircleSend_counter++;
															let msg_circle_bg_color = ["#ffc107","#007bff","#00b900","#eb4e3d","#6c757d"];	//#ae4cae
															MsgCircleSend.style.backgroundColor = msg_circle_bg_color[(ct_tl_MsgCircleSend_counter%5)];
															MsgCircleSend.style.color = "#000";
															document.getElementById("send_next_gr_alert").style.color="black";
															broadcast_file(0,0);	//continue column send file
														}, delayDefault*1000);	//wait 61 secs and resend
													}else{
														broadcast_file(0,0);	//continue column send file
														return;
													}
												}else{
													broadcast_file(0,0);	//continue column send file
													return;
												}
												
											}catch(e){
												broadcast_file(0,0);	//continue column send file 
											}
											//broadcast_file(0,0);	//continue column send file 
										}
									}
									
								}
							});

						}
						////End loop in table
						
						
					}else{
						//More than max limit
						setStopJob(0,false,0);
						
						Swal.fire({
							title: window.lang.translate('Successfully'),
							type: 'success',
							html: window.lang.translate("Send limited messages to")+' ' + ct_tl_cfg_max_recipients + ' '+window.lang.translate("Message"),
						});
						
						var d=new Date();
						var end_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 = window.lang.translate("Completed")+" "+end_date_format_str +" (max limited:"+ct_tl_cfg_max_recipients+")";
						
						show_msg_report("","","3",window.lang.translate("Send a message to friends")+' '+ct_tl_oaAccountIdActiveName+ " "+ window.lang.translate("All") +" "+ ct_tl_iSendFriendsCount+'/'+ct_tl_cfg_max_recipients+ ' '+ window.lang.translate("Person")+ ' '+ window.lang.translate("Successfully") +' blocked '+ct_tl_inactive_friends_count+ ' '+window.lang.translate("Person") );
						show_msg_report("","","3",window.lang.translate("Send a message to friends")+' '+ct_tl_oaAccountIdActiveName+" " +window.lang.translate("Message sent successfully")+ " "+(ct_tl_iProgressAllItemsCount-ct_tl_itemsSendErrorCount)+" /"+window.lang.translate("Unsuccessful")+' '+ct_tl_itemsSendErrorCount + " /"+window.lang.translate("From")+' '+  (ct_tl_iTotalMesageMustSend) + ' '+window.lang.translate("Message")+ ' ' +window.lang.translate("Successfully") );
						
						ct_tl_status_running=false;
					}
						
				} else {	//No more friends or finished
					//Not yet
					setStopJob(0,false,3);

					var oaImg="";
					if(ct_tl_oaAccountActiveImg!=""){
						oaImg=ct_tl_oaAccountActiveImg+"<br />";
					}
					

					show_msg_report("","","3",window.lang.translate("Send a message to friends")+' '+ct_tl_oaAccountIdActiveName+ " "+ window.lang.translate("All") +" "+ ct_tl_iSendFriendsCount+'/'+ct_tl_cfg_max_recipients+ ' '+ window.lang.translate("Person")+ ' '+ window.lang.translate("Successfully") +' blocked '+ct_tl_inactive_friends_count+ ' '+window.lang.translate("Person") );
					show_msg_report("","","3",window.lang.translate("Send a message to friends")+' '+ct_tl_oaAccountIdActiveName+" " +window.lang.translate("Message sent successfully")+ " "+(ct_tl_iProgressAllItemsCount-ct_tl_itemsSendErrorCount)+" /"+window.lang.translate("Unsuccessful")+' '+ct_tl_itemsSendErrorCount + " /"+window.lang.translate("From")+' '+ (ct_tl_iTotalMesageMustSend) + ' '+window.lang.translate("Message")+ ' ' +window.lang.translate("Successfully") );
						
					Swal.fire({
						title: window.lang.translate('Successfully'),
						type: 'success',
						html: oaImg+' '+window.lang.translate("Send a message to friends")+'<br />'+ct_tl_oaAccountIdActiveName+'<br />'+window.lang.translate("Successfully")+ '<br />'+ window.lang.translate("All")+ ' ' + my_broadcastline_data.length + ' '+window.lang.translate("Person"),
					});
					var d=new Date();
					var end_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 = window.lang.translate("Completed")+" "+end_date_format_str;
					ct_tl_status_running=false;
					try{
						if(localStorage){
							try{localStorage.removeItem("back_log");}catch(ee){}
							localStorage.removeItem(ct_tl_my_broadcastline_idpage_token);
						}
					}catch(exc){}
					if(ct_tl_label_user_all_send_success.length>0){
						$('#download_oa_fanpage_success_members').attr('title','Download only successfully '+ct_tl_oaAccountIdActiveName + ' '+ct_tl_label_user_all_send_success.length+' คน');
						$('#download_oa_fanpage_success_members').show();
					}
					if(ct_tl_label_user_all_send_failed.length>0){
						$('#download_oa_fanpage_failed_members').attr('title','Download only failed '+ct_tl_oaAccountIdActiveName + ' '+ct_tl_label_user_all_send_failed.length+' คน');
						$('#download_oa_fanpage_failed_members').show();
					}
				}
				
			}
	});
}

function isEmpty(obj) {
    for(var prop in obj) {
        if(obj.hasOwnProperty(prop))
            return false;
    }

    return true;
}

function checkPackagePromise(){
	if(is_allowed_rich_msg>0){
		document.getElementById('plan_package').innerHTML="plan "+ct_tl_user_type+"+Rich";
	}else{
		document.getElementById('plan_package').innerHTML="plan "+ct_tl_user_type;
	}
	//document.getElementById("plan_package").innerHTML=""+ct_tl_user_type + " " + limit_conflict_number + " PCs.";//expired[5];
	document.getElementById('plan_demo_package').innerHTML=document.getElementById('plan_package').innerHTML
	
	return new Promise(resolve => {
		if(ct_tl_user_type=="ทดลองใช้งาน" && Number(ct_tl_demo_ratelimit)>0){
			var dnow = new Date();
			var curdate = dnow.toJSON().slice(0,10);
			curdate = ct_tl_server_date;	//Hack server
			ldb.get('demo_usage_ratelimit_'+ct_tl_user_name, function (usage_ratelimit) {
				if(typeof usage_ratelimit!=="undefined" && usage_ratelimit!=null){
					var ul = usage_ratelimit.split("|");

					if(ul.length>0){
						ct_tl_demo_usage_ratelimit=ul[0];
						ct_tl_demo_usage_date=ul[1];
						ct_tl_demo_usage_ratelimit_left=[2];
						if(ct_tl_demo_usage_date!=null && ct_tl_demo_usage_date!=curdate ){
							ct_tl_demo_usage_ratelimit=0;
							ct_tl_demo_usage_ratelimit_left = ct_tl_demo_ratelimit;
							document.getElementById('plan_package').innerHTML="plan "+ct_tl_user_type+ " "+window.lang.translate("Time left")+ " "+ (ct_tl_demo_ratelimit) +" "+window.lang.translate("Messages per day");
							document.getElementById('plan_demo_package').innerHTML=document.getElementById('plan_package').innerHTML
	
							ldb.set('demo_usage_ratelimit_'+ct_tl_user_name, '0|'+curdate+'|'+ ct_tl_demo_usage_ratelimit_left+'|'+ct_tl_demo_ratelimit);
							resolve(1);
						}
						else if(Number(ct_tl_demo_usage_ratelimit)>Number(ct_tl_demo_ratelimit)){
							ct_tl_demo_usage_ratelimit_left = Number(ct_tl_demo_ratelimit) - Number(ct_tl_demo_usage_ratelimit);
							document.getElementById('plan_package').innerHTML="plan "+ct_tl_user_type+ " "+window.lang.translate("Time left") +" "+ ct_tl_demo_usage_ratelimit_left +" "+window.lang.translate("Messages per day");
							document.getElementById('plan_demo_package').innerHTML=document.getElementById('plan_package').innerHTML
							
							setStopJob(0,false,0);
							Swal.fire({
								title: window.lang.translate('Cannot do the transaction'),
								html: window.lang.translate("You have sent the full amount of messages per day")+"<br /><a href='" + LINE_URL_QRCODE + "'>Line : " + LINE_AT_ID + "</a>",
								type: 'warning',
								footer: footer_swal(),
								showCancelButton: true,
								confirmButtonColor: '#3085d6',
								cancelButtonColor: '#d33',
								confirmButtonText: window.lang.translate('Yes'),
								cancelButtonText: window.lang.translate("Cancel")
							}).then((result) => {
								if (result.value) {
									var mywinUrl = window.open(LINE_URL_QRCODE, '_blank');
									mywinUrl.focus();
								}
							});
							resolve(0);
						}else{
							ct_tl_demo_usage_ratelimit_left = Number(ct_tl_demo_ratelimit) - Number(ct_tl_demo_usage_ratelimit);
							document.getElementById('plan_package').innerHTML="plan "+ct_tl_user_type+" "+ window.lang.translate("Time left") +" "+ ct_tl_demo_usage_ratelimit_left +" "+window.lang.translate("Messages per day");
							document.getElementById('plan_demo_package').innerHTML=document.getElementById('plan_package').innerHTML
	
							resolve(1);
						}
					}else{
						ct_tl_demo_usage_ratelimit=0;
						ct_tl_demo_usage_date=curdate;
						ct_tl_demo_usage_ratelimit_left=ct_tl_demo_ratelimit;
						ldb.set('demo_usage_ratelimit_'+ct_tl_user_name, '0|'+curdate+'|'+ ct_tl_demo_ratelimit+'|'+ct_tl_demo_ratelimit);
						resolve(1);
					}
				}else{
					//ct_tl_demo_usage_ratelimit=0;
					//ct_tl_demo_usage_date=curdate;
					//ct_tl_demo_usage_ratelimit_left=ct_tl_demo_ratelimit;
					//ldb.set('demo_usage_ratelimit_'+ct_tl_user_name, '0|'+curdate+'|'+ ct_tl_demo_ratelimit+'|'+ct_tl_demo_ratelimit);
					alert (window.lang.translate("The trial version cannot do the program today"));
					resolve(0);
				}
			});
		}else{
			resolve(1);
		}
    });
}


/*
function lineNotify(msg,Bearer_token){
	let parms = {
					"message": msg
				};
				
	$.ajax({
		url: 'https://notify-api.line.me/api/notify',
		type: 'POST',
		//dataType: 'json',
		data: JSON.stringify(parms),
		headers: {
			'Authorization': 'Bearer '+Bearer_token,
			'Access-Control-Allow-Origin': '*'
		},
		contentType: 'application/x-www-form-urlencoded',
		success: function (data) {

		},
		error: function (error) {
			console.log(error);
		}
	});
}
*/

function replaceAll(string, search, replace) {
  return string.split(search).join(replace);
}
////param 'Text1|Text2|Text3|Text4'
function spintax(text) {
	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 footer_swal() {
	return "<span style='color:#FF0000'>"+window.lang.translate("You can minimize this window")+"</span>";
}
function clearLastInterval () {
  var i = setInterval (function () {}, 10000);
  clearInterval (i-1);
  clearInterval (i);
}

function wait_net_online(loop,target_name,target_id){
	//localStorage.setItem('setstop', 2);	//Set pause flag
	//ct_tl_status_stop_pause = 1;

	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 loop_continue = loop;
	
	/*
	try{
		let stored_loop=localStorage.getItem('loops');
		if (stored_loop){
			if(stored_loop!=""){
				if(!isNaN(stored_loop)){
					loop_continue=Number(stored_loop);
				}
			}
		}
	}catch(e){
	}
	*/
	
	//'back_log';
	//show_msg_report(target_id,target_name,"2",window.lang.translate("Waiting LINE OA online")+" "+(ct_tl_iSendFriendsCount+1));
	show_msg_report(target_id,target_name,"2",window.lang.translate("Waiting LINE OA online")+" "+(loop_continue+1));
	if(ct_tl_status_running){return;}
	
	run_interval(interval_preroid);
	
	function run_interval(interval_preroid){
		var tId = setInterval(function() {
			inetretrycount++;
			
			if(inetretrycount>9000000){inetretrycount=0;}
			NetRetry.innerHTML="Next "+getTimeNow(interval_preroid) +" -> "+inetretrycount;
			check_net(isShowErrBox).then((data) => {
				clearInterval(tId);
				
				pressStart_Broadcast_Button();
				
				$('#footer-summary-container').show();
				$('#close-x').show();
				$('#open-o').hide();

				ct_tl_status_stop_pause = 1;
				
				NetStatus.innerHTML="LineOA Online";
				NetStatus.style.backgroundColor = "#005800";
				NetStatus.style.color = "#000";
				
				NetMsg.innerHTML="LineOA Good.";
				NetMsg.style.backgroundColor = "#005800";
				NetMsg.style.color = "#000";
				try{
					if(tnetId!==null){
						clearInterval(tnetId);
						//tnetId=null;
					}
					//clearLastInterval();
				}catch(err){}
				setTimeout(function () {
					$('#radio_schedule *').prop('disabled',true);
					//show_msg_report(target_id,target_name,"2",window.lang.translate("Communication with LINE OA is resumed") + " "+ window.lang.translate("Person number") +" : "+(ct_tl_iSendFriendsCount+1));
					show_msg_report(target_id,target_name,"2",window.lang.translate("Communication with LINE OA is resumed") + " "+ window.lang.translate("Person number") +" : "+(loop_continue+1));
					
					ct_tl_iSendFriendsCount = loop_continue;
					//send_my_broadcastline_continue(ct_tl_iSendFriendsCount);
					send_my_broadcastline_continue(loop_continue);
					
					try{
						clearInterval(tId);
					}catch(exc){}
					return;
					
				}, (2000));
			}).catch((error) => {
				NetStatus.innerHTML="LineOA 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="LineOA 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://chat.line.biz/',	//document.location.origin,	//'https://chat.line.biz/'
		type: 'HEAD',
		data: {
			key: '',
		},
		success: function (data) {
			var NetStatus = document.getElementById('NetStatus');
			NetStatus.innerHTML="LINE OA Online";
			NetStatus.style.backgroundColor = "#005800";
			NetStatus.style.color = "#000";
			resolve("successfully")
		},
		error: function (error) {
			if(isShowErrBox){
				console.log("you are offline");
				iziToast.error({
					title: window.lang.translate('Unabled to communicate with LINE OA'),
					position: 'topCenter',
					timeout: 5000,
					message: '',
				});
			}
			var NetMsg = document.getElementById("NetMsg");
			NetStatus.innerHTML="LINE OA 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 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);
	
	try{
		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;
				}
			}
		}
	}catch(e){}
	
	try{
		clock.innerHTML = h + ":" + m + ":" + s;
		let stop_time_gr_alert = document.getElementById('stop_time_gr_alert');
		stop_time_gr_alert.innerHTML = h + ":" + m + ":" + s;
	}catch(e){}
	
	let t = setTimeout(startTime, 500);
}
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);
    }));
}

function generateUUID() {
    var d = new Date().getTime();
    var uuid = 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) {
        var r = (d + Math.random()*16)%16 | 0;
        d = Math.floor(d/16);
        return (c=='x' ? r : (r&0x3|0x8)).toString(16);
    });
    return uuid;
};
//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(''));
}

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){
	//0 green,1 red, 2 blue, 3 finished
	let my_log_detail = document.getElementById("my_log_detail");
	let my_log_detail_val = 0;
	let isWriteLog = false;
	
	if(my_log_detail){
		//0 show all,1 hide all, 2 show error,3 show completed
		my_log_detail_val = my_log_detail.value;
		if(my_log_detail_val=="1"){return;}
	}
	var color_status = "#c50606";	//red
	if(send_status=="2" && (my_log_detail_val=="3" || my_log_detail_val=="0") ){
		color_status = "#080892";	//blue
		isWriteLog = true;
	}else if(send_status=="3"){
		color_status = "#fff700";	//	finished
		msg = '<i style="font-weight:900;color:#14f200;">&nbsp;&nbsp;('+window.lang.translate("Completed")+')&nbsp;</i>'+msg;
		isWriteLog = true;
	}else if(send_status!="" && send_status!="0" && (my_log_detail_val=="2" || my_log_detail_val=="0")){	//send_status=1
		msg='<i style="font-weight:900;color:red;">&nbsp;&nbsp;('+window.lang.translate("Unsuccessful")+')&nbsp;</i>code:&nbsp;'+msg;
		isWriteLog = true;
	}else if((my_log_detail_val=="3" || my_log_detail_val=="0") ) {
		color_status = "#00f700";	//green
		msg = '<i style="font-weight:900;color:#14f200;">&nbsp;&nbsp;('+window.lang.translate("Completed")+')&nbsp;</i>'+msg;
		isWriteLog = true;
	}
	
	if(isWriteLog == false){msg="";return;}
	
	if(target_id!="" || target_name!=""){
		msg = "Id: "+ target_id + " ,"+window.lang.translate("Name")+": "+ target_name + "->" +msg;
	}
	if(typeof row_number!=="undefined"){
		msg = getFormattedDate() + "     " + msg + "&nbsp;"+window.lang.translate("Line number")+"&nbsp;"+(row_number+1);
	}else{
		msg = getFormattedDate() + "     " + msg;
	}
	if(typeof msg_type!=="undefined" && msg_type!=""){
		if(msg_type==window.lang.translate("Message")) {//"ข้อความ"){
			msg +=" "+window.lang.translate("Type")+" "+ '<i style="font-weight:900;color:#fcf803;">'+ msg_type+'</i>';
		}else{
			msg +=" "+window.lang.translate("Type")+" "+ '<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 getBroadcastTag(){
	let sel=document.getElementById("my_broadcastline_idpage");
	let opt = sel.options[sel.selectedIndex];
	my_broadcastline_id="";
	if(typeof opt!=="undefined" && opt!=null ){
		my_broadcastline_id=opt.getAttribute('data-botId');	//in popup.js
	}
	
	
	document.getElementById('recipients_option_tag_msg').textContent='<br />ไม่พบข้อมูล Tag';
	document.getElementById('recipients_option_tag_msg').innerHTML='';
	document.getElementById('recipients_option_tag_msg').textContent='<br />ไม่พบข้อมูล Tag';
	document.getElementById('recipients_option_tag_msg').innerHTML='<br />ไม่พบข้อมูล Tag';
	
	if(my_broadcastline_id==""){return;}
	
	if ($('#my_broadcastline_select_type').val() == 1) {
		$('#recipients_option_folder').show();
		$('#recipients_option_tag').hide();
	} else {
		$('#recipients_option_folder').hide();
		$('#recipients_option_tag').show();
		$('#recipients_option_tag_msg').hide();

		$('#cfg_recipients_option_tag').html('');
		
		$.ajax({
			type: 'get',
			url: 'https://chat.line.biz/api/v1/bots/' + my_broadcastline_id + '/tags',
			success: function (data) {
				$('#cfg_recipients_option_tag').html('');
				$.each(data.list, function (key, list) {
					let optText = list.name + '(' + list.count + ')';
					let optValue = list.tagId;
					$('#cfg_recipients_option_tag').append(`<option value="${optValue}">${optText}</option>`);
				});
				if(data.list.length>0){
					$('#cfg_recipients_option_tag').multiselect({
						includeSelectAllOption: true,
						enableFiltering: true,
						selectAllText: 'Select All',
						numberDisplayed: 1,
						maxHeight: 250 
					});
					try{
						if(typeof $('#cfg_recipients_option_tag').val($('#cfg_recipients_option_tag'))!="undefined" && $('#cfg_recipients_option_tag').val($('#cfg_recipients_option_tag'))!=null){
							$('#cfg_recipients_option_tag').val($('#cfg_recipients_option_tag').prop('selectedIndex', 0).val()).attr('selected',true);		//set start at selectedIndex = 0
						}
					}catch(e){}
					//$('#cfg_recipients_option_tag').multiselect('refresh');
					$('#cfg_recipients_option_tag').multiselect('rebuild');
					//$('#cfg_recipients_option_tag').multiselect('selectAll', false);
					$('#cfg_recipients_option_tag').multiselect('updateButtonText');
					
					$('#cfg_recipients_option_tag').show();
					document.getElementById('recipients_option_tag_msg').textContent='';
					document.getElementById('recipients_option_tag_msg').innerHTML='';
				}else{
					$('#cfg_recipients_option_tag').hide();
					$('#recipients_option_tag_msg').show();
					document.getElementById('recipients_option_tag_msg').textContent='<br />ไม่พบข้อมูล Tag';
					document.getElementById('recipients_option_tag_msg').innerHTML='<br />ไม่พบข้อมูล Tag';
				}
			},
			error: function (e) {
				$('#recipients_option_tag_msg').show();
				document.getElementById('recipients_option_tag_msg').textContent='<br />ไม่พบข้อมูล Tag';
				document.getElementById('recipients_option_tag_msg').innerHTML='<br />ไม่พบข้อมูล Tag';
			},
		});
	}
}



function customForm(){
	try{
		fetch("../custom/custom.json")
		.then(response => {
		   return response.json();
		})
		.then(data => console.log(data));
	}catch(err){console(err);}
}

//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() {
    // your code here script load completed
	console.log('window load');
})
window.addEventListener('error', function(e) { 
	console.log('ooops inf loop');
	try{
		clearInterval(idvideo);
	}catch(e){}
});

window.onkeyup = evt => {
    switch (evt.keyCode) {
        case 27:
            //this.onEsc();
            break;
        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();
			start_broadcast();
			break;
        default:
            return true;
    }
    return false;
}

var sleepMode = {
    prevent: function() {
        if (!this._video) {
            this._init();
        }
		try{
			if(this._video.paused){
				this._video.setAttribute('loop', 'loop');
				this._video.play();
			}
		}catch(e){}
    },
    allow: function() {
        if (!this._video) {
            return;
        }
		try{
			this._video.removeAttribute('loop');
			this._video.pause();
		}catch(e){}
    },
    _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 playAudio(){
	const masterAudio = new Audio("data:video/mp4;base64, ");
	function playSound(){
		for (let i=0;i<1;i++){
			const clone = masterAudio.cloneNode();
			window.setTimeout(()=>{
			},i*250);
		}
	}
}

function playVideo(){
	var Util={};
	Util.base64 = function(mimeType, base64) {
	  return 'data:' + mimeType + ';base64,' + base64;
	};

	var video = document.createElement('video');
		video.setAttribute('loop', '');

	function addSourceToVideo(element, type, dataURI) {
		var source = document.createElement('source');
		source.src = dataURI;
		source.type = 'video/' + type;
		element.appendChild(source);
	}

	addSourceToVideo(video,'webm', Util.base64('video/webm', 'GkXfo0AgQoaBAUL3gQFC8oEEQvOBCEKCQAR3ZWJtQoeBAkKFgQIYU4BnQI0VSalmQCgq17FAAw9CQE2AQAZ3aGFtbXlXQUAGd2hhbW15RIlACECPQAAAAAAAFlSua0AxrkAu14EBY8WBAZyBACK1nEADdW5khkAFVl9WUDglhohAA1ZQOIOBAeBABrCBCLqBCB9DtnVAIueBAKNAHIEAAIAwAQCdASoIAAgAAUAmJaQAA3AA/vz0AAA='));
	addSourceToVideo(video, 'mp4', Util.base64('video/mp4', 'AAAAHGZ0eXBpc29tAAACAGlzb21pc28ybXA0MQAAAAhmcmVlAAAAG21kYXQAAAGzABAHAAABthADAowdbb9/AAAC6W1vb3YAAABsbXZoZAAAAAB8JbCAfCWwgAAAA+gAAAAAAAEAAAEAAAAAAAAAAAAAAAABAAAAAAAAAAAAAAAAAAAAAQAAAAAAAAAAAAAAAAAAQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAIAAAIVdHJhawAAAFx0a2hkAAAAD3wlsIB8JbCAAAAAAQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABAAAAAAAAAAAAAAAAAAAAAQAAAAAAAAAAAAAAAAAAQAAAAAAIAAAACAAAAAABsW1kaWEAAAAgbWRoZAAAAAB8JbCAfCWwgAAAA+gAAAAAVcQAAAAAAC1oZGxyAAAAAAAAAAB2aWRlAAAAAAAAAAAAAAAAVmlkZW9IYW5kbGVyAAAAAVxtaW5mAAAAFHZtaGQAAAABAAAAAAAAAAAAAAAkZGluZgAAABxkcmVmAAAAAAAAAAEAAAAMdXJsIAAAAAEAAAEcc3RibAAAALhzdHNkAAAAAAAAAAEAAACobXA0dgAAAAAAAAABAAAAAAAAAAAAAAAAAAAAAAAIAAgASAAAAEgAAAAAAAAAAQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABj//wAAAFJlc2RzAAAAAANEAAEABDwgEQAAAAADDUAAAAAABS0AAAGwAQAAAbWJEwAAAQAAAAEgAMSNiB9FAEQBFGMAAAGyTGF2YzUyLjg3LjQGAQIAAAAYc3R0cwAAAAAAAAABAAAAAQAAAAAAAAAcc3RzYwAAAAAAAAABAAAAAQAAAAEAAAABAAAAFHN0c3oAAAAAAAAAEwAAAAEAAAAUc3RjbwAAAAAAAAABAAAALAAAAGB1ZHRhAAAAWG1ldGEAAAAAAAAAIWhkbHIAAAAAAAAAAG1kaXJhcHBsAAAAAAAAAAAAAAAAK2lsc3QAAAAjqXRvbwAAABtkYXRhAAAAAQAAAABMYXZmNTIuNzguMw=='));

	video.play();
}

function blankVideo(){
	var html=`
	<video>
	  <source src="data:video/mp4;base64,  ">
	  <source src="data:video/ogg;base64,  " type="video/ogg">
	  <source src="data:video/webm;base64,  " type="video/webm">
	</video>
	`;
}

async function wakelock(){
	// The wake lock sentinel.
	let wakeLock = null;

	// Function that attempts to request a screen wake lock.
	const requestWakeLock = async () => {
		try {
			wakeLock = await navigator.wakeLock.request();
			
			wakeLock.addEventListener('release', () => {
				//console.log('Screen Wake Lock released:', wakeLock.released);
			});
			
			//console.log('Screen Wake Lock released:', wakeLock.released);
		} catch (err) {
			console.error(`${err.name}, ${err.message}`);
		}
	};
	// Request a screen wake lock…
	await requestWakeLock();
} 

function getIsLogin(){
	usrfToken = "";
	return new Promise(function (resolve) {
		chrome.storage.local.get("information", function(t) {
			if(typeof t!=="undefined" && t!=null){
				if(typeof t.information!=="undefined" && t.information!=null){
					if(typeof t.information.token!=="undefined" && t.information.token!=null){
						usrfToken = t.information.token;
					}
					if(typeof t.information.is_allowed_rich_msg!=="undefined" && t.information.is_allowed_rich_msg!=null){
						is_allowed_rich_msg = t.information.is_allowed_rich_msg;
					}
					if(t.information.email && t.information.key){
						resolve(true);
					}else{
						resolve(false);
					}
				}else{
					resolve(false);
				}
			}else{
				resolve(false);
			}
		});
	});
}

function backlogDelRow(elem){
	//console.log('row delete');
	//console.log(elem);
	//U03a028f4a8dffe15fc446cf4a69d81ef
	//U03a028f4a8dffe15fc446cf4a69d81ef
	try{
		//var attrVal = document.getElementById(elem.id).getAttribute("row_number");
		if(backlog_table!=null){
			var col_storage_key = 2;
			var row_data_key = "";
			
			
			var attrVal = backlog_table.getSelectedRows()[0].getAttribute("data-y");
			row_data_key=backlog_table.getRowData(attrVal)[col_storage_key];

			setTimeout(function() {
				if(backlog_table.rows.length>1){
					backlog_table.deleteRow(Number(attrVal), 1);
				}else{
					backlog_table.setData([]);
				}
			}, 100);
			try{localStorage.removeItem(row_data_key);}catch(ee){}
		}
		
		//backlog_table.options.data.length
		
	}catch(eex){}
}
function backlogDelAllRows(){
	//U03a028f4a8dffe15fc446cf4a69d81ef
	//U03a028f4a8dffe15fc446cf4a69d81ef
	
	try{
		//var attrVal = document.getElementById(elem.id).getAttribute("row_number");
		if(backlog_table!=null){
			var col_storage_key = 2;
			var row_data_key = "";
			
			var attrVal = backlog_table.options.data.length;

			for(let i=0;i<attrVal;i++){
				row_data_key=backlog_table.getRowData(0)[col_storage_key];
				if(i=(attrVal-1)){
					backlog_table.setData([]);
				}else{
					backlog_table.deleteRow(0, 1);
				}
				try{localStorage.removeItem(row_data_key);}catch(ee){}
				
			}
			
		}
		
		//backlog_table.options.data.length
		
	}catch(eex){}
	
}
function backlogSelectedRow(){
	try{
		if(backlog_table!=null){
			var col_storage_key = 2;
			var col_number_send = 6;
			var page_id = "";
			
			var attrVal = backlog_table.getSelectedRows()[0].getAttribute("data-y");
			page_id=backlog_table.getRowData(attrVal)[col_storage_key];
			
			let sel=document.getElementById("my_broadcastline_idpage");
			
			//console.log(page_id);
			for(let sel_len=0;sel_len<sel.length;sel_len++){
				let opt = sel.options[sel_len];
				if(typeof opt!=="undefined" && opt!=null ){
					//console.log(opt.getAttribute('data-botId'));
					if(opt.getAttribute('data-botId')==page_id){
						
						//console.log(sel_len);
						sel.selectedIndex = sel_len;

						if(ct_tl_oHandler){
							//console.log("selectedIndex");
							ct_tl_oHandler.set("selectedIndex", sel_len);
						}
						
						ct_tl_my_broadcastline_select_index = sel.selectedIndex;
						ct_tl_my_broadcastline_idpage_token=opt.getAttribute('data-botId');
						
						let number_send = backlog_table.getRowData(attrVal)[col_number_send];
						document.getElementById("cfg_start_seding_no").value = Number(number_send)+1;
							
						break;
					}
				}
			}
			
		}
		
		//backlog_table.options.data.length
		
	}catch(eex){console.log(eex);}

}
async function isExistBacklog(){
	try{
		let get_all_storage = await getAllStorage();
		return new Promise(function (resolve) {
			if(typeof get_all_storage!=="undefined" && get_all_storage!=null && get_all_storage.length>0){
				document.getElementById("btn_menu_backlog_oa_tl").style.display = "inline-block";
				resolve([true, get_all_storage]);
			}else{
				document.getElementById("btn_menu_backlog_oa_tl").style.display = "none";
				resolve([false, []]);
			}
		});
		
	}catch(err){
		document.getElementById("btn_menu_backlog_oa_tl").style.display = "none";
		return new Promise(function (resolve) {
			resolve([false, []]);
		});
	}
	
}

async function showAllStorage(){	//call from gui
	try{
		let is_login = await getIsLogin();
		let is_exist_back_log = await isExistBacklog();
		if(is_exist_back_log[0]==true){
			if(!is_login){return;}
			getBacklogToTable(is_exist_back_log[1]);
		}
	}catch(ee){console.log(ee)};
	
}

function getBacklogToTable(data){
	try{
		var elements = document.getElementsByClassName("backlogDelRowClass");
		for (var i = 0; i < elements.length; i++) {
			elements[i].removeEventListener("click", backlogDelRow);
		}

	}catch(ee){
	}

	let result = json2array(data);
	
	let modalBacklog = document.getElementById("modalBacklog");
	modalBacklog.style.width = "1090px";
	modalBacklog.style.height = "500px";
	document.getElementById('grid_table_backlog').innerHTML = '';
	
	var data = [
		['Jazz', 'Honda', '2019-02-12', '', true, '$ 2.000,00', '#777700'],
		['Civic', 'Honda', '2018-07-11', '', true, '$ 4.000,01', '#007777'],
		['Jazz', 'Honda', '2019-02-12', '', true, '$ 2.000,00', '#777700'],
		['Civic', 'Honda', '2018-07-11', '', true, '$ 4.000,01', '#007777'],
		['Jazz', 'Honda', '2019-02-12', '', true, '$ 2.000,00', '#777700'],
		['Civic', 'Honda', '2018-07-11', '', true, '$ 4.000,01', '#007777'],
		['Jazz', 'Honda', '2019-02-12', '', true, '$ 2.000,00', '#777700'],
		['Civic', 'Honda', '2018-07-11', '', true, '$ 4.000,01', '#007777'],
		['Jazz', 'Honda', '2019-02-12', '', true, '$ 2.000,00', '#777700'],
		['Civic', 'Honda', '2018-07-11', '', true, '$ 4.000,01', '#007777'],
		['Jazz', 'Honda', '2019-02-12', '', true, '$ 2.000,00', '#777700'],
		['Civic', 'Honda', '2018-07-11', '', true, '$ 4.000,01', '#007777'],
		['Jazz', 'Honda', '2019-02-12', '', true, '$ 2.000,00', '#777700'],
		['Civic', 'Honda', '2018-07-11', '', true, '$ 4.000,01', '#007777'],
		['Jazz', 'Honda', '2019-02-12', '', true, '$ 2.000,00', '#777700'],
		['Civic', 'Honda', '2018-07-11', '', true, '$ 4.000,01', '#007777'],
		['Jazz', 'Honda', '2019-02-12', '', true, '$ 2.000,00', '#777700'],
		['Civic', 'Honda', '2018-07-11', '', true, '$ 4.000,01', '#007777'],
		['Jazz', 'Honda', '2019-02-12', '', true, '$ 2.000,00', '#777700'],
		['Civic', 'Honda', '2018-07-11', '', true, '$ 4.000,01', '#007777'],
	];
	
	
	backlog_table = jspreadsheet(document.getElementById('grid_table_backlog'), {
		data:result,
		defaultColWidth: 100,
        tableOverflow: true,
        tableWidth: "1040px",
		csvHeaders:true,
		tableHeight:'380px',
		editable:false,
		columns: [
			{ type: 'text', title:window.lang.translate('Sent date'), width:180 },
			{ type: 'hidden', title:'idx', width:0 },
			{ type: 'hidden', title:'account id', width:0 },
			{ type: 'text', title:window.lang.translate('Account name'), width:260 },
			{ type: 'hidden', title:'target id', width:0 },
			{ type: 'text', title:window.lang.translate('Target name'), width:200 },
			{ type: 'numeric', title:window.lang.translate('Target #no.'), width:120 },
			{ type: 'text', title:'status', width:80 },
			{ type: 'html', title:'Action',width:140, readOnly:true }
		 ]
		 
	});
	
	backlog_table.orderBy(0);	//sort column 0

	try{
		var elem = document.getElementsByClassName("backlogDelRowClass");
		for (var i = 0; i < elem.length; i++) {
			elem[i].addEventListener('click', function(e) {
				e.preventDefault();
				
				backlogDelRow(this);
				}, false);
		}
	}catch(ee){
		
	}
	
	$('#modalBacklog').w2popup();
	
}

function json2array(json){
    var result = [];
	var root = [];

	for(var i in json){
		var value = Object.values(JSON.parse(json[i]));
		value.push('<button id="backlogDelRowId'+ i +'" class="backlogDelRowClass" row_number="'+i+'" style="padding:5px;color:red;">'+window.lang.translate("Delete")+'</button>');
		root.push(value);
	}
    return root;
}

this.startLineOAInitLoad=function() {
	startLineOALoad();
}

async function startLineOALoad(){
	//debugger;
	//chrome.cookies.getAll({'url': "https://chat.line.biz/api/v1/bots"}, function (cookies) {
    //    if (cookies) {
    //        console.log(cookies); //will only pull cookies with domain value developer.chrome.com
     //   }
    //});
	
	let ret = await get_line_all_accs();	//pop.js
	await get_line_me_admin();
	let cookie = await getLineMeCookie();
	let is_login = await getIsLogin();
	//console.log("cookie:",cookie);

	document.querySelector("#dialog_loading").style.display = "none"; 
	document.querySelector("body").style.visibility = "visible";
	//history.pushState(null, null, "/");	//hide url path
	
	
	/*
	try{
		var noSleep = new NoSleep();
	}catch(e){console.log(e);}
	try{
		wakelock();
	}catch(e){console.log(e);}
	try{
		sleepMode.prevent();
	}catch(e){console.log(e);}
	try{
		try{noSleep.disable();}catch(ex){console.log(e);}
		noSleep.enable();
	}catch(e){console.log(e);}
	try{
		setTimeout(function(){
			playVideo();	//prevent screen locked
		},10000);
	}catch(e){}
	try{
		setTimeout(function(){
			chrome.power.requestKeepAwake('system');
			//chrome.power.requestKeepAwake('display');
		},15000);
	}catch(e){}
	*/
}

function get_folder_label_tag(){
	return new Promise(resolve=>{
		if ($('#my_broadcastline_select_type').val() == 2) {	//Tag Name
			//ct_tl_my_broadcastline_label = $('#cfg_recipients_option_tag').val();	//cfg_recipients_option_tag
			let all_tag = "";
			$('#cfg_recipients_option_tag :selected').each(function(i, value){ 
				if(all_tag!=""){
					all_tag += ','+$(value).text();
				}else{
					all_tag += $(value).text();
				}
			});
			resolve("Tag="+all_tag);
			return;
		}else if ($('#my_broadcastline_select_type').val() == 1) {	//folder
			//ct_tl_cfg_recipients_option_folder = $('#cfg_recipients_option_folder').val();
			let folder_name = "";
			try{folder_name = $( "#cfg_recipients_option_folder option:selected" ).text();}catch(e){}
			resolve("Name="+folder_name);
			return;
		}else{
			resolve("");
			return;
		}
	});
}

function removeDownloadLink(){
	var xx = document.getElementById("downloadLink");
	if(typeof xx!="undefined" && xx!=null){
		try{
			//x.remove();
			try{
				document.body.removeChild(xx);
			}catch(ee){}
			xx.parentNode.removeChild(xx);
		}catch(e){}
	}
}
async function DownloadLink(){
	if(permission_extract_member!=1){
		contact_detail("สิทธิ์การใช้งานฟังก์ชั่นนี้ ยังไม่ได้รับอนุญาติ");
		return;
	}
	var ids = "";
	//ct_tl_label_user_all_copy
	var xx = document.getElementById("downloadLink");
	if (ct_tl_label_user_all_copy.length==0){
		if(typeof xx!="undefined" && xx!=null){
			try{
				//x.remove();
				//document.body.removeChild(x);
				xx.parentNode.removeChild(xx);
			}catch(e){}
		}
		return;
	}
	try{
		if(typeof xx!="undefined" && xx!=null){
			xx.click();
			return;	//already create;
		}
		for (let u of ct_tl_label_user_all_copy) {
			//ids+= await u.id+"\r\n";	//u.id+", "+u.name + "\r\n"
			ids+= await u.id+", "+u.name + "\r\n";
		}
		if(ids==""){return;}
		
		//ids = 'Account Name: '+ct_tl_my_broadcastline_label_name+"\r\nFolder: "+ct_tl_my_broadcastline_name+"\r\nจำนวน: "+ct_tl_label_user_all_copy.length+"\r\n" + ids;
		let done_text = "ยังไม่เสร็จ";
		if(ct_tl_status_stop_pause==0){
			done_text = "หยุดทำงาน";
		}else if(ct_tl_status_stop_pause==2){
			done_text = "หยุดชั่วคราว";
		}else if(ct_tl_status_stop_pause==3){
			done_text = "สำเร็จ";
		}
		
		let limit_max_loaded = "จำกัดจำนวน: ทั้งหมด";
		ct_tl_cfg_max_recipients = $('#cfg_max_recipients').val();
		ct_tl_cfg_max_recipients = Number(ct_tl_cfg_max_recipients);
		if(ct_tl_label_user_all_copy.length>(ct_tl_cfg_max_recipients)){
			limit_max_loaded = "จำกัดจำนวน: "+ct_tl_cfg_max_recipients;
		}
		
		ids = 'Account Name: '+ct_tl_label_user_all_copy[0].accountName+"\r\nFolder: "+ct_tl_label_user_all_copy[0].folder+"\r\nจำนวน: "+ct_tl_label_user_all_copy.length+"\r\nวันที่: "+getNow()+"\r\n" + "Status: "+done_text+"\r\n" +limit_max_loaded+ "\r\n" + ids;
		
		let textToSave = ids;
		let folder_labels = ct_tl_label_user_all_copy[0].folder.split(',')[0];
		if(folder_labels!=""){
			folder_labels = "TAG_"+folder_labels.split('=')[1];
		}else{
			folder_labels=ct_tl_label_user_all_copy[0].folder.split('=')[1];
		}
		let save_to_file_name = ct_tl_label_user_all_copy[0].accountName+'_'+folder_labels+'_'+getDate()+'_'+ct_tl_label_user_all_copy.length+".txt";
		//let save_to_file_name = ct_tl_my_broadcastline_label_name+'_'+ct_tl_my_broadcastline_name+'_'+getDate()+'_'+ct_tl_label_user_all_copy.length+".txt";
		
		//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 xx = document.getElementById("downloadLink");
		if(typeof xx!="undefined" && xx!=null){
			try{
				//x.remove();
				//document.body.removeChild(x);
				xx.parentNode.removeChild(xx);
			}catch(e){}
		}
		let downloadLink = document.createElement("a");
		downloadLink.setAttribute("id", "downloadLink");
		downloadLink.setAttribute("title", ct_tl_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("สิทธิ์การใช้งานฟังก์ชั่นนี้ ยังไม่ได้รับอนุญาติ");	//customer.js
		return;
	}
	var ids = "";
	var xx = document.getElementById("downloadSuccessLink");
	if (ct_tl_label_user_all_send_success.length==0){
		if(typeof xx!="undefined" && xx!=null){
			try{
				xx.parentNode.removeChild(xx);
			}catch(e){}
		}
		return;
	}
	try{
		if(typeof xx!="undefined" && xx!=null){
			xx.click();
			return;	//already create;
		}
		for (let u of ct_tl_label_user_all_send_success) {
			//ids+= await u.id+"\r\n";		//u.id+", "+u.name + "\r\n"
			ids+= await u.id+", "+u.name + "\r\n";
		}
		if(ids==""){return;}
		
		let done_text = "ยังไม่เสร็จ";
		if(ct_tl_status_stop_pause==0){
			done_text = "หยุดทำงาน";
		}else if(ct_tl_status_stop_pause==2){
			done_text = "หยุดชั่วคราว";
		}else if(ct_tl_status_stop_pause==3){
			done_text = "สำเร็จ";
		}
		let limit_max_loaded = "จำกัดจำนวน: ทั้งหมด";
		ct_tl_cfg_max_recipients = $('#cfg_max_recipients').val();
		ct_tl_cfg_max_recipients = Number(ct_tl_cfg_max_recipients);
		if(ct_tl_label_user_all_copy.length>(ct_tl_cfg_max_recipients)){
			limit_max_loaded = "จำกัดจำนวน: "+ct_tl_cfg_max_recipients;
		}
		 
		ids = 'Account Name: '+ct_tl_label_user_all_send_success[0].accountName+"\r\nFolder: "+ct_tl_label_user_all_send_success[0].folder+'\r\nOnly: Successfully'+"\r\nจำนวน: "+ct_tl_label_user_all_send_success.length+"\r\nวันที่: "+getNow()+"\r\n"+"Status: "+done_text + "\r\n" +limit_max_loaded+ "\r\n" + ids;
		
		let folder_labels = ct_tl_label_user_all_copy[0].folder.split(',')[0];
		if(folder_labels!=""){
			folder_labels = "TAG_"+folder_labels.split('=')[1];
		}else{
			folder_labels=ct_tl_label_user_all_copy[0].folder.split('=')[1];
		}
		
		let textToSave = ids;
		let save_to_file_name = ct_tl_label_user_all_send_success[0].accountName+'_'+folder_labels+'_Successfully'+'_'+getDate()+'_'+ct_tl_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){
			try{
				xx.parentNode.removeChild(xx);
			}catch(e){}
		}
		let dlSuccessLink = document.createElement("a");
		dlSuccessLink.setAttribute("id", "downloadSuccessLink");
		dlSuccessLink.setAttribute("title", ct_tl_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 removeDownloadFailedLink(){
	var xx = document.getElementById("downloadFailedLink");
	if(typeof xx!="undefined" && xx!=null){
		try{
			try{
				document.body.removeChild(xx);
			}catch(ee){}
			xx.parentNode.removeChild(xx);
		}catch(e){}
	}
}
async function downloadFailedLink(){
	if(permission_extract_member!=1){
		contact_detail("สิทธิ์การใช้งานฟังก์ชั่นนี้ ยังไม่ได้รับอนุญาติ");	//customer.js
		return;
	}
	var ids = "";
	var xx = document.getElementById("downloadFailedLink");
	if (ct_tl_label_user_all_send_failed.length==0){
		if(typeof xx!="undefined" && xx!=null){
			try{
				xx.parentNode.removeChild(xx);
			}catch(e){}
		}
		return;
	}
	try{
		if(typeof xx!="undefined" && xx!=null){
			xx.click();
			return;	//already create;
		}
		for (let u of ct_tl_label_user_all_send_failed) {
			//ids+= await u.id+"\r\n";		//u.id+", "+u.name + "\r\n"
			ids+= await u.id+", "+u.name + "\r\n";
		}
		if(ids==""){return;}
		
		let done_text = "ยังไม่เสร็จ";
		if(ct_tl_status_stop_pause==0){
			done_text = "หยุดทำงาน";
		}else if(ct_tl_status_stop_pause==2){
			done_text = "หยุดชั่วคราว";
		}else if(ct_tl_status_stop_pause==3){
			done_text = "สำเร็จ";
		}
		let limit_max_loaded = "จำกัดจำนวน: ทั้งหมด";
		ct_tl_cfg_max_recipients = $('#cfg_max_recipients').val();
		ct_tl_cfg_max_recipients = Number(ct_tl_cfg_max_recipients);
		if(ct_tl_label_user_all_copy.length>(ct_tl_cfg_max_recipients)){
			limit_max_loaded = "จำกัดจำนวน: "+ct_tl_cfg_max_recipients;
		}
		
		ids = 'Account Name: '+ct_tl_label_user_all_send_failed[0].accountName+"\r\nFolder: "+ct_tl_label_user_all_send_failed[0].folder+'\r\nOnly: Failed'+"\r\nจำนวน: "+ct_tl_label_user_all_send_failed.length+"\r\nวันที่: "+getNow()+"\r\n"+"Status: "+done_text + "\r\n" +limit_max_loaded+ "\r\n" + ids;
		let folder_labels = ct_tl_label_user_all_copy[0].folder.split(',')[0];
		
		if(folder_labels!=""){
			folder_labels = "TAG_"+folder_labels.split('=')[1];
		}else{
			folder_labels=ct_tl_label_user_all_copy[0].folder.split('=')[1];
		}
		
		let textToSave = ids;
		let save_to_file_name = ct_tl_label_user_all_send_failed[0].accountName+'_'+folder_labels+'_Failed'+'_'+getDate()+'_'+ct_tl_label_user_all_send_failed.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){
			try{
				xx.parentNode.removeChild(xx);
			}catch(e){}
		}
		let dlSuccessLink = document.createElement("a");
		dlSuccessLink.setAttribute("id", "downloadFailedLink");
		dlSuccessLink.setAttribute("title", ct_tl_label_user_all_send_failed[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 lockedScreen(){
	try{
		var noSleep = new NoSleep();
	}catch(e){console.log(e);}
	try{
		wakelock();
	}catch(e){console.log(e);}
	try{
		//sleepMode.prevent();
	}catch(e){console.log(e);}
	try{
		try{noSleep.disable();}catch(ex){console.log(e);}
		noSleep.enable();
	}catch(e){console.log(e);}
	try{
		setTimeout(function(){
			playVideo();	//prevent screen locked
		},10000);
	}catch(e){}
	/*
	try{
		setTimeout(function(){
			chrome.power.requestKeepAwake('system');
			//chrome.power.requestKeepAwake('display');
		},15000);
	}catch(e){}
	*/
}

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

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

function extractNumber(n){
	let regexp = /^[0-9]|'/;
	if (regexp.test(n))
	{
		n=n.replace(/'/g, '');
		return n;
	}
	return n;
}
function extractLineId(n){
	//const regexp = /(?:'U[^']*'|'U[^']*|U[^']*)/g;
	//const regexp = /R.*|U.*|G.*/g;
	//let result = regexp.exec(n);
	return new Promise(resolve=>{
		if(n.length<1){resolve("");return;}
		let result = n.substr(0,1).toUpperCase();
		if(result=='U' || result=='R' || result=='G' ){
			resolve(n.trim().replace(/'/g, '').replace(/[\u200B-\u200D\uFEFF]/g, ''));
			return;
		}else{
			resolve("");
			return ;
		}
	});
	/*
	if(result!=null)
	{
		return result[0].trim().replace(/'/g, '').replace(/[\u200B-\u200D\uFEFF]/g, '');
	}else{
		return "";
	}
	*/
}
function generateInputData(){
	ct_tl_label_user_all = [];
	ct_tl_label_user_all_copy = [];
	ct_tl_label_user_all_send_success = [];
	ct_tl_label_user_all_send_failed = [];
	ct_tl_send_txt_err_count =0;
	
	return new Promise(async resolve => {
		let have_page_name = false;
		let pname = "";
		//$.each($('#fanpage_OA_inbox_friend_ids_send_input').val().split(/\n/), async function(i, line){
		for(let line of $('#fanpage_OA_inbox_friend_ids_send_input').val().replace(/[\u200B-\u200D\uFEFF]/gm, '').split(/\n/)){
			//.replace(/ /g,'')	//.replace(/[\u200B-\u200D\uFEFF]/gm, '')
			if(have_page_name==false){
				pname = "";
				let regexp = /(?:Account Name:[^]*$)/g;
				let result = regexp.exec(line);
				if(result!=null){
					pname = result[0].replace('Account Name:','').trim();
					have_page_name = true;
					if(pname!=""){
						await check_correct_select_option(pname);
					}
					////return false; // this is equivalent of 'break' for jQuery loop each
					//return true;       // this is equivalent of 'continue' for jQuery loop each
					continue;	//for continue for
				}
			}
			//let line_target = await extractLineId(line);
			
			let line_target ="";
			let line_name = "";
			let result = "";
			let line_type = "";
			
			if(line.length>0){
				line = line.replace(/'/g, '').replace(/[\u200B-\u200D\uFEFF]/g, '').trim();
				let line_split = line.split(',');
				if(line_split.length>0){
					result = line_split[0].substr(0,1).toUpperCase();
					let iExcept = line_split[0].indexOf(":");
					if(iExcept<0){
					//if(result=='U' || result=='R' || result=='G' ){
						if(result=='R'){
							result="ROOM";
							line_type = result;
						}else if(result=='G' || result=='C'){
							result="GROUP";
							line_type = result;
						}else if(result=='U'){
							result="USER";
							line_type = result;
						}else{
							result="UNKNOWN";
							line_type = result;
						}
						line_target = line_split[0].replace(/'/g, '').replace(/[\u200B-\u200D\uFEFF]/g, '').trim();
						if(line_split.length>1){
							line_name = line_split[1].replace(/'/g, '').replace(/[\u200B-\u200D\uFEFF]/g, '').trim();
						}
					}
				}
			}
			
			if(line_target!="" && line_target.length==33 && line_type!=""){
				if(have_page_name==true && pname!=""){	//The first index of array
					let folder_name = "";
					try{
						//folder_name=$('#cfg_recipients_option_folder').val().split('|')[0];
						folder_name=await get_folder_label_tag();
					}catch(ee){}
					ct_tl_label_user_all.push({
						'id': line_target.trim(),
						'name': line_name,
						'iconHash': '',
						'accountName':pname,
						'folder':folder_name,
						'chatType':''
					});
					pname = "";	//reset pname log only onec time
				}else{
					ct_tl_label_user_all.push({
						'id': line_target.trim(),
						'name': line_name,
						'iconHash': '',
						'accountName':'',
						'folder':'',
						'chatType':result
					});
				}
			}
		}
		//});	//for each
		resolve(true);
	});
}
async function check_correct_select_option(page_name){
	let textToFind = page_name.replace('Account Name:','');
	textToFind = textToFind.trim();
	let dd = document.getElementById('my_broadcastline_idpage');
	for (let i = 0; i < dd.options.length; i++) {
		if (dd.options[i].text == textToFind) {
			try {
				let oHandler = $("#my_broadcastline_idpage").msDropDown().data("dd");
				if(oHandler){
					dd.selectedIndex=i;
					await oHandler.set("selectedIndex", i);
					ct_tl_my_broadcastline_select_index = i;
					ct_tl_my_broadcastline_idpage_token = dd.options[i].getAttribute('data-botId');
				}
			} catch(e) {
				//console.log("Error: "+e.message);
			}
			break;
		}
	}
}


///// EVENTS handleEvent /////
async function onCompleteLineOAFanpage(){
	
	//var isGetPageList=false;
	console.log("ready use on Complete LineOA Fanpage"); 
	
	/////////
	showStart_Broadcast_Button();
	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';
				rome(dtschedule).setValue(new Date());
			}
			
		  }
	}
	document.getElementById("file_add_container").addEventListener("click", function(e){
		document.getElementById('file-file_add_container').click();
	});
	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("edit_row1col3").addEventListener("change", function(e){
		e.preventDefault();
		this.title=this.options[this.selectedIndex].text;
	});	
	document.getElementById("edit_row1col3").addEventListener("click", function(e){
		e.preventDefault();
		if(ct_tl_line_alls.length>0){
			if (ct_tl_my_broadcastline_idpage_token!=""){
				if (ct_tl_card_prev_oa_page==ct_tl_my_broadcastline_idpage_token){
					if(ct_tl_card_list.length>0){
						if(this.options.length>1){
							return;
						}else{
							populate_card_list(this,ct_tl_my_broadcastline_idpage_token);
							return;
						}
					}
				}
			}
			console.log("Get card list");
			getMsgCardList(oa_card_list_url,1,this);
		}
	});

	document.getElementById("edit_row1col4").addEventListener("change", function(e){
		e.preventDefault();
		if(is_allowed_rich_msg==0){
			Swal.fire({
				type: 'info',
				html: 'user: <b>'+$('#user_name').text()+'</b> <br /><b style="color:red;">Function not allowed ยังไม่ได้รับอนุญาติให้ใช้งานฟังก์ชั่น Rich message นี้ ติดต่อ @Linebroadcast หมดอายุใช้งานฟรี ตั้งแต่วันที่ 2023-03-01 ถึง 2023-05-31</b><br />',
				showCloseButton: true,
				showCancelButton: false,
				confirmButtonColor: '#3085d6',
				confirmButtonText: window.lang.translate('Ok'),
			}).then((result) => {
				
			});
  			this.value=this.options[0].value;
			this.title=this.options[0].text;
			return;
		}
		this.title=this.options[this.selectedIndex].text;
	});			
	document.getElementById("edit_row1col4").addEventListener("click", function(e){
		e.preventDefault();
		if(ct_tl_line_alls.length>0){
			if (ct_tl_my_broadcastline_idpage_token!=""){
				if (ct_tl_rich_prev_oa_page==ct_tl_my_broadcastline_idpage_token){
					if(ct_tl_rich_list.length>0){
						if(is_allowed_rich_msg==0){
							Swal.fire({
								//title: '<strong>INFO</strong>',
								type: 'info',
								html: 'user: <b>'+$('#user_name').text()+'</b> <br /><b style="color:red;">Function not allowed ยังไม่ได้รับอนุญาติให้ใช้งานฟังก์ชั่น Rich message นี้ ติดต่อ @Linebroadcast หมดอายุใช้งานฟรี ตั้งแต่วันที่ 2023-03-01 ถึง 2023-05-31</b><br />',
								showCloseButton: true,
								showCancelButton: false,
								confirmButtonColor: '#3085d6',
								confirmButtonText: window.lang.translate('Ok'),
							}).then((result) => {
								
							});
							this.value=this.options[0].value;
							this.title=this.options[0].text;
							return;
						}else{
							if(this.options.length>1){
								return;
							}else{
								populate_rich_list(this,ct_tl_my_broadcastline_idpage_token);
								return;
							}
						}
					}
				}
			}
			console.log("Get rich list");
			getMsgRichList(oa_rich_list_url,1,this);
		}
	});

	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) {
		document.getElementById("file-row1col2").click();
	});
	document.getElementById("get_line_fanpage").addEventListener("click", function(event) {
		event.preventDefault();
		isStartBroadcastForContinue = false;
		setTimeout(async function () {
			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 = "Start "+starttime_date_format_str;
			
			ct_tl_continue_get_friends_url="";
			$('#fanpage_OA_inbox_friend_ids_send_input').val();
			$('#download_oa_fanpage_members').hide();
			$('#download_oa_fanpage_success_members').hide();
			$('#download_oa_fanpage_failed_members').hide();
			send_my_broadcastline_start(false);	//pop.js;

			event.stopPropagation();
			event.stopImmediatePropagation();
		}, 500);
	});
	document.getElementById("download_oa_fanpage_success_members").addEventListener("click", function(event) {
		event.preventDefault();
		downloadSuccessLink();
	});
	document.getElementById("download_oa_fanpage_failed_members").addEventListener("click", function(event) {
		event.preventDefault();
		downloadFailedLink();
	});
	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) {
		var td = event.target;
		while (td !== this && !td.matches("td")) {
			td = td.parentNode;
		}
		if (td == this) {
			console.log("No table cell found");
		} else {
			if(td.cellIndex==1){	//col text
				document.getElementById("text_"+td.id).style.backgroundColor = "#fff";
			}
		}
	});
	document.querySelector("#myOLBroadcastTable tbody").addEventListener("focusout", function(event) {
		var td = event.target;
		while (td !== this && !td.matches("td")) {
			td = td.parentNode;
		}
		if (td == this) {
			console.log("No table cell found");
		} else {
			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";
			}
		}
	});
	
	document.getElementById("download_oa_fanpage_members").addEventListener("click",function(event){
		event.preventDefault();
		DownloadLink();
	});
	
	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) {
	  console.log('DOMContentLoaded');
	});
	
	const breakdownButton = document.querySelectorAll('.counterchar');
	breakdownButton.forEach(function(btn) {
	  btn.addEventListener('change', async function() {
		let tbdata = checkTableDataPromise();
		
		tbdata.then(
			function (value){
				document.getElementById("start_broadcast").style.display = "inline-block";
				if(value){
					let val = event.target.value;
					if(typeof val!='undefined' && val!=""){
						let lengthCount = val.length; 
						if (lengthCount > ct_tl_maxLimitChar) {
							event.target.value = val.substring(0, ct_tl_maxLimitChar);
							let charactersOver = (lengthCount + 1) - ct_tl_maxLimitChar;
							alert("ข้อความจำกัดอยู่ที่ 2,000 ตัวอักษร ตอนนี้เกินไป "+charactersOver+ " ตัวอักษร โปรแกรมได้ทำการตัดข้อความให้บางส่วนแล้ว ลองตรวจสอบแล้วกดเพิ่มอีกครั้ง");
							return;
						}
					}
					//document.getElementById("start_broadcast").disabled = false;
				}else{
					//document.getElementById("start_broadcast").disabled = true;
				}
			},
			function(error) {
				document.getElementById("start_broadcast").style.display = "inline-block";
			}
		);
	  });
	});

	$("#cfg_recipients_option_folder").on("change", function (e) {
		if ($("#cfg_recipients_option_folder").val().indexOf('UNREAD') > -1) {
			$('#my_broadcastline_except_unread').hide();	//checkbox unread
			document.getElementById("my_broadcastline_except_unread").checked = false;
		}else{
			document.getElementById("my_broadcastline_except_unread").checked = true;
			$('#my_broadcastline_except_unread').show();	//checkbox unread
		}
		try{
			$('#cfg_recipients_option_folder').prop('title', $('#cfg_recipients_option_folder').val().split('|')[1]);
		}catch(err){}
	});
	
	$("#my_broadcastline_select_type").on("change", function (e) {
		e.preventDefault();
		getBroadcastTag();
	});
	
	$('#fanpage_OA_inbox_friend_ids_send_input').on("change", function (e) {	//'.friends_id_lists'
		e.preventDefault();
		try{
			document.getElementById("my_broadcastline_select_type").selectedIndex=0;	//normal
			document.getElementById("cfg_recipients_option_folder").selectedIndex=0;	//ALL
			document.getElementById("cfg_recipients_option_tag").selectedIndex=0;	//ALL
			
			$('#cfg_start_seding_no').val(1);
			$('#cfg_max_recipients').val(500000);
			
			$('#recipients_option_folder').show();
			$('#recipients_option_tag').hide();
		}catch(e){}
	});
	
	$('#my_broadcastline_idpage').change(function(e){
		e.preventDefault();
		try{
			document.getElementById("my_broadcastline_select_type").selectedIndex=0;	//normal
			document.getElementById("cfg_recipients_option_folder").selectedIndex=0;	//ALL
			document.getElementById("cfg_recipients_option_tag").selectedIndex=0;	//ALL
			
			$('#cfg_start_seding_no').val(1);
			$('#cfg_max_recipients').val(500000);
			
			$('#recipients_option_folder').show();
			$('#recipients_option_tag').hide();
			
			if(ct_tl_my_broadcastline_select_index==document.getElementById("my_broadcastline_idpage").selectedIndex){
				if(ct_tl_label_user_all_copy.length>0){
					$('#download_oa_fanpage_members').show();
				}
				if(ct_tl_label_user_all_send_success.length>0){
					$('#download_oa_fanpage_success_members').show();
				}
				if(ct_tl_label_user_all_send_failed.length>0){
					$('#download_oa_fanpage_failed_members').show();
				}
			}else{
				$('#download_oa_fanpage_members').hide();
				$('#download_oa_fanpage_success_members').hide();
				$('#download_oa_fanpage_failed_members').hide();
				$('#fanpage_OA_inbox_friend_ids_send_input').val('');
			}
			$('#get_line_fanpage').show();

			let options=[];
			let objId="";

			let table = document.getElementById("myOLBroadcastTable");
			for (let i=1;i<=table.rows.length;i++) {
			   let row = table.rows[i]
			   //iterate through rows
			   //rows would be accessed using the "row" variable assigned in the for loop
			   //for (let j in row.cells) {
				let col = row.cells[3]	//Message Card
				
				objId = col.children[0].children[0].id;
				if(objId!=""){
					$("#"+objId).empty();
					options=[];
					options.push('<option value="">0-None</option>');

					let idCard=document.getElementById(objId);//.selectedIndex = "2";
					idCard.innerHTML = options.join('\n');
					idCard.title="Click to select card message";
					ct_tl_card_prev_oa_page="";
					ct_tl_card_prev_obj="";
					ct_tl_card_list = [];
				}

				col = row.cells[4]	//Rich message
				objId = col.children[0].children[0].id;
				if(objId!=""){
					$("#"+objId).empty();
					options=[];
					options.push('<option value="">0-None</option>');

					let idCard=document.getElementById(objId);//.selectedIndex = "2";
					idCard.innerHTML = options.join('\n');
					idCard.title="Click to select rich message";
					ct_tl_rich_prev_oa_page="";
					ct_tl_rich_prev_obj="";
					ct_tl_rich_list = [];
				}

			}
			
			
		}catch(e){}
	});
	
	$('#start_broadcast').show();
	$('#pause_broadcast').hide();
	$('#continue_broadcast').hide();
	$('#stop_broadcast').hide();
	$('#download_oa_fanpage_members').hide();
	$('#download_oa_fanpage_success_members').hide();
	$('#download_oa_fanpage_failed_members').hide();
	$('#get_line_fanpage').show();
	$('#group_cfg_msg_rate_limit_per_min').hide();
	
	ct_tl_txt_error_report = document.getElementById("txt_error_report");
	if(typeof ct_tl_txt_error_report!=="undefined" && ct_tl_txt_error_report!=null){
		ct_tl_txt_error_report.innerHTML="";
	}

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

		var files = e.target.files; // FileList object
		if(files.length>0){
			if (!files[0].type.match('image.*')) {
				document.getElementById('img_'+id).style.display = "none";
			}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="'+window.lang.translate("Delete file")+'"></i></i>';

			var rmClearFile = document.getElementById("rmx"+id);
			if(rmClearFile!=null){
			}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) {
		document.getElementById('id01login').style.display='none';
	});
	///
	
	var ths = document.getElementsByTagName('th');
	if(typeof ths!="undefined" && ths!=null){
		ths[4].style.display="None";	//Hide header column 4		
		var col_col4 = document.getElementById("row1col4");
		if(typeof col_col4!="undefined" && col_col4!=null){
			//document.getElementById("row1col4").style.backgroundColor = "#f7f7f7";
			col_col4.style.display = "None";
		}

		ths[3].style.display="None";	//Hide header column 4		
		var col_col3 = document.getElementById("row1col3");
		if(typeof col_col3!="undefined" && col_col3!=null){
			col_col3.style.display = "None";
		}
	}
	
	try{
		$("body").removeClass("user-select-none");
	}catch(e){
	}
	
	try{localStorage.removeItem("line_all");}catch(ee){}
	try{localStorage.removeItem("setstop");}catch(ee){}
	try{localStorage.removeItem("loops");}catch(ee){}
	
	try{
		if(IS_SHOW_BACKLOG_MENU){	//customer.js
			isExistBacklog();
		}
	}catch(ee){}
	
	//////////
	// Make the DIV element draggable:
	const FbPauseStopButtonControl = document.getElementById("modal_alert_container");
	const FbPauseStopButtonControlParent = document.getElementById("modalGrAlert");
	if(FbPauseStopButtonControl){
		FbPauseStopButtonControl.style.left = "20%";
		FbPauseStopButtonControl.style.top = "10%";
	}
	dragElement(document.getElementById("modal_alert_container"),"my_header");
	document.getElementById("start_broadcast").disabled = false;
	//dragElement(document.getElementById("modalWorkingDelay"));
	function dragElement(elmnt,dragTitleId) {
		if(!elmnt){return;}
		let pos1 = 0, pos2 = 0, pos3 = 0, pos4 = 0;
		const eleDragTitleId = document.getElementById(dragTitleId);
		if(!eleDragTitleId){return;}
		
		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:
			if(elmnt.offsetTop - pos2<0){return;}
			if(elmnt.offsetLeft - pos1<(0-elmnt.offsetWidth+50)){return;}
			
			let moveMaxRight = screen.width;
			if(FbPauseStopButtonControlParent){
				moveMaxRight = FbPauseStopButtonControlParent.offsetWidth;
			}
			
			if(elmnt.offsetLeft - pos1>(moveMaxRight-50)){return;}
			
			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;
		}
	}
	/////////
	//getIsLogin
	let is_login = await getIsLogin();
	if (is_allowed_rich_msg==2){
		Swal.fire({
			type: 'info',
			html: '<b style="color:blue;">เฉพาะฟังก์ชั่น Rich message ทดลองใช้งานฟรีได้ <r />ตั้งแต่วันที่ 2023-03-01 ถึง 2023-05-31</b><br /><a href="https://cactusmarketing.biz/blog.html" target="_blank" style="color: red;font-size: 30px;">คู่มือ Rich Message</a><br />',
			showCloseButton: true,
			showCancelButton: false,
			confirmButtonColor: '#3085d6',
			confirmButtonText: window.lang.translate('Ok'),
		}).then((result) => {
			
		});
		plan_package
	}
}

///////////////////////////
//////////////////////////
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(){
    var tId = setInterval(function() {
		try{
			if (document.readyState == "complete") {
				clearInterval(tId);
				tId = setInterval(function() {
					if (document.getElementsByName('cfg_schedule').length>1) {
						clearInterval(tId);
						onCompleteLineOAFanpage();
					}
				}, 500);
				//onComplete();
			}
		}catch(e){}
    }, 500);
})();
