
var $=jQuery.noConflict();
//window.lang.translate('Enter a maximum of 10 rows only')

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 getDateOnly(){
	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 convertDateStringToDatetimeString(dateString){
	var unixTimestamp = new Date(dateString)/1000;
	//console.log(unixTimestamp);

	var timestamp = unixTimestamp; // replace your timestamp
	var d = new Date(timestamp * 1000);
	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 convertDateStringToDateString(dateString){
	var unixTimestamp = new Date(dateString)/1000;
	var timestamp = unixTimestamp; // replace your timestamp
	var d = new Date(timestamp * 1000);
	return d.getFullYear().toString()+"-"+padDigits(d.getMonth()+1,2)+"-"+padDigits(d.getDate(),2);
}
function convertNowToUnixTimestamp(){
	const date = new Date(); // Or any Date('YYYY-MM-DD')
    const unixTimestamp = Math.floor(date.getTime() / 1000);
	return unixTimestamp;
}

const addHoursToDate = (date, n) => {
	const d = new Date(date);
	d.setTime(d.getTime() + n * 3_600_000);
	return d;
};


! async function() {
	console.log("start");
	await const_init();	//const.js
	try{
		let client_id1 = DEVICE_ID1;	//from const.js
		//let client_id2 = DEVICE_ID2;	//
		
		var device_id = client_id1;	//+"-"+client_id2;
		var device_id_tag_no = document.getElementById("device_id_tag_no");
		let ct_tl_env_ = "";
		if(typeof CT_TL_ENV_ !="undefined"){
			ct_tl_env_ = CT_TL_ENV_;
		}
		if(typeof device_id_tag_no!=="undefined" && device_id_tag_no!=null){
			device_id_tag_no.innerHTML = ">> App id. "+ct_tl_env_+"["+ device_id +"] <<";
		}
	}catch(err){console.log(err)}
	try{
		var tl_version = document.getElementById("tl_version");
		if(typeof tl_version!=="undefined" && tl_version!=null){
			tl_version.innerHTML = "Ver. "+ CT_TL_APP_VERSION + "&nbsp;&nbsp;["+ getNow() +"]&nbsp;"; //+DEVICE_ID1;
			$('#tl_version').css("font-size","14px");
			$('#tl_version').css("font-family","FontAwesome");
			$('#tl_version').css("font-style","normal");
		}
	}catch(err){console.log(err)}
	console.log(DEVICE_ID1);
}();

function show_login_box() {
	document.getElementById('user_name').innerHTML = '';
	document.getElementById('user_valid_date').innerHTML = '';
	document.getElementById('user_days_left').innerHTML = '';
	document.getElementById('plan_package').innerHTML = '';
	document.getElementById('signin_div_button').style.display='block';
	
	document.getElementById('user_plan_login_detail').style.display = 'none';
	document.getElementById('mainLineOAInbox').style.display='none';
	document.getElementById('id01login').style.display='block';
	//$('#id01login').w2popup();
	
	document.querySelector("#dialog_loading").style.display = "none"; 
	document.querySelector("body").style.visibility = "visible";
	
	document.getElementById("plan_what_package").style.display='none';
	
	document.getElementById("mydivheader").innerHTML = 'Login CACTUS TL - LineOA '+CT_TL_APP_VERSION;
	
	document.getElementById('user_login').innerHTML = 'https://linebroadcast.com';


}

function hide_login_box() {
	document.getElementById('user_plan_login_detail').style.display = 'block';
	document.getElementById('mainLineOAInbox').style.display='block';
	document.getElementById('id01login').style.display='none';
	
	document.querySelector("#dialog_loading").style.display = "none"; 
	document.querySelector("body").style.visibility = "visible";
	
	document.getElementById('signin_div_button').style.display='none';
	document.getElementById('signout_button').style.display='inline-block';
	
}


function update_info() { 
  return $.ajax({
	async: true,
	url: 'https://get.geojs.io/v1/ip/geo.json',
	type: 'GET',
  });
};

async function update_client_data_info(user_name,key,version,token,client_id){
  try {
    const data = await update_info();
	if(typeof data.country_code!=="undefined"){
		country_code=data.country_code;
	}
	if(typeof data.city!=="undefined"){
		city=data.city;
	}
	if(typeof data.ip!=="undefined"){
		ip=data.ip;
	}
	actinfo(user_name,key,"",version,client_id);	//in gfunc.js
  } catch(err) {
    console.log(err);
  }
}

function signout(){
	clear_login();
	Swal.fire({
		title: '<strong>'+window.lang.translate('Log out')+'</strong>',
		html: '<strong>'+window.lang.translate('Successfully logged out')+'</strong>',
		showCloseButton: true,
		cancelButtonAriaLabel: window.lang.translate('OK')
	}).then((result) => {
		show_login_box();
	});
}
function clear_login(){
	var information = {};
	
	chrome.storage.local.set({
		information: information
	}, function() {
		
		document.getElementById('user_name').innerHTML = '';
		document.getElementById('user_valid_date').innerHTML = '';
		document.getElementById('user_days_left').innerHTML = '';
		document.getElementById('plan_package').innerHTML = '';
		document.getElementById('signin_div_button').style.display='block';
		
		document.getElementById('user_plan_login_detail').style.display = 'none';
		document.getElementById('mainLineOAInbox').style.display='none';
		document.getElementById("plan_what_package").style.display='none';

		document.getElementById('user_login').innerHTML = 'https://linebroadcast.com';
	});

	localStorage.clear();
}

async function auth_send_request(email, pwd, token,func_call,rememberme,isOnStartup) {
	if(typeof token==="undefined" || token==null){
		token="";
	}
	if(typeof email==="undefined" || email==null){
		email="";
	}
	if(typeof pwd==="undefined" || pwd==null){
		pwd="";
	}
	if(typeof func_call==="undefined" || func_call==null){
		func_call="";
	}
	if(rememberme==true || rememberme=="on"){
		rememberme = 1;
	}else{
		rememberme = 0;
	}
	
	//console.log("e:"+email+" p:"+pwd+" t:"+token);
	
    if ((email!="" && pwd!="") || token!="") {
        var i = "";
		
		if(DEVICE_ID1==""){
			await const_init();	//const.js
		}
		//let client_id1 = await getClientID();
		//let client_id2 = await biri();
		let client_id1 = DEVICE_ID1;	//await getClientID();
		//let client_id2 = DEVICE_ID2;	//await biri();
		
		//console.log("client_id1:"+client_id1);
		//console.log("client_id2:"+client_id2);
		
		var device_id = client_id1;	//+"-"+client_id2;
		
		let ct_tl_env_ = "";
		if(typeof CT_TL_ENV_ !="undefined"){
			ct_tl_env_ = CT_TL_ENV_;
		}
		try{
			var device_id_tag_no = document.getElementById("device_id_tag_no");
			if(typeof device_id_tag_no!=="undefined" && device_id_tag_no!=null){
				device_id_tag_no.innerHTML = ">> App id. "+ct_tl_env_+"["+ device_id +"] <<";
			}
		}catch(err){}
		//console.log("App id."+device_id);
		
		try{
			var device_id_tag_no = document.getElementById("device_id_tag_no");
			if(typeof device_id_tag_no!=="undefined" && device_id_tag_no!=null){
				device_id_tag_no.innerHTML = ">> App id. ["+ clientid +"] <<";
			}
		}catch(err){}
		//console.log("App id."+device_id);
		
		let user_name=email;
		let key= "" ;
		try{ key=b64DecodeUnicode(pwd);}catch(e){}
		let version=CT_TL_APP_VERSION;
		
		/*
		0: "ok"
		1: "16/12/2020 - 31/12/2020"
		2: "xxx@gmail.com"
		3: "4"
		4: "0"
		5: "ลูกค้า"
		6: "3"
		7: "2020-12-27"	//server_date
		
		//++New normal
		8: token
		9: tf_max_speed
		10: tf_demo_ratelimit
		11: is_tf_speed_unlimit
		12: limit_conflict_number
		13: permission_extract_member
		
		//+++ Add more from auth gettime, date
		14: "1609004915851"	//client time
		15: "2020-12-26"	//client date
		
		//+++ Add more vary array from my_broadcast_lineOa.js version, time, date
		16: "TL.1.0.3"
		17: "1609004921625"	//client time
		18: "2020-12-26"	//client date
		*/

		//V7
		//"ok|0
		//$register_date" . $data['expire_date']."|1
		//$email|2
		//$days_remain|3
		//$isUnlocked_Device|4
		//$user_type|5
		//$demo_ratelimit|6
		//$current_date|7
		//$token|8
		//$tf_max_speed|9
		//$tf_demo_ratelimit|10
		//$is_tf_speed_unlimit|11
		//$limit_conflict_number|12
		//$permission_extract_member|13
		//$user_name|14
		//$device_id|15
		//$allow_app|16
		//$is_active_app"|17
        //$is_allowed_rich_msg;18

		//V4
		//"102|
		//User expire โปรแกรมหมดอายุการใช้งานแล้ว : $register_date" . $data['expire_date']." สอบถามโปรโมชั่นจากแอดมินได้ที่|
		//$email|
		//$days_remain|
		//$isUnlocked_Device|
		//$user_type|
		//$demo_ratelimit|
		//$current_date|
		//$token|
		//$tf_max_speed|
		//$tf_demo_ratelimit|
		//$is_tf_speed_unlimit|
		//$limit_conflict_number|
		//$permission_extract_member"; //Expire date

                                    
		let ip  = await getLocalIP();
        i += "appid=" + encodeURIComponent(CT_TL_APP_ID),i += "&version=" + encodeURIComponent(version), i += "&email=" + encodeURIComponent(user_name), i += "&key=" + encodeURIComponent(key), i += "&token=" + encodeURIComponent(token), i += "&user_id=" + encodeURIComponent(user_id), i += "&type=" + encodeURIComponent("first_verification"), i += "&device_id=" + encodeURIComponent(device_id), i += "&ip=" + encodeURIComponent(ip);
		//console.log(i);
		try{
			$.ajax({
			   type: "POST",
				async: true,
				url: CT_TL_REQ_AUTH_URL.replace("{env}",ct_tl_env_),	//tl_customer.js, tl_const.js
				data: i,
				//complete: function(n) {
					//var res = n.responseText;
				success: function(n){
					var res = n;	//n.responseText;
					res = replaceAll(res, "\n", "");
					res = replaceAll(res, "\r", "");
					res = replaceAll(res, "\LF", "\n");	//line feed

					//echo "-9|Outstanding or unpaid balance from your agency|$email||$isUnlocked_Device|$user_type|$demo_ratelimit|$current_date|$token|$tf_max_speed|$tf_demo_ratelimit|$is_tf_speed_unlimit|$limit_conflict_number";
		
					var ukey=b64EncodeUnicode(key);
					var dnow = new Date();
					//var accdate = dnow.toJSON().slice(0,10);
					var accdate = convertDateStringToDateString(dnow.toDateString());
					var server_date = accdate;
					
					var info = res.split("|");
					
					var resp_token = "";
					var tf_max_speed = 1;
					var tf_demo_ratelimit = 0;
					var tf_user_type = "";
					var is_tf_speed_unlimit = 0;
					var limit_conflict_number = 1;
					var is_extract_member = 0;
					var is_allowed_rich_msg = 0;

					try{
						if(typeof info[5]!=="undefined" && info[5] !=null){
							tf_user_type = info[5];
						}
						if(typeof info[7]!=="undefined" && info[7] !=null){
							server_date = info[7];
							if(server_date!=""){
								let sp_svr_date = server_date.split('-');
								if(sp_svr_date.length>2){
									dnow.setFullYear( Number(sp_svr_date[0]),Number(sp_svr_date[1])-1,Number(sp_svr_date[2]) );
									//server_date = dnow.toJSON().slice(0,10);
									server_date = convertDateStringToDateString(dnow.toDateString());
								}
							}
						}
						if(typeof info[8]!=="undefined" && info[8] !=null){
							resp_token = info[8];
						}
						if(typeof info[9]!=="undefined" && info[9] !=null){
							try{
								tf_max_speed = Number(info[9]);
							}catch(ex){}
						}
						if(typeof info[10]!=="undefined" && info[10] !=null){
							try{
								tf_demo_ratelimit = Number(info[10]);
							}catch(ex){}
						}
						if(typeof info[11]!=="undefined" && info[11] !=null){
							try{
								is_tf_speed_unlimit = Number(info[11]);
							}catch(ex){}
						}
						if(typeof info[12]!=="undefined" && info[12] !=null){
							try{
								limit_conflict_number = Number(info[12]);
							}catch(ex){}
						}
						if(typeof info[13]!=="undefined" && info[13] !=null){
							try{
								is_extract_member = Number(info[13]);
							}catch(ex){}
						}
						if(typeof info[18]!=="undefined" && info[18] !=null){
							try{
								is_allowed_rich_msg = Number(info[18]);
							}catch(ex){}
						}
						
					}catch(e){}
					
					res+="|"+(new Date()).getTime();
					res+="|"+accdate;		//+accdate
					
					if (info[0]=="ok"){
						//$("#user_register").text(res);
						information = {
							rememberme:rememberme,
							tf_max_speed:tf_max_speed,
							tf_demo_ratelimit:tf_demo_ratelimit,
							is_tf_speed_unlimit:is_tf_speed_unlimit,
							limit_conflict_number:limit_conflict_number,
							permission_extract_member:is_extract_member,
							email: user_name,
							key: ukey,
							token: resp_token,
							member: !0,	//true
							pk:user_name.substring(0, 2)+key.substring(0, 2),
							accdate: accdate,
							server_date:server_date,
							user_type:tf_user_type,
							device_id:device_id,	//const.js
							is_allowed_rich_msg:is_allowed_rich_msg,
							expired: res	//n.responseText
						}, chrome.storage.local.set({
							information: information
						}, function() {
							try{
								tf_maximum_speed_sender = Number(tf_max_speed);	//in bp_tf_broadcast_b_anpage.js
							}catch(ex){}
							try{
								tf_demo_ratelimit_setting = Number(tf_demo_ratelimit);	//in bp_tf_broadcast_b_anpage.js
							}catch(ex){}
							try{
								user_type = tf_user_type;	//in bp_tf_broadcast_b_anpage.js
							}catch(ex){}
							
							show_user_account();
							if(typeof func_call!="undefined" && func_call!=null){
								func_call();
							}
							hide_login_box();
						});
						
						
						try{
							let information_device = {
								device_id:device_id
							}
							ldb.set('information_device', information_device);
						}catch(ee){}
						update_client_data_info(user_name,key,version,resp_token,device_id);
						
					}else{
						clear_login();
						show_login_box();
						console.log("auth send request info[0] NOK");
						
						if (info.length > 1) {
							
						} else {
							alert(window.lang.translate("Invalid response from server")+ ' '+version);
						}
						
						var err_info="";
						if (info.length>0){
							err_info=info[1];
							if(typeof err_info==="undefined"){err_info=window.lang.translate("Server not response or timeout");}
			
							let user_contatc = 'user: <b>'+user_name+'</b> <br />'
									+'<b style="color:red;">'+err_info+'</b><br />'
									+'<a href="' + LINE_URL_QRCODE + '" target="_blank" >'+' '+window.lang.translate("Contact admin")+'</a> <br />'
									+'•Line:' + LINE_AT_ID + ' '+ window.lang.translate("With @ leading") +' '+ window.lang.translate("Or the agent you signed up for")+ ' <br />';	
							if(Number(info[0]) == (-55) ){
								
								Swal.fire({
								  title: window.lang.translate('User uses more than on device')+ ' '+version,
								  html: "<i style='color:#000066;font-weight: bold;'>REF.ID. "+device_id+ " " +"</i><i style='color:red;'>"+ window.lang.translate("Due to the user with e-mail")+" " +user_name+" version:"+ version+ " "+ window.lang.translate("Lock device details") +"</i>",
								  //type: 'warning',
								  customClass: 'sweetalert-lg',
								  showCancelButton: true,
								  confirmButtonColor: '#3085d6',
								  cancelButtonColor: '#d33',
								  confirmButtonText: window.lang.translate('Yes')+ ', '+window.lang.translate('Unlock device')+'!',
								  cancelButtonText: window.lang.translate('Cancel')
								}).then((result) => {
								  if (result.value) {
									  var req_unlock_data="";
									  //req_unlock_data += "&email=" + encodeURIComponent(user_name) + "&key=" + encodeURIComponent(key)+ "&token=" + encodeURIComponent(token) + "&id=" + encodeURIComponent(user_id) + "&device_id=" + encodeURIComponent(device_id)+ "&ip=" + encodeURIComponent(ip);
									  req_unlock_data = {
											'email':  encodeURIComponent(user_name),
											'key': encodeURIComponent(key),
											'token': encodeURIComponent(token),
											'id': encodeURIComponent(user_id),
											'device_id': encodeURIComponent(device_id),
											'appid': encodeURIComponent(CT_TL_APP_ID),
											'version': encodeURIComponent(version),
											'ip': encodeURIComponent(ip)
										};
										
										//console.log(req_unlock_data);
										
									  $.ajax({
										url: CT_TL_REQ_UNLOCK_URL,
										data: req_unlock_data,
										method: 'POST',
										success: function(respText){
											var res = respText;
											res = replaceAll(res, "\n", "");
											res = replaceAll(res, "\r", "");
											res = replaceAll(res, "\LF", "\n");	//line feed
											//console.log(res);
											var respJson= JSON.parse(res);
											//console.log(respJson);
											if(respJson.ok==true){
												Swal.fire(
												  window.lang.translate("Unlock device"),
												  window.lang.translate("Email")+' '+'<h2>'+user_name+ '</h2>' +' ' + window.lang.translate("Has sent the matter to successfully unlock the device") +'<br/><i style="color:red;"><b>'+respJson.msg+'</b></i>',
												  'success'
												)
											}else{
												Swal.fire(
												  window.lang.translate("Unlock device"),
												  '<h4>'+window.lang.translate("Failed to unlock")+'</h4> <br/><i style="color:red;">'+respJson.code+': '+respJson.msg+'</i>',
												  'error'
												)
											}
											
										},
										error: function (XMLHttpRequest, textStatus, errorThrown) {
											console.log(XMLHttpRequest.responseText);
											Swal.fire(
											  window.lang.translate("Unlock device"),
											  window.lang.translate("Failed to unlock")+' '+textStatus,
											  'error'
											)
										}
										
									});

								  }
								})
							}else if(Number(info[0]) == (-27) ){	//version update
								Swal.fire({
									title: '<strong>ERROR <u>'+window.lang.translate('Something went wrong')+'</u> '+version+'</strong>',
									type: 'error',
									html: 'user: <b>'+user_name+'</b> <br /><b style="color:red;">'+err_info+'</b><br />',
									showCloseButton: true,
									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(TL_WEB_STORE_URL, '_blank');
										mywinUrl.focus();
									}else{
										clear_login();	//bp_tf_auth.js
									}
								});
							}else{
								try{
									user_contatc = validate_user_err_info();	//from host customer.js
								}catch(e){}
								
								if(isOnStartup==false){
									Swal.fire({
										//target: document.getElementById('swal2-container'),
										title: '<strong>ERROR <u>'+window.lang.translate('Something went wrong')+'</u> '+version+'</strong>',
										type: 'error',
										html: user_contatc,
										//footer: footer_swal(),
										showCloseButton: true,
										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();
										}else{
											clear_login();
										}
									});
								}else{
									clear_login();
								}
							}
						}else{
							let user_contatc = 'user: <b>'+user_name+'</b> <br />'
									+'<b style="color:red;">'+window.lang.translate('Password or email you are incorrect')+'</b><br />'
									+'<a href="' + LINE_URL_QRCODE + '" target="_blank" >'+' '+window.lang.translate('Contact admin')+'</a> <br />'
									+'•Line:' + LINE_AT_ID + ' '+ window.lang.translate("With @ leading") +' '+window.lang.translate("Or the agent you signed up for")+'<br />';

							err_info = window.lang.translate("Something went wrong try again");
							try{
								user_contatc = validate_user_err_default();	//from host customer.js
							}catch(e){}
							
							Swal.fire({
								title: '<strong>ERROR <u>'+window.lang.translate('Something went wrong')+'</u> '+version+'</strong>',
								type: 'error',
								html: user_contatc,
								showCloseButton: true,
								cancelButtonAriaLabel: window.lang.translate('OK')
							}).then((result) => {
								clear_login();
							});
							
						}

					}
				},
				error: async function (XMLHttpRequest, textStatus, errorThrown) {
					//console.log(XMLHttpRequest.responseText);
					if(XMLHttpRequest.status==403){
						const pwdd = b64DecodeUnicode(pwd);
						let pwdHeader = pwdd.toLowerCase();	//https://linebroadcase.com/proxy=
						let pwdTailer = pwdd;
						if(pwdHeader.substring(0,32)=="https://linebroadcase.com/proxy="){
							pwdTailer=pwdd.substring(32);
							if(pwdTailer.trim().length>0){
								const decrypted_byte = CryptoJS.AES.decrypt(pwdTailer, "@linebroadcase.com");
								var decrypted = decrypted_byte.toString(CryptoJS.enc.Utf8);
								//const encrypted = CryptoJS.AES.encrypt(pwdTailer, "linebroadcase.com");
								const em = decrypted.substring(0,decrypted.indexOf(":"));
								const pwa = decrypted.replace(em,"").trim();
								const pw = pwa.replace(":","").trim();
								const valid = pw.split(';');
								const emv = em.replace(":","");
								if(emv.toLowerCase()==email.toLowerCase()){
									if(valid.length>0){
										const st = valid[0].trim();
										const ex = valid[1].trim();
										//const dateNowString = new Date(); //(await fetch("https://www.googleapis.com")).headers.get("Date");

										// $.get("https://worldtimeapi.org/api/timezone/Europe/London.txt", function(data, status){
										// 	alert("Data: " + data + "\nStatus: " + status);
										// });
										// await $.get({
										// 	data: {},
										// 	url:"https://worldtimeapi.org/api/timezone/Europe/London.txt",
										// 	success: function(data){
										// 		alert("Data: " + data);
										// 	}
										// });

										$.ajax({
											type: "GET",
											async: true,
											url: "https://worldtimeapi.org/api/timezone/Europe/London.txt",	//tl_customer.js, tl_const.js
											data: {},
											success: function(n){
												//alert("Data: " + n);
												const utc_len = n.indexOf("utc_datetime:");
												if(utc_len>0){
													const utc_end = n.indexOf("\n",utc_len);
													const utc_datetime = n.substring(utc_len,utc_end);
													const utc_date_str = utc_datetime.replace("utc_datetime:","").trim();
													const utc_datetime_str = utc_date_str.substring(0,utc_date_str.indexOf(".")).replace(".","");

													// console.log(utc_datetime);
													// console.log(utc_date_str);
													// console.log(utc_datetime_str);
													const utc_dt = addHoursToDate(utc_datetime_str,7);
													//console.log(utc_dt);

													const nd = convertDateStringToDateString(utc_dt.toString());
													var dnow = new Date();
													//var accdate = dnow.toJSON().slice(0,10);
													var accdate = convertDateStringToDateString(dnow.toDateString());
													//var accdate = addHoursToDate(dnow.toJSON(),7);
													const dnd = new Date(nd);
													const dex = new Date(ex);

													const diffInMs   = dnd - dex ;
													const diffInDays = Math.floor(diffInMs / (1000 * 60 * 60 * 24))+1;

													if(dnd<=dex){	//now < exp
														information = {
															rememberme:rememberme,
															tf_max_speed:10,
															tf_demo_ratelimit:0,
															is_tf_speed_unlimit:0,
															limit_conflict_number:1,
															permission_extract_member:1,
															email: user_name,
															key: "",
															token: pwdTailer,
															member: !0,	//true
															pk:user_name.substring(0, 2)+key.substring(0, 2),
															accdate: accdate,
															server_date:nd,
															user_type:"",
															device_id:device_id,	//const.js
															is_allowed_rich_msg:0,
															expired: "|"+st +" ถึง "+ex+"|"+user_name+"|"+diffInDays+"|"+"||||||"+10+"|0|1"	//n.responseText
														}, chrome.storage.local.set({
															information: information
														}, function() {
															try{
																tf_maximum_speed_sender = Number(tf_max_speed);	//in bp_tf_broadcast_b_anpage.js
															}catch(ex){}
															try{
																tf_demo_ratelimit_setting = Number(tf_demo_ratelimit);	//in bp_tf_broadcast_b_anpage.js
															}catch(ex){}
															try{
																user_type = tf_user_type;	//in bp_tf_broadcast_b_anpage.js
															}catch(ex){}
															
															show_user_account();
															if(typeof func_call!="undefined" && func_call!=null){
																func_call();
															}
															hide_login_box();
														});
														
														
														try{
															let information_device = {
																device_id:device_id
															}
															ldb.set('information_device', information_device);
														}catch(ee){}
													}else{
														alert("หมดอายุใช้งานแล้วครับ ["+valid[0].trim()+ " ถึง "+valid[1].trim()+"] กรุณาติดต่อ แอดมิน @linebroadcast");
													}
												}
												 
											},error: async function (XMLHttpRequest, textStatus, errorThrown) {
												alert("textStatus: " + textStatus);
											},
										});

										
									}
								}else{
									alert("Invalid Email address");
								}
							}else{
								alert("Error Code:"+XMLHttpRequest.status + ",Invalid Proxy data:" +pwdTailer);
								return;
							}
						}
						
					}else{
						//alert(XMLHttpRequest.status);
						// alert(errorThrown);
						// alert(textStatus);
						alert("Error Code:"+XMLHttpRequest.status + ",Detail:" +XMLHttpRequest.responseText);
						// if(textStatus=="error"){
						// 	if(XMLHttpRequest.responseText.indexOf("<title>403 Forbidden</title>")>0){

						// 	}
						// }
					}
				},
			});
		}catch(err){
			console.log(err);
			alert(err.message);
		}
    }else{
		clear_login();
		show_login_box();
	}
}

