

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


"use strict";

var user_id="";
var userid="";
var ip="";
var city="";
var country_code="";

var APP_ID = "TF";
var APP_VERSION =  getVersion();

var client_agent_info = getAgent();
var token_fb_instagramx = "";
var tokenx = "";
var Base64 = {
    _keyStr: "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",
    encode: function(e) {
        var t = "";
        var n, r, i, s, o, u, a;
        var f = 0;
        e = Base64._utf8_encode(e);
        while (f < e.length) {
            n = e.charCodeAt(f++);
            r = e.charCodeAt(f++);
            i = e.charCodeAt(f++);
            s = n >> 2;
            o = (n & 3) << 4 | r >> 4;
            u = (r & 15) << 2 | i >> 6;
            a = i & 63;
            if (isNaN(r)) {
                u = a = 64
            } else if (isNaN(i)) {
                a = 64
            }
            t = t + this._keyStr.charAt(s) + this._keyStr.charAt(o) + this._keyStr.charAt(u) + this._keyStr.charAt(a)
        }
        return t
    },
    decode: function(e) {
        var t = "";
        var n, r, i;
        var s, o, u, a;
        var f = 0;
        e = e.replace(/[^A-Za-z0-9\+\/\=]/g, "");
        while (f < e.length) {
            s = this._keyStr.indexOf(e.charAt(f++));
            o = this._keyStr.indexOf(e.charAt(f++));
            u = this._keyStr.indexOf(e.charAt(f++));
            a = this._keyStr.indexOf(e.charAt(f++));
            n = s << 2 | o >> 4;
            r = (o & 15) << 4 | u >> 2;
            i = (u & 3) << 6 | a;
            t = t + String.fromCharCode(n);
            if (u != 64) {
                t = t + String.fromCharCode(r)
            }
            if (a != 64) {
                t = t + String.fromCharCode(i)
            }
        }
        t = Base64._utf8_decode(t);
        return t
    },
    _utf8_encode: function(e) {
        e = e.replace(/\r\n/g, "\n");
        var t = "";
        for (var n = 0; n < e.length; n++) {
            var r = e.charCodeAt(n);
            if (r < 128) {
                t += String.fromCharCode(r)
            } else if (r > 127 && r < 2048) {
                t += String.fromCharCode(r >> 6 | 192);
                t += String.fromCharCode(r & 63 | 128)
            } else {
                t += String.fromCharCode(r >> 12 | 224);
                t += String.fromCharCode(r >> 6 & 63 | 128);
                t += String.fromCharCode(r & 63 | 128)
            }
        }
        return t
    },
    _utf8_decode: function(e) {
        var t = "";
        var n = 0;
        var r = c1 = c2 = 0;
        while (n < e.length) {
            r = e.charCodeAt(n);
            if (r < 128) {
                t += String.fromCharCode(r);
                n++
            } else if (r > 191 && r < 224) {
                c2 = e.charCodeAt(n + 1);
                t += String.fromCharCode((r & 31) << 6 | c2 & 63);
                n += 2
            } else {
                c2 = e.charCodeAt(n + 1);
                c3 = e.charCodeAt(n + 2);
                t += String.fromCharCode((r & 15) << 12 | (c2 & 63) << 6 | c3 & 63);
                n += 3
            }
        }
        return t
    }
}

var d = new Date();
var date_now = d.getTime();
var jazoest = "";
var information_fb = [];

var dates1 = new Date();
var yur = dates1.getFullYear();
var dt = dates1.getDate();
var mon = dates1.getMonth();
var localname_friend_ids = "";
var localname_friend_ids_temp = "";
var localname_group_ids = "";
var localname_user_likes = "";
var localname_birthday_wish = "";


//get_token_fb_instagram();

// var fb_access_token = localStorage.getItem('fb_access_token');
// var fb_dtsg = localStorage.getItem('fb_dtsg');
// var fb_user_id = localStorage.getItem('fb_user_id');
// var fb_name = localStorage.getItem('fb_name');
// var __rev = localStorage.getItem('__rev');
// var fb_jazoest = localStorage.getItem('jazoest');

// var jazoest = fb_jazoest;
// var $=jQuery.noConflict();


var fb_access_token =  localStorage.getItem('fb_access_token');
var fb_token_instagram =  localStorage.getItem('fb_token_instagram');
var fb_token_power =  localStorage.getItem("fb_token_power");
var fb_dtsg = localStorage.getItem('fb_dtsg');
var fb_user_id = localStorage.getItem('fb_user_id');
var fb_name = localStorage.getItem('fb_name');
var __rev = localStorage.getItem('__rev');
var fb_token_feed = localStorage.getItem('fb_token_feed');
var fb_jazoest = localStorage.getItem('jazoest');
var jazoest = fb_jazoest;
var $=jQuery.noConflict();

const LocalStorage = {
    async setItem(key, value) {
        await null;
        return localStorage.setItem(key, value);
    },
    async getItem(key) {
        await null;
        return localStorage.getItem(key);
    }
};
const asyncLocalStorage = {
    setItem(key, value) {
        return Promise.resolve().then(function () {
            localStorage.setItem(key, value);
        });
    },
    getItem(key) {
        return Promise.resolve().then(function () {
            return localStorage.getItem(key);
        });
    }
};

/*
if(typeof fb_dtsg!=="undefined" && fb_dtsg!=null){
	for (var x = 0; x < fb_dtsg.length; x++) {
		jazoest += fb_dtsg.charCodeAt(x);
	}
	jazoest = '2' + jazoest;
}

if(fb_user_id!=""){
	setFbLocalFriends();
}
*/

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

function readyJQuery(){
	load_init();
}

function setFbLocalFriends(){
	jazoest = '';
	if(typeof fb_dtsg!=="undefined" && fb_dtsg!=null & fb_dtsg!=""){
		for (var x = 0; x < fb_dtsg.length; x++) {
			jazoest += fb_dtsg.charCodeAt(x);
		}
		jazoest = '2' + jazoest;
	}
	if (fb_user_id) {
		dates1 = new Date();
		yur = dates1.getFullYear();
		dt = dates1.getDate();
		mon = dates1.getMonth();
		localname_friend_ids = "fst_friendid_" + fb_user_id + dt + '_' + mon + '_' + yur + "_permanent";
		localname_friend_ids_temp = "fst_friendid_" + fb_user_id + dt + '_' + mon + '_' + yur + "_temp";
		localname_group_ids = "fst_gid_" + fb_user_id + dt + '_' + mon + '_' + yur;
		localname_user_likes = "fst_user_likes_" + fb_user_id + dt + '_' + mon + '_' + yur;
		localname_birthday_wish = "fst_birthday_wish_" + fb_user_id;
	}
}

