
var accall_select_opt="";
//var line_alls=[];
var fanpage_all = [];
var $=jQuery.noConflict();

defer(function () {
    //alert("jQuery is now loaded");
	console.log("jquery loaded");
	startupJQuery();
});

function defer(method) {
    if (window.jQuery) {
        method();
    } else {
        setTimeout(function() { defer(method) }, 50);
    }
}

if (typeof jQuery == 'undefined') {
    alert('jQuery HAS NOT been loaded exit app and reload again.');
}
window.onload = function() {
	/*
	if (window.jQuery) {  
       // jQuery is loaded  
       //alert("Yeah!");
	} else {
		alert("jquery not loaded");
		location.reload();
	}
	if($ === jQuery){
	}else{
		alert("jquery not loaded");
		location.reload();
	}
	if($ === jQuery){
	}else{
		alert("jquery not loaded");
		location.reload();
	}
	if ('undefined' == typeof window.jQuery) {
    // jQuery not present
		alert("jquery not loaded");
		location.reload();
	} else {
		// jQuery present
	}
	*/
}
window.onerror = function(error) {
  // do something clever here
  //alert(error); // do NOT do this for real!
  console.log(error);
};

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



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

jQuery(document).ready(function ($) {
	iziToast.settings({
		timeout: 3000, // default timeout
		resetOnHover: true,
		// icon: '', // icon class
		transitionIn: 'flipInX',
		transitionOut: 'flipOutX',
		position: 'bottomRight', // bottomRight, bottomLeft, topRight, topLeft, topCenter, bottomCenter, center
		onOpen: function () {
			//console.log('callback');
		},
		onClose: function () {
			//console.log("callback");
		}
	});
	
	/*
	function injectScript(src) {
		return new Promise((resolve, reject) => {
			const script = document.createElement('script');
			script.src = src;
			script.addEventListener('load', resolve);
			script.addEventListener('error', e => reject(e.error));
			document.head.appendChild(script);
		});
	}

	injectScript('https://example.com/script.js')
		.then(() => {
			console.log('Script loaded!');
		}).catch(error => {
			console.error(error);
		});
		
	var scriptNames = [
		"https://code.jquery.com/jquery.min.js",
		"example.js"
	  ];
	  for (var i = 0; i < scriptNames.length; i++) {
		var script = document.createElement('script');
		script.src = scriptNames[i];
		script.async = false; // This is required for synchronous execution
		document.head.appendChild(script);
	  }
	*/
	/*
	var myScript2 = document.createElement("script");
	myScript2.setAttribute("src", MAIN_URL + PARTNER + "?version="+ (new Date().getTime()) );
	myScript2.setAttribute("crossorigin", "anonymous");
	myScript2.setAttribute("async", "false");
	myScript2.setAttribute("defer", "");
	document.head.appendChild(myScript2);
	*/
	
	console.log('document ready');
	changeIndexPageTitle();
	
});

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

function setValue (key,value) {
	if(key) {
		//var value = document.getElementById("valueInput").value;
		xdLocalStorage.setItem(key, value, function (data) {
			if(data.success) {
				//document.getElementById('result').innerHTML = 'Your data has been successfully stored.';
			} else {
				//document.getElementById('result').innerHTML = 'Ops, could not store your data.';
			}
		});
	} else {
		//alert('You must enter a key.');
	}
}
function getItem (key) {
	//document.getElementById('result').innerHTML ='';
	//var key = document.getElementById("getInput").value;
	if(key) {
		xdLocalStorage.getItem(key, function (data) {
			//document.getElementById('result').innerHTML = 'got value: "' + data.value + '" for key: "' + data.key + '"';
		});
	} else {
		//alert('You must enter a key to get.');
	}
}
function removeItem (key) {
	if(key) {
		xdLocalStorage.removeItem(key, function (data) {
			//document.getElementById('result').innerHTML = 'Key was removed';
		});
	} else {
		//alert('You must enter a key to remove.');
	}
}
function keyName (index) {
	if(index) {
		xdLocalStorage.key(index, function (data) {
			//document.getElementById('result').innerHTML = 'Key name for index ' + index + ' is: '+data.key;
		});
	} else {
		//alert('You must enter a key index.');
	}
}
function clearAll () {
	//document.getElementById('result').innerHTML ='';
	xdLocalStorage.clear(function (data) {
		//document.getElementById('result').innerHTML = 'LocalStorage was cleared.';
	});
}