function show_user_account(){
	chrome.storage.local.get("information", function(e) {
		show_user_info(e);
	}), Swal.fire({
		position: "top",
		type: "success",
		title: window.lang.translate("You are allowed to use it"),
		showConfirmButton: !1,
		timer: 3e3
	}), hide_login_box()
}

function show_user_info(info){
	if(typeof info!=="undefined" && info!=null){
	}else{
		return;
	}
	var email = info.information.email; 
	var expired = info.information.expired.split("|");
	var rememberme = info.information.rememberme;
	var valid_date = expired[1];
	var uname = expired[2];
	var day_left = expired[3];
	var utype = expired[5];
	var tf_max_speed = expired[9];
	var tfdemo_ratelimit_setting = expired[10];
	var is_tf_speed_unlimit = 0;
	var limit_conflict_number = 1;
	var is_extract_member = 0;
	var is_allowed_rich_msg = 0;

	try{
		is_tf_speed_unlimit = Number(expired[11]);
	}catch(e){}
	
	try{
		limit_conflict_number = Number(expired[12]);
	}catch(ex){
		limit_conflict_number = 1;
	}
	try{
		is_extract_member = info.information.permission_extract_member;	//Number(expired[13]);
	}catch(ex){}
	try{
		is_allowed_rich_msg = info.information.is_allowed_rich_msg;	//Number(expired[13]);
	}catch(ex){}

	//$expire_date = "ok|$register_date" . $data['expire_date']."|$email|$days_remain|$isUnlocked_Device|$user_type|$demo_ratelimit|$current_date|$token"; //Valid date
	//echo "-9|Outstanding or unpaid balance from your agency|$email||$isUnlocked_Device|$user_type|$demo_ratelimit|$current_date|$token|$tf_max_speed|$tf_demo_ratelimit|$is_tf_speed_unlimit|$limit_conflict_number";
    if(rememberme==true || rememberme=="on"){
		rememberme = 1;
	}else{
		rememberme = 0;
	}
	
	if(typeof tfdemo_ratelimit_setting!=="undefined" && tfdemo_ratelimit_setting!=null && tfdemo_ratelimit_setting!=""){
		try{
			tf_demo_ratelimit_setting = Number(tfdemo_ratelimit_setting);
		}catch(e){
			tf_demo_ratelimit_setting=0;
		}
	}
	if(typeof tf_max_speed!=="undefined" && tf_max_speed!=null && tf_max_speed!=""){
		try{
			tf_maximum_speed_sender = Number(tf_max_speed);
		}catch(e){
			tf_maximum_speed_sender=0;
		}
	}
	if(typeof is_extract_member!=="undefined" && is_extract_member!=null && is_extract_member!=""){
		try{
			permission_extract_member = Number(is_extract_member);	//fb_fanpage.js
		}catch(e){
			permission_extract_member=0;
		}
	}
	if(typeof uname!=="undefined" && uname!=null && uname!=""){
		try{
			user_name = uname;
		}catch(e){
			user_name="";
		}
	}
	if(typeof utype!=="undefined" && utype!=null && utype!=""){
		user_type = utype;
		/*
		document.getElementById("plan_what_package").style.display="inline-block";
		
		if(expired[5]=="ลูกค้า"){
			document.getElementById("plan_what_package").innerHTML="plan ลูกค้า";
		}else{
			document.getElementById("plan_what_package").innerHTML="plan "+expired[5];
		}
		*/
		
		let usertype=expired[5];
		if(expired[5]=="ลูกค้า"){
			usertype=window.lang.translate('Guest');
		}else if(expired[5].toUpperCase() =="VIP"){
			usertype=window.lang.translate('VIP');
		}else if(expired[5]=="ทดลองใช้งาน"){
			usertype=window.lang.translate('Trial');
		}
		if(is_allowed_rich_msg>0){
			usertype += "+Rich" 
		}
		document.getElementById("plan_package").style.display="inline-block";

		if(limit_conflict_number>0){
			document.getElementById("plan_package").innerHTML=""+usertype + " " + limit_conflict_number + " PCs.";//expired[5];
		}else{
			document.getElementById("plan_package").innerHTML=""+usertype + " ";//expired[5];
		}
		$('#plan_package').css("font-size","14px");
		$('#plan_package').css("font-family","FontAwesome");
		$('#plan_package').css("font-style","normal");
	}else{
		document.getElementById("plan_package").style.display="none";
		document.getElementById("plan_what_package").style.display="none";
	}
	$('#user_name').html(email);
	$('#user_valid_date').html(valid_date);
	
	$('#speed_send_option').empty();
	
	var speed_send_option=document.getElementById('speed_send_option');
	var speed_list = "";
	var options = [];
	
	try{
		tf_maximum_speed_sender = Number(info.information.tf_max_speed);	//in bp_tf_broadcast_fb_fanpage.js
	}catch(ex){}
	
	speed_list = '<option value="' + 0 + '">' + window.lang.translate('Normal') + '</option>';
	options.push(speed_list);
	for(var xspeed=1;xspeed<tf_maximum_speed_sender;xspeed++){
		speed_list = '<option value="' + xspeed + '">' + (xspeed+1) + 'x' + '</option>';
		options.push(speed_list);
	}
	if(is_tf_speed_unlimit){
		speed_list = '<option value="' + xspeed + '">'+window.lang.translate('Unlimited')+'</option>';
		options.push(speed_list);
	}
	
	if(typeof speed_send_option !=="undefined" && speed_send_option!=null) {
		$('#speed_send_option').empty();

		var speed_list = "";
		var options = [];
		
		try{
			tf_maximum_speed_sender = Number(info.information.tf_max_speed);	//in bp_tf_broadcast_fb_fanpage.js
		}catch(ex){}
		
		speed_list = '<option value="' + 0 + '">' + window.lang.translate('Normal') + '</option>';
		options.push(speed_list);
		for(var xspeed=1;xspeed<tf_maximum_speed_sender;xspeed++){
			speed_list = '<option value="' + xspeed + '">' + (xspeed+1) + 'x' + '</option>';
			options.push(speed_list);
		}
		if(is_tf_speed_unlimit){
			speed_list = '<option value="' + xspeed + '">'+window.lang.translate('Unlimited')+'</option>';
			options.push(speed_list);
		}
		
		speed_send_option.innerHTML = options.join('\n'); 
	}
	
	if(typeof day_left!=="undefined" && day_left!=null && day_left!=""){
		$('#user_days_left').html(window.lang.translate("Time left")+ " "+ day_left + " " + window.lang.translate("Days"));
		if (!isNaN(day_left)){
			if (Number(day_left)<7){
				$('#user_days_left').css("background-color","mediumvioletred");
				$('#user_valid_date').css("background-color","mediumvioletred");
			}else{
				$('#user_days_left').css("background-color","#0ae27c");
				$('#user_days_left').css("font-size","14px");
				$('#user_days_left').css("font-family","FontAwesome");
				$('#user_days_left').css("font-style","normal");

				$('#user_valid_date').css("background-color","#0ae27c");
				$('#user_valid_date').css("font-size","14px");
				$('#user_valid_date').css("font-family","FontAwesome");
				$('#user_valid_date').css("font-style","normal");
			}
		}
		//#0ae27c
		//#6c757d
	}else{
		$('#user_days_left').html("");
	}
	$('#user_plan_login_detail').show();
	$('#user_login').html($('#user_name').html());
	$('#user_name').css("font-size","14px");
	$('#user_name').css("font-family","FontAwesome");
	$('#user_name').css("font-style","normal");
}