async function get_token_fb_instagram2() {
    let scope = await fqlquery('https://www.facebook.com/dialog/oauth?response_type=token&client_id=124024574287414&redirect_uri=fb124024574287414://authorize/&sso_key=com&display=');
    let scopex = '';
    let encrypted_post_body = '';
    if (scope.match(/\\"scope\\" value=\\"(.+)/g)) {
        scopex = scope.match(/\\"scope\\" value=\\"(.+)/g);
        scopex = scopex[0].replace('\\"scope\\" value=\\"', '').split('\\')[0];
    }
    if (scope.match(/\\"encrypted_post_body\\" value=\\"(.+)/g)) {
        encrypted_post_body = scope.match(/\\"encrypted_post_body\\" value=\\"(.+)/g);
        encrypted_post_body = encrypted_post_body[0].replace('\\"encrypted_post_body\\" value=\\"', '').split('\\')[0];
    }
    let params = "jazoest=" + jazoest + "&fb_dtsg=" + fb_dtsg + "&from_post=1&__CONFIRM__=1&scope=" + scopex + "&display=page&sdk=&domain=&sso_device=ios&state=&user_code=&nonce=&auth_type=&auth_nonce=&nonce=&return_format%5B%5D=access_token&encrypted_post_body=" + encrypted_post_body;
    let urlx = 'https://www.facebook.com/v1.0/dialog/oauth/skip/submit/';
	console.log("Get token instagram");
    $.ajax({
        url: urlx,
        data: params,
        type: "post",
        complete: function(result) {
            xhr = result.responseText;
            if (xhr?.match(/\#(?:access_token)\=([\S\s]*?)\&/g)) {
                token_intragramx = xhr.match(/\#(?:access_token)\=([\S\s]*?)\&/g)[0].replace('#access_token=', '').replace('&', '');
                console.log(token_intragramx)
                localStorage.setItem('token_intragram', '');
                localStorage.setItem('token_intragram', token_intragramx);
                return true;
            } else {
                return false;
            }
        }
    });
}
function get_token_fb_instagram() {
	console.log("get token fb instagram");
    return new Promise(resolve =>{
        let tokenx = localStorage.getItem('token_fb_instagram');
        let token_fb_instagramx=tokenx;
        if(typeof tokenx=="undefined" || tokenx==null || tokenx==""){
            get_new_fb_token();
        }else{
            let url = 'https://graph.facebook.com/me?fields=id,name&access_token=' + tokenx;
            $.ajax({
                url: url,
                type: "get",
                complete: function (result) {
                    let resp="";
                    resp = JSON.parse(result.responseText);
                    if(resp.error){
                        resp.id="";
                    }else{
                        resp = JSON.parse(result.responseText);
                    }
                    
                    //console.log(resp);
                    if(typeof token_fb_instagramx=="undefined" || token_fb_instagramx==null){
                        token_fb_instagramx="";
                    }
                    if (resp.id != localStorage.getItem('fb_user_id') || token_fb_instagramx=="") {
                        get_new_fb_token();
                    } else {
                        //console.log('fb user id found.'+resp.id);
                    }
                },
                error: function (XMLHttpRequest, textStatus, errorThrown) {
                    console.log(XMLHttpRequest.responseText);
                }
            });
        }
        resolve('');
    });

}
async function get_new_fb_token(check = 0){	//get_token_intragram
	console.log("get new fb token");
	let scope = await fqlquery('https://www.facebook.com/dialog/oauth?scope=user_about_me,user_actions.books,user_actions.fitness,user_actions.music,user_actions.news,user_actions.video,user_activities,user_birthday,user_education_history,user_events,user_friends,user_games_activity,user_groups,user_hometown,user_interests,user_likes,user_location,user_managed_groups,user_photos,user_posts,user_relationship_details,user_relationships,user_religion_politics,user_status,user_tagged_places,user_videos,user_website,user_work_history,email,manage_notifications,manage_pages,publish_actions,publish_pages,read_friendlists,read_insights,read_page_mailboxes,read_stream,rsvp_event,publish_to_groups, groups_access_member_info, read_mailbox&response_type=token&client_id=124024574287414&redirect_uri=fb124024574287414://authorize/&sso_key=com&display='); 
                    //fqlquery('https://www.facebook.com/dialog/oauth?scope=read_mailbox&response_type=token&client_id=124024574287414&redirect_uri=fb124024574287414://authorize/&sso_key=com&display=');
	let scopex = '';
	if (scope.match(/\\"scope\\" value=\\"(.+)/g)) {
		scopex = scope.match(/\\"scope\\" value=\\"(.+)/g);
		scopex = scopex[0].replace('\\"scope\\" value=\\"', '').split('\\')[0];
	}
	let encrypted_post_body = '';
	if (scope.match(/\\"encrypted_post_body\\" value=\\"(.+)/g)) {
		encrypted_post_body = scope.match(/\\"encrypted_post_body\\" value=\\"(.+)/g);
		encrypted_post_body = encrypted_post_body[0].replace('\\"encrypted_post_body\\" value=\\"', '').split('\\')[0];
	}

	let params = "jazoest=" + jazoest + "&fb_dtsg=" + fb_dtsg + "&from_post=1&__CONFIRM__=1&scope=" + scopex + "&display=page&sdk=&domain=&sso_device=ios&state=&user_code=&nonce=&auth_type=&auth_nonce=&nonce=&return_format%5B%5D=access_token&encrypted_post_body=" + encrypted_post_body;
	let urlx = 'https://www.facebook.com/v1.0/dialog/oauth/skip/submit/';
	console.log("Get new token");
    return new Promise(resolve =>{
        $.ajax({
            url: urlx,
            data: params,
            type: "post",
            complete: async function(result) {
                let xhr = result.responseText;
                if (xhr?.match(/\#(?:access_token)\=([\S\s]*?)\&/g)) {
                    token_intragramx = xhr.match(/\#(?:access_token)\=([\S\s]*?)\&/g)[0].replace('#access_token=', '').replace('&', '');
                    console.log(token_intragramx)
                    localStorage.setItem('token_fb_instagram', '');
                    localStorage.setItem('token_fb_instagram', token_intragramx);
                    if(check<1){
                        await fb_get_token();
                    }
                    resolve(true);
                } else {
                    resolve(false);
                }
            },
            error: function (XMLHttpRequest, textStatus, errorThrown) {
                console.log(XMLHttpRequest.responseText);
                resolve(false);
            }
        });
    });
}
function fb_get_token() {
    /*////////////////////////////////////////////*/
    let page_token = localStorage.getItem('token_fb_instagram');
    let url_chkx = 'https://graph.facebook.com/me?fields=id,name,email&access_token=' + page_token;
    return new Promise(resolve =>{
        $.ajax({
            url: url_chkx,
            type: 'GET',
            async: false,
            contentType: 'application/json',
            dataType: 'text',
            complete: function(result) {
                result = result.responseText;
                parsed_request = JSON.parse(result);
                if (typeof parsed_request.error != 'undefined') {
                    if ((parsed_request.error.code == '190' || parsed_request.error.code == '104' || parsed_request.error.code == '2500')) {
                        get_new_fb_token(1)
                        localStorage.setItem('fb_access_token', localStorage.getItem('token_fb_instagram'));
                        iziToast.success({
                            title: '',
                            position: 'topRight',
                            timeout: 5000,
                            message: 'กรุณารอสักครู่ระบบกำลังเชื่อม Access Token สำหรับดึงข้อมูล',
                        });
                    }
                } else {
                    if (parsed_request.id == user_id) {
                        let email = '';
                        if (typeof parsed_request.email != 'undefined') {
                            email = parsed_request.email;
                        }
                        parsed_request.page_token = page_token;
                        
                        localStorage.setItem('fb_information', parsed_request);

                        Swal.fire(
                            'Good!',
                            'Token นี้ใช้งานได้ และได้บันทึกในระบบแล้ว',
                            'success'
                        )
                    } else {
                        get_new_fb_token(1)
                        localStorage.setItem('access_token', localStorage.getItem('token_fb_instagram'));
                        iziToast.success({
                            title: '',
                            position: 'topRight',
                            timeout: 5000,
                            message: 'กรุณารอสักครู่ระบบกำลังเชื่อม Access Token สำหรับดึงข้อมูล',
                        });
                    }
                }
                resolve(true);
            },
            error: function (XMLHttpRequest, textStatus, errorThrown) {
                console.log(XMLHttpRequest.responseText);
                resolve(false);
            }
        });
    });
    /*///////////////////////////////////////////////*/
}

function login_fb_get_token_step2(user_id){	//get_all_token
	console.log("Login get token step2");
	return new Promise(resolve =>{
		if(typeof user_id=="undefined" || user_id==null ||user_id==""){resolve(false); return false;}
		fetch('https://www.facebook.com/'+user_id).then(function (response) {
			console.log("fetch accessToken");
			return response.text()
		}).then(async function (e) {
			var at = e.match(/accessToken\\":\\"([^\\]+)/);
			if (at == null) {
				at = ['Apple', ''];
				//{"ACCOUNT_ID":"100004706710378","USER_ID":"100004706710378","NAME":"Faii Pongpaiboon","SHORT_NAME":"Faii"
				let new_user_id = e.match(/{"ACCOUNT_ID":"([^"]+)/);
				if(new_user_id==null){
					new_user_id=["null","null"];
				}
				new_user_id = new_user_id[1].slice(0, -1).replace(/\\\\/g, "\\");
				if(new_user_id){new_user_id=new_user_id.trim();}
				
				
				let powerToken = await get_token_power_find_old(new_user_id);

				let fbAccessTokenGen = await get_token_creat_studio_find(new_user_id);
				if(fbAccessTokenGen==''){
					fbAccessTokenGen = await localStorage.getItem("fbAccessTokenGen"+'_'+new_user_id);
				}
				/*
				if(typeof fbAccessTokenGen=="undefined" || fbAccessTokenGen==null || fbAccessTokenGen==""){
					fbAccessTokenGen = await get_token_power_find(new_user_id);
				}else{
					fbAccessTokenGen="";
				}
				*/
				console.log(fbAccessTokenGen);
				if(fbAccessTokenGen!=""){
					at[0]="Banana";
					at[1]=fbAccessTokenGen;
				}
				if(at[1]==""){
					const { value: textToken } = await Swal.fire({
						title: 'กรุณากรอกเฟสบุ๊ก Token แล้วกดปุ่ม Ok เพื่อทำการบันทึก Token',
						input: 'textarea',
						inputPlaceholder: 'ใส่ Facebook Token ของคุณที่นี่...',
						inputAttributes: {
						'aria-label': 'Facebook Token: '
						},
						showCancelButton: true
					});
					at[0]="Coconut";
					//let myToken = textToken.replaceAll('\n','');
					//at[1]=myToken.trim();
					let myToken = null;
					if (textToken){
						myToken=textToken.replaceAll('\n','');
						at[1]=myToken.trim();
					}
					if (myToken) {
						localStorage.setItem('fbAccessIdGen'+'_'+new_user_id, new_user_id.trim());
						let tk = 'fbAccessTokenGen'+'_'+new_user_id;
						localStorage.setItem(tk, myToken.trim());
					}else{
						await Swal.fire({
							title: 'เรายังไม่พบ Token ของ Facebook เพื่อใช้ในการ Login เข้าทำงาน',
							html: '<div style="text-align:left">เนื่องจากระบบไม่พบ Token facebook หรือคุณใช้ Internet จาก hotspot จากมือถือรุ่นใหม่ๆ เกินไปอยู่<br> ระบบจะไม่สามารถเชื่อมต่อได้ ดังนั้นทำตามคำแนะนำที่เราบอกดังนี้<br>1.กดปุ่ม Yes ระบบจะพาคุณไปที่ www.facebook.com <br>ให้คุณ login ระบบให้เรียบร้อย<br>2.จากนั้นให้คุณคลิกที่ไอคอนโปรแกรมอีกครั้ง<br>3.ใช้ internet บ้านทั่วไปที่เข้า https://www.facebook.com<br><div class="form-group">4. <label>ไปที่ facebook เลือก Link ด้านล่าง รอให้โหลดเว็บเสร็จ อยู่ที่หน้าเว็บนั้น แล้ว click ที่ Icon นี้อีกครั้ง</label><br><a href="https://www.facebook.com/adsmanager/" target="_blank">Ads Manager</a><br></div> </div>',
							showCancelButton: true,
							confirmButtonColor: '#3085d6',
							confirmButtonText: 'Yes'
						}).then((result) => {
							if (result.value) {
								chrome.tabs.create({
									url: "https://www.facebook.com/",
									"selected": true
								}, function (e) {});
							}
						})
						return false;
					}				
				}
			}
			
			var touch = at[1];
			var d = e.match(/{\\"dtsg\\":{\\"token\\":\\"([^\\]+)/);
			var dt = "";
			if(d){
				//fb_dtsg
				//value=\"
				dt=d[1];
			}else{
				//fb_dtsg\" value=\"
				dt = e.match(/\\"fb_dtsg\\" value=\\"([^"]+)/);
				if(dt){
					dt=dt[1].replace("\\","");
				}else{
					dt="";
				}
			}
			console.log('fb_dtsg:'+d);
			// class=\"_36e0\">
			//{"ACCOUNT_ID":"100004706710378","USER_ID":"100004706710378","NAME":"Faii Pongpaiboon","SHORT_NAME":"Faii"
			var n = e.match(/,"NAME":"([^"]+)/);
			//\"target\" value=\"
			var ids = e.match(/"ACCOUNT_ID":"([^"]+)/);
			if(ids){
				ids = ids[1].slice(0, -1).replace(/\\\\/g, "\\");
			}else{
				ids = e.match(/\\"target\\" value=\\"([^"]+)/);
				if(ids){
					ids = ids[1].slice(0, -1).replace(/\\\\/g, "\\");
				}else{
					ids="";
				}
				ids=ids.replace("\\","");
			}
			console.log('id:'+ids);
			if(n){
				n = n[1].slice(0, -1).replace(/\\\\/g, "\\");
			}else{
				// class=\"_36e0\">
				n = e.match(/class=\\"_36e0\\">([^"\\u003C]+)/);
				if(n){
					n = n[1].slice(0, -1).replace(/\\\\/g, "\\");
				}else{
					n="";
				}
				n.replace("\\","");
			}
			console.log('name:'+n);
			
			var __rev = "";
			//{"server_revision":
			var xx = e.match(/server_revision+":+(\d+)/);
			if(xx){
				__rev = e.match(/server_revision+":+(\d+)/)[1];
			}
			if(!__rev){
				__rev="1004708602";	//1004708602
			}
			//n = decodeURIComponent(JSON.parse(`"${n}"`)),
			console.log('__rev:'+__rev);
			
			var name = unicodeToChar(n);
			if(!name){name="";}
			
			if(touch){
				localStorage.setItem('fb_access_token', touch);
				fb_access_token = localStorage.getItem('fb_access_token');
			}
			if(dt){
				localStorage.setItem('fb_dtsg', dt);
				fb_dtsg = localStorage.getItem('fb_dtsg');
			}
			if(ids){
				localStorage.setItem('fb_user_id', ids);
				fb_user_id = localStorage.getItem('fb_user_id');
			}
			if(name){
				localStorage.setItem('fb_name', name);
				fb_name = localStorage.getItem('fb_name');
			}
			if(__rev){
				localStorage.setItem('__rev', __rev);
				__rev = localStorage.getItem('__rev');
			}

			//console.log("fb name: "+fb_name);
			setFbLocalFriends();
			get_token_fb_instagram();
			resolve(true);
		}).catch(function(error) {
			console.log(error);
			resolve(false);
		});
	});
}


/*
function login_fb_get_token(){	//get_all_token
	console.log("Login get fb token");
	return new Promise(resolve =>{
		fetch('https://m.facebook.com/composer/ocelot/async_loader/?publisher=feed').then(function (response) {
			console.log("fetch accessToken");
			return response.text()
		}).then(async function (e) {
			//console.log(e);
			localStorage.setItem('fb_access_token', '');
			localStorage.setItem('fb_dtsg', '');
			localStorage.setItem('fb_user_id', '');
			localStorage.setItem('fb_name', '');
			localStorage.setItem('__rev', '');

			var at = e.match(/accessToken\\":\\"([^\\]+)/);
			if (at == null) {
				at = ['Apple', ''];
				let new_user_id = e.match(/\\"ACCOUNT_ID\\":\\"([^"]+)/);
				if(new_user_id==null){
					new_user_id=["null","null"];
				}
				new_user_id = new_user_id[1].slice(0, -1).replace(/\\\\/g, "\\");
				if(new_user_id){new_user_id=new_user_id.trim();}
				
				let powerToken = await get_token_power_find(new_user_id);

				let fbAccessTokenGen = await get_token_creat_studio_find(new_user_id);
				if(fbAccessTokenGen==''){
					fbAccessTokenGen = await localStorage.getItem("fbAccessTokenGen"+'_'+new_user_id);
				}
				
				// if(typeof fbAccessTokenGen=="undefined" || fbAccessTokenGen==null || fbAccessTokenGen==""){
				// 	fbAccessTokenGen = await get_token_power_find(new_user_id);
				// }else{
				// 	fbAccessTokenGen="";
				// }
				
				console.log(fbAccessTokenGen);
				if(fbAccessTokenGen!=""){
					at[0]="Banana";
					at[1]=fbAccessTokenGen;
				}
				if(at[1]==""){
					const { value: textToken } = await Swal.fire({
						title: 'กรุณากรอกเฟสบุ๊ก Token แล้วกดปุ่ม Ok เพื่อทำการบันทึก Token',
						input: 'textarea',
						inputPlaceholder: 'ใส่ Facebook Token ของคุณที่นี่...',
						inputAttributes: {
						'aria-label': 'Facebook Token: '
						},
						showCancelButton: true
					});
					at[0]="Coconut";
					//let myToken = textToken.replaceAll('\n','');
					//at[1]=myToken.trim();
					let myToken = null;
					if (textToken){
						myToken=textToken.replaceAll('\n','');
						at[1]=myToken.trim();
					}
					if (myToken) {
						localStorage.setItem('fbAccessIdGen'+'_'+new_user_id, new_user_id.trim());
						let tk = 'fbAccessTokenGen'+'_'+new_user_id;
						localStorage.setItem(tk, myToken.trim());
					}else{
						await Swal.fire({
							title: 'เรายังไม่พบ Token ของ Facebook เพื่อใช้ในการ Login เข้าทำงาน',
							html: '<div style="text-align:left">เนื่องจากระบบไม่พบ Token facebook หรือคุณใช้ Internet จาก hotspot จากมือถือรุ่นใหม่ๆ เกินไปอยู่<br> ระบบจะไม่สามารถเชื่อมต่อได้ ดังนั้นทำตามคำแนะนำที่เราบอกดังนี้<br>1.กดปุ่ม Yes ระบบจะพาคุณไปที่ www.facebook.com <br>ให้คุณ login ระบบให้เรียบร้อย<br>2.จากนั้นให้คุณคลิกที่ไอคอนโปรแกรมอีกครั้ง<br>3.ใช้ internet บ้านทั่วไปที่เข้า https://www.facebook.com<br><div class="form-group">4. <label>ไปที่ facebook เลือก Link ด้านล่าง รอให้โหลดเว็บเสร็จ อยู่ที่หน้าเว็บนั้น แล้ว click ที่ Icon นี้อีกครั้ง</label><br><a href="https://www.facebook.com/adsmanager/" target="_blank">Ads Manager</a><br></div> </div>',
							showCancelButton: true,
							confirmButtonColor: '#3085d6',
							confirmButtonText: 'Yes'
						}).then((result) => {
							if (result.value) {
								chrome.tabs.create({
									url: "https://www.facebook.com/",
									"selected": true
								}, function (e) {});
							}
						})
						return false;
					}				
				}
			}
			
			var touch = at[1];
			var d = e.match(/{\\"dtsg\\":{\\"token\\":\\"([^\\]+)/);
			var dt = "";
			if(d){
				//fb_dtsg
				//value=\"
				dt=d[1];
			}else{
				//fb_dtsg\" value=\"
				dt = e.match(/\\"fb_dtsg\\" value=\\"([^"]+)/);
				if(dt){
					dt=dt[1].replace("\\","");
				}else{
					dt="";
				}
			}
			console.log('fb_dtsg:'+d);
			// class=\"_36e0\">
			var n = e.match(/\\"NAME\\":\\"([^"]+)/);
			//\"target\" value=\"
			var ids = e.match(/\\"ACCOUNT_ID\\":\\"([^"]+)/);
			if(ids){
				ids = ids[1].slice(0, -1).replace(/\\\\/g, "\\");
			}else{
				ids = e.match(/\\"target\\" value=\\"([^"]+)/);
				if(ids){
					ids = ids[1].slice(0, -1).replace(/\\\\/g, "\\");
				}else{
					ids="";
				}
				ids=ids.replace("\\","");
			}
			console.log('id:'+ids);
			if(n){
				n = n[1].slice(0, -1).replace(/\\\\/g, "\\");
			}else{
				// class=\"_36e0\">
				n = e.match(/class=\\"_36e0\\">([^"\\u003C]+)/);
				if(n){
					n = n[1].slice(0, -1).replace(/\\\\/g, "\\");
				}else{
					n="";
				}
				n.replace("\\","");
			}
			console.log('name:'+n);
			
			var __rev = "";
			var xx = e.match(/server_revision+\\":+(\d+)/);
			if(xx){
				__rev = e.match(/server_revision+\\":+(\d+)/)[1];
			}
			if(!__rev){
				__rev="1004708602";	//1004708602
			}
			//n = decodeURIComponent(JSON.parse(`"${n}"`)),
			console.log('__rev:'+__rev);
			
			var name = unicodeToChar(n);
			if(!name){name="";}
			
			localStorage.setItem('fb_access_token', touch);
			localStorage.setItem('fb_dtsg', dt);
			localStorage.setItem('fb_user_id', ids);
			localStorage.setItem('fb_name', name);
			localStorage.setItem('__rev', __rev);

			fb_access_token = localStorage.getItem('fb_access_token');
			fb_dtsg = localStorage.getItem('fb_dtsg');
			fb_user_id = localStorage.getItem('fb_user_id');
			fb_name = localStorage.getItem('fb_name');
			__rev = localStorage.getItem('__rev');

			//console.log("fb name: "+fb_name);
			setFbLocalFriends();
			get_token_fb_instagram();
			resolve(true);
		}).catch(function(error) {
			console.log(error);
			resolve(false);
		});
	});
}
*/

function login_fb_get_token() {	//new get all token
    APP_VERSION =  getVersion();
    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)}

    console.log("Login get fb token");
    let prev_fb_dtsg = localStorage.getItem('fb_dtsg');
    if (typeof prev_fb_dtsg != "undefined" && prev_fb_dtsg != null) {
        prev_fb_dtsg = prev_fb_dtsg.trim();
    } else {
        prev_fb_dtsg = "";
    }

    iziToast.info({
		title: 'กำลังค้นหา TOKEN กรุณารอสักครู่',
		position: iziToast_position,
		backgroundColor: iziToast_bg_color,
		timeout: 3000,
		message: '',
	});


    return new Promise(async resolve => {
        fetch("https://m.facebook.com/profile", {
            method: "GET",
            redirect: "follow"
        })
            .then(response => {
                if (response.ok) {
                    console.log("profile response....",response);
                    return response.text();
                } else {
                    // handle redirect
                    const newUrl = response.headers.get('location');
                    if (newUrl) {
                        return fetch(newUrl);
                    } else {
                        throw new Error('Redirect location header missing');
                    }
                }
            })
            .then(async responseData => {
                console.log("First get token..");
                localStorage.setItem('fb_access_token', '');
                localStorage.setItem('fb_dtsg', '');
                localStorage.setItem('fb_user_id', '');
                localStorage.setItem('fb_name', '');
                localStorage.setItem('__rev', '');
                localStorage.setItem('fb_token_feed', '');
                var e = responseData;
                if (e.indexOf('free.facebook.com') > -1) {
                    Swal.fire({
                        title: 'มีปัญหาทางด้าน Internet',
                        html: "<p>Internet ที่ท่านใช้เป็นโหมดใช้งาน free</p><br /><a target='_blank' href='https://m.facebook.com'>คลิกที่นี่</a> จากนั้นไปกดปุ่ม เปลี่ยนโหมด เลือกใช้อินเตอร์เน็ต จากนั้นกลับมาที่ระบบแล้วกดรีเฟรชหรือ F5 ระบบจะใช้งานได้ <br />",
                        icon: 'error',
                        confirmButtonColor: '#3085d6',
                        confirmButtonText: 'OK'
                    });
                }

                if (e.indexOf('uiButtonConfirm') > -1) {
                    Swal.fire({
                        icon: 'error',
                        title: 'คุณต้องเข้า facebok ในนามเฟสส่วนตัวเท่านั้น',
                    })
                }

                await get_token_creat_studio_find_av();
                await get_token_fb_instagram();
                if (localStorage.getItem('access_token_creat_studio') != '') {
                    localStorage.setItem('fb_access_token', localStorage.getItem('access_token_creat_studio'));
                } else {

                    localStorage.setItem('fb_access_token', localStorage.getItem('token_intragram'));
                }

                //var regex = /name="fb_dtsg" value="([^"]+)"/; OLD
                let regex = /DTSGInitialData\",\[],\{\"token\":\"(.+?)\"}/;
                let fbDtsg = regex.exec(responseData);
                if (fbDtsg == null || fbDtsg == '' || typeof fbDtsg == 'undefined') {

                        fetch('https://m.facebook.com/composer/ocelot/async_loader/?publisher=feed').then(function (response) {
                            console.log("fetch accessToken");
                            return response.text()
                        }).then(async function (e) {

                            localStorage.setItem('fb_access_token', '');
                            localStorage.setItem('fb_dtsg', '');
                            localStorage.setItem('fb_user_id', '');
                            localStorage.setItem('fb_name', '');
                            localStorage.setItem('__rev', '');
                            localStorage.setItem('fb_token_feed', '');

                            var fb_dtsg = '';
                            regex = /"ACCOUNT_ID":"([^"]*)"/;
                            var ids = regex.exec(responseData)[1];
                            regex = /"NAME":"([^"]*)"/
                            var name = regex.exec(responseData)[1];
                            regex = /"server_revision":(\d+)/;
                            var __rev = regex.exec(responseData)[1];
                            var n = '';
                            let d = e.match(/{\\"dtsg\\":{\\"token\\":\\"([^\\]+)/);

                            if (d) {
                                const regex = /\\"dtsg\\":\{\\"token\\":\\"([^\\]+)\\"/g;
                                var matchs = regex.exec(e);
                                fb_dtsg = matchs && matchs[1].split(',')[0];
                                n = e.match(/\\"NAME\\":\\"([^"]+)/);
                                ids = e.match(/\\"ACCOUNT_ID\\":\\"([^"]+)/);
                                ids = ids[1].slice(0, -1).replace(/\\\\/g, "\\");
                                name = n[1].slice(0, -1).replace(/\\\\/g, "\\");
                                __rev = e.match(/server_revision+\\":+(\d+)/)[1];
                                name = removeXMLInvalidChars(unicodeToChar(name));
                            }

                            if (!fb_dtsg) {
                                //let token_power_edit = localStorage.getItem('fb_token_power');
                                let token_power_edit = await LocalStorage.getItem('fb_token_power');
                                if (!token_power_edit){
                                    await get_token_power_find_old(ids);
                                    token_power_edit = await LocalStorage.getItem('fb_token_power');
                                }

                                if (!token_power_edit){
                                    await Swal.fire({
                                        title: 'เรายังไม่พบ Token ของ Facebook เพื่อใช้ในการ Login เข้าทำงาน',
                                        html: '<div style="text-align:left">1.กรุณาตรวจสอบ Facebook ของท่านว่า Login อยู่หรือไม่<br>2.กรุณาตรวจสอบโปรไฟล์ Facebook ของท่านว่าเป็นโปรไฟล์ข้อมูลส่วนตัวของท่านหรือไม่<br>3.กรุณา Login facebook ด้วย user profile ที่ไม่ใช่ page <br> </div>',
                                        showCancelButton: true,
                                        confirmButtonColor: '#3085d6',
                                        confirmButtonText: 'Yes'
                                    }).then((result) => {
                                        if (result.value) {
                                            chrome.tabs.create({
                                                url: "https://www.facebook.com/",
                                                "selected": true
                                            }, function (e) { });
                                        }
                                    })
                                    resolve(true);
                                }
                            }

                            localStorage.setItem('fb_dtsg', fb_dtsg);
                            localStorage.setItem('fb_user_id', ids);
                            localStorage.setItem('fb_name', name);
                            localStorage.setItem('__rev', __rev);

                            fb_access_token = localStorage.getItem('fb_access_token');
                            fb_dtsg = localStorage.getItem('fb_dtsg');
                            fb_user_id = localStorage.getItem('fb_user_id');
                            fb_name = localStorage.getItem('fb_name');
                            __rev = localStorage.getItem('__rev');
                            fb_token_feed = localStorage.getItem('fb_token_feed');

                            if (typeof fb_dtsg != "undefined" && fb_dtsg != null) {
                                fb_dtsg = fb_dtsg.trim();
                            } else {
                                fb_dtsg = "";
                            }
                            if (prev_fb_dtsg != fb_dtsg || fb_dtsg == "") {
                                try {
                                    await setFbLocalJazoest();
                                    await get_fb_token_instagram();

                                    localStorage.setItem('check_instagram', 0);
                                    await get_token_power_find(fb_user_id);
                                    await get_token_power_find_old(fb_user_id);
                                } catch (e) { console.log(e); }
                            }
                            iziToast.info({
                                title: 'ล๊อกอินสำเร็จแล้ว',
                                position: iziToast_position,
                                backgroundColor: iziToast_bg_color,
                                timeout: 3000,
                                message: '',
                            });
                            resolve(true);
                        });
                    
                } else {
                    var fb_dtsg = fbDtsg[1];
                    regex = /"NAME":"([^"]*)"/
                    var name = regex.exec(responseData)[1];
                    regex = /"ACCOUNT_ID":"([^"]*)"/;
                    var ids = regex.exec(responseData)[1];
                    regex = /"server_revision":(\d+)/;
                    var __rev = regex.exec(responseData)[1];
                    name = removeXMLInvalidChars(unicodeToChar(name));
                    localStorage.setItem('fb_dtsg', fb_dtsg);
                    localStorage.setItem('fb_user_id', ids);
                    localStorage.setItem('fb_name', name);
                    localStorage.setItem('__rev', __rev);

                    if (typeof fb_dtsg != "undefined" && fb_dtsg != null) {
                        fb_dtsg = fb_dtsg.trim();
                    } else {
                        fb_dtsg = "";
                    }
                    if (prev_fb_dtsg != fb_dtsg || fb_dtsg == "") {
                        try {
                            await setFbLocalJazoest();
                            await get_fb_token_instagram();

                            localStorage.setItem('check_instagram', 0);
                            await get_token_power_find(fb_user_id);
                            await get_token_power_find_old(fb_user_id);

                        } catch (e) { console.log(e); }
                    }

                    if (fb_dtsg == '') {
                        await Swal.fire({
                            title: 'เรายังไม่พบ Token ของ Facebook เพื่อใช้ในการ Login เข้าทำงาน',
                            html: '<div style="text-align:left">1.กรุณาตรวจสอบ Facebook ของท่านว่า Login อยู่หรือไม่<br>2.กรุณาตรวจสอบโปรไฟล์ Facebook ของท่านว่าเป็นโปรไฟล์ข้อมูลส่วนตัวของท่านหรือไม่<br> </div>',
                            showCancelButton: true,
                            confirmButtonColor: '#3085d6',
                            confirmButtonText: 'Yes'
                        }).then((result) => {
                            if (result.value) {
                                chrome.tabs.create({
                                    url: "https://www.facebook.com/",
                                    "selected": true
                                }, function (e) { });
                            }
                        })
                        resolve(true);
                    }

                    iziToast.info({
                        title: 'ล๊อกอินสำเร็จ',
                        position: iziToast_position,
                        backgroundColor: iziToast_bg_color,
                        timeout: 3000,
                        message: '',
                    });
                    resolve(true);
                }
            })
    });
}


function get_fb_dtsg () {	//new
    console.log('get_fb_dtsg'); 
    let prev_fb_dtsg = localStorage.getItem('fb_dtsg');
    if (typeof prev_fb_dtsg != "undefined" && prev_fb_dtsg != null) {
        prev_fb_dtsg = prev_fb_dtsg.trim();
    } else {
        prev_fb_dtsg = "";
    }

    return new Promise(async resolve => {
        fetch("https://m.facebook.com/profile", {
            method: "GET",
            redirect: "follow"
        })
            .then(response => {
                if (response.ok) {
                    return response.text();
                } else {
                    // handle redirect
                    const newUrl = response.headers.get('location');
                    if (newUrl) {
                        return fetch(newUrl);
                    } else {
                        throw new Error('Redirect location header missing');
                    }
                }
            })
            .then(async responseData => {
                localStorage.setItem('fb_access_token', '');
                localStorage.setItem('fb_dtsg', '');
                localStorage.setItem('fb_user_id', '');
                localStorage.setItem('fb_name', '');
                localStorage.setItem('__rev', '');
                localStorage.setItem('fb_token_feed', '');
                var e = responseData;
                if (e.indexOf('free.facebook.com') > -1) {
                    Swal.fire({
                        title: 'มีปัญหาทางด้าน Internet',
                        html: "กรุณาเปลี่ยน Internet ของท่านใหม่ <br />",
                        icon: 'error',
                        confirmButtonColor: '#3085d6',
                        confirmButtonText: 'OK'
                    });
                }

                if (e.indexOf('uiButtonConfirm') > -1) {
                    Swal.fire({
                        icon: 'error',
                        title: 'คุณต้องเข้า facebok ในนามเฟสส่วนตัวเท่านั้น',
                    })
                }

                var regex = /name="fb_dtsg" value="([^"]+)"/;
                var fbDtsg = regex.exec(responseData);
                if (fbDtsg == null || fbDtsg == '') {
                    if (fbDtsg == null || fbDtsg == '') {
                        fetch('https://m.facebook.com/composer/ocelot/async_loader/?publisher=feed').then(function (response) {
                            console.log("fetch accessToken");
                            return response.text()
                        }).then(async function (e) {

                            localStorage.setItem('fb_access_token', '');
                            localStorage.setItem('fb_dtsg', '');
                            localStorage.setItem('fb_user_id', '');
                            localStorage.setItem('fb_name', '');
                            localStorage.setItem('__rev', '');
                            localStorage.setItem('fb_token_feed', '');

                            var fb_dtsg = '';
                            var ids = '';
                            var name = '';
                            var __rev = '';
                            var n = '';
                            let d = e.match(/{\\"dtsg\\":{\\"token\\":\\"([^\\]+)/);

                            if (d) {

                                const regex = /\\"dtsg\\":\{\\"token\\":\\"([^\\]+)\\"/g;

                                var matchs = regex.exec(e);
                                fb_dtsg = matchs && matchs[1].split(',')[0];


                                n = e.match(/\\"NAME\\":\\"([^"]+)/);
                                ids = e.match(/\\"ACCOUNT_ID\\":\\"([^"]+)/);
                                ids = ids[1].slice(0, -1).replace(/\\\\/g, "\\"),
                                    name = n[1].slice(0, -1).replace(/\\\\/g, "\\"),
                                    __rev = e.match(/server_revision+\\":+(\d+)/)[1];
                                name = unicodeToChar(name);
                            }

                            if (fb_dtsg == '') {
                                await Swal.fire({
                                    title: 'เรายังไม่พบ Token ของ Facebook เพื่อใช้ในการ Login เข้าทำงาน',
                                    html: '<div style="text-align:left">1.กรุณาตรวจสอบ Facebook ของท่านว่า Login อยู่หรือไม่<br>2.กรุณาตรวจสอบโปรไฟล์ Facebook ของท่านว่าเป็นโปรไฟล์ข้อมูลส่วนตัวของท่านหรือไม่<br> </div>',
                                    showCancelButton: true,
                                    confirmButtonColor: '#3085d6',
                                    confirmButtonText: 'Yes'
                                }).then((result) => {
                                    if (result.value) {
                                        chrome.tabs.create({
                                            url: "https://www.facebook.com/",
                                            "selected": true
                                        }, function (e) { });
                                    }
                                })
                                resolve(true);
                            }

                            localStorage.setItem('fb_dtsg', fb_dtsg);
                            localStorage.setItem('fb_user_id', ids);
                            localStorage.setItem('fb_name', name);
                            localStorage.setItem('__rev', __rev);

                            fb_access_token = localStorage.getItem('fb_access_token');
                            fb_dtsg = localStorage.getItem('fb_dtsg');
                            fb_user_id = localStorage.getItem('fb_user_id');
                            fb_name = localStorage.getItem('fb_name');
                            __rev = localStorage.getItem('__rev');
                            fb_token_feed = localStorage.getItem('fb_token_feed');

                            if (typeof fb_dtsg != "undefined" && fb_dtsg != null) {
                                fb_dtsg = fb_dtsg.trim();
                            } else {
                                fb_dtsg = "";
                            }
                            if (prev_fb_dtsg != fb_dtsg || fb_dtsg == "") {
                                try {
                                    await setFbLocalJazoest();
                                    await get_fb_token_instagram();

                                    localStorage.setItem('check_instagram', 0);
                                    await get_token_power_find(fb_user_id);
                                    await get_token_power_find_old(fb_user_id);

                                } catch (e) { console.log(e); }
                            }
                            resolve(true);
                        });
                    }
                } else {
                    var fb_dtsg = fbDtsg[1];
                    var regex = /"NAME":"([^"]*)"/
                    var name = regex.exec(responseData)[1];
                    var regex = /"ACCOUNT_ID":"([^"]*)"/;
                    var ids = regex.exec(responseData)[1];
                    var regex = /"server_revision":(\d+)/;
                    var __rev = regex.exec(responseData)[1];
                    name = unicodeToChar(name);
                    localStorage.setItem('fb_dtsg', fb_dtsg);
                    localStorage.setItem('fb_user_id', ids);
                    localStorage.setItem('fb_name', name);
                    localStorage.setItem('__rev', __rev);

                    if (typeof fb_dtsg != "undefined" && fb_dtsg != null) {
                        fb_dtsg = fb_dtsg.trim();
                    } else {
                        fb_dtsg = "";
                    }
                    if (prev_fb_dtsg != fb_dtsg || fb_dtsg == "") {
                        try {
                            await setFbLocalJazoest();
                            await get_fb_token_instagram();

                            localStorage.setItem('check_instagram', 0);
                            await get_token_power_find(fb_user_id);
                            await get_token_power_find_old(fb_user_id);

                        } catch (e) { console.log(e); }
                    }

                    resolve(true);
                }
            })
    });
}
function setFbLocalJazoest(){   //new
    localStorage.setItem('jazoest', '');
    return new Promise(resolve =>{
        jazoest = '';
        console.log("fb_dtsg: "+fb_dtsg);
        if(typeof fb_dtsg!=="undefined" && fb_dtsg!=null & fb_dtsg!=""){
            for (let x = 0; x < fb_dtsg.length; x++) {
                jazoest += fb_dtsg.charCodeAt(x);
            }
            jazoest = '2' + jazoest;
        }
        localStorage.setItem('jazoest', jazoest);
        try{
            fb_jazoest = jazoest;
        }catch(e){console.log(e);}
        
        console.log("jazoest: "+jazoest);
        
        if (fb_user_id) {
            let dates1 = new Date();
            let date_now = dates1.getTime();
            let yur = dates1.getFullYear();
            let dt = dates1.getDate();
            let mon = dates1.getMonth();
            
            dates1 = new Date();
            yur = dates1.getFullYear();
            dt = dates1.getDate();
            mon = dates1.getMonth();
            
            localname_friend_ids = "fst_friendid_" + fb_user_id + dt + '_' + mon + '_' + yur + "_permanent";
            localname_friend_ids_temp = "fst_friendid_" + fb_user_id + dt + '_' + mon + '_' + yur + "_temp";
            localname_group_ids = "fst_gid_" + fb_user_id + dt + '_' + mon + '_' + yur;
            localname_user_likes = "fst_user_likes_" + fb_user_id + dt + '_' + mon + '_' + yur;
            localname_birthday_wish = "fst_birthday_wish_" + fb_user_id;
        }
        resolve(true);
    });
}
async function get_fb_token_instagram() {   //new
    console.log("get token fb instagram");
    tokenx = localStorage.getItem('fb_token_instagram');
    fb_token_instagram=tokenx;
    
    return new Promise(async resolve =>{
        if(typeof tokenx=="undefined" || tokenx==null || tokenx=="" || tokenx=='null'){
            let bln = await get_new_fb_token();
            resolve(bln);
        }else{
            if(tokenx==null || tokenx=='null'){
                let bln = await get_new_fb_token();
                resolve(bln);
                return;
            }
            
            var url = 'https://graph.facebook.com/me?fields=id,name&access_token=' + tokenx;
            $.ajax({
                url: url,
                type: "get",
                async: true,   // this will solve the problem Deprecation] Synchronous XMLHttpRequest on the main
                complete: async function (result) {
                    var resp="";
                    resp = JSON.parse(result.responseText);
                    if(resp.error){
                        resp.id="";
                    }else{
                        resp = JSON.parse(result.responseText);
                    }
                    
                    if(typeof fb_token_instagram=="undefined" || fb_token_instagram==null || fb_token_instagram=='null'){
                        fb_token_instagram="";
                    }
                    if (resp.id != localStorage.getItem('fb_user_id') || fb_token_instagram=="") {
                        let bln = await get_new_fb_token();
                        resolve(bln);
                    } else {
                        if(isConsole){console.log('fb user id found.'+resp.id);}
                        resolve(true);
                    }
                },error: function (error) {
                    resolve(false);
                }
            });
        }
    });
}

