

var $=jQuery.noConflict();

///// Movable login Box ///////
var popup_root = document.getElementById("id01login");
var popup = document.getElementById("logintitle");
var popup_bar = document.getElementById("mydivheader");
//-- let the popup make draggable & movable.
var offset = { x: 0, y: 0 };

popup_bar.addEventListener('mousedown', mouseDown, false);
window.addEventListener('mouseup', mouseUp, false);

function mouseUp()
{
	window.removeEventListener('mousemove', popupMove, true);
}

function mouseDown(e){
	offset.x = e.clientX - popup.offsetLeft;
	offset.y = e.clientY - popup.offsetTop;
	window.addEventListener('mousemove', popupMove, true);
}

function popupMove(e){
	popup.style.position = 'absolute';
	var top = e.clientY - offset.y;
	var left = e.clientX - offset.x;
	popup.style.top = top + 'px';
	popup.style.left = left + 'px';
}
//-- / let the popup make draggable & movable.
window.onkeydown = function(e){
	if(e.keyCode == 27){ // if ESC key pressed
		popup_root.style.display = "none";
	}
}

///////////////

/*
window.onbeforeunload = function(e) {
    e = e || window.event;
    // For IE and Firefox prior to version 4
    if (e) {
        e.returnValue = "คุณแน่ใจใช่ไหมว่าจะปิดแท็บนี้ หากคุณปิดแท็บระบบจะหยุดทำงาน";
    }
    // For Safari
    return "คุณแน่ใจใช่ไหมว่าจะปิดแท็บนี้ หากคุณปิดแท็บระบบจะหยุดทำงาน";
};
window.addEventListener("beforeunload", function (e) {
	e.preventDefault();
	var confirmationMessage = "คุณแน่ใจใช่ไหมว่าจะปิดแท็บนี้ หากคุณปิดแท็บระบบจะหยุดทำงาน";

	  (e || window.event).returnValue = confirmationMessage;     // Gecko + IE
return confirmationMessage;                                // Safari, Chrome, and other WebKit-derived browsers 
});
window.addEventListener("beforeunload", function(event) {
  event.returnValue = "คุณแน่ใจใช่ไหมว่าจะปิดแท็บนี้ หากคุณปิดแท็บระบบจะหยุดทำงาน";
});

*/

defer(function () {
	console.log("jquery loaded");
	document.querySelector("#dialog_loading").style.display = "block"; 
	startupJQuery();
});

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.onload = function() {
}
window.onerror = function(error) {
  // do something clever here
  console.log(error);
};


if (window.location.href.split('index.html#')[1] == 'openbroadcast'
	) {
	console.log('openbroadcast');
	localStorage.setItem('line_all', '');
	//if (localStorage.getItem('fanpage_all') == '') {
	//	localStorage.setItem('fanpage_all', '')
	//	console.log("hashchange#premium_broadcastbylabel->fanpage_all");
	//	fanpage_all = [];
	//	get_fanpage();
	//}
}



//update_license_info(null);
jQuery.noConflict();

jQuery(document).ready(function ($) {
	iziToast.settings({
		timeout: 3000, // default timeout
		resetOnHover: true,
		// icon: '', // icon class
		transitionIn: 'flipInX',
		transitionOut: 'flipOutX',
		position: 'bottomRight', // bottomRight, bottomLeft, topRight, topLeft, topCenter, bottomCenter, center
		onOpen: function () {
			//console.log('callback');
		},
		onClose: function () {
			//console.log("callback");
		}
	});
	
	console.log('document ready');
	changeIndexPageTitle();

});

function progressbarx() {
	$('.progressbar').each(function () {
		var t = $(this),
			dataperc = t.attr('data-perc'),
			barperc = Math.round(dataperc * 10);
		t.find('.bar').animate({
			width: dataperc + '%'
		}, dataperc);
		t.find('.label').html('<div class="perc"></div>');
		var length = t.find('.bar').css('width'),
			labelpos = (parseInt(length));
		t.find('.label').css('left', labelpos);
		t.find('.perc').text(dataperc + '%');
	});
}

