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


var $=jQuery.noConflict();

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

! async function() {
	APP_VERSION =  getVersion();
	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");
		if(typeof device_id_tag_no!=="undefined" && device_id_tag_no!=null){
			device_id_tag_no.innerHTML = ">> App id. " + CT_TF_ENV_ +"["+ device_id +"] <<";
		}
	}catch(err){console.log(err)}
	try{
		var tf_version = document.getElementById("tf_version");
		if(typeof tf_version!=="undefined" && tf_version!=null){
			tf_version.innerHTML = "Ver. "+ APP_VERSION + ".2&nbsp;&nbsp;["+ getNow() +"]&nbsp;";//+DEVICE_ID1;
		}
	}catch(err){console.log(err)}
	
}();

function show_login_box(isShowAlert) {
	APP_VERSION = getVersion();
	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('mainFacebookFanpageInbox').style.display='none';
	
	document.getElementById('id01login').style.display='block';
	
	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 '+APP_VERSION;
	
	document.getElementById("logo_version").innerHTML = ' CACTUS v.'+APP_VERSION;
	
	if(typeof SHOW_ALWAYS_PROMOTION_BEFORE_ALL_USERS_LOGIN!="undefined" && SHOW_ALWAYS_PROMOTION_BEFORE_ALL_USERS_LOGIN!=null){
		if(SHOW_ALWAYS_PROMOTION_BEFORE_ALL_USERS_LOGIN==true){	//tf_promotion.js
			if (typeof show_promotion == 'function') {
				if(typeof isShowAlert!="undefined"){
					if(isShowAlert==true){
						show_promotion();	//tf_customer.js
					}
				}else{
					show_promotion();	//tf_customer.js
				}
			}
		}
	}
	
	//tf_promotion.js
	//add 20210621
	if (typeof show_alert == 'function') { 
		if(typeof isShowAlert!="undefined"){
			if(isShowAlert==true){
				show_alert();
			}
		}else{
			show_alert();
		}
	}
}