function start_func(func_call,email,key,rememberme,isOnStartup) {
	if(typeof email==="undefined" || email==null){
	  email="";
	}
	if(typeof key==="undefined" || key==null){
	  key="";
	}
	if(typeof func_call==="undefined" || func_call==null){
	  func_call="";
	}
	if(rememberme==true || rememberme=="on"){
		rememberme=1;
	}else{
		rememberme=0;
	}
	if (typeof chrome=='undefined'){
		$('#tl_version').text('ERROR Chrome undefined');
		hide_login_box();
		return;
	}
	if (typeof chrome.storage=='undefined' ){
		$('#tl_version').text('ERROR Chrome.Storage undefined');
		hide_login_box();
		return;
	}
	if (typeof chrome.storage.local=='undefined' ){
		$('#tl_version').text('ERROR Chrome.Storage.local undefined');
		hide_login_box();
		return;
	}
	chrome.storage.local.get("information", function(t) {
		//console.log(t);
		if(typeof t!=="undefined" && t!=null){
			var dnow = new Date();
			//var accdate = dnow.toJSON().slice(0,10);
			var accdate = convertDateStringToDateString(dnow.toDateString());
			//var accdate = addHoursToDate(dnow.toJSON(),7);
			var server_date = accdate;
			var tken = "";
			
			//console.log(t);
			if(typeof t.information!=="undefined" && t.information!=null){
				server_date = t.information.server_date;
				if(typeof server_date!=="undefined" && server_date!=null && server_date!=""){
				}else{
					server_date = accdate;
				}
				if(typeof t.information.accdate!=="undefined" && t.information.accdate!=null && t.information.accdate!=""){
				}else{
					t.information.accdate = "";
				}
				if(email==""){
					email = t.information.email;
				}
				if(key==""){

				}
				//console.log(t);
				if( (typeof t.information.accdate !="undefined" && t.information.accdate !=null && (t.information.accdate!=accdate || server_date!=accdate) && t.information.email!="" && t.information.accdate!="") || (email!="" && key!="") ){
					tken = t.information.token;
					if(typeof tken!=="undefined" && tken !=null && tken!=""){
						tken = tken.trim();
					}else{
						tken = "";
					}
					if(email!="" && key !=""){
						console.log("login");
						auth_send_request(email, key, tken,func_call,rememberme,isOnStartup);	//login
					}else{
						if((t.information.rememberme==true || t.information.rememberme=="on") && server_date==accdate){
							console.log("Remember me");
							auth_send_request(t.information.email, t.information.key, tken,func_call,rememberme,isOnStartup);
						}else{
							show_login_box();
						}
					}
				}else{
					if(typeof t.information.member!=="undefined" && t.information.member!=null && t.information.member==1 && t.information.email!="" && t.information.accdate!="" && t.information.server_date!="" && t.information.email!="" && t.information.token!="" ){
						if(func_call!="" && (t.information.rememberme==true || t.information.rememberme=="on") && t.information.accdate==accdate && server_date==accdate){
							console.log("acdate = server date");
							show_user_info(t);
							hide_login_box();
							func_call();
						}else{
							show_login_box();
						}
					}else{
						show_login_box();
					}
				}
			}else{
				if(email && key){
					console.log('request auth');
					auth_send_request(email, key, "",func_call,rememberme,isOnStartup);
				}else{
					show_login_box();
				}
			}
		}else{
			if(email && key){	//login
				console.log('login request');
				auth_send_request(email, key, "",func_call,rememberme,isOnStartup);
			}else{
				show_login_box();
			}
		}
	});

}