function setValue (key,value) {
	if(key) {
		//var value = document.getElementById("valueInput").value;
		return Promise.resolve().then(function () {
            localStorage.setItem(key, value);
        });
		// localStorage.setItem(key, value, function (data) {
		// 	if(data.success) {
		// 		//document.getElementById('result').innerHTML = 'Your data has been successfully stored.';
		// 	} else {
		// 		//document.getElementById('result').innerHTML = 'Ops, could not store your data.';
		// 	}
		// });
	}else{
		return new Promise(resolve => null);
	}
}
function getItem (key) {
	if(key) {
		// localStorage.getItem(key, function (data) {
		// 	return new Promise(resolve => data);
		// 	//return data;
		// 	//document.getElementById('result').innerHTML = 'got value: "' + data.value + '" for key: "' + data.key + '"';
		// });
		return Promise.resolve().then(function () {
            return localStorage.getItem(key);
        });
	}else{
		return new Promise(resolve => "");
	}
}
function removeItem (key) {
	if(key) {
		return Promise.resolve().then(function () {
            localStorage.removeItem(key);
        });
		// localStorage.removeItem(key, function (data) {
		// 	//document.getElementById('result').innerHTML = 'Key was removed';
		// });
	}else{
		return new Promise(resolve => null);
	}
}
function keyName (index) {
	if(index) {
		return Promise.resolve().then(function () {
            localStorage.key(index);
        });
		// localStorage.key(index, function (data) {
		// 	//document.getElementById('result').innerHTML = 'Key name for index ' + index + ' is: '+data.key;
		// });
	}else{
		return new Promise(resolve => null);
	}
}
function clearAll () {
	//document.getElementById('result').innerHTML ='';
	return Promise.resolve().then(function () {
		return localStorage.clear();
	});

	// localStorage.clear(function (data) {
	// 	//document.getElementById('result').innerHTML = 'LocalStorage was cleared.';
	// });
}