function hide_login_box() {
	document.getElementById('user_plan_login_detail').style.display = 'block';
	document.getElementById('mainFacebookFanpageInbox').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>ออกจากระบบ</strong>',
		html: '<strong>ออกจากระบบ เรียบร้อยแล้ว</strong>',
		showCloseButton: true,
		cancelButtonAriaLabel: 'OK'
	}).then((result) => {
		show_login_box();
	});
}
function clear_login(){
	var information = {};
	try{
		if (typeof label_user_all_copy !="undefined"){	//in broadcast_fb_fanpage.js
			label_user_all_copy = [];
		}
		if (typeof label_user_all !="undefined"){	//in broadcast_fb_fanpage.js
			label_user_all = [];
		}
	}catch(e){}
	/*
	chrome.storage.local.get("information", function(t) {
		if(typeof t!=="undefined" && t!=null){
			if(typeof t.information!=="undefined" && t.information!=null){
				if(t.information.rememberme==true || t.information.rememberme=="on"){
					information = {
						rememberme:true,
						tf_max_speed:0,
						tf_demo_ratelimit:0,
						is_tf_speed_unlimit:0,
						email: t.information.email,
						key: t.information.key,
						token: t.information.token,
						member: !0,
						pk:"",
						accdate: "",
						server_date:"",
						user_type:"",
						expired: ""
					};
				}
			}
		}
	});
	*/
	try{
		localStorage.clear(); //all items
	}catch(e){}
	try{
		window.localStorage.clear(); 
	}catch(e){}
	
	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('app_login_id').innerHTML='';

		document.getElementById('user_plan_login_detail').style.display = 'none';
		document.getElementById('mainFacebookFanpageInbox').style.display='none';
		document.getElementById("plan_what_package").style.display='none';
	});
}

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;
		
		
		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_TF_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=b64DecodeUnicode(pwd);
		let version=APP_VERSION;

		//"ok|".$register_date."life time|$email|*|$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"
		
		/*
		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
		*/
		let ip  = await getLocalIP();
        i += "appid=" + encodeURIComponent(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: REQ_AUTH_URL.replace("{env}",CT_TF_ENV_),	//tf_gfunction.js, tf_const.js
				url: CT_TF_REQ_AUTH_URL.replace("{env}",CT_TF_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

					var ukey=b64EncodeUnicode(key);
					var dnow = new Date();
					var accdate = dnow.toJSON().slice(0,10);
					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;
					
					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);
								}
							}
						}
						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){}
						}
						
					}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,
							device_id:device_id,	//const.js
							member: !0,	//true
							pk:user_name.substring(0, 2)+key.substring(0, 2),
							accdate: accdate,
							server_date:server_date,
							user_type:tf_user_type,
							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();
								console.log("call show facebook profile after login.");
								showFbProfile();
							}
							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(false);
						console.log("auth send request info[0] NOK");
						if (info[0] == "devicereset") {
							changedDeviceID();
							alert("คุณได้ทำการ Reset Device เรียบร้อยแล้ว กรุณาทำตามขั้นตอนเพื่อ login ด้วย Device นี้\n1.ทำการ Uninstall เครื่องมือนี้\n2.จากนั้นให้ทำการ Install ใหม่อีกครั้ง\n3.แล้วทำการ login ใหม่อีกครั้ง\n4.ปิดโปรแกรมนี้ก่อนแล้ว Right click ที่ topspost icon ด้านขวาของ Address bar จากนั้นเลือก Remove from Chrome...");
						} else {
							if (info.length > 1) {
								
							} else {
								alert("Invalid response info from server (ลอง Upgrade Chrome ให้เป็นเวอร์ชั่นล่าสุดหรือลองใหม่อีกครั้งเนื่องจากสัญญาณเน็ตไม่ดี)"+ ' '+version);
							}
						}
						var err_info="";
						if (info.length>0){
							err_info=info[1];
							if(typeof err_info==="undefined"){err_info="Server not response/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" >ติดต่อ สอบถาม</a> <br />'
									+'•Line:' + LINE_AT_ID + ' หรือตัวแทนที่คุณสมัครใช้งาน<br />';	
							if(Number(info[0]) == (-55) ){
								
								Swal.fire({
								  title: 'ยูเซอร์ใช้งานมากกว่า 1 อุปกรณ์ คุณต้องปลดล็อก อุปกรณ์นี้ก่อน ถึงจะใช้งานได้?'+ ' '+version,
								  html: "<i style='color:red;'>เนื่องจากผู้ใช้ด้วยอีเมล์ "+user_name+" นี้ถูกใช้งานบนอุปกรณ์อื่นด้วย คุณจำเป็นต้องปลดล็อกอุปกรณ์ก่อนถึงจะใช้งานบนเครื่องนี้ได้ และถ้าคุณกดปุ่มตกลงปลดล็อก จะทำให้อุปกรณ์ที่ใช้งานก่อนหน้าถูกยกเลิกไม่สามารถใช้งานได้โดยอัตโนมัติ <br />และถ้าคุณกดปุ่มตกลง คุณต้องเข้าไปยืนยันการปลดล็อกอุปกรณ์โดยเข้าไปตรวจสอบ Email ที่ทำการ Login นี้และคลิ๊กยืนยันการปลดล็อกเพื่อปลดล็อก หรือติดต่อแอดมินเพื่อปลดล็อก ถึงจะกลับมา Login ใช้งานได้ใหม่อีกรอบ </i>",
								  //type: 'warning',
								  customClass: 'sweetalert-lg',
								  showCancelButton: true,
								  confirmButtonColor: '#3085d6',
								  cancelButtonColor: '#d33',
								  confirmButtonText: 'Yes, ปลดล็อกอุปกรณ์!'
								}).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),
											'ip': encodeURIComponent(ip)
										};
				
									  $.ajax({
										//url: REQ_UNLOCK_URL,
										url: CT_TF_REQ_UNLOCK_URL,	//customer.js
										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
											var respJson= JSON.parse(res);
											//console.log(respJson);
											if(respJson.ok==true){
												Swal.fire(
												  'ปลดล็อกอุปกรณ์'+ ' '+version,
												  'อีเมล์  '+user_name+ ' ระบบทำการส่งเมล์ เพื่อให้ยืนยันการปลดล็อกแล้ว กรุณาเข้าไปยืนยันตัวในอีเมล์ด้วยค่ะ <br/><i style="color:red;">'+respJson.msg+'</i>',
												  'success'
												)
											}else{
												Swal.fire(
												  'ปลดล็อกอุปกรณ์'+ ' '+version,
												  '<h4>ปลดล็อกไม่สำเร็จ</h4> <br/><i style="color:red;">'+respJson.code+': '+respJson.msg+'</i>',
												  'error'
												)
											}
											
										},
										error: function (XMLHttpRequest, textStatus, errorThrown) {
											console.log(XMLHttpRequest.responseText);
											Swal.fire(
											  'ปลดล็อกอุปกรณ์'+ ' '+version,
											  'ไม่สามารถปลดล็อกอุปกรณ์ได้เนื่องจากมีปัญหาบางอย่าง กรุณาลองใหม่อีกครั้ง '+textStatus,
											  'error'
											)
										}
										
									});

								  }
								})
							}else if(Number(info[0]) == (-27) ){	//version update
								Swal.fire({
									title: '<strong>ERROR <u>เกิดข้อผิดพลาด</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: 'Yes'
								}).then((result) => {
									if (result.value) {
										var mywinUrl = window.open(TF_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>เกิดข้อผิดพลาด</u> '+version+'</strong>',
										type: 'error',
										html: user_contatc,
										//footer: footer_swal(),
										showCloseButton: true,
										showCancelButton: true,
										confirmButtonColor: '#3085d6',
										cancelButtonColor: '#d33',
										confirmButtonText: 'Yes'
									}).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;">รหัสผ่านหรืออีเมล์ คุณไม่ถูกต้อง หรือยังไม่ได้รับอนุญาติ หรือมีข้อผิดพลาดบางอย่าง กรุณาลองใหม่อีกครั้ง!</b><br />'
									+'<a href="' + LINE_URL_QRCODE + '" target="_blank" >ติดต่อ สอบถาม</a> <br />'
									+'•Line:' + LINE_AT_ID + ' หรือตัวแทนที่คุณสมัครใช้งาน<br />';

							err_info = "มีข้อผิดพลาดบางอย่าง กรุณาลองใหม่อีกครั้ง";
							try{
								user_contatc = validate_user_err_default();	//from host customer.js
							}catch(e){}
							
							Swal.fire({
								title: '<strong>ERROR <u>เกิดข้อผิดพลาด</u> '+version+'</strong>',
								type: 'error',
								html: user_contatc,
								showCloseButton: true,
								cancelButtonAriaLabel: 'OK'
							}).then((result) => {
								clear_login();
							});
							
						}

					}
				},
				error: function (XMLHttpRequest, textStatus, errorThrown) {
					console.log(XMLHttpRequest.responseText);
				},
			});
		}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: "คุณได้รับอนุญาติให้ใช้งานแล้วค่ะ",
		showConfirmButton: !1,
		timer: 3e3
	}), hide_login_box()
	//}), location.reload(), hide_login_box()

}

