// ---- BEGIN -- json lib function JSONRequest(obj) { this.obj = obj; var jsonreqcnt = 0; var jsonparent; var jsononreq = function() {}; var jsononclear = function() {}; var jsonreqpendding = 0; var jsonreqnode = []; var jsontimeoutcounter = 0; var json_check_timeout = function() { var ctime = new Date(); var i; var s; for(i in jsonreqnode) { if (ctime - jsonreqnode[i].reqtime > 10000) { if (jsonreqnode[i].parentNode != null) { s = document.createElement('script'); s.setAttribute('src', jsonreqnode[i].src); s.setAttribute('type', "text/javascript"); s.reqtime = new Date(); jsonparent.removeChild(jsonreqnode[i]); delete jsonreqnode[i]; jsonparent.appendChild(s); jsonreqnode[i] = s; jsontimeoutcounter++; } } } setTimeout("json_check_timeout()",10000); } this.json_init = function(obj){ jsonparent = obj; //json_check_timeout(); } this.json_request = function(url, param, rvar, callback, norand){ if (!jsonparent) { this.json_init(document.getElementsByTagName("head")[0]); } jsonreqpendding++; jsononreq(); jsonreqcnt++; s = document.createElement('script'); var attr = url + "?" + param + "&var=" + rvar + "&callback=document.longdoaccount.jsonp.json_clear(" + jsonreqcnt + ");" + callback; if (! norand) { attr += "&rand="+Math.random(); } s.setAttribute('src', attr); s.setAttribute('type', "text/javascript"); s.reqtime = new Date(); jsonreqnode[jsonreqcnt] = s; jsonparent.appendChild(s); } this.json_clear = function(nid) { // if (jsonreqnode[nid]) { jsonreqpendding--; jsononclear(); jsonparent.removeChild(jsonreqnode[nid]); delete jsonreqnode[nid]; //jsonreqnode[nid] = false; // } } var json_attach = function(onreq, onclear){ jsononreq = onreq; jsononclear = onclear; } } /** * * Name: Longdo Js Interface * Version: 2.5 * Author: Suraphat (suraphat@longdo.com) * Repository: https://git.longdo.com/mm/longdo-js-interface * */ function LongdoJsInterface(options) { let transaction = 1 let cachedTile = {} const identifyAndroid = (options || {}).identifyAndroid || '' const identifyIos = (options || {}).identifyIos || 'LongdoJsInterface' const onRefreshFCMTokenCallbackName = '_longdoJsInterface_onRefreshFCMToken' window[onRefreshFCMTokenCallbackName] = () => { } const oMessageFCMCallbackName = '_longdoJsInterface_onMessageFCM' window[oMessageFCMCallbackName] = () => { } this.Util = { getQueryString: function (obj) { let str = [] for (let p in obj) { if (obj[p] !== undefined) { if (obj[p] instanceof Array) { for (var i = 0; i < obj[p].length; i++) { str.push(encodeURIComponent(p) + '[' + i + ']=' + encodeURIComponent(JSON.stringify(obj[p][i]))) } } else { str.push(encodeURIComponent(p) + '=' + encodeURIComponent(obj[p])) } } } return str.join('&') }, isAndroidNativeApp: function () { const ua = window.navigator.userAgent || window.navigator.vendor || window.opera || '' return ua.indexOf('Android') > -1 && ua.indexOf(identifyAndroid) > -1 && (('flutter_inappwebview' in window) || (typeof Android !== 'undefined')) }, isIosNativeApp: function () { const ua = window.navigator.userAgent || window.navigator.vendor || window.opera || '' return ua.indexOf('Mac') > -1 && ua.indexOf(identifyIos) > -1 && ua.indexOf('Version') < 0 }, isOnLine: function () { if (window.navigator) { if ('onLine' in window.navigator) { return window.navigator.onLine } } return null }, addScriptTag: function (option) { option = option || {} return new Promise((resolve, reject) => { let script = document.createElement('script') script.onload = (e) => { resolve(e) } script.onreadystatechange = (e) => { resolve(e) } script.onerror = (e) => { reject(e) } for (var key in option) { script[key] = option[key] } document.head.appendChild(script) }) }, cacheLongdoMapTheme: async (longdoObj, cacheName) => { const keyList = [ 'menu.arrowActive', 'menu.arrowDown', 'menu.arrowUp', 'poi.addressIcon', 'poi.lineIcon', 'poi.openIcon', 'poi.poiLabel.en.obsoleted', 'poi.poiLabel.en.unverified', 'poi.poiLabel.th.obsoleted', 'poi.poiLabel.th.unverified', 'poi.tagIcon', 'poi.telIcon', 'poi.urlIcon', 'search.zoomIcon', 'ui.clearOff', 'ui.clearOn', 'ui.dpad', 'ui.fullscreenDown', 'ui.fullscreenUp', 'ui.geolocation', 'ui.geolocationMarkerIcon.url', 'ui.geolocationMarkerIcon.urlHD', 'ui.legendTraffic.en', 'ui.legendTraffic.th', 'ui.measureOff', 'ui.measureOn', 'ui.rangeOff', 'ui.rangeOn', 'ui.zoomBar', 'ui.zoomIn', 'ui.zoomInMini', 'ui.zoomOut', 'ui.zoomOutMini', 'ui.zoomSlider' ] if (this.Util.isOnLine() === true) { // online for (let i = 0; i < keyList.length; i++) { let temp = longdoObj.MapTheme const key = keyList[i] const splitedName = key.split('.') for (let j = 0; j < splitedName.length - 1; j++) { temp = temp[splitedName[j]] } try { await this.addCache({ cacheName: cacheName, url: temp[splitedName[splitedName.length - 1]], }) } catch (error) { console.warn(error) } } } else { // offline for (let i = 0; i < keyList.length; i++) { let temp = longdoObj.MapTheme const key = keyList[i]; const splitedName = key.split('.') for (let j = 0; j < splitedName.length - 1; j++) { temp = temp[splitedName[j]] } try { const newUrl = await this.getCache({ cacheName: cacheName, url: temp[splitedName[splitedName.length - 1]], returnType: 'stringUrl' }) temp[splitedName[splitedName.length - 1]] = newUrl } catch (error) { console.warn(error) } } } }, cacheLongdoMapLayer: (longdoObj, cacheName, longdoMapObj) => { const overrideLayer = (layerType) => { const layerName = layerType.name() return new longdoObj.Layer(layerName, { type: longdoObj.LayerType.Custom, defer: async (element, projection, tile, zoom, hd) => { let url = layerType.image(projection, tile, hd) url = url.replace('longdo.com', 'simplethai.net') if (this.Util.isAndroidNativeApp() || this.Util.isIosNativeApp()) { const key = `_${layerName}:x:${tile.u}:y:${tile.v}:z:${zoom}` cachedTile[key] = cachedTile[key] || {} // cache tile once when online if (this.Util.isOnLine() === true && !cachedTile[key].url) { if (!(cachedTile[key] && cachedTile[key].added)) { try { await this.addCache({ cacheName: cacheName, url: url }) cachedTile[key] = Object.assign(cachedTile[key] || {}, { added: true }) } catch (error) { console.warn(error) } } } // get cache to object variable if (!cachedTile[key].url) { try { const localUrl = await this.getCache({ cacheName: cacheName, url: url, returnType: this.Util.isOnLine() === true ? 'stringContent' : 'stringUrl', }) if (localUrl) { cachedTile[key] = Object.assign(cachedTile[key] || {}, { url: localUrl }) cachedTile[key] = Object.assign(cachedTile[key] || {}, { added: true }) } } catch (error) { console.warn(error) } } element.src = this.Util.isOnLine() === true ? `data:image/png;base64,${cachedTile[key].url}` : cachedTile[key].url } else { element.src = url } } }) } const setBase = longdoMapObj.Layers.setBase longdoMapObj.Layers.setBase = function (layer) { setBase(overrideLayer(layer)) } const add = longdoMapObj.Layers.add longdoMapObj.Layers.add = function (layer) { add(overrideLayer(layer)) } const remove = longdoMapObj.Layers.remove longdoMapObj.Layers.remove = function (layer) { remove(overrideLayer(layer)) } longdoMapObj.Layers.setBase(longdoObj.Layers.POI) return longdoMapObj }, isObject: function (obj) { return typeof obj === 'object' && !Array.isArray(obj) && obj !== null }, toSoundId: function (name) { const ref = { 'newMail': { iOS: 1000, Android: 1000 }, 'sendMail': { iOS: 1001, Android: 1001 }, 'newMessage': { iOS: 1003, Android: 1003 }, 'sendMessage': { iOS: 1004, Android: 1004 }, 'alarm': { iOS: 1005, Android: 1005 }, 'lowPower': { iOS: 1006, Android: 1006 }, 'callDropped': { iOS: 1051, Android: 1051 }, 'beep': { iOS: 1052, Android: 1052 }, 'lock': { iOS: 1100, Android: 1100 }, 'tink': { iOS: 1103, Android: 1103 }, 'tock': { iOS: 1104, Android: 1104 }, 'photoShutter': { iOS: 1108, Android: 1108 }, 'shake': { iOS: 1109, Android: 1109 }, 'beginRecord': { iOS: 1113, Android: 1113 }, 'endRecord': { iOS: 1114, Android: 1114 }, } if (this.isAndroidNativeApp()) { return ref[name]?.Android } else if (this.isIosNativeApp()) { return ref[name]?.iOS || 1052 } else { return null } }, initMethod: function ({ name, title, params, supportiOS = true, supportAndroid = true, preCheck }) { return (resolve, reject) => { if (!(resolve instanceof Function)) { resolve = null } if (!(reject instanceof Function)) { reject = null } if (preCheck) { const result = preCheck() if (resolve && result.success === true) { resolve(result.result) } else if (reject && result.success === false) { reject(result.result) } params = result } const callbackName = `_${name}Callback${new Date().getTime()}${transaction++}` if (name === 'getGeolocation') { console.log(callbackName) } if (params && params.callback) { if (!(params.callback instanceof Function)) { if (reject) { reject({ code: 2, message: 'callback must be function' }) } else { return { code: 2, message: 'callback must be function' } } } const callback = params.callback window[callbackName] = (result) => { if (name === 'getGeolocation') { console.log('call from :', callbackName) console.log(result) } if (resolve) { resolve(callback(result)) } else { return callback(result) } } delete params.callback } else { window[callbackName] = (result) => { if (resolve) { if (this.isObject(result)) { resolve(result) } else { try { resolve(JSON.parse(result)) } catch { resolve(result) } } } else { if (this.isObject(result)) { return result } else { try { return JSON.parse(result) } catch { return result } } } } } const errorCallbackName = `_error${name}Callback${new Date().getTime()}${transaction++}` if (name === 'getGeolocation') { console.log(errorCallbackName) } if (params && params.errorCallback) { if (!(params.errorCallback instanceof Function)) { if (reject) { reject({ code: 2, message: 'errorCallback must be function' }) } else { return { code: 2, message: 'errorCallback must be function' } } } const callback = params.errorCallback window[errorCallbackName] = (errorMessage, errorCode = 0) => { if (name === 'getGeolocation') { console.log('error call from :', errorCallbackName) console.log(JSON.stringify(errorMessage)) console.log(errorCode) } if (reject) { reject(callback({ code: errorCode, message: errorMessage })) } else { return callback({ code: errorCode, message: errorMessage }) } } delete params.errorCallback } else { window[errorCallbackName] = (errorMessage, errorCode = 0) => { if (reject) { reject({ code: errorCode, message: errorMessage }) } else { return { code: errorCode, message: errorMessage } } } } const sendParams = Object.assign(params || {}, { callbackName, errorCallbackName }) if (supportAndroid && this.isAndroidNativeApp()) { if (name === 'capture') { //force unsupport parameters delete sendParams.width delete sendParams.height } else if (name === 'openUrl') { //force unsupport parameters delete sendParams.title Object.assign(sendParams, { title: params.title }) } if ('flutter_inappwebview' in window) { window.flutter_inappwebview.callHandler(name, ...Object.values(sendParams)); } else { Android[name](...Object.values(sendParams)) } } else if (supportiOS && this.isIosNativeApp() && 'webkit' in window) { window.webkit.messageHandlers[name].postMessage(sendParams) } else if (reject) { reject({ code: 1, message: `Unsupport ${title}` }) } else { return { code: 1, message: `Unsupport ${title}` } } } } } this.setOffline = ({ fileList, baseFileIndex = 0 }) => new Promise(this.Util.initMethod({ name: 'setOffline', title: 'set offline', params: { fileList, baseFileIndex: parseInt(baseFileIndex) }, preCheck: () => { if (!(fileList instanceof Array)) { return { result: { code: 2, message: 'fileList must be {Array.<{fileName: String, path: String, url: String}>}' }, success: false } } if (fileList.length === 0) { return { result: true, success: true } } if (this.Util.isAndroidNativeApp()) { fileList = JSON.stringify(fileList) } return { fileList, baseFileIndex } } })) this.addCache = ({ cacheName, url }) => new Promise(this.Util.initMethod({ name: 'addCache', title: 'add cache', params: { cacheName, url } })) this.getCache = ({ cacheName, url, returnType }) => new Promise(this.Util.initMethod({ name: 'getCache', title: 'get cache', params: { cacheName, url, returnType, callback: (result) => { if (this.Util.isObject(result)) { return result.result } else { return result } } } })) this.deleteCache = ({ cacheName, url }) => new Promise(this.Util.initMethod({ name: 'deleteCache', title: 'delete cache', params: { cacheName, url }, preCheck: () => { if (cacheName === null) { return { result: { code: 2, message: 'please specify cacheName' }, success: false } } return { cacheName, url } } })) this.addStorage = ({ key, value }) => new Promise(this.Util.initMethod({ name: 'addStorage', title: 'add storage', params: { key, value } })) this.getStorage = ({ key }) => new Promise(this.Util.initMethod({ name: 'getStorage', title: 'get storage', params: { key, callback: (result) => { if (this.Util.isObject(result)) { return result.result } else { return result } } } })) this.deleteStorage = ({ key }) => new Promise(this.Util.initMethod({ name: 'deleteStorage', title: 'delete storage', params: { key } })) this.getUniqueDeviceId = () => new Promise(this.Util.initMethod({ name: 'getUniqueDeviceId', title: 'get unique device id' })) this.getFCMToken = () => { if (this.Util.isAndroidNativeApp()) { Android.getFCMToken() return true } else if (this.Util.isIosNativeApp() && 'webkit' in window) { window.webkit.messageHandlers.getFCMToken.postMessage({}) return true } return false } this.setOnRefreshFCMToken = ({ onRefreshFCMToken }) => { if (!(onRefreshFCMToken instanceof Function)) { return false } window[onRefreshFCMTokenCallbackName] = onRefreshFCMToken return true } this.setOnMessageFCM = ({ onMessageFCM }) => { if (!(onMessageFCM instanceof Function)) { return false } window[oMessageFCMCallbackName] = onMessageFCM return true } this.readyOnMessageFCM = () => { if (this.Util.isIosNativeApp() && 'webkit' in window) { window.webkit.messageHandlers.readyOnMessageFCM.postMessage({}) return true } return false } this.setBadgeNotification = ({ numberOfNotification }) => new Promise(this.Util.initMethod({ name: 'setBadgeNotification', title: 'set badge notification', params: { numberOfNotification: parseInt(numberOfNotification) } })) this.getGeolocation = () => new Promise(this.Util.initMethod({ name: 'getGeolocation', title: 'get geololocation' })) this.setOnWatchGeolocation = ({ callback, errorCallback }) => this.Util.initMethod({ name: 'getGeolocation', title: 'set on watch geololocation', params: { callback, errorCallback } })() this.stopWatchGeolocation = () => new Promise(this.Util.initMethod({ name: 'stopGetGeolocation', title: 'stop watch geololocation' })) this.openUrl = ({ url, title = 'Open with' }) => new Promise(this.Util.initMethod({ name: 'openUrl', title: 'open url', params: { url, title }, preCheck: () => { if (url === null) { return { result: { code: 2, message: 'please specify url' }, success: false } } return { url, title } } })) this.selectImageFile = () => new Promise(this.Util.initMethod({ name: 'selectImageFile', title: 'select image file' })) this.capture = (option = { width: 150, height: 50 }) => new Promise(this.Util.initMethod({ name: 'capture', title: 'capture', params: { width: parseInt(option.width) || 150, height: parseInt(option.height) || 50 } })) this.saveImage = ({ url, base64 }) => new Promise(this.Util.initMethod({ name: 'saveImage', title: 'save image', params: { encodeUrlOrBase64: (url || base64), type: url === null ? 'base64' : 'url' }, preCheck: () => { if (url === null && base64 === null) { return { result: { code: 2, message: 'please specify url or base64' }, success: false } } return { encodeUrlOrBase64: (url || base64), type: url === null ? 'base64' : 'url' } } })) this.shareUrl = (url) => new Promise(this.Util.initMethod({ name: 'shareUrl', title: 'share URL', params: { url }, preCheck: () => { if (url === null) { return { result: { code: 2, message: 'please specify url' }, success: false } } return { url } } })) this.getAppVersion = () => new Promise(this.Util.initMethod({ name: 'getAppVersion', title: 'get app version' })) this.getLanguage = () => new Promise(this.Util.initMethod({ name: 'getLanguage', title: 'get language' })) this.setLanguage = ({ lang = 'th' }) => new Promise(this.Util.initMethod({ name: 'setLanguage', title: 'set language', params: { lang } })) this.setCookie = ({ domain, cookie }) => new Promise(this.Util.initMethod({ name: 'setCookie', title: 'set cookie', params: { domain, cookie }, supportiOS: false })) this.flushCookie = () => new Promise(this.Util.initMethod({ name: 'flushCookie', title: 'flush cookie', supportiOS: false })) this.speak = ({ text = '', lang = 'th' }) => new Promise(this.Util.initMethod({ name: 'speak', title: 'speak', params: { text, lang } })) this.alwaysOn = ({ on = true }) => new Promise(this.Util.initMethod({ name: 'alwaysOn', title: 'always on', params: { on } })) this.scanQrCode = () => new Promise(this.Util.initMethod({ name: 'scanQrCode', title: 'scan qr code', params: { callback: (result) => { if (this.Util.isObject(result)) { return result.content } else { return result } } } })) this.loginLongdo = () => new Promise(this.Util.initMethod({ name: 'loginLongdo', title: 'login longdo' })) this.getLongdoInfo = () => new Promise(this.Util.initMethod({ name: 'getLongdoInfo', title: 'get longdo info' })) this.logoutLongdo = () => new Promise(this.Util.initMethod({ name: 'logoutLongdo', title: 'logout longdo' })) this.startListen = ({ lang = 'th', callback, errorCallback }) => this.Util.initMethod({ name: 'startListen', title: 'start listen', params: { lang, callback, errorCallback } })() this.stopListen = () => new Promise(this.Util.initMethod({ name: 'stopListen', title: 'stop listen' })) this.openSetting = () => new Promise(this.Util.initMethod({ name: 'openSetting', title: 'open setting' })) this.vibrate = ({ type = "" }) => new Promise(this.Util.initMethod({ name: 'vibrate', title: 'vibrate', params: { type } })) this.sound = ({ soundId }) => new Promise(this.Util.initMethod({ name: 'sound', title: 'sound', params: { soundId: this.Util.toSoundId(soundId) } })) this.sendToProbe = ({ on = true }) => new Promise(this.Util.initMethod({ name: 'sendToProbeChange', title: 'send to probe', params: { on } })) this.updateToken = ({ on = true }) => new Promise(this.Util.initMethod({ name: 'updateTokenChange', title: 'update token', params: { on } })) this.hideLaunchscreen = () => new Promise(this.Util.initMethod({ name: 'hideLaunchscreen', title: 'hide launchscreen' })) // this.detectLight = ({ // detect = true, // callback, // errorCallback // }) => new Promise(this.Util.initMethod({ // name: 'detectLight', // title: 'detect light', // params: { // detect, // callback, // errorCallback // } // })) } function LongdoAccount() { var self = this; self.longdo_servername = 'www.longdo.com/'; document.longdocomapiaccount = this; // ref. in prettyPhoto.js var longdo_lib; this.pdpa; this.debug = false; this.client = false; this.uuid = false; this.device_name = false; this.model = false; this.os_version = false; this.fb_connected = false; self.pdpa_div = false; self.pdpa_config = {}; var error_msg_div = 'pp-longdocom-error-txt'; var info_msg_div = 'pp-longdocom-info-txt'; this.setPdpaConfig = function(obj) { self.pdpa_config = obj; } this.setMsgDiv = function(ele_id) { this.setInfoMsgDiv(ele_id); this.setErrorMsgDiv(ele_id); } this.setErrorMsgDiv = function(ele_id) { error_msg_div = ele_id; } this.setInfoMsgDiv = function(ele_id) { info_msg_div = ele_id; } this.mylang = 'th'; this.cookieDomain = '.longdo.com'; this.jsonp = false; var jq_prettyphoto_initialed = false; var jq_prettyphoto_function_initialed = false; this.thisPageUsingOtherJSLibrary = false; //var longdoLoginElement = false; this.closePrettyPhoto = function() { if (longdo_lib.jq && longdo_lib.jq.prettyPhotoLongdoHook && longdo_lib.jq.prettyPhotoLongdoHook.close) { longdo_lib.jq.prettyPhotoLongdoHook.close(); } } this.getElementLoginLinks = function() { return "a[href$='/login'], a[href*='/login?destination'], .login-with-longdo-com"; } this.getElementLogoutLinks = function() { return "a[href$='/logout'], a[href*='/logout?destination'], .logout-with-longdo-com"; } this.showLongdoLoginForm = function(msg, des, callback) { //if (longdoLoginElement && longdoLoginElement.length > 0) { // longdoLoginElement.click(); //} else { if(typeof(msg) == 'undefined') msg = false; if(typeof(des) == 'undefined') des = false; if(typeof(callback) != 'function') callback = false; self.initLongdoLogin(); if (!longdo_lib || !longdo_lib.jq || !longdo_lib.jq.prettyPhotoLongdoHook || !longdo_lib.jq.prettyPhotoLongdoHook.openLink) { setTimeout(function(){ self.showLongdoLoginForm(msg, des, callback); }, 200); return; } var href = '/login'; if (des) { href = des; } else { var longdoLoginElement = longdo_lib.jq(self.getElementLoginLinks()); if(longdoLoginElement.length > 0) { var login_href = ''; if(longdoLoginElement.attr('href')) { login_href = longdoLoginElement.attr('href').replace(longdoLoginElement.attr('baseURI'), ''); } if(login_href && !/^javascript:/.test(login_href)) href = '/' + login_href; } } var settings = { changepicturecallback: function() { self.setFBLoginButtonID('longdo-login-fb-btn'); self.setGGLoginButtonID('longdo-login-gg-btn'); self.setAppleLoginButtonID('longdo-login-apple-btn'); self.initSocialAccountButton(); if (msg && msg.txt) { if (msg.type == 'error') { self.showErrorMsgLongdoLogin(msg.txt) } else if (msg.type == 'info') { self.showInfoMsgLongdoLogin(msg.txt) } } }, login_callback: callback, callback: function(){ if(self.loginFormCloseCloseCallback) { self.loginFormCloseCloseCallback = self.loginFormCloseCloseCallback.bind(null); self.loginFormCloseCloseCallback(); } if(self.pdpa_div) { self.pdpa_div.style.zIndex++; var consent_div = document.getElementsByClassName("consent-div"); if(consent_div && consent_div[0]) { consent_div[0].style.zIndex++; } } } } if(msg.settings) { settings = Object.assign(settings, msg.settings); } longdo_lib.jq.prettyPhotoLongdoHook.openLink(href, settings); if(self.pdpa_div) { self.pdpa_div.style.zIndex--; var consent_div = document.getElementsByClassName("consent-div"); if(consent_div && consent_div[0]) { consent_div[0].style.zIndex--; } } void(0); } this.showLongdoRequestPwdForm = function(email) { if(!longdo_lib.jq) { window.open('https://'+self.longdo_servername+'user/password/force', '_blank'); return; } this.initLongdoLogin(); if (!longdo_lib.jq.prettyPhotoLongdoHook) { setTimeout(function(){ self.showLongdoRequestPwdForm(); }, 200); return; } //self.closePrettyPhoto(); if(!email) { email = ''; } longdo_lib.jq.prettyPhotoLongdoHook.openLink('/forgotpwd', {forgotpwd_email: email}); //setTimeout(function(){ longdo_lib.jq.prettyPhotoLongdoHook.changePage('', function(){ longdo_lib.jq.prettyPhotoLongdoHook.openLink('/forgotpwd'); }) }, 1000); void(0); } this.showPrettyPhotoPopup = function(op, param) { this.initLongdoLogin(); if (!longdo_lib.jq.prettyPhotoLongdoHook) { setTimeout(function(){ self.showPrettyPhotoPopup(op, param); }, 200); return; } if (typeof(param) == 'object') { longdo_lib.jq.prettyPhotoLongdoHook.openLink(op, param); } else { longdo_lib.jq.prettyPhotoLongdoHook.openLink(op); } } this.initPrettyPhotoAPI = async function() { if (!longdo_lib.jq) { // jQuery is loading .. setTimeout(function(){ self.initPrettyPhotoAPI(); }, 200); return; } if (!longdo_lib.jq.prettyPhotoLongdoHook && !jq_prettyphoto_initialed) { self.loadPrettyPhoto(); jq_prettyphoto_initialed = true; } if(!longdo_lib.jq.prettyPhotoLongdoHook) { setTimeout(function(){ self.initPrettyPhotoAPI(); }, 200); return; } if (longdo_lib.jq.prettyPhotoLongdoHook && !jq_prettyphoto_function_initialed) { jq_prettyphoto_function_initialed = true; await longdo_lib.jq("longdo").prettyPhotoLongdoHook(); } } this.appendSocialAccountButton = function(eles) { if (typeof(eles) != 'object' || !eles.length || eles.length < 1) { return; } var fb_loginbar_button_id = 'longdocom-loginbar-fb-button'; var gg_loginbar_button_id = 'longdocom-loginbar-gg-button'; var content = document.createElement("span"); content.id = fb_loginbar_button_id; content.className = 'longdocom-loginbar-social-button'; //var ele; //var num_ele = eles.length; //for(var i=0; i 0) { longdoLoginElement.unbind('click').bind('click',function(){ self.showLongdoLoginForm(); return false; }); self.appendSocialAccountButton(longdo_lib.jq(".longdo-loginbar-button")); } else { var longdoLogoutElement = longdo_lib.jq(logout_id ? logout_id : self.getElementLogoutLinks()); if (longdoLogoutElement && longdoLogoutElement.length > 0) { longdoLogoutElement.unbind('click').bind('click',function(){ self.logout(); }); } } jq_longdologin_initialed = true; } else if(!jq_longdologin_initialed) { setTimeout(function(){ self.initLongdoLogin(obj); }, 200); return; } var client = obj && obj.client ? obj.client : ''; var locale = obj && obj.locale ? locale : self.mylang; if (obj && obj.cookieDomain) { self.cookieDomain = obj.cookieDomain; } if(!self.pdpa) { self.pdpa = new LongdoPDPA(longdo_lib); let pdpa_config = {client: client, locale: locale}; longdo_lib.jq.extend(pdpa_config, self.pdpa_config); self.pdpa.init(pdpa_config); self.pdpa_div = getEleByID(self.pdpa.pdpa_div_content_id); } } this.getCookie = function(cname) { var name = cname + "="; var decodedCookie = decodeURIComponent(document.cookie); var ca = decodedCookie.split(";"); for(var i = 0; i 0) { err_txt.html(''); this.hideElementByJq(err_txt); } } this.showMsgLongdoLogin = function(ele_id, errortxt, req) { if (!longdo_lib || !longdo_lib.jq) { var msg_div = getEleByID(ele_id); if(msg_div) { msg_div.innerHTML = errortxt; msg_div.style.display = 'block'; } return; } var err_txt = longdo_lib.jq('#'+ele_id); if(err_txt && err_txt.length > 0) { err_txt.html(errortxt); this.showElementByJq(err_txt); } else if(ele_id == error_msg_div) { self.showPrettyPhotoPopup('/showmsg?msg='+errortxt, { default_width: '400', default_height: '100' }); return; } } this.hideErrorMsgLongdoLogin = function() { this.hideMsgLongdoLogin(error_msg_div); } this.showErrorMsgLongdoLogin = function(txt, req) { this.hideInfoMsgLongdoLogin(); this.showMsgLongdoLogin(error_msg_div, txt, req); } this.hideInfoMsgLongdoLogin = function() { this.hideMsgLongdoLogin(info_msg_div); } this.showInfoMsgLongdoLogin = function(txt) { this.hideErrorMsgLongdoLogin(); this.showMsgLongdoLogin(info_msg_div, txt); } this.hideElementByJq = function(ele) { if (!longdo_lib || !longdo_lib.jq) { return; } if (typeof(ele) == 'string') { ele = longdo_lib.jq(ele); } if(typeof(ele) == 'object' && ele.length > 0) { ele.addClass('pp-longdocom-hide'); } } this.showElementByJq = function(ele) { if (!longdo_lib || !longdo_lib.jq) { return; } if (typeof(ele) == 'string') { ele = longdo_lib.jq(ele); } if(typeof(ele) == 'object' && ele.length > 0) { ele.removeClass('pp-longdocom-hide'); } } this.enableButtonOnLoginForm = function() { if (longdo_lib.jq && longdo_lib.jq != 'failed' && longdo_lib.jq('#longdologin-form-ajax').length > 0) { // login form on prettyphoto popup var pp_login_form = longdo_lib.jq('#longdologin-form-ajax'); pp_login_form.find('.button-submit-ajax').removeAttr("disabled").removeClass('pp-longdocom-btn-waiting'); pp_login_form.find('.longdo-login-social-button').removeClass('longdo-login-social-button-waiting'); } else { // on longdo.com page var login_button = getEleByID('login-button'); var loading = getEleByID('loading-login'); var fb_button = getEleByID(fb_login_button_div_id); var gg_button = getEleByID(gg_login_button_div_id); var line_button = getEleByID(line_login_button_div_id); if (login_button && loading) { login_button.style.display = 'block'; loading.style.display = 'none'; } if (fb_button) { removeClass(fb_button, 'longdo-login-social-button-waiting'); } if (gg_button) { removeClass(gg_button, 'longdo-login-social-button-waiting'); } } } this.disableButtonOnLoginForm = function() { if (longdo_lib && longdo_lib.jq && longdo_lib.jq != 'failed' && longdo_lib.jq('#longdologin-form-ajax').length > 0) { // login form on prettyphoto popup var pp_login_form = longdo_lib.jq('#longdologin-form-ajax'); pp_login_form.find('.button-submit-ajax').attr("disabled", "disabled").addClass('pp-longdocom-btn-waiting'); pp_login_form.find('.longdo-login-social-button').addClass('longdo-login-social-button-waiting'); } else { // on longdo.com page var login_button = getEleByID('login-button'); var loading = getEleByID('loading-login'); var fb_button = getEleByID(fb_login_button_div_id); var gg_button = getEleByID(gg_login_button_div_id); var line_button = getEleByID(line_login_button_div_id); if (login_button && loading) { login_button.style.display = 'none'; loading.style.display = 'block'; } if (fb_button) { addClass(fb_button, 'longdo-login-social-button-waiting'); } if (gg_button) { addClass(gg_button, 'longdo-login-social-button-waiting'); } } } this.login_ajax = function(destination, target) { var username_val = ''; var password_val = ''; var socialtoken_val = ''; if(longdo_lib.jq('#username-ajax').length > 0) username_val = longdo_lib.jq('#username-ajax').val(); if(longdo_lib.jq('#pass-ajax').length > 0) password_val = longdo_lib.jq('#pass-ajax').val(); if(longdo_lib.jq('#socialtoken-ajax').length > 0) socialtoken_val = longdo_lib.jq('#socialtoken-ajax').val(); var msgcode = ''; if(username_val == '' && password_val == '' && socialtoken_val == '') { msgcode = 'userpwd_required'; } else if(username_val == '' && !socialtoken_val == '') { msgcode = 'email_required'; } else if(username_val != '' && password_val == '' && socialtoken_val == '') { msgcode = 'pwd_required'; } //var msgcode = username_val != '' ? (password_val != '' ? "" : "pwd_required") : (password_val != '' ? "user_required" : "userpwd_required") ; if(msgcode != '') { this.showErrorMsgLongdoLogin(this.getMessageByMsgCode(msgcode)); return;} //this.hideElementByJq('#longdologin-form-ajax'); this.disableButtonOnLoginForm(); this.hideErrorMsgLongdoLogin() if (!target) { target = false; } if (!destination) { destination = false; } else { destination = encodeURIComponent(destination); } longdo_lib.jq.ajax({ url: 'https://'+self.longdo_servername+'ajax/app/signin', dataType: "json", type: "POST", data: {'username': username_val, 'pass': password_val, 'socialtoken': socialtoken_val, 'locale': self.mylang}, success: function( response ) { self.login_ajax_callback(response, destination, target) }, beforeSend: function(xhr){ xhr.withCredentials = true; }, xhrFields: { withCredentials: true }, crossDomain: true }); //self.jsonp.json_request('https://'+self.longdo_servername+'action/login', 'username='+encodeURIComponent(username_val)+'&pass='+encodeURIComponent(password_val)+'&getuser=1', 'rs', 'self.login_ajax_callback(rs)'); } this.forgotpwd_ajax = function() { var username_val = ''; if(longdo_lib.jq('.pp-longdocom #username-ajax')) username_val = longdo_lib.jq('.pp-longdocom #username-ajax').val(); var msgcode = username_val != '' ? '' : "user_required"; if(msgcode != '') { this.showErrorMsgLongdoLogin(this.getMessageByMsgCode(msgcode)); return;} //this.hideElementByJq('#longdologin-form-ajax'); this.disableButtonOnLoginForm(); this.hideErrorMsgLongdoLogin(); longdo_lib.jq.ajax({ url: 'https://'+self.longdo_servername+'ajax/app/resetpassword', dataType: "json", type: "POST", data: {'uname': username_val, 'locale': self.mylang}, success: function( response ) { self.forgotpwd_ajax_callback(response) }, beforeSend: function(xhr){ xhr.withCredentials = true; }, xhrFields: { withCredentials: true }, crossDomain: true }); } this.getMessageByMsgCode = function(code, arg) { var en = (this.mylang == 'en'); if (typeof(arg) == 'undefined') { arg = ''; } switch (code) { case "forgotpwd_completed": if(arg && arg != '') { arg = '
('+arg+')
'; } return (en ? "Further instructions have been sent to your e-mail address{email}" : "ระบบได้ส่งขั้นตอนการเข้าสู่ระบบให้ท่านทางอีเมลเรียบร้อยแล้ว{email}").replace('{email}', arg);; case "forgotpwd_notfound": return en ? "Sorry, invalid a username or an e-mail address" : "ไม่พบชื่อผู้ใช้ หรือ อีเมลนี้ในระบบ"; case "socialmail_found": return en ? "You already have a Longdo.COM account,
please enter your Longdo.COM password" : "ระบบพบว่าท่านเคยมีบัญชีผู้ใช้ Longdo.COM อยู่แล้ว
โปรดใส่รหัสผ่าน Longdo.COM"; case "socialmail_regist": return en ? "Please enter new password for create new Longdo.COM account" : "กรุณากรอกรหัสผ่านใหม่ เพื่อสร้างบัญชีผู้ใช้กับ Longdo.COM"; case "fbmail_invalid": return en ? "Invalid e-mail address, please enter your e-mail." : "อีเมลไม่ถูกต้อง กรุณากรอกอีเมลของท่าน"; case "userpwd_incorrect": return en ? "The username or password is incorrect" : "ชื่อผู้ใช้ หรือ รหัสผ่านไม่ถูกต้อง"; case "regist_fail": return en ? "Failed to register, Please try again" : "ลงทะเบียนไม่สำเร็จ โปรดลองใหม่อีกครั้ง"; case "connecting_fb": return en ? "Connecting with Facebook .." : "กำลังเชื่อมต่อ Facebook .."; case "pwd_required": return en ? "Password is required" : "โปรดระบุรหัสผ่าน"; case "user_required": return en ? "Username/E-mail address is required" : "โปรดระบุชื่อผู้ใช้/อีเมลผู้ใช้"; case "userpwd_required": return en ? "Username/E-mail address and Password are required" : "โปรดระบุชื่อผู้ใช้/อีเมลผู้ใช้ และ รหัสผ่าน"; case "longdocom_failed": return en ? "Longdo.COM is not available right now. Please try again later" : "Longdo.COM อยู่ในระหว่างการพัฒนาระบบ/เกิดข้อผิดหลาด กรุณาลองใหม่ภายหลัง"; case "signin": return en ? "Sign In" : "เข้าสู่ระบบ"; case "forgotpwd": return en ? "Forgot Password" : "ลืมรหัสผ่าน"; case "register": return en ? "Register" : "ลงทะเบียน"; case "signup": return en ? "Sign Up" : "สมัครบัญชีผู้ใช้"; case "userormail": return en ? "Username / E-mail Address" : "ชื่อผู้ใช้ / อีเมลผู้ใช้"; case "userormailortel": return en ? "Username / E-mail / Mobile phone no." : "ชื่อผู้ใช้ / อีเมล / เบอร์มือถือ"; case "mail": return en ? "E-mail" : "อีเมล"; case "pwd": return en ? "Password" : "รหัสผ่าน"; case "signin_via": return en ? "Sign In using" : "เข้าสู่ระบบโดย"; case "signin_via_fb": return en ? "Sign In using Facebook Account" : "เข้าสู่ระบบโดยบัญชีผู้ใช้งาน Facebook"; case "signin_via_line": return en ? "Sign In using Line Account" : "เข้าสู่ระบบโดยบัญชีผู้ใช้งาน Line"; case "signin_via_gg": return en ? "Sign In using Google Account" : "เข้าสู่ระบบโดยบัญชีผู้ใช้งาน Google"; case "mail_newpwd": return en ? "E-mail New Password" : "ขอรหัสผ่านใหม่ทางอีเมล"; case "user_not_activated": if(arg && arg != '') { arg = '
('+arg+')
'; } return (en ? "Your account is not activated.
Please check your e-mail to activate your account.{email}Resend Activation Email" : "บัญชีของท่านยังไม่ได้ทำการยืนยันอีเมล
กรุณาตรวจสอบอีเมล และยืนยันบัญชีผู้ใช้{email}
ให้ระบบส่งอีเมลยืนยันอีกครั้ง").replace("{email}", arg).replace("{plainemail}", arg.replace(/<[^>]*>/g, "").replace(/^\s*\(/, '').replace(/\)$/, '')); //case "": // return en ? "" : // ""; default: return code; } } //this.resend_activation_mail = function(ele) { // if (!ele.uid) { // this.consoleLog('Unknown UID.'); // return; // } // // self.jsonp.json_request('https://'+self.longdo_servername+'action/resendactivationmail', 'uid='+ele.uid, 'rs', 'self.resend_activation_mail_callback(rs)'); //} this.forgotpwd_ajax_callback = function(rs) { if(rs && rs.status) { if (rs.status.code == 200) { // success, return e-mail this.showInfoMsgLongdoLogin(this.getMessageByMsgCode("forgotpwd_completed", rs.data.mail)); } else if (rs.status.error_code == "incorrect:email") { // user not found this.showErrorMsgLongdoLogin(this.getMessageByMsgCode('forgotpwd_notfound')); } else if (rs.status.text) { this.showErrorMsgLongdoLogin(rs.status.text); } } else { this.showErrorMsgLongdoComFailed(); } this.enableButtonOnLoginForm(); } this.socialregist_ajax = function() { var username_val = ''; if(longdo_lib.jq('.pp-longdocom #username-ajax')) username_val = longdo_lib.jq('.pp-longdocom #username-ajax').val(); else if(longdo_lib.jq('#username-ajax')) username_val = longdo_lib.jq('#username-ajax').val(); var pwd_val = ''; if(longdo_lib.jq('.pp-longdocom #pass-ajax')) pwd_val = longdo_lib.jq('.pp-longdocom #pass-ajax').val(); else if(longdo_lib.jq('#pass-ajax')) pwd_val = longdo_lib.jq('#pass-ajax').val(); var msgcode = username_val != '' ? '' : "user_required"; if (!pwd_val) { if (msgcode != '') { msgcode = "userpwd_required"; } else { msgcode = "pwd_required"; } } if(msgcode != '') { this.showErrorMsgLongdoLogin(this.getMessageByMsgCode(msgcode)); return;} //this.hideElementByJq('#longdologin-form-ajax'); this.disableButtonOnLoginForm(); this.hideErrorMsgLongdoLogin() longdo_lib.jq.ajax({ url: 'https://'+self.longdo_servername+'action/socialregist/', dataType: "json", type: "POST", data: {'email': username_val, 'pwd': pwd_val, 'socialtoken': self.socialtoken}, success: function( response ) { self.socialregist_ajax_callback(response); }, beforeSend: function(xhr){ xhr.withCredentials = true; }, xhrFields: { withCredentials: true }, crossDomain: true }); //self.jsonp.json_request('https://'+self.longdo_servername+'action/socialregist', 'email='+username_val+'&pwd='+pwd_val+'&socialtoken='+self.socialtoken, 'rs', 'self.socialregist_ajax_callback(rs)'); } this.login_callback_customize = function(rs) { var is_rsobj = (typeof rs == 'object' || typeof rs == 'array'); var uid = is_rsobj ? rs.uid : rs; if(is_rsobj) { this.setUserSession(rs); } var continue_task = true; if(this.loginCompleteCallback) { var cb_rs = this.loginCompleteCallback.call(null, rs); continue_task = (cb_rs !== false) } if(continue_task) { var uid = rs && rs.uid ? parseInt(rs.uid, 10) : parseInt(uid, 10); if (longdo_lib.jq && longdo_lib.jq.prettyPhotoLongdoHook && typeof(longdo_lib.jq.prettyPhotoLongdoHook.login_callback) == 'function') { try { longdo_lib.jq.prettyPhotoLongdoHook.login_callback(uid); } catch (ex) { longdo_lib.consoleLog(ex); window.location.reload(true); } finally { longdo_lib.jq.prettyPhotoLongdoHook.close(); } } else { window.location.reload(true); } } } this.socialregist_ajax_callback = function(rs) { rs = parseInt(rs, 10); if (rs > 0) { this.login_callback_customize(rs); } else if (rs == 0) { this.enableButtonOnLoginForm(); this.showErrorMsgLongdoLogin(this.getMessageByMsgCode('regist_fail')); } else { this.enableButtonOnLoginForm(); this.showErrorMsgLongdoComFailed(); } } this.socialconnect_ajax = function() { var username_val = ''; if(longdo_lib.jq('#username-ajax')) username_val = longdo_lib.jq('#username-ajax').val(); var pwd_val = ''; if(longdo_lib.jq('#pass-ajax')) pwd_val = longdo_lib.jq('#pass-ajax').val(); var msgcode = username_val != '' ? '' : "user_required"; if (!pwd_val) { if (msgcode != '') { msgcode = "userpwd_required"; } else { msgcode = "pwd_required"; } } if(msgcode != '') { this.showErrorMsgLongdoLogin(this.getMessageByMsgCode(msgcode)); return;} this.disableButtonOnLoginForm(); //this.hideElementByJq('#longdologin-form-ajax'); this.hideErrorMsgLongdoLogin() // register page on Longdo.com by Social button var consent_checkbox = document.getElementById('consent-privacypolicy'); var accepted_consent = consent_checkbox && consent_checkbox.checked; longdo_lib.jq.ajax({ url: 'https://'+self.longdo_servername+'ajax/app/signin/', dataType: "json", type: "POST", data: {'username': username_val, 'pass': pwd_val, 'socialtoken': self.socialtoken, 'allowpdpa': accepted_consent, 'locale': self.mylang}, success: function( response ) { self.login_ajax_callback(response) }, beforeSend: function(xhr){ xhr.withCredentials = true; }, xhrFields: { withCredentials: true }, crossDomain: true }); //self.jsonp.json_request('https://'+self.longdo_servername+'action/login', 'username='+encodeURIComponent(username_val)+'&pass='+encodeURIComponent(pwd_val)+'&socialtoken='+self.socialtoken+'&getuser=1', 'rs', 'self.login_ajax_callback(rs)'); } this.checksocialmail_ajax_callback = function(user_rs) { let user = user_rs.data; if (user_rs && user && (user_rs.status && user_rs.status.code == 200)) { if (user.uid > 0) { this.login_callback_customize(user); } else { // request pwd for connect social account (Should not be in this case) self.enableButtonOnLoginForm(); self.showPrettyPhotoPopup('/socialconnect?username='+user.name, { changepicturecallback: function() { self.showInfoMsgLongdoLogin(self.getMessageByMsgCode('socialmail_found')); }, login_callback: self.login_callback_customize }); } } else { self.enableButtonOnLoginForm(); self.showPrettyPhotoPopup('/socialregist?username='+user.email, { changepicturecallback: function() { self.showInfoMsgLongdoLogin(self.getMessageByMsgCode('socialmail_regist')); }, login_callback: self.login_callback_customize }); } } this.loadPrettyPhoto = function() { longdo_lib.checkloadjscssfile('https://'+self.longdo_servername+'api/prettyPhoto/js/jquery.prettyPhoto.js', 'js'); longdo_lib.checkloadjscssfile('https://'+self.longdo_servername+'api/css/prettyPhoto.css', 'css'); } this.initJSONP = function() { if (this.jsonp) { return; } this.jsonp = new JSONRequest(); //self.jsonp.json_init(document.getElementsByTagName("head")[0]); } var fb_login_button_div_id = 'fb-login-button'; var gg_login_button_div_id = 'gg-login-button'; var line_login_button_div_id = 'line-login-button'; var apple_login_button_div_id = 'apple-login-button' this.setFBLoginButtonID = function(id) { fb_login_button_div_id = id; } this.setGGLoginButtonID = function(id) { gg_login_button_div_id = id; } this.setAppleLoginButtonID = function(id) { apple_login_button_div_id = id; } this.setLineLoginButtonID = function(id) { line_login_button_div_id = id; } var facebook_app_id = '148173948530677'; var facebook_scopes = 'email,public_profile'; // ,user_birthday var facebook_required_fields_when_login = 'id,name,email'; var googleHandleClientLoad = function() { // Step 2: Reference the API key gapi.client.setApiKey(google_api_key); window.setTimeout(checkAuth,1); } var checkAuth = function() { gapi.auth.authorize({client_id: google_client_id, scope: google_scopes, immediate: true}, handleAuthResult); } var handleAuthResult = function(authResult) { //var authorizeButton = document.getElementById('authorize-button'); if (authResult && !authResult.error) { //authorizeButton.style.visibility = 'hidden'; makeApiCall(); } else { //authorizeButton.style.visibility = ''; //authorizeButton.onclick = handleAuthClick; } } var handleAuthClick = function(event) { // Step 3: get authorization to use private data gapi.auth.authorize({client_id: google_client_id, scope: google_scopes, immediate: false}, handleAuthResult); return false; } // Load the API and make an API call. Display the results on the screen. var makeApiCall = function() { // Step 4: Load the Google+ API gapi.client.load('plus', 'v1', function() { // Step 5: Assemble the API request var request = gapi.client.plus.people.get({ 'userId': 'me' }); // Step 6: Execute the API request request.execute(function(resp) { var heading = document.createElement('h4'); var image = document.createElement('img'); image.src = resp.image.url; heading.appendChild(image); heading.appendChild(document.createTextNode(resp.displayName)); document.getElementById('content').appendChild(heading); }); }); } var username = ''; var passwd = ''; var getEleByID = function(id) { var ele = document.getElementById(id); return (ele ? ele : false); } this.ggLongdoRegis = function() { handleAuthClick(); } this.redirectPage = function(url) { window.location.replace(url); } var validateEmail = function(email) { var re = /^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/; return re.test(email); } this.processConnectedFacebookUser = function(user_rs) { var client_param = this.client ? '&client='+this.client : ''; var device_param = this.device_name ? '&device_name='+this.device_name : ''; device_param += this.model ? '&model='+this.model : ''; device_param += this.os_version ? '&os_version='+this.os_version : ''; device_param += this.uuid ? '&uuid='+this.uuid : ''; var social_param = ''; if (self.socialtoken) { social_param += '&socialtoken='+self.socialtoken; } if (!user_rs || !user_rs.data) { FB.api('/me?fields='+facebook_required_fields_when_login, function(response) { var email = response.email; longdo_lib.consoleLog(response); if (email && validateEmail(email)) { if (/secure.longdo.com/.test(window.location.hostname)) { self.redirectPage('https://secure.longdo.com/iregister/social.php?email='+email+client_param+device_param+social_param); } else { longdo_lib.jq.ajax({ url: 'https://'+self.longdo_servername+'ajax/app/checksocialmail', dataType: "json", type: "POST", data: {'email': email, 'socialtoken': self.socialtoken}, success: function( response ) { self.checksocialmail_ajax_callback(response) }, beforeSend: function(xhr){ xhr.withCredentials = true; }, xhrFields: { withCredentials: true }, crossDomain: true }); // self.jsonp.json_request('https://'+self.longdo_servername+'action/checksocialmail', 'email='+email+social_param, 'rs', 'self.checksocialmail_ajax_callback(rs)'); } } else { if (/secure.longdo.com/.test(window.location.hostname)) { if(!email) { email = ''; } self.redirectPage('https://secure.longdo.com/iregister/social.php?email='+email+client_param+device_param+social_param); } else { self.enableButtonOnLoginForm(); self.showLongdoLoginForm({txt: self.getMessageByMsgCode('fbmail_invalid')+(email ? '
('+email+')' : ''), type: 'error', settings: {socialtoken: self.socialtoken}}, '/requireemail'); } } }); } else if (user_rs && (user_rs.status && user_rs.status.code != 200)) { this.enableButtonOnLoginForm(); var msg; if(user_rs.status.error_code) { msg = this.getMessageByMsgCode(user_rs.status.error_code); if(msg == user_rs.status.error_code && user_rs.status.text) { msg = user_rs.status.text; } } else { msg = user_rs.status.text; } this.showErrorMsgLongdoLogin(msg); } else { // success var redirect_url = this.getRedirectLoggedinPathByClient(device_param, social_param); if (redirect_url != '') { self.setUserSession(user_rs.data); redirect_url = redirect_url.replace('{uid}', user_rs.data.uid); redirect_url = redirect_url.replace('{username}', user_rs.data.name); redirect_url = redirect_url.replace('{ldtoken}', user_rs.longdousertoken); self.redirectPage(redirect_url); } else { self.login_callback_customize(user_rs.data); } } } this.getRedirectLoggedinPathByClient = function(device_param, social_param) { var redirect_path = ''; switch(this.client) { case 'longdocardappios': case 'longdocardappandroid': redirect_path = 'https://card.longdo.com/privateapi/longdo/getusertoken?uid={uid}'+device_param+social_param; break; case 'longdomapappios': redirect_path = 'ldmap://map/login/{username}/{ldtoken}'; break; case 'longdotrafficappandroid': case 'longdotrafficappios': redirect_path = 'ldtraffic://login/{username}/{ldtoken}'; break; default: redirect_path = ''; break; } return redirect_path; } this.checkConnectedFacebookUser = function(fb_uid, fb_accesstoken) { longdo_lib.jq.ajax({ url: 'https://'+self.longdo_servername+'ajax/app/signin', dataType: "json", type: "POST", data: {'socialtoken': 'fb:'+fb_uid+':'+fb_accesstoken, 'locale': self.mylang}, success: function( response ) { self.processConnectedFacebookUser(response) }, beforeSend: function(xhr){ xhr.withCredentials = true; }, xhrFields: { withCredentials: true }, crossDomain: true }); } this.checkConnectedGoogleUser = function(sc_uid, sc_accesstoken, variable, callback) { if (!callback) { callback = 'self.processConnectedGoogleUser(rs)'; } if (!variable) { variable = 'rs'; } self.jsonp.json_request('https://'+self.longdo_servername+'ajax/app/signin', 'socialtoken=gg:'+sc_uid+':'+sc_accesstoken+'&locale='+self.mylang, variable, callback); } var hasClass = function(ele, clsname) { return ( (" " + ele.className + " ").replace(/[\n\t]/g, " ").indexOf(" "+clsname+" ") > -1 ); } var addClass = function(ele, name) { if (!hasClass(ele, name)) { ele.className += (ele.className ? ' ' : '') +name; } } var removeClass = function(ele, name) { if (hasClass(ele, name)) { ele.className=ele.className.replace(new RegExp('(\\s|^)'+name+'(\\s|$)'),' ').replace(/^\s+|\s+$/g, ''); } } this.fbLongdoLogin = function(evt) { if (typeof evt != 'undefined') { var ele = evt.target || evt.srcElement || evt.toElement; if (ele && hasClass(ele, 'longdo-login-social-button-waiting')) { return; } } if (!FB) { setTimeout(function() { self.fbLongdoLogin(evt); }, 200); } self.showInfoMsgLongdoLogin(self.getMessageByMsgCode('connecting_fb')); self.disableButtonOnLoginForm(); self.initialFacebook(); FB.login(function(response) { if (response.authResponse) { var fb_uid = response.authResponse.userID; var fb_accesstoken = response.authResponse.accessToken; var user = self.checkConnectedFacebookUser(fb_uid, fb_accesstoken); self.socialtoken = 'fb:'+fb_uid+':'+fb_accesstoken; } else { self.enableButtonOnLoginForm(); self.hideInfoMsgLongdoLogin(); } }, { scope: facebook_scopes}); } this.appleLongdoLogin = function(evt) { if (typeof evt != 'undefined') { var ele = evt.target || evt.srcElement || evt.toElement; if (ele && hasClass(ele, 'longdo-login-social-button-waiting')) { return; } } if (!AppleID) { setTimeout(function() { self.appleLongdoLogin(evt); }, 200); } else { try { const data = AppleID.auth.signIn(); } catch ( error ) { //handle error. } } } this.ggLongdoLogin = function(evt) { if (typeof evt != 'undefined') { var ele = evt.target || evt.srcElement || evt.toElement; if (ele && hasClass(ele, 'longdo-login-social-button-waiting')) { return; } } if (!gapi) { setTimeout(function() { self.ggLongdoLogin(evt); }, 200); } self.showInfoMsgLongdoLogin(self.getMessageByMsgCode('connecting_fb')); self.disableButtonOnLoginForm(); //self.initialGoogle(); /*var user = self._GoogleAuth.currentUser.get(); var isAuthorized = user.hasGrantedScopes(scope); if(self._GoogleAuth.isSignedIn.get()) { var user = self._GoogleAuth.currentUser.get(); var profile = user.getBasicProfile(); console.log('ID: ' + profile.getId()); console.log('Full Name: ' + profile.getName()); console.log('Given Name: ' + profile.getGivenName()); console.log('Family Name: ' + profile.getFamilyName()); console.log('Image URL: ' + profile.getImageUrl()); console.log('Email: ' + profile.getEmail()); alert('Email: ' + profile.getEmail() + ', AccToken: ' + user.getAuthResponse().id_token); var sc_uid = profile.getId() var sc_accesstoken = user.getAuthResponse().id_token; self.checkConnectedSocialUser('gg', sc_uid, sc_accesstoken); } else { self._GoogleAuth.SignIn(); } */ // Sign the user in, and then retrieve their ID. if (self._GoogleAuth.isSignedIn.get()) { var user = self._GoogleAuth.currentUser.get(); var profile = user.getBasicProfile(); var sc_uid = profile.getId() var sc_accesstoken = user.getAuthResponse().id_token; self.checkConnectedSocialUser('gg', sc_uid, sc_accesstoken); } else { self._GoogleAuth.signIn().then(function() { var user = self._GoogleAuth.currentUser.get(); var profile = user.getBasicProfile(); var sc_uid = profile.getId() var sc_accesstoken = user.getAuthResponse().id_token; self.checkConnectedSocialUser('gg', sc_uid, sc_accesstoken); }); } } var initButtonStyle = function(type, ele) { ele.style.cursor = 'pointer'; ele.style.WebkitBorderRadius = '3px'; ele.style.borderRadius = '3px'; ele.style.MozBorderRadius = '3px'; ele.style.WebkitAppearance = 'none'; ele.style.height = '32px'; ele.style.lineHeight = '32px'; ele.style.color = '#FFF'; ele.style.margin = '0px auto 15px'; if (!ele.style.width) { ele.style.width = '220px'; } if(type == 'fb') { ele.style.background = '#4c69ba'; ele.style.background = '-webkit-gradient(linear, center top, center bottom, from(#4c69ba), to(#3b55a0))'; ele.style.background = '-webkit-linear-gradient(#4c69ba, #3b55a0)'; ele.style.background = '-moz-linear-gradient(top, #3b55a0, #4c69ba)'; ele.style.background = '-ms-linear-gradient(top, #3b55a0, #4c69ba)'; ele.style.background = '-o-linear-gradient(top, #3b55a0, #4c69ba)'; ele.style.border = '1px solid #4c69ba'; ele.style.fontFamily = 'Helvetica Neue, Helvetica, Arial, lucida grande,tahoma,verdana,arial,sans-serif'; ele.style.fontSize = '17px'; } else { ele.style.background = '#357FFF'; ele.style.fontFamily = 'Helvetica,Tahoma'; ele.style.border = '1px solid #245bc2'; ele.style.fontSize = '16px'; } } this.setEventSubscribeFacebookUser = function() { if (typeof(FB) != 'undefined') { FB.getLoginStatus(function(response) { var auth = response.authResponse; if(response.status == 'connected'){ var fb_uid = auth.userID; var fb_accesstoken = auth.accessToken; var user = self.checkConnectedFacebookUser(fb_uid, fb_accesstoken); self.socialtoken = 'fb:'+fb_uid+':'+fb_accesstoken; } }); //FB.Event.subscribe('auth.authResponse.Change', function(response) { // var auth = response.authResponse; // alert('fv'); // alert (auth.userID); // if(response.status == 'connected'){ // var fb_uid = auth.userID; // var fb_accesstoken = auth.accessToken; // // var user = self.checkConnectedFacebookUser(fb_uid, fb_accesstoken); // // self.socialtoken = 'fb:'+fb_uid+':'+fb_accesstoken; // } //}); } } var fb_initialed = false; this.initialFacebook = function() { if (typeof(FB) != 'undefined' && !fb_initialed) { FB.init({ appId : facebook_app_id, status : true, // check login status cookie : true, // enable cookies to allow the server to access the session xfbml : true, // parse XFBML version : 'v2.12' }); fb_initialed = true; if(this.fb_connected == 1) { this.setEventSubscribeFacebookUser(); } } else if (typeof(FB) == 'undefined') { setTimeout(function(){ self.initialFacebook(); }, 200); } if(this.fb_connected == 1 && !document.getElementById('ld-fb-loading')) { var ld = document.createElement("div"); ld.id = "ld-fb-loading"; ld.style.fontFamily = "Helvetica"; ld.style.fontSize = "13px"; ld.style.color = "#537041"; ld.style.margin = "30px auto 50px"; ld.style.border = "1px solid #537041"; ld.style.width = "80%"; ld.style.padding = "5px 3px"; ld.style.textAlign = "center"; ld.style.backgroundColor = "#e0ffb7"; ld.style.lineHeight = "24px"; ld.innerHTML = "Please wait, connecting with Facebook .."; if(document.getElementById('signup-form')) { document.getElementById('signup-form').parentNode.insertBefore(ld, document.getElementById('signup-form').nextSibling); //document.getElementById('signup-form').parentNode.insertBefore(ld, document.getElementById('signup-form').parentNode.firstChild); document.getElementById('signup-form').style.display = 'none'; } else { document.body.insertBefore(ld, document.body.firstChild); } } } this.apple_client_id = ''; this.apple_redirect_url = ''; var apple_initialed = false; this._appleAuth = false; this.initialApple = function() { if (typeof(AppleID) != 'undefined' && !apple_initialed) { apple_initialed = true; self._appleAuth = AppleID.auth.init({ clientId : '', scope : 'name email', redirectURI : window.location.protocol+'//'+window.location.hostname+'/', // '', //state : '[STATE]', //nonce : '[NONCE]', usePopup : true //or false defaults to false }); } else if (typeof(AppleID) == 'undefined') { setTimeout(function(){ self.initialApple(); }, 200); } document.addEventListener('AppleIDSignInOnSuccess', (data) => { var token = data.detail.authorization.id_token; var base64Url = token.split('.')[1]; var base64 = base64Url.replace(/-/g, '+').replace(/_/g, '/'); var jsonPayload = decodeURIComponent(atob(base64).split('').map(function(c) { return '%' + ('00' + c.charCodeAt(0).toString(16)).slice(-2); }).join('')); var obj = JSON.parse(jsonPayload); if(obj) { console.log(obj); } }); } var gg_initialed = false; this._GoogleAuth = false; this.initialGoogle = function() { if (typeof(gapi) != 'undefined' && !gg_initialed) { /* gapi.auth2.init(function() {}); gapi.client.init({ 'apiKey': 'AIzaSyCUSFmsse6-1NuI6iMCiZGTJplby_nsrbE', 'clientId': '338003150336-eq22b14bcb7mqohrmkgrmphf53to80nb.apps.googleusercontent.com', 'scope': 'https://www.googleapis.com/auth/userinfo.profile', }).then(function () { self._GoogleAuth = gapi.auth2.getAuthInstance(); self._GoogleAuth.isSignedIn.listen(self.ggUpdateSigninStatus); }); */ gg_initialed = true; self._GoogleAuth = gapi.auth2.init({ client_id: '338003150336-eq22b14bcb7mqohrmkgrmphf53to80nb.apps.googleusercontent.com', fetch_basic_profile: true, scope: 'profile' }); } else if (typeof(gapi) == 'undefined') { setTimeout(function(){ self.initialGoogle(); }, 200); } if(this.fb_connected == 1 && !document.getElementById('ld-fb-loading')) { var ld = document.createElement("div"); ld.id = "ld-fb-loading"; ld.style.fontFamily = "Helvetica"; ld.style.fontSize = "13px"; ld.style.color = "#537041"; ld.style.margin = "30px auto 50px"; ld.style.border = "1px solid #537041"; ld.style.width = "80%"; ld.style.padding = "5px 3px"; ld.style.textAlign = "center"; ld.style.backgroundColor = "#e0ffb7"; ld.style.lineHeight = "24px"; ld.innerHTML = "Please wait, connecting with Facebook .."; if(document.getElementById('signup-form')) { document.getElementById('signup-form').parentNode.insertBefore(ld, document.getElementById('signup-form').nextSibling); //document.getElementById('signup-form').parentNode.insertBefore(ld, document.getElementById('signup-form').parentNode.firstChild); document.getElementById('signup-form').style.display = 'none'; } else { document.body.insertBefore(ld, document.body.firstChild); } } } this.ggUpdateSigninStatus = function(isSignedIn) { console.log('Signin state changed to ', isSignedIn); var user = self._GoogleAuth.currentUser.get(); if (isSignedIn) { isAuthorized = true; // Make API request // gapi.client.request(requestDetails) // Reset currentApiRequest variable. var request = gapi.client.drive.about.get({'fields': 'user'}); // Execute the API request. request.execute(function(response) { console.log(response); }); var gg_uid = response.authResponse.userID; var gg_accesstoken = response.authResponse.accessToken; var user = self.checkConnectedSocialUser('gg', gg_uid, gg_accesstoken); self.socialtoken = 'fb:'+fb_uid+':'+fb_accesstoken; } else { isAuthorized = false; self.enableButtonOnLoginForm(); self.hideInfoMsgLongdoLogin(); } } this.initSocialAccountButton = async function() { if(!longdo_lib) { longdo_lib = await new LongdoComAPI(); } var fb_login_button = getEleByID(fb_login_button_div_id); var gg_login_button = getEleByID(gg_login_button_div_id); var line_login_button = getEleByID(line_login_button_div_id); var apple_login_button = getEleByID(apple_login_button_div_id); if (fb_login_button) { (function(d, s, id) { var js, fjs = d.getElementsByTagName(s)[0]; if (d.getElementById(id)) {return;} js = d.createElement(s); js.id = id; js.async = true; js.src = "//connect.facebook.net/en_US/sdk.js"; fjs.parentNode.insertBefore(js, fjs); self.initialFacebook(); }(document, 'script', 'facebook-jssdk')); if (fb_login_button) { fb_login_button.onclick = this.fbLongdoLogin; //if (fb_login_button.offsetHeight == 0 || fb_login_button.offsetWidth == 0) { if (fb_login_button_div_id == 'fb-login-button') { // for secure.longdo page fb_login_button.innerHTML = ' Log in with Facebook'; initButtonStyle('fb', fb_login_button); } } } if (gg_login_button) { (function(d) { var js, id = 'google-jssdk', ref = d.getElementsByTagName('script')[0]; if (d.getElementById(id)) {return;} js = d.createElement('script'); js.id = id; js.src = "//apis.google.com/js/api.js"; js.async = true; js.defer = true; js.onload = function(){gapi.load('auth2', self.initialGoogle);}; js.onreadystatechange = "if (this.readyState === 'complete') this.onload()"; ref.parentNode.insertBefore(js, ref); }(document)); gg_login_button.onclick = this.ggLongdoLogin; if (gg_login_button == 'gg-login-button') { // for secure.longdo page gg_login_button.innerHTML = 'Log in with Google'; initButtonStyle('gg', gg_login_button); } } if(apple_login_button) { (function(d) { var js, id = 'apple-jssdk', ref = d.getElementsByTagName('script')[0]; if (d.getElementById(id)) {return;} js = d.createElement('script'); js.id = id; js.src = "//appleid.cdn-apple.com/appleauth/static/jsapi/appleid/1/en_US/appleid.auth.js"; js.onload = function(){self.initialApple();}; js.async = true; js.defer = true; ref.parentNode.insertBefore(js, ref); }(document)); apple_login_button.onclick = this.appleLongdoLogin; } } self.initJSONP(); } function LongdoPDPA(_longdo_lib) { var self = this; var longdo_servername = 'www.longdo.com/'; var longdo_lib = _longdo_lib ? _longdo_lib : false; var lduser = false; var config = {lang: 'th', client: 'longdo', username: '', ldtoken: '', isForceHidePDPADialog: false}; var cookie_name = 'longdo_pdpa_longdo'; var username; var ldtoken; this.pdpa_div_content_id = 'pdpa-longdocom-div'; var privacy_url = 'https://'+longdo_servername+'privacy'; // 'privacy-new'; var terms_url = 'https://map.longdo.com/terms'; var force_hide_dialog = false; this.init = async function(obj_config) { if(!longdo_lib) { longdo_lib = await new LongdoComAPI(); } longdo_lib.checkloadjscssfile('https://'+longdo_servername+'api/css/prettyPhoto.css', 'css'); await self.initUserInfo(obj_config); } this.initUserInfo = async function(obj_config) { if (!longdo_lib.jq) { setTimeout(async function(){ await self.initUserInfo(obj_config); }, 200); return; } if(!obj_config.client) { obj_config.client = document.domain.replace(/^.*:\/\//g, "").replace(/\/$/g, "").replace(/-test/g, "").replace(/\.com$/g, "").replace(/\.longdo$/g, ""); } // console.log("Clent: " + obj_config.client); longdo_lib.jq.extend(config, obj_config); // cookie_name = 'longdo_pdpa_' + config.client; username = config.username ? config.username : longdo_lib.getUsername(); ldtoken = config.ldtoken ? config.ldtoken : longdo_lib.getLdToken(); lduser = longdo_lib.getUserInfo(config.username, config.ldtoken); if(config.isForceHidePDPADialog) { force_hide_dialog = true; } await self.reload(); } this.getPdpaInfo = function() { return (lduser && lduser.web_pdpa ? lduser.web_pdpa : null); } this.reload = async function() { hidePDPAContent(); if(!(await self.isUserAllowed()) && !force_hide_dialog) { displayPDPAContent(); } } var isLoggedin = function() { return (lduser && lduser.uid); } this.isUserAllowed = async function () { if(isLoggedin()) { // authen //return !!(lduser && lduser.web_pdpa && lduser.web_pdpa[config.client] && lduser.web_pdpa[config.client].allowed); return !!(lduser && lduser.web_pdpa && lduser.web_pdpa.allowed); } else { // anonymous return !!longdo_lib.getCookie(cookie_name) || !!(await longdo_lib.getAppStorage(cookie_name)); } } this.setPDPA = async function (allowed) { longdo_lib.jq('.accept-button').attr("disabled", "disabled"); if(username && ldtoken) { longdo_lib.jq.ajax({ url: 'https://'+longdo_servername+'/ajax/app/setpdpa', dataType: "json", type: "POST", data: {'username': username, 'ldtoken': ldtoken, 'client' : config.client, 'allow': (allowed == false ? 0 : 1), 'referrer': document.location.href}, success: async function( response ) { if(response.status.code == 200) { lduser = response.data; } else if(response.status.code == 401) { // Unauthorized username = ''; ldtoken = ''; await self.setPDPA(allowed); } longdo_lib.jq('.accept-button').removeAttr("disabled", "disabled"); }, beforeSend: function(xhr){ xhr.withCredentials = true; }, xhrFields: { withCredentials: true }, crossDomain: true, async:false }); } else { // anonymous var lji = new LongdoJsInterface(); if (lji.Util.isIosNativeApp() || lji.Util.isAndroidNativeApp()) { await longdo_lib.setAppStorage(cookie_name, (allowed == false ? '' : true)); } else { longdo_lib.setCookie(cookie_name, (allowed == false ? '' : true)); } longdo_lib.jq('.accept-button').removeAttr("disabled", "disabled"); if(!!allowed) { hidePDPAContent(); } } await self.reload(); } var displayPDPAContent = function() { var re = new RegExp(privacy_url.replace(/^.*:\/\//g, "").replace(/\//g, "\\\/").replace(/www\./, ""),"i"); if (document.location.href.replace(/www\./, "").search(re) !== -1) { return; } if(document.getElementById(self.pdpa_div_content_id)){ return } var button = document.createElement("button"); button.onclick = self.setPDPA; button.innerHTML = 'ยอมรับ / Accept'; button.className = 'accept-button'; //มีการอัปเดต ความเป็นส่วนตัวของคุณและนโยบายคุกกี้ //เว็บไซต์นี้ใช้คุกกี้เราใช้คุกกี้เพื่อนำเสนอเนื้อหาและโฆษณาที่ท่านอาจสนใจ เพื่อให้ท่านได้รับประสบการณ์ที่ดียิ่งขึ้น คลิกเพื่อดูข้อมูลเพิ่มเติมเกี่ยวกับการใช้คุกกี้ของเราผ่านทาง pdpa_policy และ นโยบายคุกกี้ //Update to our Privacy & Cookie Policies //We use cookies to personalize your experience and analytics purposes to show you offers tailored to your interests. By using our website and our services without changing your settings, you agree to our use of cookies as described in our pdpa_policy and Cookie Policy. console.log(config.client); var lji = new LongdoJsInterface(); var p = document.createElement("p"); // p.innerHTML = isLoggedin() ? // 'กรุณายอมรับข้อกำหนดและเงื่อนไขการให้บริการ/ผลิตภัณฑ์ ภายใต้เครื่องหมายบริการ Longdo และ บริการ/ผลิตภัณฑ์ ในชื่อ พร้อมไป หรือ PromptPai กรุณาศึกษารายละเอียด ' : // 'เว็บไซต์นี้ใช้คุกกี้เพื่อวัตถุประสงค์ในการปรับปรุงประสบการณ์ของผู้ใช้ให้ดียิ่งขึ้น กรุณาศึกษารายละเอียด '; var cookieThText = lji.Util.isIosNativeApp() ? '' : 'และเว็บไซต์/แอปพลิเคชันนี้ใช้คุกกี้เพื่อวัตถุประสงค์ในการปรับปรุงประสบการณ์ของผู้ใช้ให้ดียิ่งขึ้น '; p.innerHTML = ['map', 'traffic'].indexOf(config.client) >= 0 ? ('Longdo ให้ความสำคัญกับข้อมูลส่วนบุคคลของท่าน ' + cookieThText + 'โปรดอ่านรายละเอียดเกี่ยวกับเงื่อนไขการใช้งานและนโยบายความเป็นส่วนตัว') : ('Longdo ให้ความสำคัญกับข้อมูลส่วนบุคคลของท่าน ' + cookieThText + 'โปรดอ่านรายละเอียดเกี่ยวกับนโยบายความเป็นส่วนตัว'); if (['map', 'traffic'].indexOf(config.client) >= 0) { p.querySelector('#term-url-link').onclick = function(e) {longdo_lib.openNewWindow(e, terms_url, config.client)}; } p.querySelector('#policy-url-link').onclick = function(e) {longdo_lib.openNewWindow(e, privacy_url, config.client)}; var p_en = document.createElement("p"); // p_en.innerHTML = isLoggedin() ? // 'Please indicate that you have read and agree to the Terms and Conditions and Privacy Policy under the product and/or service name "Longdo", and the product and/or service name "PromptPai". ' : // 'This site uses cookies from Google Analytics to give you the best experience on our site. '; var cookieEnText = lji.Util.isIosNativeApp() ? '' : 'This site/application uses cookies from Google Analytics to give you the best experience on our site. '; p_en.innerHTML = ['map', 'traffic'].indexOf(config.client) >= 0 ? ("We treat any personal data supplied by you as confidential and will only process such information according to our privacy policy. " + cookieEnText + "Please refer to the Longdo's Terms and Privacy Policy for more details.") : ("We treat any personal data supplied by you as confidential and will only process such information according to our privacy policy. " + cookieEnText + "Please refer to the Longdo's Privacy Policy for more details."); if (['map', 'traffic'].indexOf(config.client) >= 0) { p_en.querySelector('#en-term-url-link').onclick = function(e) {longdo_lib.openNewWindow(e, terms_url, config.client)}; } p_en.querySelector('#en-policy-url-link').onclick = function(e) {longdo_lib.openNewWindow(e, privacy_url, config.client)}; // var w = window.innerWidth || document.documentElement.clientWidth || document.body.clientWidth; var logo = document.createElement("div"); logo.className = 'consent-logo'; var content = document.createElement("div"); content.className = 'consent-content'; content.appendChild(p); content.appendChild(p_en); content.appendChild(button); var content_div = document.createElement("div"); content_div.className = 'consent-div'; content_div.style.zIndex = 2147483647; content_div.appendChild(logo); content_div.appendChild(content); var overlay = document.createElement("div"); overlay.id = self.pdpa_div_content_id; overlay.style.zIndex = 2147483647; overlay.appendChild(content_div); if(isLoggedin()) { overlay.className = ' cookie-consent-blocked'; } var body = document.getElementsByTagName('body')[0]; body.appendChild(overlay); } var hidePDPAContent = function() { if(document.getElementById(self.pdpa_div_content_id)) { document.getElementById(self.pdpa_div_content_id).remove(); } } } function LongdoComAPI() { var self = this; var thisPageUsingOtherJSLibrary = false; var longdo_servername = 'www.longdo.com/'; this.jq = false; this.initJQuery = function() { if (typeof jQuery == 'undefined') { if (typeof $ == 'function') { thisPageUsingOtherJSLibrary = true; } var rs = self.getScript('https://'+longdo_servername+'/api/prettyPhoto/js/jquery-1.6.1.min.js', function() { if (typeof jQuery=='undefined') { self.jq = 'failed'; self.consoleLog('Error: Load jQuery Failed.'); } else { if (thisPageUsingOtherJSLibrary) { self.jq = jQuery; } else { self.jq = jQuery.noConflict(); } } document.longdocomapijq = self.jq; // ref. in prettyPhoto.js }); } else { self.jq = jQuery; document.longdocomapijq = self.jq; // ref. in prettyPhoto.js } } this.getCookie = function(cname) { var name = cname + "="; var decodedCookie = decodeURIComponent(document.cookie); var ca = decodedCookie.split(";"); for(var i = 0; i } error console.log(error); return ""; } } return ""; } this.setAppStorage = async function(key, val) { var lji = new LongdoJsInterface(); if (lji.Util.isIosNativeApp() || lji.Util.isAndroidNativeApp()) { try { const result = await lji.addStorage({ key: key, value: encodeURI(val) }) // {Boolean} result console.log(result) } catch (error) { // {<{code: Number, message: String}>} error console.log(error) } } } this.consoleLog = function(msg) { if(window.console && window.console.log) { console.log(msg); } } this.getScript = function(url, success) { (function(d, s, id) { var js, fjs = d.getElementsByTagName(s)[0]; if (d.getElementById(id)) {return;} js = d.createElement(s); js.id = id; js.async = true; js.defer = true; js.src = url; fjs.parentNode.insertBefore(js, fjs); js.onload = success; js.onreadystatechange = "if (this.readyState === 'complete') this.onload()"; }(document, 'script', 'longdocom-jq')); } this.getUserInfo = function(uname, ldtoken) { let lduser = false; if(!uname) {uname = self.getUsername();} if(!ldtoken) {ldtoken = self.getLdToken();} if(uname && ldtoken) { self.jq.ajax({ url: 'https://'+longdo_servername+'/ajax/app/userinfo', dataType: "json", type: "POST", data: {'username': uname, 'ldtoken': ldtoken}, success: function( response ) { if(response.status.code == 200) { lduser = response.data; } }, beforeSend: function(xhr){ xhr.withCredentials = true; }, xhrFields: { withCredentials: true }, crossDomain: true, async:false }); } return lduser; } this.getUsername = function() { return self.getCookie('longdouser_username'); } this.getLdToken = function() { return self.getCookie('longdouser_longdousertoken'); } var filesadded = ""; //list of files already added this.loadjscssfile = function(filename, filetype) { var lastupdated = '?20210801'; if (filetype=="js") { //if filename is a external JavaScript file var fileref=document.createElement('script') fileref.setAttribute("type","text/javascript") fileref.setAttribute("src", filename+lastupdated) } else if (filetype=="css") { //if filename is an external CSS file var fileref=document.createElement("link") fileref.setAttribute("rel", "stylesheet") fileref.setAttribute("type", "text/css") fileref.setAttribute("href", filename+lastupdated) } if (typeof fileref!="undefined") document.getElementsByTagName("head")[0].appendChild(fileref); } this.checkloadjscssfile = async function(filename, filetype) { if (filesadded.indexOf("["+filename+"]") == -1) { self.loadjscssfile(filename, filetype) filesadded += "["+filename+"]"; // List of files added in the form "[filename1],[filename2],etc" } } this.sleep = function (ms) { return new Promise(resolve => setTimeout(resolve, ms)); } this.openNewWindow = function(e, url, client) { e.preventDefault() var userAgent = getUserAgentMeta(client) if ('flutter_inappwebview' in window) { window.flutter_inappwebview.callHandler('openUrl', url); } else if (typeof Android !== 'undefined') { Android.openUrl(url) } else if (userAgent === 'iOS application') { if (((window.webkit || {}).messageHandlers || {}).openUrl) { window.webkit.messageHandlers.openUrl.postMessage({ url: url }) } else { window.location.href = `https://native.openUrl?url=${encodeURIComponent(url)}` } } else { window.open(url, '_blank') } return false } var getUserAgentMeta = function(client) { var userAgentMeta = document.querySelector('meta[name="user_agent"]') if (userAgentMeta !== null) { var content = userAgentMeta.getAttribute('content') var re = new RegExp(client,"i"); if (navigator.userAgent.search(re) !== -1 && content === 'iOS application') { // promptpai ios app return content } else if (content === 'iOS application') { // promptpai ios browser or other ios app return 'iOS browser' } if (content !== null) { return content } else { return '' } } else { var ua = window.navigator.userAgent || window.navigator.vendor || window.opera || '' if (ua.indexOf('Mac') > -1 && ua.indexOf('Version') < 0 && ua.indexOf('LongdoJsInterface') > -1) { return 'iOS application' } } return '' } var getDomainName = function() { let hostName = document.location.hostname; return hostName.substring(hostName.lastIndexOf(".", hostName.lastIndexOf(".") - 1) + 1); } self.initJQuery(); }