/////////////////////////////////////////////////////////////////
function startupJQuery(){
	console.log("Gui Jquery startup");
	/*
	$('button[typeaccount="premium"]').click(function () {
		funtion_name = $(this).attr('id');
		call_myFun = window[funtion_name];
		start_ext(call_myFun);
	});
	$('button[typeaccount="vip"]').click(function () {
		funtion_name = $(this).attr('id');
		call_myFun = window[funtion_name];
		start_vip(call_myFun);
	});
	$('button[typeaccount="premium_next"]').click(function () {
		funtion_namex = $(this).attr('id');
		call_myFunx = window[funtion_namex];
		start_ext(call_myFunx);
	});
	$('button[typeaccount="premium_stop"]').click(function () {
		Swal.fire({
			title: 'คุณต้องการทำรายการนี้?',
			text: "คุณจะหยุดระบบนี้ไว้ชั่วคราว?",
			type: 'warning',
			showCancelButton: true,
			confirmButtonColor: '#3085d6',
			cancelButtonColor: '#d33',
			confirmButtonText: 'Yes'
		}).then((result) => {
			if (result.value) {
				names = $(this).attr('id');
				//call_myFun_stop  =  window[funtion_name];	
				id_element = names.replace('_stop', '');
				//console.log('id_element:'+id_element);
				classx = $('#' + id_element);
				stopx = $('.' + id_element + '_stop');
				play = $('.' + id_element + '_play');
				next = $('.' + id_element + '_next');
				timeout = $('.' + id_element + '_settimeout');
				stop_text = $('.' + id_element + '_stop_text');
				time_text = $('.' + id_element + '_time');
				bittext = $('.' + id_element + '_bit');
				//console.log(names);
				localStorage.setItem(names, '1');
				stopx.hide();
				play.hide();
				next.show();
				stop_text.show();
				time_text.hide();
				clearTimeout(id_element + '_time_out');
				return false;
			}
		})
	});
	$('.unlock_account:checkbox').change(function () {
		// this will contain a reference to the checkbox   
		if (this.checked) {
			$('.unlock_account').prop('checked', false);
			start_ext(unlock);
		} else {
			$('.unlock_account').prop('checked', true);
			Swal.fire({
				title: 'คุณจะออกจากระบบ ?',
				text: "ถ้าคุณต้องการออกจากระบบ  กดปุ่ม Yes",
				type: 'warning',
				showCancelButton: true,
				confirmButtonColor: '#3085d6',
				cancelButtonColor: '#d33',
				confirmButtonText: 'Yes'
			}).then((result) => {
				if (result.value) {
					$('.unlock_account').prop('checked', false);
					$('.all_account').hide();
					$('.free_account').show();
					$('#access_token_div').hide();
					$('#access_token_div_intragram').hide();
					chrome.storage.local.clear(function () {
						var error = chrome.runtime.lastError;
						if (error) {
							console.error(error);
						}
					});
					Swal.fire('ออกจากระบบ  เรียบร้อย', 'หากคุณต้องการเข้าระบบ  อีกครั้งให้กดที่รุปกุญแจอีกครั้ง', 'success')
				}
			})
		}
	});
	
	$('input,textarea').bind('paste', function (e) {
		var elem = $(this);
		setTimeout(function () {
			var text = elem.val();
			text = text.split('?__tn__=');
			text = text[0].split('&__xts__');
			text = text[0].split('?__xts__');
			text = text[0].replace(/'/g, "");
			elem.val(text);
		}, 100);
	});
	$('#fst789_log_in_cancel').click(function () {
		hide_log_in_box();
	});
	*/
	
	$("#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);
		}
	});
	$("#btn_menu_backlog_oa_tl" ).mousedown(function() {
		event.stopPropagation();
	});
	$("#btn_menu_backlog_oa_tl" ).click(function() {
		if(IS_SHOW_BACKLOG_MENU){	//customer.js
			showAllStorage();	//broadcast_line_oa.js
		}else{
			document.getElementById("btn_menu_backlog_oa_tl").style.display = "none";
		}
		//$('#modalBacklog').w2popup();
	});
	
	/*
	$("#btn_menu_config_oa_tl" ).mousedown(function() {
		event.stopPropagation();
	});
	$("#btn_menu_config_oa_tl" ).click(function() {
		let modalConfig = document.getElementById("modalConfig");
		modalConfig.style.width = "1090px";
		modalConfig.style.height = "500px";
		$('#modalConfig').w2popup();
	});
	*/
	
	$("#close_modal_config" ).click(function() {
		$('#modalConfig').w2popup("close");
	});
	
	
	
	
	///backlog modal
	$("#select_this_backlog" ).mousedown(function() {
		event.stopPropagation();
	});
	$("#select_this_backlog" ).click(function() {
		backlogSelectedRow();	//broadcast_line_oa.js
		$('#modalBacklog').w2popup("close");
	});
	$("#close_modal_backlog" ).mousedown(function() {
		event.stopPropagation();
	});
	$("#close_modal_backlog" ).click(function() {
		//console.log("close modal backlog");
		$('#modalBacklog').w2popup("close");
	});
	$("#delete_all_backlog" ).mousedown(function() {
		event.stopPropagation();
	});
	$("#delete_all_backlog" ).click(function() {
		backlogDelAllRows()	//broadcast_line_oa.js
	});
	/////
	console.log("Gui Jquery ready");
}
///////////////////////////////////////////////////////////////////

function close_window() {
	if (confirm("Close Window?")) {
		close();
	}
}
function uniqueall(a) {
	return a.filter((item, i, ar) => ar.indexOf(item) === i);
}

function arrUnique(arr) {
	var cleaned = [];
	arr.forEach(function (itm) {
		var unique = true;
		cleaned.forEach(function (itm2) {
			if (_.isEqual(itm, itm2)) unique = false;
		});
		if (unique) cleaned.push(itm);
	});
	return cleaned;
}