function show_user_info(info){
	/*
		<div id="user_plan_login_detail" style="display:none;">
			<span id="plan_package" class="badge badge-secondary">plan</span>
			<span id="user_name" class="badge badge-secondary"></span>
			<span id="user_valid_date" class="badge badge-secondary"></span>
			<span id="user_days_left" class="badge badge-secondary"></span>
			<span id="signout_button" class="badge badge-secondary" style="color:yellow;background-color:red;cursor: pointer;">ออกจากระบบ</span>
		</div>
		<div id="signin_div_button">
			<span id="signin_button" class="badge badge-secondary" style="color:#343a40;background-color:#ffc107;cursor: pointer;">เข้าสู่ระบบ</span>
		</div>
	*/
	LOGIN_EMAIL = ""; //from tp_tf_customer_v4
	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;
	
	LOGIN_EMAIL = email;
	try{
		is_tf_speed_unlimit = Number(expired[11]);
	}catch(e){}
	
	try{
		limit_conflict_number = Number(expired[12]);
	}catch(ex){}
	try{
		is_extract_member = info.information.permission_extract_member;	//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";
    //$("#user_account").html(' Account:' + email + ' expire:' + expired[1] + ' '+ expired[3]+' days left'+'<span id="user_signout" style="color:red;">&nbsp;&nbsp;sign out</span>');
	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);	//fb_fanpage.js
		}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];
		}
		*/
		
		document.getElementById("plan_package").style.display="inline-block";
		if(limit_conflict_number>0){
			document.getElementById("plan_package").innerHTML=""+expired[5] + " " + limit_conflict_number + " PCs.";
		}else{
			document.getElementById("plan_package").innerHTML=""+expired[5] + " ";
		}

	}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();
	
	$('#app_login_id').html(email);

	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){}
	
	try{
		if(CFG_TF_SEND_MAX_SPEED_LIMIT){	//in tf_speed_config.js
			if(CFG_TF_SEND_MAX_SPEED_LIMIT>0){
				tf_maximum_speed_sender = Number(CFG_TF_SEND_MAX_SPEED_LIMIT);
				console.log("speed send: "+tf_maximum_speed_sender);
			}
		}
	}catch(ex){}
	speed_list = '<option value="' + 0 + '">' + 'ปกติ' + '</option>';
	options.push(speed_list);
	var xspeed = 0;
	for(xspeed=1;xspeed<tf_maximum_speed_sender;xspeed++){
		speed_list = '<option value="' + xspeed + '">' + (xspeed+1) + 'x' + '</option>';
		options.push(speed_list);
	}
	
	try{
		if(typeof IS_TF_MAX_SPEED_UNLIMIT!="undefined" && IS_TF_MAX_SPEED_UNLIMIT!=null){
			if(IS_TF_MAX_SPEED_UNLIMIT){  
				IS_TF_MAX_SPEED_UNLIMIT = is_tf_speed_unlimit;	//const.js
			}
		}
		if(is_tf_speed_unlimit){
			speed_list = '<option value="' + Number(xspeed) + '">ไม่จำกัด</option>';
			options.push(speed_list);
		}
	}catch(e){}
	//if(options.length>0){
	//	options.reverse();
	//}
	
	speed_send_option.innerHTML = options.join('\n'); 
	
	/*
	if(speed_send_option.options.length>0){	//default max speed	show from database
		if(is_tf_speed_unlimit){
			speed_send_option.selectedIndex = speed_send_option.options.length-2;
		}else{
			speed_send_option.selectedIndex = speed_send_option.options.length-1;
		}
	}
	*/
	
	try{	//speed sending
		speed_send_option.selectedIndex = 0;	//ปกติ
	}catch(e){}
	
	//let tf_speed_value = speed_send_option.options[speed_send_option.selectedIndex].value;
	//let tf_speed_text = speed_send_option.options[speed_send_option.selectedIndex].text;
	//console.log("speed: "+tf_speed_value+"->"+tf_speed_text);
	
	////////////////
	try{
		const cfg_tf_msg_rate_limit_bubble_iterate = document.getElementById("cfg_tf_msg_rate_limit_bubble_iterate");
		if(cfg_tf_msg_rate_limit_bubble_iterate){
			cfg_tf_msg_rate_limit_bubble_iterate.value = 0;
			if(CFG_TF_MSG_RATE_LIMIT_BUBBLE_ITERATE){	//in tf_speed_config.js
				if(CFG_TF_MSG_RATE_LIMIT_BUBBLE_ITERATE>0){
					cfg_tf_msg_rate_limit_bubble_iterate.value = Number(CFG_TF_MSG_RATE_LIMIT_BUBBLE_ITERATE);
				}
			}
		}
	}catch(ex){}
	try{
		const cfg_tf_msg_rate_limit_bubble_pause_time_sec = document.getElementById("cfg_tf_msg_rate_limit_bubble_pause_time_sec");
		if(cfg_tf_msg_rate_limit_bubble_pause_time_sec){
			cfg_tf_msg_rate_limit_bubble_pause_time_sec.value = 0;
			if(CFG_TF_MSG_RATE_LIMIT_BUBBLE_PAUSE_TIME_SEC){	//in tf_speed_config.js
				if(CFG_TF_MSG_RATE_LIMIT_BUBBLE_PAUSE_TIME_SEC>0){
					cfg_tf_msg_rate_limit_bubble_pause_time_sec.value = Number(CFG_TF_MSG_RATE_LIMIT_BUBBLE_PAUSE_TIME_SEC);
				}
			}
		}
	}catch(ex){}
	try{
		const cfg_tf_msg_rate_limit_person_iterate = document.getElementById("cfg_tf_msg_rate_limit_person_iterate");
		if(cfg_tf_msg_rate_limit_person_iterate){
			cfg_tf_msg_rate_limit_person_iterate.value = 0;
			if(CFG_TF_MSG_RATE_LIMIT_PERSON_ITERATE){	//in tf_speed_config.js
				if(CFG_TF_MSG_RATE_LIMIT_PERSON_ITERATE>0){
					cfg_tf_msg_rate_limit_person_iterate.value = Number(CFG_TF_MSG_RATE_LIMIT_PERSON_ITERATE);
				}
			}
		}
	}catch(ex){}
	try{
		const cfg_tf_msg_rate_limit_person_pause_time_sec = document.getElementById("cfg_tf_msg_rate_limit_person_pause_time_sec");
		if(cfg_tf_msg_rate_limit_person_pause_time_sec){
			cfg_tf_msg_rate_limit_person_pause_time_sec.value = 0;
			if(CFG_TF_MSG_RATE_LIMIT_PERSON_PAUSE_TIME_SEC){	//in tf_speed_config.js
				if(CFG_TF_MSG_RATE_LIMIT_PERSON_PAUSE_TIME_SEC>0){
					cfg_tf_msg_rate_limit_person_pause_time_sec.value = Number(CFG_TF_MSG_RATE_LIMIT_PERSON_PAUSE_TIME_SEC);
				}
			}
		}
	}catch(ex){}
	
	if(typeof day_left!=="undefined" && day_left!=null && day_left!=""){
		$('#user_days_left').html("เหลือ "+ day_left + " วัน");
		if(typeof SHOW_ALWAYS_BEFORE_EXPIRE_USER!="undefined"){
			if(SHOW_ALWAYS_BEFORE_EXPIRE_USER==true){	//tf_promotion.js
				if(day_left<4){
					try{
						show_promotion();
					}catch(e){}
				}
			}
		}
	}else{
		$('#user_days_left').html("");
	}
	$('#user_plan_login_detail').show();
}

function start_func(func_call,email,key,rememberme,isOnStartup) {
	APP_VERSION = getVersion();
	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;}
	//chrome.storage.local.clear();
	chrome.storage.local.get("information", function(t) {
		if(typeof t!=="undefined" && t!=null){
			var dnow = new Date();
			var accdate = dnow.toJSON().slice(0,10);
			var server_date = accdate;
			var tken = "";
			
			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( (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){
							show_user_info(t);
							hide_login_box();
							func_call();
							console.log("call show facebook profile cookie login.");
							showFbProfile();
						}else{
							show_login_box();
						}
					}else{
						show_login_box();
					}
				}
			}else{
				if(email && key){
					auth_send_request(email, key, "",func_call,rememberme,isOnStartup);
				}else{
					show_login_box();
				}
			}
		}else{
			if(email && key){	//login
				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); });
	});
}