/////////////////////////////////////////////////////////////////
function startupJQuery(){
	console.log("Gui Jquery startup");
	//progressbarx();
	$('button[typeaccount="premium"]').click(function () {
		funtion_name = $(this).attr('id');
		call_myFun = window[funtion_name];
		start_ext(call_myFun);
	});
	$('button[typeaccount="vip"]').click(function () {
		funtion_name = $(this).attr('id');
		call_myFun = window[funtion_name];
		start_vip(call_myFun);
	});
	$('button[typeaccount="premium_next"]').click(function () {
		funtion_namex = $(this).attr('id');
		call_myFunx = window[funtion_namex];
		start_ext(call_myFunx);
	});
	$('button[typeaccount="premium_stop"]').click(function () {
		Swal.fire({
			title: 'คุณต้องการทำรายการนี้?',
			text: "คุณจะหยุดระบบนี้ไว้ชั่วคราว?",
			type: 'warning',
			showCancelButton: true,
			confirmButtonColor: '#3085d6',
			cancelButtonColor: '#d33',
			confirmButtonText: 'Yes'
		}).then((result) => {
			if (result.value) {
				names = $(this).attr('id');
				//call_myFun_stop  =  window[funtion_name];	
				id_element = names.replace('_stop', '');
				//console.log('id_element:'+id_element);
				classx = $('#' + id_element);
				stopx = $('.' + id_element + '_stop');
				play = $('.' + id_element + '_play');
				next = $('.' + id_element + '_next');
				timeout = $('.' + id_element + '_settimeout');
				stop_text = $('.' + id_element + '_stop_text');
				time_text = $('.' + id_element + '_time');
				bittext = $('.' + id_element + '_bit');
				//console.log(names);
				localStorage.setItem(names, '1');
				stopx.hide();
				play.hide();
				next.show();
				stop_text.show();
				time_text.hide();
				clearTimeout(id_element + '_time_out');
				// alert(stop_ok);
				return false;
			}
		})
	});
	$('.unlock_account:checkbox').change(function () {
		// this will contain a reference to the checkbox   
		if (this.checked) {
			$('.unlock_account').prop('checked', false);
			start_ext(unlock);
		} else {
			$('.unlock_account').prop('checked', true);
			Swal.fire({
				title: 'คุณจะออกจากระบบ ?',
				text: "ถ้าคุณต้องการออกจากระบบ  กดปุ่ม Yes",
				type: 'warning',
				showCancelButton: true,
				confirmButtonColor: '#3085d6',
				cancelButtonColor: '#d33',
				confirmButtonText: 'Yes'
			}).then((result) => {
				if (result.value) {
					$('.unlock_account').prop('checked', false);
					$('.all_account').hide();
					$('.free_account').show();
					$('#access_token_div').hide();
					$('#access_token_div_intragram').hide();
					chrome.storage.local.clear(function () {
						var error = chrome.runtime.lastError;
						if (error) {
							console.error(error);
						}
					});
					Swal.fire('ออกจากระบบ  เรียบร้อย', 'หากคุณต้องการเข้าระบบ  อีกครั้งให้กดที่รุปกุญแจอีกครั้ง', 'success')
				}
			})
		}
	});
	$('input,textarea').bind('paste', function (e) {
		var elem = $(this);
		setTimeout(function () {
			var text = elem.val();
			text = text.split('?__tn__=');
			text = text[0].split('&__xts__');
			text = text[0].split('?__xts__');
			text = text[0].replace(/'/g, "");
			elem.val(text);
		}, 100);
	});
	$('#fst789_log_in_cancel').click(function () {
		hide_log_in_box();
	});
	$('#refresh_page').click(function () {
		window.location.href = window.location.href+'openbroadcast';
		//line_alls=[];
		//get_line();
	});
	
	$("#btn_menu_manual").on("click", function (e) {
		try{
			manual_detail();	//from host customer.js
		}catch(e){
			alert('Error:'+e);
		}
	});
	$("#btn_menu_contact").on("click", function (e) {
		try{
			contact_detail();	//from host customer.js
		}catch(e){
			alert('Error:'+e);
		}
	});
	$("#btn_menu_moreinfo").on("click", function (e) {
		try{
			moreinfo_detail();	//from host customer.js
		}catch(e){
			alert('Error:'+e);
		}
	});
	$("#btn_menu_downloadapp").on("click", function (e) {
		try{
			download_software();	//from host customer.js
		}catch(e){
			alert('Error:'+e);
		}
	});
	console.log("Gui Jquery ready");
}
///////////////////////////////////////////////////////////////////

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

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

function getAppTitle(){
	try{
		var manifestData = chrome.runtime.getManifest();
		//console.log(manifestData.version);
		//console.log(manifestData.default_locale);
		var apptitle = manifestData?.browser_action?.default_title;	//in gfunc.js

		if(!apptitle){
			apptitle = manifestData.short_name; //+"."+manifestData.version;
		}
		console.log("App title:" + apptitle);
		return apptitle;
	}catch(e){}
	return "";
}

function changeIndexPageTitle(){
	try{
		let app_caption_title = getAppTitle();
		if(typeof APP_VERSION!=="undefined" && APP_VERSION!=null && APP_VERSION!=""){
			app_caption_title = app_caption_title.replace(".ENT","");
			app_caption_title = app_caption_title.replace("v"+APP_VERSION.replace("TF.",""),"");
		}else{
			let manifestData = chrome.runtime.getManifest();
			APP_VERSION = manifestData.version;
		}
		document.title = app_caption_title +" v"+APP_VERSION.replace("TF","");
	}catch(e){}
	return "";
}

async function onCompleteGui(){
	
	document.getElementById('mainFacebookFanpageInbox').style.display='none';
	
	console.log("ready use on complete Gui"); 
	
	document.getElementById("logo_version").innerHTML = '  CACTUS v.'+APP_VERSION;
	
	document.addEventListener('DOMContentLoaded', function(event) {
	  //the event occurred
	  console.log('DOMContentLoaded');
	})
	for (var radioCounter = 0 ; radioCounter < document.getElementsByName('cfg_schedule').length; radioCounter++) {
		  document.getElementsByName('cfg_schedule')[radioCounter].onchange = function() {
			//VALUE OF THE CLICKED RADIO ELEMENT
			this.value=true;
			if (this.id=='cfg_schedule_now'){
				document.getElementById('cfg_schedule_later').value=false;
				document.getElementById('lbl_dtschedule').style.display='none';
			}else if(this.id=='cfg_schedule_later'){
				document.getElementById('cfg_schedule_now').value=false;
				document.getElementById('lbl_dtschedule').style.display='block';
				//var now = new Date();
				//now.setDate(now.getDate() + 10);
				//rome(dtschedule,{initialValue: new Date(),min: new Date(), max: now });
				var dtschedule = document.getElementById('dtschedule');
				rome(dtschedule).setValue(new Date());
			}
			
		  }
	}

	txt_error_report = document.getElementById("txt_error_report");
	
	document.getElementById("logmeclose").addEventListener("click", function(event) {
		//event.preventDefault();
		document.getElementById('id01login').style.display='none';
	});
	
	document.getElementById("signin_button").addEventListener("click", function(event) {
		document.getElementById('user_name').innerHTML = '';
		document.getElementById('user_valid_date').innerHTML = '';
		document.getElementById('user_days_left').innerHTML = '';
		document.getElementById('plan_package').innerHTML = '';
		document.getElementById('user_plan_login_detail').style.display = 'none';
		document.getElementById('mainFacebookFanpageInbox').style.display='none';
		document.getElementById('id01login').style.display='block';
		
		if(SHOW_ALWAYS_PROMOTION_BEFORE_ALL_USERS_LOGIN==true){	//tf_promotion.js
			show_promotion();	//tf_customer.js
		}
		show_alert();	//tf_customer.js
		
	});
	document.getElementById("signout_button").addEventListener("click", function(event) {

		signout();	//bp_tf_broadcast_fb_fanpage.js
		
	});
	
	const checkbox = document.getElementById('mypolicy');
	const loginsubmit = document.getElementById('loginsubmit');
	if(loginsubmit){
		loginsubmit.disabled = true;
		loginsubmit.style.backgroundColor  = "#989b9c";
		loginsubmit.style.color = "#d6cfcf";
		loginsubmit.style.cursor = "default";
	}
	if(checkbox){
		checkbox.addEventListener('change', (event) => {
			if(loginsubmit){
				if (event.currentTarget.checked) {
					loginsubmit.disabled = false;
					loginsubmit.style.backgroundColor  = "#022f52";
					loginsubmit.style.color = "#FFF";
					loginsubmit.style.cursor = "pointer";
				} else {
					loginsubmit.disabled = true;
					loginsubmit.style.backgroundColor  = "#989b9c";
					loginsubmit.style.color = "#d6cfcf";
					loginsubmit.style.cursor = "default";
				}
			}
		});
	}
	
	const mypolicy_link = document.getElementById("mypolicy_link");
	if(mypolicy_link){
		mypolicy_link.addEventListener('click', (event) => {
			if(CT_TF_MY_POLICY){	//customer.js
				window.open(CT_TF_MY_POLICY,"_blank");
			}
		});
	}
	
	document.getElementById("loginsubmit").addEventListener("click", function(event) {
		//login validate here
		let form_email=document.getElementById("uname").value;
		let form_key=document.getElementById("psw").value;
		let rememberme=document.getElementById('rememberme').checked;
		if(rememberme==true || rememberme=="on"){rememberme=1;}else{rememberme=0;}
		let uname = document.getElementById('uname');
		let psw = document.getElementById('psw');
		if(typeof uname!=="undefined" && uname!=null && uname.value.trim()!=""){
		}else{
			Swal.fire({
				title: 'มีปัญหา',
				html: "คุณยังไม่ได้ใส่อีเมล์สำหรับล็อกอิน <br />",
				type: 'error',
				confirmButtonColor: '#3085d6',
				confirmButtonText: 'OK'
			});
			uname.focus();
			return;
		}
		if(typeof psw!=="undefined" && psw!=null && psw.value.trim()!=""){
		}else{
			Swal.fire({
				title: 'มีปัญหา',
				html: "คุณยังไม่ได้ใส่รหัสผ่านสำหรับล็อกอิน <br />",
				type: 'error',
				confirmButtonColor: '#3085d6',
				confirmButtonText: 'OK'
			});
			psw.focus();
			return;
		}
		console.log("loginsubmit call startFbFanpageLoad in tp_tf_fb_fanpage and start_func in tp_tf_auth from tp_tf_gui get login and facebook token");
		start_func(startFbFanpageLoad,form_email,b64EncodeUnicode(form_key),rememberme,false);	//startFbFanpageLoad function in startup.js
	});
	
	const togglePassword = document.querySelector('#togglePassword');
	const login_password = document.querySelector('#psw');
	togglePassword.addEventListener('click', function (e) {
		// toggle the type attribute
		const type = login_password.getAttribute('type') === 'password' ? 'text' : 'password';
		login_password.setAttribute('type', type);
		// toggle the eye slash icon
		this.classList.toggle('fa-eye-slash');
	});
	
	
	//document.getElementById('id01login').style.display='block';
	//func_call,email,key,rememberme,isOnStartup
	document.getElementById("start_broadcast").disabled = true;
	
	console.log("on startup call startFbFanpageLoad in tp_tf_fb_fanpage and start_func in tp_tf_auth from tp_tf_gui get login and facebook token");
	start_func(startFbFanpageLoad,"","","",true);	//on start up	//startFbFanpageLoad function in bp_tf_broadcast_fb_fanpage.js
	
	try{
		let move_to_done_folder_div = document.getElementById("move_to_done_folder_div");
		if(typeof move_to_done_folder_div!=="undefined" && move_to_done_folder_div!=null){
			if(IS_SHOW_MOVE_TO_DONE_FOLDER_DIV){	//customer.js
				move_to_done_folder_div.style.display = "inline-block";
			}else{
				move_to_done_folder_div.style.display = "none";
			}
		}
	}catch(e){}
	try{
		let get_fb_fanpage = document.getElementById("get_fb_fanpage");
		if(typeof get_fb_fanpage!=="undefined" && get_fb_fanpage!=null){
			if(IS_SHOW_GET_FB_FANPAGE_BTN){	//customer.js
				get_fb_fanpage.style.display = "inline-block";
			}else{
				get_fb_fanpage.style.display = "none";
			}
		}
	}catch(e){}
	try{
		let speed_send_option = document.getElementById("group_speed_send_option");
		if(typeof speed_send_option!=="undefined" && speed_send_option!=null){
			if(IS_SHOW_SPEED_LIMIT_OPTION){	//customer.js
				speed_send_option.style.display = "inline-block";
			}else{
				speed_send_option.style.display = "none";
			}
		}
	}catch(e){}
	try{
		let tf_header_version = document.getElementById("tf_version");
		if(typeof tf_header_version!=="undefined" && tf_header_version!=null){
			if(IS_SHOW_TF_HEADER_VERSION){	//customer.js
				tf_header_version.style.display = "inline-block";
			}else{
				tf_header_version.style.display = "none";
			}
		}
	}catch(e){}
	try{
		let text_spintext_Preamble = document.getElementById("text_spintext_Preamble");
		if(typeof text_spintext_Preamble!=="undefined" && text_spintext_Preamble!=null){
			if(IS_SHOW_TF_RND_MSGSEND_HEADER){	//customer.js
				text_spintext_Preamble.style.display = "inline-block";
			}else{
				text_spintext_Preamble.style.display = "none";
			}
		}
	}catch(e){}
	try{
		let text_spintext_Conclusion = document.getElementById("text_spintext_Conclusion");
		if(typeof text_spintext_Conclusion!=="undefined" && text_spintext_Conclusion!=null){
			if(IS_SHOW_TF_RND_MSGSEND_FOOTER){	//customer.js
				text_spintext_Conclusion.style.display = "inline-block";
			}else{
				text_spintext_Conclusion.style.display = "none";
			}
		}
	}catch(e){}
	
	

	try{
		if (typeof login_footer_container == 'function') { 
			//setTimeout(function(){
				login_footer_container();
			//},3000);
		}
	}catch(e){}
	try{
		if (typeof header_detail == 'function') {
			setTimeout(function(){
				header_detail();
			},3000);
		}
	}catch(e){}
	try{
		if (typeof footer_detail == 'function') {
			setTimeout(function(){
				footer_detail();
			},3000);
		}
	}catch(e){console.log(e);}
	try{
		if (typeof footer_remark == 'function') {
			setTimeout(function(){
				footer_remark();
			},3000);
		}
	}catch(e){console.log(e);}
	try{
		if (typeof header_top_tf_main_menu == 'function') {
			header_top_tf_main_menu();
		}
	}catch(e){console.log(e);}
	
	try{
		var dnow = new Date();
		var curdate = dnow.toJSON().slice(0,10);
		server_date = curdate;
		ldb.get('pop_server_date', function (pop_server_date) {
			if(typeof pop_server_date!=="undefined" && pop_server_date!=null){
				var ul = pop_server_date.split("|");
				if(ul.length>1){
					server_date = ul[1];
				}
			}
		});
	}catch(e){}
	
	setTimeout(function(){
		document.getElementById("btn_menu_manual_fb_fp").addEventListener("click", function(event) {
			try{
				manual_detail();	//from host customer.js
			}catch(e){
				console.log(e);
			}
		});
		document.getElementById("btn_menu_contact_fb_fp").addEventListener("click", function(event) {
			try{
				contact_detail();	//from host customer.js
			}catch(e){
				console.log(e);
			}
		});
		document.getElementById("btn_menu_moreinfo_fb_fp").addEventListener("click", function(event) {
			try{
				moreinfo_detail();	//from host customer.js
			}catch(e){
				console.log(e);
			}
		});
		document.getElementById("btn_menu_downloadapp_fb_fp").addEventListener("click", function(event) {
			try{
				download_software();	//from host customer.js
			}catch(e){
				console.log(e);
			}
		});
		
		try{
			document.getElementById("btn_menu_config_oa_tl").addEventListener("click", function(event) {
				try{
					let modalConfig = document.getElementById("modalConfig");
					modalConfig.style.width = "350px";
					modalConfig.style.height = "350px";
					$('#modalConfig').w2popup();
				}catch(e){
					console.log(e);
				}
			});
		}catch(e){}
		
		try{
			document.getElementById("btn_menu_config_fb_fp").addEventListener("click", async function(event) {
				try{
					//let modalConfig = document.getElementById("modalConfig");
					//modalConfig.style.width = "350px";
					//modalConfig.style.height = "350px";
					//$('#modalConfig').w2popup();
					let new_user_id = localStorage.getItem('fb_user_id');
					//let fbAccessIdGen = await localStorage.getItem("fbAccessIdGen"+'_'+new_user_id);
					
					let fbAccessTokenGen = await localStorage.getItem("fbAccessTokenGen"+'_'+new_user_id);
					if(typeof fbAccessTokenGen!=="undefined" && fbAccessTokenGen!=null && fbAccessTokenGen!=""){
						if(fbAccessTokenGen){
							
						}else{
							fbAccessTokenGen="";
						}
					}else{
						fbAccessTokenGen="";
					}
					const { value: textToken } = await Swal.fire({
						title: 'กรุณากรอกเฟสบุ๊ก Token แล้วกดปุ่ม Ok เพื่อทำการบันทึก Token',
						input: 'textarea',
						inputValue: fbAccessTokenGen,
						inputPlaceholder: 'ใส่ Facebook Token ของคุณที่นี่...',
						inputAttributes: {
							'aria-label': 'Facebook Token: '
						},
						showCancelButton: true
					});
					//let myToken = textToken.replaceAll('\n','');
					let myToken = null;
					if (textToken){
						myToken=textToken.replaceAll('\n','');
					}
					
					if (myToken) {
						localStorage.setItem('fbAccessIdGen'+'_'+new_user_id, new_user_id.trim(),'');
						let tk = 'fbAccessTokenGen'+'_'+new_user_id;
						localStorage.setItem(tk, myToken.trim());
						
						console.log("onClick login_fb_get_token");
						await login_fb_get_token();	//gfunc.js
					}
					
				}catch(e){
					console.log(e);
				}
			});
		}catch(e){}
		
		var element =  document.getElementById('btn_menu_promotion_fb_fp');
		if (typeof(element) != 'undefined' && element != null)
		{
			document.getElementById("btn_menu_promotion_fb_fp").addEventListener("click", function(event) {
				try{
					show_promotion();	//from host customer.js
				}catch(e){
					console.log(e);
				}
			});
		}

	},5000);
	//if (isUserPass == false) {return false;}
	//"ok|16/12/2020 - 31/12/2020|soymos@gmail.com|4|0|ลูกค้า|3|2020-12-27|1609004915851|2020-12-26|TL.1.0.3|1609004921625|2020-12-26"
	/*
	0: "ok"
	1: "16/12/2020 - 31/12/2020"
	2: "soymos@gmail.com"
	3: "4"
	4: "0"
	5: "ลูกค้า"
	6: "3"
	7: "2020-12-27"
	8: "1609004915851"
	9: "2020-12-26"
	10: "TL.1.0.3"
	11: "1609004921625"
	12: "2020-12-26"
	*/
	
};
function ready(fn) {
  if (document.readyState != 'loading'){
    fn();
  } else if (document.addEventListener) {
    document.addEventListener('DOMContentLoaded', fn);
	console.log("ready state");
  } else {
    document.attachEvent('onreadystatechange', function() {
      if (document.readyState != 'loading')
        fn();
    });
  }
}

(function(){
    var tId = setInterval(function() {
		try{
			if (document.readyState === "complete") {
				clearInterval(tId);
				tId = setInterval(function() {
					if (document.getElementsByName('cfg_schedule').length>1) {
						clearInterval(tId);
						onCompleteGui();
					}
				}, 500);
				//onCompleteGui();
			}
		}catch(e){}
    }, 500);
})();