function getAppTitle(){
	try{
		var manifestData = chrome.runtime.getManifest();
		//console.log(manifestData.version);
		//console.log(manifestData.default_locale);
		var apptitle = manifestData?.browser_action?.default_title;	//in gfunc.js
		if(!apptitle){
			apptitle = manifestData.short_name; //+"."+manifestData.version;
		}
		console.log(apptitle);
		return apptitle;
	}catch(e){}
	return "";
}

async function changeIndexPageTitle(){
	try{
		let app_caption_title = getAppTitle();
		CT_TL_APP_VERSION = await getVersion();
		//console.log(CT_TL_APP_VERSION);
		if(typeof CT_TL_APP_VERSION!=="undefined" && CT_TL_APP_VERSION!=null && CT_TL_APP_VERSION!=""){
			app_caption_title = app_caption_title.replace(".ENT","");
			app_caption_title = app_caption_title.replace("v"+CT_TL_APP_VERSION.replace("TL.",""),"");
		}else{
			let manifestData = chrome.runtime.getManifest();
			CT_TL_APP_VERSION = manifestData.version;
		}
		//document.title = app_caption_title +"Ver. "+CT_TL_APP_VERSION;
		document.title = app_caption_title +" v"+CT_TL_APP_VERSION.replace("TL","");
	}catch(e){}
	return "";
}