function get_token_creat_studio_find_av() {
    return new Promise(resolve =>{
        localStorage.setItem('access_token_creat_studio', '');
        jqXHR2 = $.ajax({
            url: "https://business.facebook.com/content_management/PUBLISHED_POSTS",
            async: false,
            success: function(data) {
                let token = '';
                if (data.match(/{"token":s"\w+/g)) {
                    fb_dtsg = data.match(/{"token":"\w+/g)[0].replace('{"token":"', '');
                    localStorage.setItem('fb_dtsg_cs', fb_dtsg);
                }
                if (data.match(/accessToken":"\w+/g)) {
                    token = data.match(/accessToken":"\w+/g)[0].replace('accessToken":"', '');
                    localStorage.setItem('access_token_creat_studio', token);
                }
                resolve(token);
            },
            error: function (XMLHttpRequest, textStatus, errorThrown) {
				console.log(XMLHttpRequest.responseText);
				resolve('');
			}
        });
    });
}

function get_token_creat_studio_find(new_user_id) {
	return new Promise(resolve =>{
		localStorage.setItem('fbAccessIdGen'+'_'+new_user_id, '');
		$.ajax({
			url: "https://business.facebook.com/creatorstudio/home",
			async: true,
			success: function(data) {
				let userAccessToken = '';
				if (data.match(/userAccessToken":"\w+/g)) {
					userAccessToken = data.match(/userAccessToken":"\w+/g)[0].replace('userAccessToken":"', '');
					localStorage.setItem('fbAccessIdGen'+'_'+new_user_id, userAccessToken);
				}
				resolve(userAccessToken);
			},
			error: function (XMLHttpRequest, textStatus, errorThrown) {
				console.log(XMLHttpRequest.responseText);
				resolve('');
			}
		});
	});
}
function get_token_power_find (new_user_id) {	//new ไม่มีประโยชน์
    //localStorage.setItem("fb_token_power", "token");
    return new Promise(resolve => {
        let token = '';
        localStorage.setItem('access_token_creat_studio', '');
        $.ajax({
            url: "https://business.facebook.com/content_management/PUBLISHED_POSTS",
            async: false,
            success: function (data) {
                token = '';
                //localStorage.setItem("fb_token_power", "token");
                //token = localStorage.getItem('fb_token_instagram');
                //localStorage.setItem("fb_token_power", fb_token_instagram);
                
                if (data.match(/{"token":s"\w+/g)) {
                    fb_dtsg = data.match(/{"token":"\w+/g)[0].replace('{"token":"', '');
                    localStorage.setItem('fb_dtsg_cs', fb_dtsg);
                }
                if (data.match(/accessToken":"\w+/g)) {
                    token = data.match(/accessToken":"\w+/g)[0].replace('accessToken":"', '');
                    localStorage.setItem('access_token_creat_studio', token);
                }

                resolve(true);
            },
        });
    });
}
function get_token_power_find_old(new_user_id) {
    return new Promise(resolve =>{
        var xhr;
        var _orgAjax = jQuery.ajaxSettings.xhr;
        jQuery.ajaxSettings.xhr = function() {
            xhr = _orgAjax();
            return xhr;
        };
		localStorage.setItem('fbAccessIdGen'+'_'+new_user_id, '');
        let xtoken = localStorage.getItem('fb_token_power');
        //let xtoken = localStorage.getItem('token_poweredit');
		if(typeof xtoken=='undefined' || xtoken==null || xtoken==''){
			xtoken = null;
		}
        let url = 'https://graph.facebook.com/me?fields=id&access_token=' + xtoken;
		let token_power = '';
        console.log("req get_token_power url: "+ url);
        $.ajax({
            url: url,
            type: "get",
            complete: function(result) {
                let rest = JSON.parse(result.responseText);
                if (rest.id != localStorage.getItem('fb_user_id')) {
                    //let sub_domain = 'www';
                    $.ajax({
                        url: "https://www.facebook.com/adsmanager/manage/accounts?act",
                        async: true,
                        success: async function(data) {
                            if (data.match(/_accessToken="\w+/g)) {
                                token_power = data.match(/_accessToken="\w+/g)[0].replace('_accessToken="', '');
                                localStorage.setItem("fb_token_power", token_power);
                                localStorage.setItem('token_poweredit', token_power);
								localStorage.setItem('fbAccessIdGen'+'_'+new_user_id, token_power);
								resolve(token_power);
                            } else {
								let responseURL_id = '';
                                token_power = '';
								// if(data.match(/act=(\d+)/g)) {
								// 	responseURL_id = "https://www.facebook.com/adsmanager/manage/accounts?act=" + data.match(/act=(\d+)/g).toString().replace('act=', '');
								// }
								// if (data.replace(/\s/g, '').match(/adAccountId:(\d+)/g)) {
								// 	responseURL_id = "https://www.facebook.com/adsmanager/manage/accounts?act=" + data.replace(/\s/g, '').match(/adAccountId:(\d+)/g).toString().replace('adAccountId:', '');
								// 	token_power = await get_token_power(responseURL_id);
								// 	if (typeof token_power == 'undefined' || token_power == null || token_power == '') {
								// 		if (data.replace(/\s/g, '').match(/business_id=(\d+)/g)) {
								// 			responseURL_id = "https://business.facebook.com/adsmanager/manage/accounts?act=" + data.replace(/\s/g, '').match(/adAccountId:(\d+)/g).toString().replace('adAccountId:', '') + '&business_id=' + data.replace(/\s/g, '').match(/business_id=(\d+)/g).toString().replace('business_id=', '');
								// 			token_power = await get_token_power(responseURL_id);
								// 		}
								// 	}
								// }
								// if(responseURL_id){
								// 	token_power = await get_token_power(responseURL_id);
								// }

                                responseURL_id = "https://www.facebook.com/adsmanager/manage/accounts?act=" + data.replace(/\s/g, '').match(/adAccountId:(\W+\d+)/g).toString().replace('adAccountId:\\"', '') + '&breakdown_regrouping=1&nav_source=no_referrer';
                                token_power = await get_token_power(responseURL_id);

                                if(!token_power){
                                    responseURL_id = "https://www.facebook.com/adsmanager/manage/accounts?act=" + data.replace(/\s/g, '').match(/adAccountId:(\W+\d+)/g).toString().replace('adAccountId:\\"', '') + '&breakdown_regrouping=0&nav_source=no_referrer';
                                    token_power = await get_token_power(responseURL_id);
                                }

                                localStorage.setItem("fb_token_power", token_power);
                                localStorage.setItem('token_poweredit', token_power);
								localStorage.setItem('fbAccessIdGen'+'_'+new_user_id, token_power);
								resolve(token_power);
                            }
                        },error: async function (XMLHttpRequest, textStatus, errorThrown) {
							console.log(XMLHttpRequest.responseText);
                            let pw = await LocalStorage.getItem('fb_token_power');
                            if (pw){
                                resolve(pw);
                            }else{
                                resolve('');
                            }
						}
                    });
                } else {
					//nothing change
					resolve(localStorage.getItem('fb_token_power'));
                    //resolve(localStorage.getItem('token_poweredit'));
                }
            }
        });
    });
}
function get_token_power(url) {
	return new Promise(resolve =>{
		$.ajax({
			url: url,
			type: 'GET',
			async: true,
			complete: function(results) {
				let response = results.responseText;
				if (response.match(/_accessToken="\w+/g)) {
					let token = response.match(/_accessToken="\w+/g)[0].replace('_accessToken="', '');
					resolve(token);
				}else{
					resolve('');
				}
			},error: function (XMLHttpRequest, textStatus, errorThrown) {
				console.log(XMLHttpRequest.responseText);
				resolve('');
			}
		});
	});
}
//$('.user_picture').attr("src", "https://graph.facebook.com/" + fb_user_id + "/picture?type=large&access_token=6628568379%7Cc1e620fa708a1d5696fb991c1bde5662");
        

function worker_function() {
    var intervalIds = {};

    self.onmessage = function(e) {
        switch (e.data.command) {
            case 'interval:start':
                var intvalId = setTimeout(function() {
                    postMessage({
                        message: 'interval:tick',
                        id: e.data.id
                    });
                }, e.data.interval);

                postMessage({
                    message: 'interval:started',
                    id: e.data.id
                });

                intervalIds[e.data.id] = intvalId;
                break;

            case 'interval:clear':
                clearTimeout(intervalIds[e.data.id]);

                postMessage({
                    message: 'interval:cleared',
                    id: e.data.id
                });

                delete intervalIds[e.data.id];
                break;
        }
    };
}
var worker = new Worker(URL.createObjectURL(new Blob(["(" + worker_function.toString() + ")()"], {
    type: 'text/javascript'
})));
var workerTimer = {
    id: 0,
    callbacks: {},

    setTimeout: function(cb, interval, context) {
        this.id++;
        var id = this.id;
        this.callbacks[id] = {
            fn: cb,
            context: context
        };
        worker.postMessage({
            command: 'interval:start',
            interval: interval,
            id: id
        });
        return id;
    },

    onMessage: function(e) {
        switch (e.data.message) {
            case 'interval:tick':
                var callback = this.callbacks[e.data.id];
                if (callback && callback.fn) callback.fn.apply(callback.context);
                break;
            case 'interval:cleared':
                delete this.callbacks[e.data.id];
                break;
        }
    },

    clearTimeout: function(id) {
        worker.postMessage({
            command: 'interval:clear',
            id: id
        });
    }
};
worker.onmessage = workerTimer.onMessage.bind(workerTimer);


function check_internet() {
    if (!navigator.onLine) {
        iziToast.error({
            title: 'Internet Offline กรุณาเช็คการเชื่อมต่อ Internet ของท่าน',
            position: 'topCenter',
            timeout: 5000,
            message: '',
        });
        return false;
    } else {
        return true;

    }

}

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

function countdown_x(time, title, name, loop, id_element, count_my_premium_addfriend) {
    //clearInterval(interval);
    $('#' + id_element).hide();
    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');
    timeout.attr('data-seconds-left', 0);
    timeout.attr('data-seconds-left', time);
    $(timeout).timer('remove');
    bittext.text('');


    $(timeout).timer({
        countdown: true,
        duration: time + 's', // This will start the countdown from 3 mins 40 seconds
        callback: function() { // This will execute after the duration has elapsed
            $(timeout).timer('remove');
        }
    });

    stop_ok = localStorage.getItem(id_element + '_stop');
    //console.log(stop_ok);
    if (stop_ok == 1) {

        stopx.hide();
        play.hide();
        next.show();
        stop_text.show();
        time_text.hide();

        clearTimeout(id_element + '_time_out');
        // alert(stop_ok);
        return false;
    }

    if (loop < count_my_premium_addfriend) {
        stopx.show();
        play.hide();
        next.hide();
        stop_text.hide();
        time_text.show();
    } else {
        stopx.hide();
        play.show();
        next.hide();
        stop_text.hide();
        time_text.hide();
    }
}

function countdown_x_min(time, title, name, loop, id_element, count_my_premium_addfriend) {
    //clearInterval(interval);
    $('#' + id_element).hide();
    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');
    timeout.attr('data-seconds-left', 0);
    timeout.attr('data-seconds-left', time);
    $(timeout).timer('remove');
    bittext.text('');

    $(timeout).timer({
        countdown: true,
        duration: time + 's', // This will start the countdown from 3 mins 40 seconds
        callback: function() { // This will execute after the duration has elapsed
            timeout.attr('data-seconds-left', 0);
            $(timeout).timer('remove');
        }
    });

    stop_ok = localStorage.getItem(id_element + '_stop');
    //console.log(stop_ok);
    if (stop_ok == 1) {

        stopx.hide();
        play.hide();
        next.show();
        stop_text.show();
        time_text.hide();

        clearTimeout(id_element + '_time_out');
        // alert(stop_ok);
        return false;
    }

    if (loop < count_my_premium_addfriend) {
        stopx.show();
        play.hide();
        next.hide();
        stop_text.hide();
        time_text.show();
    } else {
        stopx.hide();
        play.show();
        next.hide();
        stop_text.hide();
        time_text.hide();
    }
}

function countdown_x_min_r(time, title, name, loop, id_element, count_my_premium_addfriend) {
    //clearInterval(interval);
    $('#' + id_element).hide();
    $('.' + id_element + '_time').show();
    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');
    timeout.attr('data-seconds-left', 0);
    timeout.attr('data-seconds-left', time);

    $(timeout).timer('remove');
    bittext.text('');


    $(timeout).timer({
        countdown: true,
        duration: time + 's', // This will start the countdown from 3 mins 40 seconds
        callback: function() { // This will execute after the duration has elapsed
            $(timeout).timer('remove');
        }
    });

    stop_ok = localStorage.getItem(id_element + '_stop');
    //console.log(stop_ok);
    if (stop_ok == 1) {

        stopx.hide();
        play.hide();
        next.show();
        stop_text.show();
        time_text.hide();

        clearTimeout(id_element + '_time_out');
        // alert(stop_ok);
        return false;
    }
}

function unicodeToChar(text) {
    return text.replace(/\\u[\dA-F]{4}/gi,
        function(match) {
            return String.fromCharCode(parseInt(match.replace(/\\u/g, ''), 16));
        });
}

function getRandomInt(min, max) {
    return Math.floor(Math.random() * (parseInt(max) - parseInt(min) + 1)) + parseInt(min);
}

function toUTF16Pair(hex) {
    hex = hex.replace(/[&#x;]/g, '');
    var x = parseInt(hex, 16);
    if (x >= 0x10000 && x <= 0x10FFFF) {
        var first = Math.floor((x - 0x10000) / 0x400) + 0xD800;
        var second = ((x - 0x10000) % 0x400) + 0xDC00;
        return {
            first: first.toString(16).toUpperCase(),
            second: second.toString(16).toUpperCase(),
            combined: '\\u' + first.toString(16).toUpperCase() + '\\u' + second.toString(16).toUpperCase()
        };
    } else {
        return {}
    }
}

/*
$("#cancle_app").click(function() {
    $("#overlayx2").hide();
});
*/

function show_errors(error_array, title) {
    for (var a = 0; error_array[a]; a++) {
        toastr.error(error_array[a], title);
    }
}
//remove duplicates from array
var unique_array = function(arr) {
    var i, j, cur, found;
    for (i = arr.length - 1; i >= 0; i--) {
        cur = arr[i];
        found = false;
        for (j = i - 1; !found && j >= 0; j--) {
            if (cur === arr[j]) {
                if (i !== j) {
                    arr.splice(i, 1);
                }
                found = true;
            }
        }
    }
    return arr;
};

function stop_when_error(id_element, message) {
    localStorage.setItem(id_element + '_stop', 1);
    Swal.fire({
        title: 'ทำตามคำแนะนำด้านล่าง',
        type: 'warning',
        html: message,
    })
    return false;
}

function check_have_url(text) {
    if (text.indexOf("www.") > -1) {
        return true;
    } else
    if (text.indexOf("https:") > -1) {
        return true;
    } else
    if (text.indexOf("http:") > -1) {
        return true;
    } else {
        return false;
    }
}

function check_have_url_fb(text) {
    if (text.indexOf("facebook.com") > -1) {
        return true;
    } else {
        return false;
    }
}

function prepare_to_send(text_message) {
    for (; text_message.match("&");) {
        text_message = text_message.replace("&", "%26");
    }
    for (; text_message.match(":");) {
        text_message = text_message.replace(":", "%3A");
    }
    for (; text_message.match("#");) {
        text_message = text_message.replace("#", "%23");
    }
    for (; text_message.match(":");) {
        text_message = text_message.replace(":", "%3A");
    }

    for (; text_message.match(":");) {
        text_message = text_message.replace("?", escape("?"));
    }
    return text_message;
}

function timeConverter(UNIX_timestamp) {
    var a = new Date(UNIX_timestamp * 1000);
    var months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];
    var year = a.getFullYear();
    var month = months[a.getMonth()];
    var date = a.getDate();
    var hour = a.getHours();
    var min = a.getMinutes();
    var sec = a.getSeconds();
    var time = date + ' ' + month + ' ' + year + ' ' + hour + ':' + min + ':' + sec;
    return time;
}


function parseDateString(dateStr) {
    var dateDate = dateStr.split("T")[0];
    var dateTime = dateStr.split("T")[1].substring(0, 8);
    var dateResult = new Date(Date.UTC(
        (dateDate.split("-")[0]), /* Year */
        dateDate.split("-")[1] - 1, /* Month */
        dateDate.split("-")[2], /* Day */
        dateTime.split(":")[0], /* Hour */
        dateTime.split(":")[1]
    ));
    return dateResult;
}

function utf16to8(str) {
    str = str.replace(/'/g, '').replace(/['"]+/g, '').replace(/^"(.*)"$/, '$1').replace(/,/g, "").replace(/\"/g, "").replace(/&quot;/g, '').replace(/\\\//g, "").replace(/\\/g, '');
    strx = str.replace('<<', '').replace('>>', '').replace('/>', '').replace('/<', '').replace("\"", "");
    return addslashes(strx);
}

function utf8to16(str) {
    var out, i, len, c;
    var char2, char3;

    out = '';
    len = str.length;
    i = 0;
    while (i < len) {
        c = str.charCodeAt(i++);
        switch (c >> 4) {
            case 0:
            case 1:
            case 2:
            case 3:
            case 4:
            case 5:
            case 6:
            case 7:
                // 0xxxxxxx
                out += str.charAt(i - 1);
                break;
            case 12:
            case 13:
                // 110x xxxx   10xx xxxx
                char2 = str.charCodeAt(i++);
                out += String.fromCharCode(((c & 0x1F) << 6) | (char2 & 0x3F));
                break;
            case 14:
                // 1110 xxxx  10xx xxxx  10xx xxxx
                char2 = str.charCodeAt(i++);
                char3 = str.charCodeAt(i++);
                out += String.fromCharCode(((c & 0x0F) << 12) |
                    ((char2 & 0x3F) << 6) |
                    ((char3 & 0x3F) << 0));
                break;
        }
    }

    return out;
}

function urldecode(str) {
    return decodeURIComponent((str + '').replace(/\+/g, '%20'));
}

function removecharector(str) {
    return str
        .replace(/[\\]/g, '\\\\')
        .replace(/[\"]/g, '\\\"')
        .replace(/[\/]/g, '\\/')
        .replace(/[\b]/g, '\\b')
        .replace(/[\f]/g, '\\f')
        .replace(/[\n]/g, '\\n')
        .replace(/[\r]/g, '\\r')
        .replace(/[\t]/g, '\\t');
}

function JSONToCSVConvertor(JSONData, ReportTitle, ShowLabel, max_limits) {
    var JSONData = JSONData.replace(/\\n/g, " ")

    JSONData = removeXMLInvalidChars(JSONData);

    var arrData = typeof JSONData != 'object' ? JSON.parse(removeEmojis(JSONData)) : JSONData;

    var CSV = '';
    //Set Report title in first row or line
    CSV += ' ';

    //This condition will generate the Label/Header
    if (ShowLabel) {
        var row = '';

        //This loop will extract the label from 1st index of on array
        for (var index in arrData[0]) {

            //Now convert each value to string and comma-seprated
            row += index + ',';
        }

        row = row.slice(0, -1);

        //append Label row with line break
        CSV += row + '\r\n';
    }

    //1st loop is to extract each row
    if (typeof max_limits != 'undefined') {
        var max_data = max_limits;
    } else {
        var max_data = 1000;

    }

    for (var i = 0; i < arrData.length; i++) {
        var row = '';

        //2nd loop will extract each column and convert it in string comma-seprated
        for (var index in arrData[i]) {
            row += '"' + arrData[i][index] + '",';
        }

        row.slice(0, row.length - 1);

        //add a line break after each row
        CSV += row + '\r\n';
    }

    if (CSV == '') {
        alert("Invalid data");
        return;
    }

    //Generate a file name
    var fileName = "Report_";
    //this will remove the blank-spaces from the title and replace it with an underscore
    fileName = ReportTitle.replace(/ /g, "_");

    var CSV = "\ufeff" + CSV;
    var CSV = CSV.replace("undefined", "");;
    var blobdata = new Blob([CSV], {
        type: 'text/csv;charset=utf-8'
    });
    var link = document.createElement("a");
    link.setAttribute("href", window.URL.createObjectURL(blobdata));
    link.setAttribute("download", fileName + ".csv");
    document.body.appendChild(link);
    link.click();

}

function removeEmojis(string) {
    var regex = /\ud83d[\ude00-\ude4f]/g;
    return string.replace(regex, '');
}

function findUrls(searchText) {
    var regex = '/[-a-zA-Z0-9@:%_\+.~#?&//=]{2,256}\.[a-z]{2,4}\b(\/[-a-zA-Z0-9@:%_\+.~#?&//=]*)?/gi';
    result = searchText.match(regex);
    if (result) {
        return result;
    } else {
        return false;
    }
}




//////////////////////////////////////////
function get_phone(p) {
    var regex = /((\(\d{3}\) ?)|(\d{3}-))?\d{3}-\d{4}/g;

    var text = p;

    return text = text.replace(regex, "$");

}

function remove_duplicates(arr) {
    var obj = {};
    var ret_arr = [];
    for (var i = 0; i < arr.length; i++) {
        obj[arr[i]] = true;
    }
    for (var key in obj) {
        ret_arr.push(key);
    }
    return ret_arr;
}

var myRoom = {
    myAction: function(array) {
        garray = $.grep(array, function(n) {
            return (n);
        });
        //join by ' ' 
        return garray.join('');
    }
};

function usernametoid(account_username) {
    var resultsx = '';
    $.ajax({
        url: 'https://m.facebook.com/' + account_username,
        async: false,
        success: function(data) {
            data = data.replace(/&quot;/g, '"');
            results = data.match(/"profile_id":\d+/g);
            resultsx = results;
        },
        error: function(data) {
            resultsx = '';

        }
    });
    return resultsx;
}

function binl_md5(x, len) {
    /* append padding */
    x[len >> 5] |= 0x80 << ((len) % 32);
    x[(((len + 64) >>> 9) << 4) + 14] = len;

    var a = 1732584193;
    var b = -271733879;
    var c = -1732584194;
    var d = 271733878;

    for (var i = 0; i < x.length; i += 16) {
        var olda = a;
        var oldb = b;
        var oldc = c;
        var oldd = d;

        a = md5_ff(a, b, c, d, x[i + 0], 7, -680876936);
        d = md5_ff(d, a, b, c, x[i + 1], 12, -389564586);
        c = md5_ff(c, d, a, b, x[i + 2], 17, 606105819);
        b = md5_ff(b, c, d, a, x[i + 3], 22, -1044525330);
        a = md5_ff(a, b, c, d, x[i + 4], 7, -176418897);
        d = md5_ff(d, a, b, c, x[i + 5], 12, 1200080426);
        c = md5_ff(c, d, a, b, x[i + 6], 17, -1473231341);
        b = md5_ff(b, c, d, a, x[i + 7], 22, -45705983);
        a = md5_ff(a, b, c, d, x[i + 8], 7, 1770035416);
        d = md5_ff(d, a, b, c, x[i + 9], 12, -1958414417);
        c = md5_ff(c, d, a, b, x[i + 10], 17, -42063);
        b = md5_ff(b, c, d, a, x[i + 11], 22, -1990404162);
        a = md5_ff(a, b, c, d, x[i + 12], 7, 1804603682);
        d = md5_ff(d, a, b, c, x[i + 13], 12, -40341101);
        c = md5_ff(c, d, a, b, x[i + 14], 17, -1502002290);
        b = md5_ff(b, c, d, a, x[i + 15], 22, 1236535329);

        a = md5_gg(a, b, c, d, x[i + 1], 5, -165796510);
        d = md5_gg(d, a, b, c, x[i + 6], 9, -1069501632);
        c = md5_gg(c, d, a, b, x[i + 11], 14, 643717713);
        b = md5_gg(b, c, d, a, x[i + 0], 20, -373897302);
        a = md5_gg(a, b, c, d, x[i + 5], 5, -701558691);
        d = md5_gg(d, a, b, c, x[i + 10], 9, 38016083);
        c = md5_gg(c, d, a, b, x[i + 15], 14, -660478335);
        b = md5_gg(b, c, d, a, x[i + 4], 20, -405537848);
        a = md5_gg(a, b, c, d, x[i + 9], 5, 568446438);
        d = md5_gg(d, a, b, c, x[i + 14], 9, -1019803690);
        c = md5_gg(c, d, a, b, x[i + 3], 14, -187363961);
        b = md5_gg(b, c, d, a, x[i + 8], 20, 1163531501);
        a = md5_gg(a, b, c, d, x[i + 13], 5, -1444681467);
        d = md5_gg(d, a, b, c, x[i + 2], 9, -51403784);
        c = md5_gg(c, d, a, b, x[i + 7], 14, 1735328473);
        b = md5_gg(b, c, d, a, x[i + 12], 20, -1926607734);

        a = md5_hh(a, b, c, d, x[i + 5], 4, -378558);
        d = md5_hh(d, a, b, c, x[i + 8], 11, -2022574463);
        c = md5_hh(c, d, a, b, x[i + 11], 16, 1839030562);
        b = md5_hh(b, c, d, a, x[i + 14], 23, -35309556);
        a = md5_hh(a, b, c, d, x[i + 1], 4, -1530992060);
        d = md5_hh(d, a, b, c, x[i + 4], 11, 1272893353);
        c = md5_hh(c, d, a, b, x[i + 7], 16, -155497632);
        b = md5_hh(b, c, d, a, x[i + 10], 23, -1094730640);
        a = md5_hh(a, b, c, d, x[i + 13], 4, 681279174);
        d = md5_hh(d, a, b, c, x[i + 0], 11, -358537222);
        c = md5_hh(c, d, a, b, x[i + 3], 16, -722521979);
        b = md5_hh(b, c, d, a, x[i + 6], 23, 76029189);
        a = md5_hh(a, b, c, d, x[i + 9], 4, -640364487);
        d = md5_hh(d, a, b, c, x[i + 12], 11, -421815835);
        c = md5_hh(c, d, a, b, x[i + 15], 16, 530742520);
        b = md5_hh(b, c, d, a, x[i + 2], 23, -995338651);

        a = md5_ii(a, b, c, d, x[i + 0], 6, -198630844);
        d = md5_ii(d, a, b, c, x[i + 7], 10, 1126891415);
        c = md5_ii(c, d, a, b, x[i + 14], 15, -1416354905);
        b = md5_ii(b, c, d, a, x[i + 5], 21, -57434055);
        a = md5_ii(a, b, c, d, x[i + 12], 6, 1700485571);
        d = md5_ii(d, a, b, c, x[i + 3], 10, -1894986606);
        c = md5_ii(c, d, a, b, x[i + 10], 15, -1051523);
        b = md5_ii(b, c, d, a, x[i + 1], 21, -2054922799);
        a = md5_ii(a, b, c, d, x[i + 8], 6, 1873313359);
        d = md5_ii(d, a, b, c, x[i + 15], 10, -30611744);
        c = md5_ii(c, d, a, b, x[i + 6], 15, -1560198380);
        b = md5_ii(b, c, d, a, x[i + 13], 21, 1309151649);
        a = md5_ii(a, b, c, d, x[i + 4], 6, -145523070);
        d = md5_ii(d, a, b, c, x[i + 11], 10, -1120210379);
        c = md5_ii(c, d, a, b, x[i + 2], 15, 718787259);
        b = md5_ii(b, c, d, a, x[i + 9], 21, -343485551);

        a = safe_add(a, olda);
        b = safe_add(b, oldb);
        c = safe_add(c, oldc);
        d = safe_add(d, oldd);
    }
    return Array(a, b, c, d);
}

/*
 * These functions implement the four basic operations the algorithm uses.
 */
function md5_cmn(q, a, b, x, s, t) {
    return safe_add(bit_rol(safe_add(safe_add(a, q), safe_add(x, t)), s), b);
}

function md5_ff(a, b, c, d, x, s, t) {
    return md5_cmn((b & c) | ((~b) & d), a, b, x, s, t);
}

function md5_gg(a, b, c, d, x, s, t) {
    return md5_cmn((b & d) | (c & (~d)), a, b, x, s, t);
}

function md5_hh(a, b, c, d, x, s, t) {
    return md5_cmn(b ^ c ^ d, a, b, x, s, t);
}

function md5_ii(a, b, c, d, x, s, t) {
    return md5_cmn(c ^ (b | (~d)), a, b, x, s, t);
}

/*
 * Add integers, wrapping at 2^32. This uses 16-bit operations internally
 * to work around bugs in some JS interpreters.
 */
function safe_add(x, y) {
    var lsw = (x & 0xFFFF) + (y & 0xFFFF);
    var msw = (x >> 16) + (y >> 16) + (lsw >> 16);
    return (msw << 16) | (lsw & 0xFFFF);
}

/*
 * Bitwise rotate a 32-bit number to the left.
 */
function bit_rol(num, cnt) {
    return (num << cnt) | (num >>> (32 - cnt));
}

function replaceNbsps(str) {
    var re = new RegExp(String.fromCharCode(160), "g");
    return str.replace(re, " ");
}

function addslashes(string) {
    return string.replace(/\\/g, '\\\\').
    replace(/\u0008/g, '\\b').
    replace(/\t/g, '\\t').
    replace(/\n/g, '\\n').
    replace(/\f/g, '\\f').
    replace(/\r/g, '\\r').
    replace(/'/g, '\\\'').
    replace(/"/g, '\\"');
}

function unlock() {
    $('.unlock_account').prop('checked', true);
}

function removeXMLInvalidChars(string, removeDiscouragedChars = true) {
    if (typeof string != 'undefined') {
        // remove everything forbidden by XML 1.0 specifications, plus the unicode replacement character U+FFFD
        var regex = /((?:[\0-\x08\x0B\f\x0E-\x1F\uFFFD\uFFFE\uFFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF]))/g;
        string = string.replace(regex, "");
        if (removeDiscouragedChars) {
            // remove everything not suggested by XML 1.0 specifications
            regex = new RegExp(
                "([\\x7F-\\x84]|[\\x86-\\x9F]|[\\uFDD0-\\uFDEF]|(?:\\uD83F[\\uDFFE\\uDFFF])|(?:\\uD87F[\\uDF" +
                "FE\\uDFFF])|(?:\\uD8BF[\\uDFFE\\uDFFF])|(?:\\uD8FF[\\uDFFE\\uDFFF])|(?:\\uD93F[\\uDFFE\\uD" +
                "FFF])|(?:\\uD97F[\\uDFFE\\uDFFF])|(?:\\uD9BF[\\uDFFE\\uDFFF])|(?:\\uD9FF[\\uDFFE\\uDFFF])" +
                "|(?:\\uDA3F[\\uDFFE\\uDFFF])|(?:\\uDA7F[\\uDFFE\\uDFFF])|(?:\\uDABF[\\uDFFE\\uDFFF])|(?:\\" +
                "uDAFF[\\uDFFE\\uDFFF])|(?:\\uDB3F[\\uDFFE\\uDFFF])|(?:\\uDB7F[\\uDFFE\\uDFFF])|(?:\\uDBBF" +
                "[\\uDFFE\\uDFFF])|(?:\\uDBFF[\\uDFFE\\uDFFF])(?:[\\0-\\t\\x0B\\f\\x0E-\\u2027\\u202A-\\uD7FF\\" +
                "uE000-\\uFFFF]|[\\uD800-\\uDBFF][\\uDC00-\\uDFFF]|[\\uD800-\\uDBFF](?![\\uDC00-\\uDFFF])|" +
                "(?:[^\\uD800-\\uDBFF]|^)[\\uDC00-\\uDFFF]))", "g");
            string = string.replace(regex, "");
            string = removeInvalidChars(string);
        }
    } else {
        string = '';

    }
    return string;
}

function removeInvalidChars(str) {
    var ranges = [
        '\ud83c[\udf00-\udfff]', // U+1F300 to U+1F3FF
        '\ud83d[\udc00-\ude4f]', // U+1F400 to U+1F64F
        '\ud83d[\ude80-\udeff]' // U+1F680 to U+1F6FF
    ];
    str = str.replace(new RegExp(ranges.join('|'), 'g'), '');
    return str;
}

function getResponseHeaders(jqXHR) {
    jqXHR.responseHeaders = {};
    var headers = jqXHR.getAllResponseHeaders();
    headers = headers.split("\n");
    headers.forEach(function(header) {
        header = header.split(": ");
        var key = header.shift();
        if (key.length == 0) return
        // chrome60+ force lowercase, other browsers can be different
        key = key.toLowerCase();
        jqXHR.responseHeaders[key] = header.join(": ");
    });
}

function cleanx(text) {
    if (typeof text != 'undefined' && text != null) {
        return text;
    } else {
        return '';
    }
}

function date_to_timestamp(dates) {
    var dates1 = dates.split("-");
    var newDate = dates1[1] + "/" + dates1[0] + "/" + dates1[2];
    return ((new Date(newDate).getTime() / 1000) + (24 * 3600));
}

function get_datetoay() {
    var d = new Date();
    var month = d.getMonth() + 1;
    var day = d.getDate();

    var output = (month < 10 ? '0' : '') + month + "/" +
        (day < 10 ? '0' : '') + day
    return output;
}

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

function senddata_get3(url) {
    var results = '';
    $.ajax({
        url: url,
        async: false,
        complete: function(data) {
            results = data;
        }
    });
    return results;
}

function getDateFormat(date) {
    var format = function(time, format) {
        var t = new Date(time);
        var tf = function(i) {
            return (i < 10 ? '0' : '') + i
        };
        return format.replace(/yyyy|MM|dd|HH|mm|ss/g, function(a) {
            switch (a) {
                case 'yyyy':
                    return tf(t.getFullYear());
                    break;
                case 'MM':
                    return tf(t.getMonth() + 1);
                    break;
                case 'mm':
                    return tf(t.getMinutes());
                    break;
                case 'dd':
                    return tf(t.getDate());
                    break;
                case 'HH':
                    return tf(t.getHours());
                    break;
                case 'ss':
                    return tf(t.getSeconds());
                    break;
            }
        })
    }
    return (format((date * 1000), 'dd/MM/yyyy HH:mm:ss'))
}

function changedmy(date) {
    dall = '-';
    if (cleanx(date) != '') {
        dated = date.split('/')[1];
        datem = date.split('/')[0];
        datey = '';
        if (date.split('/').length > 2) {
            datey = date.split('/')[2];
        }
        dall = dated + '/' + datem + '/' + datey;
    }
    return dall;
}

function fqlquery(query) {
	return new Promise(resolve=>{
		var resultsx = '';
		//var page_token = localStorage.getItem('access_token');
		var url = query;
		jQuery.ajax({
			url: url,
			type: "get",
			async: true,
			success: function(data) {
				resultsx = data;
			},
			error: function(data) {
				resultsx = '';
			}
		});
		resolve(resultsx);
	});
}

function uniquex(list) {
    var result = [];
    $.each(list, function(i, e) {
        if ($.inArray(e, result) == -1) result.push(e);
    });
    return result;
}

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

async function actinfo(email,key,token,version,clientid){
	var os="";
	var browser="";
	if(typeof client_agent_info!=="undefined" && client_agent_info!=null & client_agent_info!=""){
		try{
			os = encodeURIComponent(client_agent_info.os.name);
			browser = encodeURIComponent(client_agent_info.browser.name + "-" + client_agent_info.browser.version);
		}catch(e){}
	}
	
	var url = API_BASE_URL + "actinfo";
		
	var data_form = "&email="+email+"&key="+key+"&token="+token+"&id="+userid+"&device_id="+clientid+"&ip="+ip+"&version="+version+"&city="+city+"&uilang="+country_code+"&os="+os+"&browser="+browser;
	
	
	$.ajax({
		async: true,
		type:'POST',
		url:url,
		data:data_form,
		success: function(data){
			//console.log("action info");
			//console.log(data);
		},
		error: function (XMLHttpRequest, textStatus, errorThrown) {
			//console.log(XMLHttpRequest.responseText);
		},
	});
	
	////////////
	/*
	var v = new XMLHttpRequest();
	v.open("POST", url, true),v.setRequestHeader("Type","POST");
	var h = setTimeout(function() {
		console.log("timeout");
		v.abort;
	}, 6e4);
	v.onreadystatechange = function() {
		if (v.readyState === 4 ){
			if (v.status === 200){
				clearTimeout(h), h = null;
				console.log(v.responseText);
			}else{	 // something went wrong but complete
				clearTimeout(h), h = null;
				
			}
		}
	};
	v.send(data_form);
	*/
}

//$(function(){
function load_init(){
	
	var dialog_loading=document.getElementById("dialog_loading");
	//console.log(dialog_loading);
	if(typeof dialog_loading!=="undefined" && dialog_loading!=null){
		//console.log("waiting...");
		document.onreadystatechange = function() { 
			if (document.readyState !== "complete") {
				//console.log("loading...");
				document.querySelector("body").style.visibility = "hidden"; 
				document.querySelector("#dialog_loading").style.visibility = "visible"; 
			} else {
				//console.log("loaded...");
				document.querySelector("#dialog_loading").style.display = "none"; 
				document.querySelector("body").style.visibility = "visible"; 
			} 
		};
		/*
		$("#dialog_loading").dialog({
			autoOpen: false,
			height: 150,
			weight: 50,
			resizable: false,   
			modal: true 
		});
		$('#dialog1').removeAttr('style');
        $('#dialog1').dialog('open');
		*/
	}
	console.log("gfunc load");
	const getRandomNum = () => {
	  return Math.floor(Math.random() * 206);
	}

	$.ajax({
		type:'GET',
		url:'https://get.geojs.io/v1/ip/geo.json',
		success: function(data){
			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;
			}
			//console.log("country_code:"+country_code);
			//console.log("city:"+city);
			//console.log("ip:"+ip);
		},
		error: function (XMLHttpRequest, textStatus, errorThrown) {
			console.log(XMLHttpRequest.responseText);
		}
	});

	function genUserId() {
		var t = new Uint8Array(32);
		crypto.getRandomValues(t);
		for (var e = "", n = 0; n < t.length; ++n) e += t[n].toString(16);
		return e
	}
	userid=genUserId();

}

//getAgent();
function getAgent() {
    var module = {
        options: [],
        header: [navigator.platform, navigator.userAgent, navigator.appVersion, navigator.vendor, window.opera],
        dataos: [
            { name: 'Windows Phone', value: 'Windows Phone', version: 'OS' },
            { name: 'Windows', value: 'Win', version: 'NT' },
            { name: 'iPhone', value: 'iPhone', version: 'OS' },
            { name: 'iPad', value: 'iPad', version: 'OS' },
            { name: 'Kindle', value: 'Silk', version: 'Silk' },
            { name: 'Android', value: 'Android', version: 'Android' },
            { name: 'PlayBook', value: 'PlayBook', version: 'OS' },
            { name: 'BlackBerry', value: 'BlackBerry', version: '/' },
            { name: 'Macintosh', value: 'Mac', version: 'OS X' },
            { name: 'Linux', value: 'Linux', version: 'rv' },
            { name: 'Palm', value: 'Palm', version: 'PalmOS' }
        ],
        databrowser: [
            { name: 'Chrome', value: 'Chrome', version: 'Chrome' },
            { name: 'Firefox', value: 'Firefox', version: 'Firefox' },
            { name: 'Safari', value: 'Safari', version: 'Version' },
            { name: 'Internet Explorer', value: 'MSIE', version: 'MSIE' },
            { name: 'Opera', value: 'Opera', version: 'Opera' },
            { name: 'BlackBerry', value: 'CLDC', version: 'CLDC' },
            { name: 'Mozilla', value: 'Mozilla', version: 'Mozilla' }
        ],
        init: function () {
            var agent = this.header.join(' '),
                os = this.matchItem(agent, this.dataos),
                browser = this.matchItem(agent, this.databrowser);
            
            return { os: os, browser: browser };
        },
        matchItem: function (string, data) {
            var i = 0,
                j = 0,
                html = '',
                regex,
                regexv,
                match,
                matches,
                version;
            
            for (i = 0; i < data.length; i += 1) {
                regex = new RegExp(data[i].value, 'i');
                match = regex.test(string);
                if (match) {
                    regexv = new RegExp(data[i].version + '[- /:;]([\\d._]+)', 'i');
                    matches = string.match(regexv);
                    version = '';
                    if (matches) { if (matches[1]) { matches = matches[1]; } }
                    if (matches) {
                        matches = matches.split(/[._]+/);
                        for (j = 0; j < matches.length; j += 1) {
                            if (j === 0) {
                                version += matches[j] + '.';
                            } else {
                                version += matches[j];
                            }
                        }
                    } else {
                        version = '0';
                    }
                    return {
                        name: data[i].name,
                        version: parseFloat(version)
                    };
                }
            }
            return { name: 'unknown', version: 0 };
        }
    };
    
    var e = module.init(),
        debug = '';
    
    debug += 'os.name = ' + e.os.name + '<br/>';
    debug += 'os.version = ' + e.os.version + '<br/>';
    debug += 'browser.name = ' + e.browser.name + '<br/>';
    debug += 'browser.version = ' + e.browser.version + '<br/>';
    
    debug += '<br/>';
    debug += 'navigator.userAgent = ' + navigator.userAgent + '<br/>';
    debug += 'navigator.appVersion = ' + navigator.appVersion + '<br/>';
    debug += 'navigator.platform = ' + navigator.platform + '<br/>';
    debug += 'navigator.vendor = ' + navigator.vendor + '<br/>';
    
	//console.log(debug);
    //document.getElementById('log').innerHTML = debug;
	return e;
}

function getVersion(){
	try{
		var manifestData = chrome.runtime.getManifest();
		//console.log(manifestData.version);
		//console.log(manifestData.default_locale);
		var fst_version_var	= APP_ID+"."+manifestData.version;	//in gfunc.js
		console.log(fst_version_var);

        
        //$("#mydivheader").text = "Login "+fst_version_var;
		return fst_version_var;
	}catch(e){}
	return "";
}

//dragElement(document.getElementById("logintitle"));

function dragElement(elmnt) {
  var pos1 = 0, pos2 = 0, pos3 = 0, pos4 = 0;
  if (document.getElementById(elmnt.id + "header")) {
    // if present, the header is where you move the DIV from:
    document.getElementById(elmnt.id + "header").onmousedown = dragMouseDown;
  } else {
    // otherwise, move the DIV from anywhere inside the DIV:
    elmnt.onmousedown = dragMouseDown;
  }

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

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

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