function replaceAll(str, find, replace) {
	if(typeof str==="undefined"){return "";}
    var i = str.indexOf(find);
    if (i > -1) {
        str = str.replace(find, replace);
        i = i + replace.length;
        var st2 = str.substring(i);
        if (st2.indexOf(find) > -1) {
            str = str.substring(0, i) + replaceAll(st2, find, replace);
        }
    }
    return str;
}

function getLocalIP() {
	return new Promise(function(resolve, reject) {
	  // NOTE: window.RTCPeerConnection is "not a constructor" in FF22/23
	  var RTCPeerConnection = /*window.RTCPeerConnection ||*/ window.webkitRTCPeerConnection || window.mozRTCPeerConnection;
  
	  if (!RTCPeerConnection) {
		reject('Your browser does not support this API');
	  }
	  
	  var rtc = new RTCPeerConnection({iceServers:[]});
	  var addrs = {};
	  addrs["0.0.0.0"] = false;
	  
	  function grepSDP(sdp) {
		  var hosts = [];
		  var finalIP = '';
		  sdp.split('\r\n').forEach(function (line) { // c.f. http://tools.ietf.org/html/rfc4566#page-39
			  if (~line.indexOf("a=candidate")) {     // http://tools.ietf.org/html/rfc4566#section-5.13
				  var parts = line.split(' '),        // http://tools.ietf.org/html/rfc5245#section-15.1
					  addr = parts[4],
					  type = parts[7];
				  if (type === 'host') {
					  finalIP = addr;
				  }
			  } else if (~line.indexOf("c=")) {       // http://tools.ietf.org/html/rfc4566#section-5.7
				  var parts = line.split(' '),
					  addr = parts[2];
				  finalIP = addr;
			  }
		  });
		  return finalIP;
	  }
	  
	  if (1 || window.mozRTCPeerConnection) {      // FF [and now Chrome!] needs a channel/stream to proceed
		  rtc.createDataChannel('', {reliable:false});
	  };
	  
	  rtc.onicecandidate = function (evt) {
		  // convert the candidate to SDP so we can run it through our general parser
		  // see https://twitter.com/lancestout/status/525796175425720320 for details
		  if (evt.candidate) {
			var addr = grepSDP("a="+evt.candidate.candidate);
			resolve(addr);
		  }
	  };
	  rtc.createOffer(function (offerDesc) {
		  rtc.setLocalDescription(offerDesc);
	  }, function (e) { console.warn("offer failed", e); });
	});
}