async function onCompleteGui(){
	CT_TL_APP_VERSION = await getVersion();
	
	document.getElementById('mainLineOAInbox').style.display='none';
	
	console.log("ready use on complete Gui"); 
	
	document.getElementById("logo_version").innerHTML = ' CACTUS '+ CT_TL_APP_VERSION.replace("TL.","TL v.");
	
	
	document.addEventListener('DOMContentLoaded', function(event) {
	  //the event occurred
	  console.log('DOMContentLoaded');

	})
	for (var radioCounter = 0 ; radioCounter < document.getElementsByName('cfg_schedule').length; radioCounter++) {
		  document.getElementsByName('cfg_schedule')[radioCounter].onchange = function() {
			//VALUE OF THE CLICKED RADIO ELEMENT
			this.value=true;
			if (this.id=='cfg_schedule_now'){
				document.getElementById('cfg_schedule_later').value=false;
				document.getElementById('lbl_dtschedule').style.display='none';
			}else if(this.id=='cfg_schedule_later'){
				document.getElementById('cfg_schedule_now').value=false;
				document.getElementById('lbl_dtschedule').style.display='block';
				//var now = new Date();
				//now.setDate(now.getDate() + 10);
				//rome(dtschedule,{initialValue: new Date(),min: new Date(), max: now });
				var dtschedule = document.getElementById('dtschedule');
				rome(dtschedule).setValue(new Date());
			}
			
		  }
	}
	
	
	document.getElementById("dtschepause_chk").addEventListener("click", function(event) {
		//event.preventDefault();
		let dtschepause_chk = document.getElementById("dtschepause_chk");
		if(dtschepause_chk.checked == true){
			document.getElementById('dtschepause').disabled = false;
			let dtschepause = document.getElementById('dtschepause');
			//rome(dtschepause, { date: false });	//time only
			rome(dtschepause).setValue(new Date());
		}else{
			document.getElementById('dtschepause').disabled = true;
		}
		
	});
	
	
	txt_error_report = document.getElementById("txt_error_report");
	
	document.getElementById("logmeclose").addEventListener("click", function(event) {
		//event.preventDefault();
		document.getElementById('id01login').style.display='none';
	});
	
	document.getElementById("signin_button").addEventListener("click", function(event) {
		document.getElementById('user_name').innerHTML = '';
		document.getElementById('user_valid_date').innerHTML = '';
		document.getElementById('user_days_left').innerHTML = '';
		document.getElementById('plan_package').innerHTML = '';
		document.getElementById('user_plan_login_detail').style.display = 'none';
		document.getElementById('mainLineOAInbox').style.display='none';
		document.getElementById('id01login').style.display='block';
	});
	document.getElementById("signout_button").addEventListener("click", function(event) {

		signout();	//bp_tf_broadcast_fb_fanpage.js
		
	});
	document.getElementById("loginsubmit").addEventListener("click", function(event) {
		//login validate here
		let form_email=document.getElementById("uname").value;
		let form_key=document.getElementById("psw").value;
		let rememberme=document.getElementById('rememberme').checked;
		if(rememberme==true || rememberme=="on"){rememberme=1;}else{rememberme=0;}
		let uname = document.getElementById('uname');
		let psw = document.getElementById('psw');
		if(typeof uname!=="undefined" && uname!=null && uname.value.trim()!=""){
		}else{
			Swal.fire({
				title: window.lang.translate("Something went wrong"),
				html: window.lang.translate("You have not entered your login email"),
				type: 'error',
				confirmButtonColor: '#3085d6',
				confirmButtonText: window.lang.translate('OK')
			});
			uname.focus();
			return;
		}
		if(typeof psw!=="undefined" && psw!=null && psw.value.trim()!=""){
		}else{
			Swal.fire({
				title: window.lang.translate("Something went wrong"),
				html: window.lang.translate("You have not entered your login password"),
				type: 'error',
				confirmButtonColor: '#3085d6',
				confirmButtonText: window.lang.translate('OK')
			});
			psw.focus();
			return;
		}
		start_func(startLineOALoad,form_email,b64EncodeUnicode(form_key),rememberme,false);	//startLineOALoad function in bp_tf_broadcast_fb_fanpage.js
	});

	const togglePassword = document.querySelector('#togglePassword');
	const login_password = document.querySelector('#psw');
	togglePassword.addEventListener('click', function (e) {
		// toggle the type attribute
		const type = login_password.getAttribute('type') === 'password' ? 'text' : 'password';
		login_password.setAttribute('type', type);
		// toggle the eye slash icon
		this.classList.toggle('fa-eye-slash');
	});
	
	document.getElementById("clear_error_report").addEventListener("click", function(event) {
		document.getElementById("txt_error_report").innerHTML = "";
	});
	
	/*
	const data_lang = document.getElementById('data_lang');
	data_lang.addEventListener('change', function (e) {
		let opt = data_lang.options[data_lang.selectedIndex];
		console.log(opt.value);
		window.lang.change(opt.value);
	});
	*/
	/*
	const switch_lang = document.getElementsByClassName("data_lang_oa_tl");
	for (let i = 0; i < switch_lang.length; i++) {
		 switch_lang[i].addEventListener("change", function(e) {
			let opt = switch_lang[i].options[switch_lang[i].selectedIndex];
			console.log(opt.value);
			window.lang.change(opt.value);
			let select = document.getElementsByClassName("data_lang_oa_tl");
			for (let j = 0; j < select.length; j++) {
				if(select[j].id!=switch_lang[i].id){
					select[j].selectedIndex = switch_lang[i].selectedIndex;
				}
			}
		 });
	 }
	*/
	
	/*
	const switch_lang = document.querySelectorAll('.switch-lang');
	for (let i = 0; i < switch_lang.length; i++) {
		 switch_lang[i].addEventListener("click", function() {
		   const data_lang=switch_lang[i].getAttribute('data-lang') || "th";
			window.lang.change(data_lang);
		 });
	 }
	*/
	
	//document.getElementById('id01login').style.display='block';
	//func_call,email,key,rememberme,isOnStartup
	document.getElementById("start_broadcast").disabled = true;
	
	//start_func(startLineOALoad,"","","",true);	//on start up	//startLineOALoad function in bp_tf_broadcast_fb_fanpage.js
	
	try{
	
		if (typeof CT_TL_SEND_MSG_RATE_LIMIT_MAX_PER_MIN !== 'undefined') {	//customer.js
			if(CT_TL_SEND_MSG_RATE_LIMIT_MAX_PER_MIN<1){CT_TL_SEND_MSG_RATE_LIMIT_MAX_PER_MIN=ct_tl_rateLimitedMaxPerMin;}
			ct_tl_rateLimitedMaxPerMin = CT_TL_SEND_MSG_RATE_LIMIT_MAX_PER_MIN;
			document.getElementById("cfg_msg_rate_limit_per_min").max = ct_tl_rateLimitedMaxPerMin;
		}
		let set_default_send_msg_rate_limit_max_per_min=ct_tl_rateLimitedMaxPerMin;
		if (typeof CT_TL_SET_DEFAULT_SEND_MSG_RATE_LIMIT_MAX_PER_MIN !== 'undefined') {
			if(CT_TL_SET_DEFAULT_SEND_MSG_RATE_LIMIT_MAX_PER_MIN<1){CT_TL_SET_DEFAULT_SEND_MSG_RATE_LIMIT_MAX_PER_MIN=ct_tl_rateLimitedMaxPerMin;}
			set_default_send_msg_rate_limit_max_per_min = CT_TL_SET_DEFAULT_SEND_MSG_RATE_LIMIT_MAX_PER_MIN;
			document.getElementById("cfg_msg_rate_limit_per_min").value = set_default_send_msg_rate_limit_max_per_min;
		}
		
		
		let set_send_msg_delay_rate_limit_min=0;
		if (typeof CT_TL_SEND_MSG_DELAY_RATE_LIMIT_MIN !== 'undefined') {
			if(CT_TL_SEND_MSG_DELAY_RATE_LIMIT_MIN<0){CT_TL_SEND_MSG_DELAY_RATE_LIMIT_MIN=0;}
			set_send_msg_delay_rate_limit_min = CT_TL_SEND_MSG_DELAY_RATE_LIMIT_MIN;
			document.getElementById("cfg_delay").min = set_send_msg_delay_rate_limit_min;
		}
		let set_default_send_msg_delay_rate_limit_min=0;
		if (typeof CT_TL_SET_DEFAULT_SEND_MSG_DELAY_RATE_LIMIT_MIN !== 'undefined') {
			if(CT_TL_SET_DEFAULT_SEND_MSG_DELAY_RATE_LIMIT_MIN<0){CT_TL_SET_DEFAULT_SEND_MSG_DELAY_RATE_LIMIT_MIN=0;}
			set_default_send_msg_delay_rate_limit_min = CT_TL_SET_DEFAULT_SEND_MSG_DELAY_RATE_LIMIT_MIN;
			document.getElementById("cfg_delay").value = set_default_send_msg_delay_rate_limit_min;
		}
		
		setTimeout(function(){
			document.getElementById("cfg_msg_rate_limit_per_min").max = ct_tl_rateLimitedMaxPerMin;
			document.getElementById("cfg_msg_rate_limit_per_min").value = set_default_send_msg_rate_limit_max_per_min;
			document.getElementById("cfg_delay").min = set_send_msg_delay_rate_limit_min;
			document.getElementById("cfg_delay").value = set_default_send_msg_delay_rate_limit_min;
		},3000);
		
	}catch(e){console.log(e);}
	try{
		let get_line_fanpage = document.getElementById("get_line_fanpage");
		if(typeof get_line_fanpage!=="undefined" && get_line_fanpage!=null){
			if(IS_SHOW_GET_TL_FANPAGE_BTN){	//customer.js
				get_line_fanpage.style.display = "inline-block";
			}else{
				get_line_fanpage.style.display = "none";
			}
		}
	}catch(e){}
	try{
		let speed_send_option = document.getElementById("group_cfg_msg_rate_limit_per_min");
		if(typeof speed_send_option!=="undefined" && speed_send_option!=null){
			if(typeof IS_SHOW_TL_SPEED_LIMIT_OPTION!="undefined"){	//customer.js
				if(IS_SHOW_TL_SPEED_LIMIT_OPTION==false){
					speed_send_option.style.display = "none";
				}else{
					speed_send_option.style.display = "inline-block";
				}
				let limit_max=document.getElementById("cfg_msg_rate_limit_per_min");
				limit_max.addEventListener("change", function(event) {
					let x = limit_max.value;
					if (isNaN(x) || x < 1 || x > CT_TL_SEND_MSG_RATE_LIMIT_MAX_PER_MIN) {
						limit_max.value = CT_TL_SEND_MSG_RATE_LIMIT_MAX_PER_MIN;
					}
				});
				
			}else{
				speed_send_option.style.display = "none";
			}
		}
	}catch(e){console.log(e);}
	try{
		let tl_delay_send_option = document.getElementById("group_cfg_delay");
		if(typeof tl_delay_send_option!=="undefined" && tl_delay_send_option!=null){
			if(typeof IS_SHOW_TL_SEND_DELAY_OPTION!="undefined"){	//customer.js
				if(IS_SHOW_TL_SEND_DELAY_OPTION==false){
					tl_delay_send_option.style.display = "none";
				}else{
					tl_delay_send_option.style.display = "inline-block";
				}
				let delay_min=document.getElementById("cfg_delay");
				delay_min.min=CT_TL_SEND_MSG_DELAY_RATE_LIMIT_MIN;
				delay_min.addEventListener("change", function(event) {
					let x = limit_max.value;
					if (isNaN(x) || x < 0 || x < CT_TL_SEND_MSG_DELAY_RATE_LIMIT_MIN) {
						delay_min.value = CT_TL_SEND_MSG_DELAY_RATE_LIMIT_MIN;
					}
				});
				
			}else{
				tl_delay_send_option.style.display = "none";
			}
		}
	}catch(e){console.log(e);}
	try{
		let tl_header_version = document.getElementById("tl_version");
		if(typeof tl_header_version!=="undefined" && tl_header_version!=null){
			if(IS_SHOW_TL_HEADER_VERSION){	//customer.js
				tl_header_version.style.display = "inline-block";
			}else{
				tl_header_version.style.display = "none";
			}
		}
	}catch(e){}

	
	try{
		if (typeof login_footer_container == 'function') { 
			//setTimeout(function(){
				login_footer_container();
			//},3000);
		}
	}catch(e){}
	try{
		if (typeof header_detail == 'function') {
			setTimeout(function(){
				header_detail();
			},3000);
		}
	}catch(e){}
	try{
		if (typeof footer_detail == 'function') {
			setTimeout(function(){
				footer_detail();
				$('#user_login').html($('#user_name').html());
			},3000);
		}
	}catch(e){console.log(e);}
	try{
		if (typeof footer_remark == 'function') {
			setTimeout(function(){
				footer_remark();
			},3000);
		}
	}catch(e){console.log(e);}	
	try{
		if (typeof header_top_tl_main_menu == 'function') {
			header_top_tl_main_menu();
		}
	}catch(e){console.log(e);}
	
	try{
		var dnow = new Date();
		var curdate = dnow.toJSON().slice(0,10);
		server_date = curdate;
		ldb.get('pop_server_date', function (pop_server_date) {
			if(typeof pop_server_date!=="undefined" && pop_server_date!=null){
				var ul = pop_server_date.split("|");
				if(ul.length>1){
					server_date = ul[1];
				}
			}
		});
	}catch(e){}
	
	
	setTimeout(async function(){
		try{
			document.getElementById("btn_menu_backlog_oa_tl").addEventListener("click", function(event) {
				try{
					showAllStorage();	//from host broadcast_line_oa.js
				}catch(e){
					console.log(e);
				}
			});
		}catch(e){}
		
		try{
			document.getElementById("btn_menu_manual_oa_tl").addEventListener("click", function(event) {
				try{
					manual_detail();	//from host customer.js
				}catch(e){
					console.log(e);
				}
			});
		}catch(e){}
		try{
			document.getElementById("btn_menu_contact_oa_tl").addEventListener("click", function(event) {
				try{
					contact_detail();	//from host customer.js
				}catch(e){
					console.log(e);
				}
			});
		}catch(e){}
		try{
			document.getElementById("btn_menu_moreinfo_oa_tl").addEventListener("click", function(event) {
				try{
					moreinfo_detail();	//from host customer.js
				}catch(e){
					console.log(e);
				}
			});
		}catch(e){}
		try{
			document.getElementById("btn_menu_downloadapp_oa_tl").addEventListener("click", function(event) {
				try{
					download_software();	//from host customer.js
				}catch(e){
					console.log(e);
				}
			});
		}catch(e){}
		
		try{
			try{
				chrome.storage.local.get("config_tl", function(t) {
					if(typeof t.config_tl!=="undefined" && t.config_tl!=null){
						if(t.config_tl.show_log_detail){
							let store_cfg = t.config_tl.show_log_detail;
							document.getElementById('my_log_detail').selectedIndex = store_cfg;
							//document.getElementById('my_log_detail').value = store_cfg;
							//document.getElementById('my_log_detail').options[store_cfg].selected = 'selected';
							console.log("store_cfg:"+store_cfg);
						}
					}
				});
			}catch(ex){}
			document.getElementById("btn_menu_config_oa_tl").addEventListener("click", function(event) {
				event.preventDefault();
				try{
					let modalConfig = document.getElementById("modalConfig");
					modalConfig.style.width = "350px";
					modalConfig.style.height = "350px";
					$('#modalConfig').w2popup();
					
					w2popup.on('close', function(event) {
						event.stopPropagation();
						console.log('event: ' + event.type, event);
						let cfg = document.getElementById('my_log_detail').value;
						config_tl = {
							show_log_detail:cfg
						},
						chrome.storage.local.set({
							config_tl: config_tl
						}, function() {
							chrome.storage.local.get("config_tl", function(t) {
								if(typeof t.config_tl!=="undefined" && t.config_tl!=null){
									if(t.config_tl.show_log_detail){
										cfg = t.config_tl.show_log_detail;
										console.log("cfg:"+cfg);
									}
								}
							});
						});
					});
					
				}catch(e){
					console.log(e);
				}
			});
		}catch(e){}
		
		loadInitLang();	//tp_tl_lang.js
		let isLineOa = await get_line_me_admin();
		if(isLineOa){
			start_func(startLineOALoad,"","","",true);	//on start up	auth.js //startLineOALoad function in bp_tf_broadcast_fb_fanpage.js
		}
	},5000);
		
	//if (isUserPass == false) {return false;}
	//"ok|16/12/2020 - 31/12/2020|soymos@gmail.com|4|0|ลูกค้า|3|2020-12-27|1609004915851|2020-12-26|TL.1.0.3|1609004921625|2020-12-26"
	/*
	0: "ok"
	1: "16/12/2020 - 31/12/2020"
	2: "soymos@gmail.com"
	3: "4"
	4: "0"
	5: "ลูกค้า"
	6: "3"
	7: "2020-12-27"
	8: "1609004915851"
	9: "2020-12-26"
	10: "TL.1.0.3"
	11: "1609004921625"
	12: "2020-12-26"
	*/
	
	
	function get_line_me_admin() {
		const line_me_admin = "https://chat.line.biz/api/v1/me";
		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);
				document.querySelector("#dialog_loading").style.display = "none"; 
				document.querySelector("body").style.visibility = "visible";
				Swal.fire({
					title: window.lang.translate('Line OA not logged in yet'),
					html: window.lang.translate("You have to log in Line OA first")+ "<br /><b style='color:red;'> คุณต้องทำการ Login Line OA แล้วต้องเข้าไปยังหน้าแชท ให้เรียบร้อยก่อนเป็นอันดับแรก คลิก OK เพื่อไป Login Line OA</b>",
					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');
						//https://chat.line.biz/U97028224c1aae20d338854c5273f9ef3/chat/
					}
				})
				resolve(false);
			});
		});
	}


};



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);
						onCompleteGui();
					}
				}, 500);
				//onCompleteGui();
			}
		}catch(e){}
    }, 500);
})();
