var first_document_title = document.title;
var first_load = true;
var content_offset_y = 0;
var content_offset_y_lg = 0;
var content_offset_y_sm = 0;
var lastScrollTop = 0;
var width = window.innerWidth;
var secondaryArticleViewSent = false;
var currentStateArticle = 1;
var currentSharingUrl = "";
var isZhHant = false;
var isStickyNavBar = false;
var defaultCover = "/public/images/Sinchew-cover.png?v=0.3";
var defaultCoverFinance = "/public/images/Sinchew-cover-finance.jpg?v=0.3";
var isArticlePage = false;

var isMobile = {
    Android: function() {
        return navigator.userAgent.match(/Android/i);
    },
    BlackBerry: function() {
        return navigator.userAgent.match(/BlackBerry/i);
    },
    iOS: function() {
        return navigator.userAgent.match(/iPhone|iPad|iPod/i);
    },
    Opera: function() {
        return navigator.userAgent.match(/Opera Mini/i);
    },
    Windows: function() {
        return navigator.userAgent.match(/IEMobile/i);
    },
    any: function() {
        return (isMobile.Android() || isMobile.BlackBerry() || isMobile.iOS() || isMobile.Opera() || isMobile.Windows());
    }
    };

	var isMobileApp = {
		AndroidApp: function() {
			return navigator.userAgent.match(/Android/i) && navigator.userAgent.match(/wv/i);
		},
		iOSApp: function() {
			return navigator.userAgent.match(/iPhone|iPad|iPod/i) && navigator.userAgent.match(/wv/i);
		},
		anyApp: function() {
			return (isMobileApp.AndroidApp() || isMobileApp.iOSApp());
		}
	};

var userPlatform = isMobileApp.anyApp() ? 'app' : 'web';

document.addEventListener('DOMContentLoaded', function(e) {
	jQuery('a.internalLink:not([target="_blank"])').click(internalLinkRegClickEvent);
	
	if (!isMobileApp.anyApp()) {
		if (getCookie('cookieConsent') !== 'true') {
			$('.cookie-consent-banner').removeClass('hidden');
		}
		window.scrollTo(0, 0);
	}

	if($(".desktop-sticky-header-wrapper").length){
		content_offset_y_lg = $(".desktop-sticky-header-wrapper").offset().top -10;
		content_offset_y_sm = $(".sticky-header-wrapper").offset().top -10;
	}

	if($("body").width < 920){
		content_offset_y = content_offset_y_sm;
	}
	else{
		content_offset_y = content_offset_y_lg;
	}
	scrollProgressBar();
	advertorialRegistrationAndEvent();
	checkLogin();
	loadGallery();
	renderCurrentMenuItem();
	initPostView();
	//initCustomPostView();
	initFont();
//	loadMarquee();
	loadMarquee_v2();
	loadBookmark();
	initArticlePrevNextPages();
	initHotTopic();
	initMyFavPreference();
	fixClampText();
	showAppPromo();
	resetCnTypeExpiryDate();
	articleContentProgressTracker();
	articlePageProgressTracker();

	if(!$(".webview").length){
		// $(window).bind("popstate", function(event) {
		// 	if(first_load == true){}else{
		// 		if(event.originalEvent.state && event.originalEvent.state.internal_link && event.originalEvent.state.internal_link == 'Y'){
		// 			document.title=event.originalEvent.state.page_title;
		// 			ajaxLoadContent(event.originalEvent.state.page_href);
		// 		}
		// 		else{
		// 			document.title=first_document_title;
		// 			ajaxLoadContent(document.location);
		// 		}
		// 	}
		// });
	}

	if($( ".article-page" ).length){
		isArticlePage = true;
	}

	// if(jQuery('.main-header').length){	

	// 	var hot_topic_bar_wrapper_height= 0;
	// 	if(isArticlePage==true && jQuery('.hot-topic-bar-wrapper').length ){
	// 		hot_topic_bar_wrapper_height= jQuery('.hot-topic-bar-wrapper').height();
	// 	}

	// 	var sticky_nav_offset = jQuery('.main-header').offset().top + jQuery('.main-header').height() + hot_topic_bar_wrapper_height;

	// 	const customTemplates = ['prn2023']; 
	// 	let isCustomTemplate = false;		
	// 	for(let cls of customTemplates) {
	// 	  if($('body').hasClass(cls)) {
	// 		isCustomTemplate = true;
	// 		break;
	// 	  }
	// 	}

	// 	$( window ).scroll(function() {

	// 		if(isArticlePage==false){
	// 			if(isCustomTemplate==false){
	// 				stickyMenu();
	// 			}
	// 		}

	// 		if (jQuery(window).scrollTop() >= sticky_nav_offset) {
	// 			jQuery('#floating-breadcrumb').addClass("sticky");
	// 			if($( ".scroll-up" ).length){
	// 				jQuery('.scroll-up').removeClass("hidden");
	// 			}
	// 		} else {
	// 			jQuery('#floating-breadcrumb').removeClass("sticky");
	// 			if($( ".scroll-up" ).length){
	// 				jQuery('.scroll-up').addClass("hidden");					
	// 			}				
	// 		}	
	// 	});
	// }

	if(jQuery('.main-header').length){

		var hot_topic_bar_wrapper_height= 0;
		if(isArticlePage==true && jQuery('.hot-topic-bar-wrapper').length ){
			hot_topic_bar_wrapper_height= jQuery('.hot-topic-bar-wrapper').height();
		}

		var top_ads_frame_height = 0;
		var top_ads_frame_height_interval = setInterval(() => {
			if(jQuery('.ads-frame.mobile-ads-frame').length) {
				top_ads_frame_height = jQuery('.ads-frame.mobile-ads-frame').first().height();
				clearInterval(top_ads_frame_height_interval);
			}
		}, 1000);
		var sticky_nav_offset_1 = jQuery('.main-header').offset().top + jQuery('.main-header').height();
		sticky_nav_offset_1 = (sticky_nav_offset_1 < 1) ? 1 : sticky_nav_offset_1;
		var sticky_nav_offset_2 = jQuery('.main-header').offset().top + jQuery('.main-header').height() + jQuery('.desktop-sticky-header-wrapper').height();

		$(window).resize(function() {
			sticky_nav_offset_1 = jQuery('.main-header').offset().top + jQuery('.main-header').height();
			sticky_nav_offset_1 = (sticky_nav_offset_1 < 1) ? 1 : sticky_nav_offset_1;
			sticky_nav_offset_2 = jQuery('.main-header').offset().top + jQuery('.main-header').height() + jQuery('.desktop-sticky-header-wrapper').height();
		});

		const customTemplates = ['prn2023','custom'];
		let isCustomTemplate = false;		
		for(let cls of customTemplates) {
		  if($('body').hasClass(cls)) {
			isCustomTemplate = true;
			break;
		  }
		}

		let prevScrollPos = jQuery(window).scrollTop();

		$( window ).scroll(function() {

			if(isArticlePage==false){
				if(isCustomTemplate==false){
					stickyMenu();
				}
			}

			if(isArticlePage==true && isStickyNavBar==false) {
				if(jQuery(window).scrollTop() >= sticky_nav_offset_1 && jQuery(window).scrollTop() < sticky_nav_offset_2) {
					jQuery('#floating-breadcrumb').addClass("sticky");
					var topHeaderPosition = jQuery('#body-header-wrapper').height() - jQuery(window).scrollTop() + top_ads_frame_height;
					jQuery('#floating-breadcrumb').css("transform", "translateY(" + topHeaderPosition + "px)");
	
					if($( ".scroll-up" ).length){
						jQuery('.scroll-up').addClass("hidden");
					}
				} 
				else if(jQuery(window).scrollTop() >= sticky_nav_offset_2) {
					jQuery('#floating-breadcrumb').addClass("sticky");
					jQuery('.desktop-sticky-header-wrapper').addClass('sticky');
	
					if($( ".scroll-up" ).length){
						jQuery('.scroll-up').removeClass("hidden");
					}
	
					if (prevScrollPos > jQuery(window).scrollTop() && jQuery(window).scrollTop() >= sticky_nav_offset_1) {
						jQuery('#floating-breadcrumb').css("transform", "translateY(" + jQuery('.desktop-sticky-header-wrapper').height() + "px)");
						jQuery('.desktop-sticky-header-wrapper.sticky').css("transform", "translateY(0)");
						jQuery('.footer-sticky-icon').css("transform", "translateY(180px)");
					}
					else {
						jQuery('#floating-breadcrumb').css("transform", "translateY(0)");
						jQuery('.desktop-sticky-header-wrapper.sticky').css("transform", "translateY(-100%)");
						jQuery('.footer-sticky-icon').css("transform", "translateY(70px)");
					}
				}
				else {
					jQuery('#floating-breadcrumb').css("transform", "translateY(-100%)");
					jQuery('.desktop-sticky-header-wrapper').css("transform", "translateY(0)");
					jQuery('.desktop-sticky-header-wrapper').removeClass('sticky');
	
					if($( ".scroll-up" ).length){
						jQuery('.scroll-up').addClass("hidden");
					}
				}
	
				prevScrollPos = jQuery(window).scrollTop();
			}
			else {
				if (jQuery(window).scrollTop() >= sticky_nav_offset_1) {
					jQuery('#floating-breadcrumb').addClass("sticky");
					if($( ".scroll-up" ).length){
						jQuery('.scroll-up').removeClass("hidden");
					}
				} else {
					jQuery('#floating-breadcrumb').removeClass("sticky");
					if($( ".scroll-up" ).length){
						jQuery('.scroll-up').addClass("hidden");					
					}				
				}	
			}

			isStickyNavBar = false;
		});
	}

	if($( ".article-page" ).length){
		$( window ).scroll(function() {
			var floating_ivs = $("ivs-player.setInitWidthAtr:not(.setInitWidth) > .ivs-sdk-wrapper.ivs-content-loaded.ivs-floating-widget");
			if(floating_ivs.length){
				floating_ivs.each(function() {
					var parent = $( this ).parent();
					parent.css( "display","block" );
					parent.css( "height",parent.attr("data-init-height") );
					parent.addClass("setInitWidth");
				});
			}

			var nonfloating_ivs = $("ivs-player.setInitWidthAtr.setInitWidth > .ivs-sdk-wrapper.ivs-content-loaded:not(.ivs-floating-widget)");
			if(nonfloating_ivs.length){
				nonfloating_ivs.each(function() {
					var parent = $( this ).parent();
					parent.css( "height","" );
					parent.css( "display","" );
					parent.removeClass("setInitWidth");
				});
			}
			if($("ivs-player:not(.setInitWidthAtr) > .ivs-sdk-wrapper.ivs-content-loaded:not(.ivs-floating-widget)").length){
				$("ivs-player:not(.setInitWidthAtr) > .ivs-sdk-wrapper.ivs-content-loaded:not(.ivs-floating-widget)").each(function() {
					var parent = $( this ).parent();
					parent.attr("data-init-height",parent.outerHeight());
					parent.addClass("setInitWidthAtr");
				});
			}
		});

	}
	else{
		$('.bottom-floading-icon').removeClass('hidden');
	}

	if($(".melaka-election").length){
		$(window).scroll(function() {
			var scrollPos = $(window).scrollTop();
			if (scrollPos > 10) {
				$('.bottom-floading-icon').removeClass('hidden');
				$('#scroll-up').addClass('fadeIn');
			} else {
				$('.bottom-floading-icon').addClass('hidden');
				$('#scroll-up').removeClass('fadeIn');
			}
		});
	}


    window.addEventListener('resize', function () {
       if (window.innerWidth !== width) {
		   let width_diff =Math.abs( width - window.innerWidth);
			width = window.innerWidth;
			if(width_diff > 10){
				fixClampText();
			}
       }
    });

	if($( "#wpadminbar" ).length){
		$("body").removeClass('pb');
	}
	else{

		$('body').bind('cut copy', function(e) {
			if($("body.pb").length)
				e.preventDefault();
		});
	}

	stickyAdsInit();
	stickyHpFn($(".side_hp_ads_panel")[0], $($(".side_hp_ads_panel")[0]).parent());

	if(jQuery("#secondary_article").length){
		jQuery(window).scroll(function() {
			if(secondary_post_loaded){
				if(isScrolledIntoViewAnimate(jQuery("#secondary_article_header"))){
					if(currentStateArticle == 1){
						if(jQuery(".webview.article-page.mobile-article").length){
							//avoid url change in webview
							currentSharingUrl = secondary_article_url;
							let app_sharing_url_message = {event: "articleurl", sharing_url: currentSharingUrl, post_id: secondary_article_id, post_title: secondary_article_title, post_date:secondary_article_date, post_cover_image:secondary_article_cover_image,share_count: get_share_view_count(secondary_article_id)};
							
							if(typeof AppInterfaceV2 !== 'undefined'){
								AppInterfaceV2.postMessage(JSON.stringify(app_sharing_url_message));	
							}
							if (typeof AppInterface === 'undefined') {
								if(typeof window.webkit != 'undefined'){
									window.webkit.messageHandlers.share.postMessage(JSON.stringify(app_sharing_url_message));
								}
							}
							else{	
								AppInterface.articleurl(JSON.stringify(app_sharing_url_message));
							}
						}
						else{
							let url = new URL(secondary_article_url);
							history.replaceState({}, '',url);
							updateChartbeatVirtualPageChange(currentStateArticle, primary_article_title, secondary_article_title, url);
							display_share_view_count(get_share_view_count(secondary_article_id));
						}
						document.title = secondary_article_title;
						currentStateArticle = 2;
					}
					if(!secondaryArticleViewSent ){
						secondaryArticleViewSent = true;

						if(jQuery(".webview.article-page.mobile-article").length){
							let url = new URL(secondary_article_url);
							ga('create', 'UA-33948949-1', 'auto');
							ga('set', {
								location: secondary_article_url,
								title: secondary_article_gatitle,
								page: url.pathname

							});
							ga('send', 'pageview');
							gtag('event', 'page_view', {
							page_title: secondary_article_gatitle,
							page_location: secondary_article_url,
							page_path: url.pathname,
							send_to: 'G-74B2VR88L4'
							});

							gtag('event', 'page_view', {
							page_title: secondary_article_gatitle,
							page_location: secondary_article_url,
							page_path: url.pathname,
							send_to: 'G-YBRYTH4EC2'
							});

							gtag('event', 'page_view', {
								page_title: secondary_article_gatitle,
								page_location: secondary_article_url,
								page_path: url.pathname,
								send_to: 'AW-11054747425'
							});							
						}
						else{

							ga('create', 'UA-33948949-1', 'auto');
							ga('set', {
								location: location.href,
								title: secondary_article_gatitle
							});
							ga('send', 'pageview');
							gtag('event', 'page_view', {
							page_title: secondary_article_gatitle,
							page_location: location.href,
							send_to: 'G-74B2VR88L4'
							});
							
							gtag('event', 'page_view', {
							page_title: secondary_article_gatitle,
							page_location: location.href,
							send_to: 'G-YBRYTH4EC2'
							});

							gtag('event', 'page_view', {
								page_title: secondary_article_gatitle,
								page_location: location.href,
								send_to: 'AW-11054747425'
							});
						}

							
						if (typeof(Storage) !== "undefined") {
							var reactcookies = localStorage.getItem("react_post_"+secondary_article_id);
							if(reactcookies == 'Y'){
								$("#emoji-wrapper_nd").addClass("disabled");
								var react = localStorage.getItem("react_post_result_"+secondary_article_id);
								$("#emoji_post_"+react+"_count_nd").parent().addClass("voted");
								$("#emoji_post_"+react+"_count_nd").parent().append('<i class="fas fa-check-circle"></i>');
							}
						} 
						else{
							$("#emoji-wrapper_nd").addClass("disabled");
						}
						
						var xmlhttp_second_view = new XMLHttpRequest();

						   xmlhttp_second_view.onreadystatechange = function() {
							if (xmlhttp_second_view.readyState == XMLHttpRequest.DONE) {	
								if (xmlhttp_second_view.status == 200) {
									eval(xmlhttp_second_view.responseText);
								}
							}
						};

						xmlhttp_second_view.open("POST", "/front-ajx.php", true);
						xmlhttp_second_view.setRequestHeader('content-type', 'application/x-www-form-urlencoded');
						xmlhttp_second_view.send("action=secondary_post_view&postid="+secondary_article_id+"&postdate="+secondary_article_date);

					}
				}
				else if(currentStateArticle == 2 && isScrolledIntoViewAnimate(jQuery("#emoji-wrapper"))){
					if(jQuery(".webview.article-page.mobile-article").length){
						//avoid url change in webview
						currentSharingUrl = primary_article_url;
						let app_sharing_url_message = {event: "articleurl", sharing_url: currentSharingUrl, post_id: primary_article_id, post_title: primary_article_title, post_date:primary_article_date, post_cover_image:primary_article_cover_image,share_count:get_share_view_count(primary_article_id)};
						
						if(typeof AppInterfaceV2 !== 'undefined'){
							AppInterfaceV2.postMessage(JSON.stringify(app_sharing_url_message));
						}
						if (typeof AppInterface === 'undefined') {
							if(typeof window.webkit != 'undefined'){
								window.webkit.messageHandlers.share.postMessage(JSON.stringify(app_sharing_url_message));
							}
						}
						else{	
							AppInterface.articleurl(JSON.stringify(app_sharing_url_message));
						}
					}
					else{
						let url = new URL(primary_article_url);
						history.replaceState({}, '',url);
						updateChartbeatVirtualPageChange(currentStateArticle, primary_article_title, secondary_article_title, url);
						display_share_view_count(get_share_view_count(primary_article_id));
					}
					document.title = primary_article_title;
					currentStateArticle = 1;
				}
			}
		});
	}


	$( "#search" ).focus(function() {
		/*
		$(".site-search-desktop").addClass("focus");
		retrieve_suggested_keyword();
		retrieve_topic_keyword();
		setTimeout(
			function() 
			{
				$(".site-search-desktop-hover").fadeIn();
			}, 500);
		*/


		retrieve_suggested_keyword();
		retrieve_topic_keyword();
		$(".site-search-desktop-hover").show();			
		 
	});
	
	 $( "#search" ).focusout(function() {
		var hovered = $(".site-search-desktop-hover").find("a:hover").length;

		if(!hovered){
			$(".site-search-desktop-hover").fadeOut();
			$(".site-search-desktop-hotkw").css("display","none");
			$(".site-search-desktop-topic").css("display","none");
			setTimeout(
				function() 
				{
					$(".site-search-desktop").removeClass("focus");
					var $election_social_element = $(".melaka-election .social-page-share.global-topnav.mobile-hidden");
					if ($election_social_element.hasClass("hidden")) {
					  	$election_social_element.removeClass("hidden");
					}

				}, 500);
		}
	 });

	if ($('#search-mobile').length) {
		$('#search-mobile').autocomplete({
			source: function(request, response) {
			   var search_term = request.term.trim().toLowerCase();
			   var search_term_length = search_term.length;
			   var search_id = "t1";
			   if(search_term_length== 0){
					response("");
					return;
			   }
			   else if(search_term_length < 2){
				   if(search_term.isCHS(0)){
					   search_id  = "t1";
				   }
				   else{
					   search_id  = "t2";
				   }
			   }
			   else{
				   search_id  = "t3";
			   }
			   var arg_body = {id: search_id, params: {query_string: search_term}};
	
			   $.ajax({
				   type: "POST",
				   contentType: "application/json; charset=utf-8",
				   url: 'https://searchapi.sinchew.com.my/simple-search',
				   data: JSON.stringify(arg_body),
				   dataType: "json",
				   success: function(data) {
					   var sug_result = [];
					  if(data.hits && data.hits.hits){
						  for(let i = 0; i < data.hits.hits.length; i++){ 
							  var item = data.hits.hits[i];
							  var object = new Object();
							  object.label = item._source.keyword_term;
							  object.value = item._source.keyword_term;
							  object.ID = item._source.keyword_term;
							  sug_result.push(object);
						   }	
					  }
	
					  console.log(sug_result);
					  response( sug_result);
				   },
				   error : function(data) {
					response( "");
				   }
				});
			},
			appendTo: "#mobile-site-search",
			   close: function( event, ui ) {
				  
				   },
			   open: function( event, ui ) {
				  
				   }
		   
	   });
	}

	if ($('#search').length) {
		$('#search').autocomplete({
			source: function(request, response) {
			   var search_term = request.term.trim().toLowerCase();
			   var search_term_length = search_term.length;
			   var search_id = "t1";
			   if(search_term_length== 0){
					response("");
					return;
			   }
			   else if(search_term_length < 2){
				   if(search_term.isCHS(0)){
					   search_id  = "t1";
				   }
				   else{
					   search_id  = "t2";
				   }
			   }
			   else{
				   search_id  = "t3";
			   }
			   var arg_body = {id: search_id, params: {query_string: search_term}};
	
			   $.ajax({
				   type: "POST",
				   contentType: "application/json; charset=utf-8",
				   url: 'https://searchapi.sinchew.com.my/simple-search',
				   data: JSON.stringify(arg_body),
				   dataType: "json",
				   success: function(data) {
					   var sug_result = [];
					  if(data.hits && data.hits.hits){
						  for(let i = 0; i < data.hits.hits.length; i++){ 
							  var item = data.hits.hits[i];
							  var object = new Object();
							  object.label = item._source.keyword_term;
							  object.value = item._source.keyword_term;
							  object.ID = item._source.keyword_term;
							  sug_result.push(object);
						   }	
					  }
	
					  console.log(sug_result);
					  response( sug_result);
				   },
				   error : function(data) {
					response( "");
				   }
				});
			},
			appendTo: "#desktop-site-search",
			   close: function( event, ui ) {
				  
				   },
			   open: function( event, ui ) {
				  
				   }
		   
	   });
	}


   if(typeof autoLoadMoreInListing !== 'undefined' && autoLoadMoreInListing == true){
	   initAutoLoadMoreInListing();
   }

	
});

 function isScrolledIntoViewAnimate(elem) {
    	
	        var docViewTop = jQuery(window).scrollTop();
	        var docViewBottom = docViewTop + jQuery(window).height();
	        
	        var elemTop = (jQuery(elem).offset().top) ;
	        var elemBottom = elemTop + jQuery(elem).height();
	        	//alert(docViewTop +"," + docViewBottom + "," + elemTop + "," + elemBottom);
	
	        return ((elemBottom <= docViewBottom) && (elemTop >= docViewTop));
    	
    }



function advertorialRegistrationAndEvent(){

	$(".adv-post").each(function() {
		let advpostparent = $( this ).parent();
		if(!advpostparent.hasClass("cloned") && !$( this ).parents("#myfav-box").length ){
			if($( this ).parents(".hot-posts-frame-list").length){
				if($( this ).parents(".home-latest-post-frame-list").length){
					let advpost = $( this );
					registerAdvertorialEvent(advpost);
				}
			}
			else{
				let advpost = $( this );
				registerAdvertorialEvent(advpost);
			}
		}
		
	});
}
 var arr_article_hotpost_adv = [];
function registerAdvertorialEvent(advpost = "", selector = "", sendImpression = true){
	var article_hot_post_adv = false;

	if(advpost != null){
	}
	else{
		advpost = $(selector+"");
		if(selector.includes("_ARTI_") == true){
			if(arr_article_hotpost_adv.includes(selector) == false){
				arr_article_hotpost_adv.push(selector);
			}
			else{
				sendImpression = false;
			}
			article_hot_post_adv = true;
		}
	}

	let advcode = advpost.attr("adv-placement");
	let advtitle = advpost.attr("adv-title");

	if(sendImpression == true){
		if(gatitle && gatitle != ''){
			ga('send', {
				hitType: 'event',
				eventCategory: advcode,
				eventAction: 'Impression',
				eventLabel: advtitle,
				title: gatitle
			});
			gtag('event', 'Impression', {
			'event_category' : advcode,
			'event_label' : advtitle
			});
		}
		else{
			ga('send', {
				hitType: 'event',
				eventCategory: advcode,
				eventAction: 'Impression',
				eventLabel: advtitle
			});
			gtag('event', 'Impression', {
			'event_category' : advcode,
			'event_label' : advtitle
			});
		}
	}

	if(article_hot_post_adv == true){
		let tmp_id = advpost.attr("id");
			$('div[id='+tmp_id+']').find("a").each(function() {
			let childlink = $(this);
			childlink.unbind("click");
			childlink.click({advcode: advcode, advtitle: advtitle},sendAdvertorialClickEvent);
		});
	}
	else{
		advpost.find("a").each(function() {
			let childlink = $(this);
			childlink.unbind("click");
			childlink.click({advcode: advcode, advtitle: advtitle},sendAdvertorialClickEvent);
		});
	}
}

function sendAdvertorialClickEvent(e){
	e.preventDefault();
	let advcode = e.data.advcode;
	let advtitle = e.data.advtitle;
	if(gatitle && gatitle != ''){
		ga('send', {
			hitType: 'event',
			eventCategory: advcode,
			eventAction: 'Click',
			eventLabel: advtitle,
			title: gatitle
		});
		gtag('event', 'Click', {
			'event_category' : advcode,
			'event_label' : advtitle
			});
	}
	else{
		ga('send', {
			hitType: 'event',
			eventCategory: advcode,
			eventAction: 'Click',
			eventLabel: advtitle
		});
		gtag('event', 'Click', {
			'event_category' : advcode,
			'event_label' : advtitle
			});
	}

	var self = jQuery(this);
	var href = self.attr('href');
	window.location.href = href;
}

function sendReadMoreClickEvent() {
	if(typeof gatitle !== 'undefined' && gatitle && gatitle != ''){
		ga('send', {
			hitType: 'event',
			eventCategory: 'Interaction',
			eventAction: 'expand_read_more_clicked',
			eventLabel: gatitle
		});
		
		gtag('event', 'expand_read_more_clicked', {
			'event_category': 'Interaction',
			'event_label': gatitle	
		});
		
		console.log("Read more clicked event sent");
	}
}

function sendArticleContentProgressEvent(title, percentage) {
	let eventName = `${userPlatform}_article_read_${percentage}%`;

	if(typeof title !== 'undefined' && title && title != ''){
		ga('send', {
			hitType: 'event',
			eventCategory: 'Interaction',
			eventAction: eventName,
			eventLabel: title
		});
		
		gtag('event', eventName, {
			'event_category': 'Interaction',
			'event_label': title	
		});
		
		console.log(`${eventName} - ${title} article read progress was sent`);
	} else { 
		console.log("Error sending article read progress");
	}
}

function sendArticlePageProgressEvent(title, percentage) {
	let eventName = `${userPlatform}_article_scroll_${percentage}%`;

	if(typeof title !== 'undefined' && title && title != ''){
		ga('send', {
			hitType: 'event',
			eventCategory: 'Interaction',
			eventAction: eventName,
			eventLabel: title
		});
		
		gtag('event', eventName, {
			'event_category': 'Interaction',
			'event_label': title	
		});
		
		console.log(`${eventName} - ${title} article scroll progress was sent`);
	}
}

function advertorialOnClick(e, element){
	e.preventDefault();
	var self =  jQuery(element);
	let advcode = self.attr('advcode');
	let advtitle = self.attr('advtitle'); 
	if(typeof gatitle !== 'undefined' && gatitle && gatitle != ''){
		ga('send', {
			hitType: 'event',
			eventCategory: advcode,
			eventAction: 'Click',
			eventLabel: advtitle,
			title: gatitle
		});
		gtag('event', 'Click', {
			'event_category' : advcode,
			'event_label' : advtitle
			});
	}
	else{
		ga('send', {
			hitType: 'event',
			eventCategory: advcode,
			eventAction: 'Click',
			eventLabel: advtitle
		});
		gtag('event', 'Click', {
			'event_category' : advcode,
			'event_label' : advtitle
			});
	}

	var href = self.attr('href');
	window.location.href = href;
}

function setReduceAdsTargeting(reduceAdsAccess) {
	return;
    if (typeof googletag === 'undefined' || !googletag.cmd) return;
    googletag.cmd.push(function() {
        var value = reduceAdsAccess ? 'true' : 'false';
        googletag.pubads().setTargeting('Reduce_Ads', value);
    });
}

function setArticlePageGamTargeting(subscriptionPlan) {
    if (typeof googletag === 'undefined' || !googletag.cmd) {
        return;
    }
    googletag.cmd.push(function() {
        const finalPlan = subscriptionPlan;
        googletag.pubads().setTargeting('Subscription_Plan', finalPlan);
    });
}


function checkArticleAccess_internal(articleId) {
	return;
    const unlockUI = (source) => {
        console.log(`Access Granted via: ${source}`);
        
        localStorage.setItem('paid_article_' + articleId, 'Y');

        if (window.paywallManager) {
            window.paywallManager.removePaywallIfApiAllows(articleId);
        }

    };

    if (localStorage.getItem('paid_article_' + articleId) === 'Y') {
        unlockUI('LocalStorage');
        return; 
    }

    const token = localStorage.getItem('access_token');
    const uid = localStorage.getItem('uid');

    if (!token || !uid) {
        return; 
    }

    $.ajax({
        url: DONATION_API_URL + '/api/check-article-access',
        type: "POST",
        data: { 
            article_id: articleId,
            user_id: uid
        },
        success: function(response) {
            if (response && response.can_view_premium_content === true) {
                unlockUI('Local Backend');
            } else {

                console.log("Local check failed. Trying Remote Agmo API...");
                
                $.ajax({
                    url: `${sso_url}/api/sso-single-article/check-article/${articleId}`,
                    type: "GET",
                    headers: {
                        "Authorization": "Bearer " + token,
                        "Accept": "application/json"
                    },
                    success: function(agmoResponse) {
                        if (agmoResponse && agmoResponse.data && agmoResponse.data.has_record === true) {
                            unlockUI('Remote Agmo API');
                        } else {
                            console.log("Access Denied: No record found anywhere.");
                        }
                    },
                    error: function(err) {
                        console.error("Agmo check failed (CORS or Network):", err);
                    }
                });
            }
        },
        error: function(xhr, status, error) {
            console.error("Local Backend check failed:", xhr);
        }
    });
}

function updateDonationButtonVisibility(isLoggedIn, hasAccess) {
    const $body = $("body");

    const isLockedArticlePage = $body.hasClass('content-with-lock');
    const isBasicMember = $body.hasClass('basic-lock-released'); 
    const $paywallPrompt = $(".article-page-content:not(#secondary_article_content) .prompt-login-wrapper");
    const isPaywallVisible = $paywallPrompt.length > 0 && $paywallPrompt.css('display') !== 'none';

	const $headerDonationBtn = $(".article-page-breadcrumb .open-donation-modal, .article-page-title-header .open-donation-modal");
    const $contentDonationBtn = $(".donation-row");

	const isWebview = $(".webview").length > 0;

    function applyVisibility() {
		if (!isLockedArticlePage) {
			// Public Article: Show All
			$headerDonationBtn.removeClass('hidden');
			$contentDonationBtn.removeClass('hidden');
		} 
		else {
			// Locked Article Page
			if (hasAccess && !isPaywallVisible) {
				// Unlocked (VIP/Paid/Basic-on-Basic): Hide Header, Show Content
				$headerDonationBtn.addClass('hidden');
				$contentDonationBtn.removeClass('hidden');
			} 
			else {
				// Blocked (Guest OR Basic-on-VIP): Hide All
				$headerDonationBtn.removeClass('hidden');
				$contentDonationBtn.addClass('hidden');
			}
		}
    }

	if (isWebview) {
		const isIosWebview = /iphone|ipad|ipod/i.test(navigator.userAgent);
		const isAndroidWebview = /android/i.test(navigator.userAgent);
		const isOldAndroidWebview = isAndroidWebview && typeof AppInterfaceV2 === 'undefined';
		const isNewAndroidWebview = isAndroidWebview && typeof AppInterfaceV2 !== 'undefined';
		const isHuaweiWebview = isAndroidWebview && typeof HuaweiInterface !== 'undefined';
		const isFlutterWebview = typeof FlutterInterface !== 'undefined';
	
		if (isOldAndroidWebview) { // no bridge
			$headerDonationBtn.addClass('hidden');
			$contentDonationBtn.addClass('hidden');
			return;
		}
	
		$.getJSON(ax_host + "/ajx-api/webview_settings")
			.done(function(result) {
				if (isIosWebview && !result.on_ios) {
					$headerDonationBtn.addClass('hidden');
					$contentDonationBtn.addClass('hidden');
					return;
				}
				if (isNewAndroidWebview && !result.on_android) {
					$headerDonationBtn.addClass('hidden');
					$contentDonationBtn.addClass('hidden');
					return;
				}
				applyVisibility();
			});
	}
	else {
		applyVisibility();
	}

}


function processPendingUnlocks() { 
    const uid = localStorage.getItem('uid');
    if (!uid) return;

    const pendingUnlocks = JSON.parse(localStorage.getItem('pendingUnlocks') || '[]');    
    if (pendingUnlocks.length === 0) return;
    
    console.log('Processing', pendingUnlocks.length, 'pending unlocks/donations');
    
    pendingUnlocks.forEach((unlockItem) => {
        $.ajax({
            url: DONATION_API_URL + '/api/payment/claim-unlock', 
            type: "POST",
            headers: {
                "Accept": "application/json",
                "Content-Type": "application/json"
            },
            data: JSON.stringify({
                user_id: uid,
                gateway_transaction_id: unlockItem.transaction_id
            }),
            success: function(response) {
                console.log('Claimed successfully for type:', unlockItem.type, 'article:', unlockItem.article_id);
                let currentPending = JSON.parse(localStorage.getItem('pendingUnlocks') || '[]');
                currentPending = currentPending.filter(d => d.transaction_id !== unlockItem.transaction_id);
                localStorage.setItem('pendingUnlocks', JSON.stringify(currentPending));
            },
            error: function(xhr) {
                console.error('Failed to claim', unlockItem.type, unlockItem.article_id);
            }
        });
    });
}


function checkLogin(){
	$.ajax({
		url: `${sso_url}/isUserLogged`,
		type: "GET",
		xhrFields : {
			withCredentials : true
		},
		beforeSend: function(xhr) {
			xhr.setRequestHeader("Accept", "application/json");
		},
		success: function(response) {

            if (response && response.message === "Unauthenticated") {
                response.is_auth = false;
            }

            if (response && response.is_auth === true) {
                const currentUname = localStorage.getItem('uname');
                const currentUmail = localStorage.getItem('umail');
                const currentUid = localStorage.getItem('uid');

                if (currentUname !== response.name) localStorage.setItem('uname', response.name);
                if (currentUmail !== response.email) localStorage.setItem('umail', response.email);
                if (currentUid !== response.user_id) localStorage.setItem('uid', response.user_id);

                if (response.access_token) {
                    localStorage.setItem('access_token', response.access_token);
                }

				if (response.membership_plan) {
					localStorage.setItem('user_membership_tier', response.membership_plan);
				} else {
					localStorage.setItem('user_membership_tier', 'basic');
				}

            } else {
                if ($(".webview").length == 0) {
                    localStorage.removeItem('uname');
                    localStorage.removeItem('umail');
                    localStorage.removeItem('uid');
                    localStorage.removeItem('access_token');
					localStorage.removeItem('user_membership_tier');
                }
            }

            if (typeof processPendingUnlocks === 'function') {
                processPendingUnlocks();
            }

            if (typeof isArticlePage !== 'undefined' && isArticlePage) {
                var post_id = document.getElementById('single-post-id')?.getAttribute("data-pid");
                if (post_id) {
                    checkArticleAccess_internal(post_id);
                }
            }


			let subscriptionPlan = 'not-login';

			if(response.is_auth == true) {
				if($("#header-action")) {
					$("#header-login-btn").remove();
					$("#header-action").prepend(
						'<div id="header-login-btn" class="header-login-btn main-header-action-btn" >'+
							'<i class="fas fa-user-check" onclick="profilepage();"></i>'+
							'<span onclick="profilepage();">个人中心</span>'+

							'<div class="logout_hover" onclick="logoutpage();">'+
								'<i class="fas fa-walking"></i>'+
								'<span>登出</span>'+
							'</div>'+

						'</div>'
					);

					// $("#side-menu-stockportfolio").remove();
					// $("#side-menu-stockportfolio-action").prepend(
					// 	'<div id="side-menu-stockportfolio" onclick="stockportfoliopage();">'+
					// 	'<img src="/public/images/slide_menu_stockportfolio_icon.png" />'+
					// 	'<span>我的股票</span>'+
					// 	'</div>'
					// );	

					$("#side-menu-login").remove();
					$("#side-menu-login-action").prepend(
						'<div id="side-menu-profile" onclick="profilepage();">'+
						'<img src="/public/images/slide_menu_login_icon.png" />'+
						'<span>个人中心</span>'+
						'</div>'
					);

					$('<a class="side_menu_item" id="side-menu-logout-action">'+
							'<div id="side-menu-logout" onclick="logoutpage();">'+
								'<i class="fas fa-walking"></i>'+
								'<span>登出</span>'+
							'</div>'+
						'</a>').insertBefore(".slide-menu-footer");

						let logoutButtonHovered;
						$('#header-login-btn').on('mouseenter', function () {
							clearTimeout(logoutButtonHovered);
							$('.logout_hover').addClass('visible');
						});
						$('#header-login-btn, .logout_hover').on('mouseleave', function () {
							logoutButtonHovered = setTimeout(() => {
								$('.logout_hover').removeClass('visible');
							}, 1000);
						});
						$('#header-login-btn, .logout_hover').on('mouseenter', function () {
							clearTimeout(logoutButtonHovered);
						});
				}

				var bodyelement = document.getElementsByTagName('body')[0];
				bodyelement.classList.add("memberloggedin");

				if($(".prompt-login-wrapper").length) {
					if(response.can_view_premium_content == true && response.membership_plan == "vvip") {
						bodyelement.classList.add("all-lock-released");
					}
					else if(response.can_view_premium_content == true && response.membership_plan == "vip") {
						bodyelement.classList.add("vip-lock-released");
					}
					else {
						bodyelement.classList.add("basic-lock-released");
						$('#vip-details-wrapper table tr:last-child td:nth-child(2) button').prop('disabled', true);
						$('#prompt-login-wrapper-container .login-button').css('display', 'none');

						while($(".vip-wrapper .content-locked-area").length > 0){
							$(".vip-wrapper .content-locked-area")[0].parentNode.removeChild($(".vip-wrapper .content-locked-area")[0]);
						}
					}

					$('.prompt-login-wrapper').each(function() {
						var prev_last_p = $(this).parent().closest('div').prevAll('p').first();
						if (prev_last_p.length) {
							var prev_last_p_text = prev_last_p.text().trim();
							if(prev_last_p_text !== '') {
								var last_character = prev_last_p_text.slice(-1);
						
								var punctuationMarks = ['。', '．', '.', '：', ':', '！', '!', '？', '?', ';', '；'];
								if (!punctuationMarks.includes(last_character)) {
									var next_elm = $(this).nextAll('.content-locked-area').first();
									next_elm = next_elm.children('cdiv').first();
									next_elm = next_elm.children().first();
									while (next_elm.length && next_elm.is('div')) {
										// Skip <div>
										next_elm = next_elm.next();
									}

									if (next_elm.length && next_elm.is('p')) {
										var next_first_p = next_elm;
										if (next_first_p.length) {
											var next_first_p_text = next_first_p.text().trim();
											var merged_p = $('<p></p>').text(prev_last_p_text + next_first_p_text);
											prev_last_p.replaceWith(merged_p);
											next_first_p.remove();
										}
									}
								}
							}
						}
					});
				}

				if(response.membership_plan){
					subscriptionPlan = response.membership_plan;
				}

                var hasAccess = $("body").hasClass("all-lock-released") || 
                                $("body").hasClass("vip-lock-released") || 
                                $("body").hasClass("basic-lock-released");
				updateDonationButtonVisibility(true, hasAccess);


				initMatomoAnalytics(response.user_id);

				if ($(".webview.article-page.mobile-article").length > 0 && localStorage.getItem('pendingBridgeNotify')) {
					localStorage.removeItem('pendingBridgeNotify');
					notifymobile({
						uid: response.user_id,
						uname: response.name,
						umail: response.email,
						access_token: response.access_token,
						membership_plan: response.membership_plan || 'basic'
					}, "UserLoggedIn");
				}
			}
			else {

				updateDonationButtonVisibility(false, false);

				if($(".prompt-login-wrapper").length) {
					var bodyelement = document.getElementsByTagName('body')[0];
					bodyelement.classList.add("locked");
					while($(".content-locked-area").length > 0){
						$(".content-locked-area")[0].parentNode.removeChild($(".content-locked-area")[0]);
					}
				}
				subscriptionPlan = 'not-login';
				initMatomoAnalytics('');
			}

            if (isArticlePage === true) {
                setArticlePageGamTargeting(subscriptionPlan);
            }

			if (isArticlePage === true || pageType === 'cat') {
				if (response.membership_access) {
					var reduceAds = response.membership_access.find(
						function(a) { return a.slug === 'reduce-ads'; }
					);
					setReduceAdsTargeting(reduceAds ? reduceAds.has_access : false);
				} else {
					setReduceAdsTargeting(false);
				}
			}
		},
        error: function(xhr) {

            if (xhr.status === 401 && $(".webview").length == 0) {
                localStorage.removeItem('uname');
                localStorage.removeItem('umail');
                localStorage.removeItem('uid');
                localStorage.removeItem('access_token');
            }

            const subscriptionPlan = 'not-login';
            if (isArticlePage === true) {
                setArticlePageGamTargeting(subscriptionPlan);
            }
			if (isArticlePage === true || pageType === 'cat') {
				setReduceAdsTargeting(false);
			}
        }

	});
}

function stickyMenu(recalc = false){
	if($(document).scrollTop() >= content_offset_y){
		if((!$("body").hasClass("sticky-header")) || recalc){
			$("body").addClass("sticky-header");
			$('#sticky_mob_kuaixun').removeClass('mobile-hidden');
			$("#content").css("margin-top", ($(".desktop-sticky-header-wrapper").height()+10)+"px");
			//jQuery('.header-row1-wrapper').addClass("hidden");			
		}
	}
	else{
		if($("body").hasClass("sticky-header")){
			$("body").removeClass("sticky-header");
			$('#sticky_mob_kuaixun').addClass('mobile-hidden');
			$("#content").css("margin-top", "0px");
			//jQuery('.header-row1-wrapper').removeClass("hidden");
		}
	}
}

function internalLinkRegClickEvent(e){
		return;
		if($(".webview").length) return;
		var self = jQuery(this);
		var href = self.attr('href');

		if(this.hostname  != window.location.hostname) return;

		var title = self.attr('data-title');
		if( self.attr('to-prev') && self.attr('to-prev') == 1){
			curr_history_chain_number = curr_history_chain_number - 2;
		}
		e.preventDefault();
		document.title = title;
		window.history.pushState({'internal_link':'Y','page_title': title, 'page_href': href},title, href);

		ajaxLoadContent(href, true);
}

function ajaxLoadContent(href, scrollback = false){
	
	renderCurrentMenuItem();

	first_load = false;
	$.ajax({
		url: addOrReplaceParam(href,'_ACSS',1)
	})
	.done(function( html ) {
		unloadAllExternalScript();
		$( "#content" ).html( html );
		jQuery('#content a.internalLink:not([target="_blank"])').click(internalLinkRegClickEvent);
		if(scrollback){
			if($("body").hasClass("sticky-header")){
				window.scrollTo(0, content_offset_y +1);
				stickyMenu(true);
			}
		}
		//caterJsafterContentRender();

		initFont();
		loadGallery();
		//loadMarquee();
		loadMarquee_v2();
		initPostView();
		//initCustomPostView();
		initArticlePrevNextPages();
		initHotTopic();
		initMyFavPreference();
		fixClampText();
	});
}

var addOrReplaceParam = function(url, param, value) {
	param = encodeURIComponent(param);
	var r = "([&?]|&amp;)" + param + "\\b(?:=(?:[^&#]*))*";
	var a = document.createElement('a');
	var regex = new RegExp(r);
	var str = param + (value ? "=" + encodeURIComponent(value) : ""); 
	a.href = url;
	var q = a.search.replace(regex, "$1"+str);
	if (q === a.search) {
	   a.search += (a.search ? "&" : "") + str;
	} else {
	   a.search = q;
	}
	return a.href;
 }
 
function caterJsafterContentRender (o, pars) {
	var elm = document.getElementById("content");
	
	Array.from(elm.querySelectorAll("script")).forEach( oldScript => {
		const newScript = document.createElement("script");
		Array.from(oldScript.attributes)
		.forEach( attr => newScript.setAttribute(attr.name, attr.value) );
		newScript.appendChild(document.createTextNode(oldScript.innerHTML+ "var opq=1;"));
		oldScript.parentNode.replaceChild(newScript, oldScript);
	});
}


function unloadAllExternalScript(){
	window.IVS = null;
	// if($('style[class="ivs-hs-style"]').length){
	// 	$('style[class="ivs-hs-style"]').remove();
	// }
	// if($('script[data-ivs-loaded-sdk="1"]').length){
	// 	$('script[data-ivs-loaded-sdk="1"]').remove();
	// }
	
	$(':not(footer) style:not([init-frame-load=1])').remove();
	$(':not(footer) script:not([init-frame-load=1])').remove();
	$(':not(footer) link:not([init-frame-load=1])').remove();
}


function loadGallery(){
	if(jQuery('#post_gallery_ul').length){
        gallery_slider = jQuery('#post_gallery_ul').lightSlider({
                    pager:false,
                    item:1,
                    slideMargin: 0,
                    speed:400,
                    auto:true,
                    loop:true,
                    pause: 8000,
                    onSliderLoad: function (el) {
                        jQuery('.post_gallery li').each(function() {
                           jQuery(this).css("margin-top", (jQuery('.post_gallery').height()-jQuery(this).height())/2);
                        });
                        
                    } 
                });
    }

}


function renderCurrentSubMenuItem(){
	jQuery("#cssmenu-level-2  .menu-item").removeClass('current-item');
	var path = window.location.pathname;
	path = decodeURIComponent(path);
	var hostname = window.location.hostname;

	var hostname_path = hostname + path;


	jQuery("#cssmenu-level-2 > ul li > a").each(function () {

		var href = jQuery(this).attr('href');
		
		href = decodeURIComponent(href);
		href = href.replace(hostname, "");
		href = href.replace("http://","");
		href = href.replace("https://","");

		let url = new URL(jQuery(this).attr('href'));
		let hostname_path_item = url.hostname + decodeURIComponent(url.pathname);


		if (path.substring(0, href.length) === href  && href.substring(0, path.length) === path) {
			if(href == "/"){
					if(jQuery(this).closest('li').hasClass('menu-more')){
					}
					else{
						jQuery(this).closest('li').addClass('current-item');
						
					}
			}
			else{
				jQuery(this).closest('li').addClass('current-item');
			}
		}
		else if(hostname_path_item == hostname_path){
			jQuery(this).closest('li').addClass('current-item');
		}
		else if(typeof(parent_cat_url) !== "undefined" &&  parent_cat_url == hostname_path_item){
			jQuery(this).closest('li').addClass('current-item');
			if(jQuery(this).closest('li').parent().parent().hasClass('menu-item')){
				jQuery(this).closest('li').parent().parent().addClass('current-item')
			}
		}
	});
}

function renderCurrentMenuItem(){
	jQuery("#cssmenu  .menu-item").removeClass('current-item');
	var path = window.location.pathname;
	path = decodeURIComponent(path);
	var hostname = window.location.hostname;

	var hostname_path = hostname + path;

	var fragment = window.location.hash;

	jQuery("#cssmenu #nav li > a").each(function () {

		var href = jQuery(this).attr('href');
		
		href = decodeURIComponent(href);
		href = href.replace(hostname, "");
		href = href.replace("http://","");
		href = href.replace("https://","");

		let url = new URL(jQuery(this).attr('href'));
		let hostname_path_item = url.hostname + decodeURIComponent(url.pathname);

		var fragment_item = "";
		if (url.hash) {
			fragment_item = url.hash; // e.g., '#section-lishi'
		}
		
		if (path.substring(0, href.length) === href  && href.substring(0, path.length) === path) {
			if(href == "/"){
					if(jQuery(this).closest('li').hasClass('menu-more')){
					}
					else{
						jQuery(this).closest('li').addClass('current-item');
					}
			}
			else{
				jQuery(this).closest('li').addClass('current-item');
				if(jQuery(this).closest('li').parent().parent().hasClass('menu-item')){
					jQuery(this).closest('li').parent().parent().addClass('current-item')
				}
			}
		}
		else if(hostname_path_item == hostname_path){

			if(fragment_item==""){	//menu file no fragment
				jQuery(this).closest('li').addClass('current-item'); //default
			}

			//jQuery(this).closest('li').addClass('current-item');
			if(jQuery(this).closest('li').parent().parent().hasClass('menu-item')){
				jQuery(this).closest('li').parent().parent().addClass('current-item')
			}
		}
		else if(typeof(parent_cat_url) !== "undefined" &&  parent_cat_url == hostname_path_item){
			jQuery(this).closest('li').addClass('current-item');
			if(jQuery(this).closest('li').parent().parent().hasClass('menu-item')){
				jQuery(this).closest('li').parent().parent().addClass('current-item')
			}
		}
	});


	$('#cssmenu .menu-item').click(function(e) {
		$('#cssmenu .menu-item').removeClass('current-item');
		$(this).addClass('current-item');
	});


	initSecondLevelMenu();
	initInnerMenu();
	scrollCurrentMenuItemToVisible();

}

function initInnerMenu(){
	if(jQuery(".category-page-sub-menu").length){
		var path = window.location.pathname;
		path = decodeURIComponent(path);
		var hostname = window.location.hostname;

		var hostname_path = hostname + path;

		jQuery(".category-page-sub-menu  li > a").each(function () {

			var href = jQuery(this).attr('href');
			
			href = decodeURIComponent(href);
			href = href.replace(hostname, "");
			href = href.replace("http://","");
			href = href.replace("https://","");

			let url = new URL(jQuery(this).attr('href'));
			let hostname_path_item = url.hostname + decodeURIComponent(url.pathname);

			
			if (path.substring(0, href.length) === href  && href.substring(0, path.length) === path) {
				if(href == "/"){
						if(jQuery(this).closest('li').hasClass('menu-more')){
						}
						else{
							jQuery(this).closest('li').addClass('current-item');
						}
				}
				else{
					jQuery(this).closest('li').addClass('current-item');
					if(jQuery(this).closest('li').parent().parent().hasClass('menu-item')){
						jQuery(this).closest('li').parent().parent().addClass('current-item')
					}
				}
			}
			else if(hostname_path_item == hostname_path){
				jQuery(this).closest('li').addClass('current-item');
				if(jQuery(this).closest('li').parent().parent().hasClass('menu-item')){
					jQuery(this).closest('li').parent().parent().addClass('current-item')
				}
			}
			else if(typeof(parent_cat_url) !== "undefined" &&  parent_cat_url == hostname_path_item){
				jQuery(this).closest('li').addClass('current-item');
				if(jQuery(this).closest('li').parent().parent().hasClass('menu-item')){
					jQuery(this).closest('li').parent().parent().addClass('current-item')
				}
			}
		});
	}

}

function scrollCurrentMenuItemToVisible(){
	if($("body").width() < 920){
		if(jQuery("#cssmenu #nav > .current-item").length){
			let current_item = jQuery("#cssmenu #nav > .current-item").first();
			let min_x_pos = current_item.offset().left + current_item.width();
			let min_left_pos = current_item.offset().left;
			
			if(min_x_pos > $("body").width()){
				$("#nav").scrollLeft(current_item.offset().left);
			}
			else if(min_left_pos < 0){
				$("#nav").scrollLeft(current_item.position().left);
			}
		}
		if(jQuery("#cssmenu-level-2 > ul > .current-item").length){
			let current_item = jQuery("#cssmenu-level-2 > ul > .current-item").first();
			let min_x_pos = current_item.offset().left + current_item.width();
			let min_left_pos = current_item.offset().left;
			if(min_x_pos > $("body").width()){
				$("#cssmenu-level-2 > ul").scrollLeft(current_item.offset().left);
			}
			else if(min_left_pos < 0){
				$("#cssmenu-level-2 > ul").scrollLeft(current_item.position().left);
			}
		}
		if(jQuery(".category-page-sub-menu  .current-item").length){
			let current_item = jQuery(".category-page-sub-menu .current-item").first();
			let min_x_pos = current_item.offset().left + current_item.width();
			let min_left_pos = current_item.offset().left;
			if(min_x_pos > $("body").width()){
				$(".category-page-sub-menu").scrollLeft(current_item.offset().left);
			}
			else if(min_left_pos < 0){
				$(".category-page-sub-menu").scrollLeft(current_item.position().left);
			}
		}
	}
}

function initSecondLevelMenu(){
	var pageURL = decodeURIComponent(window.location.href);
	var secondLevelCat = null;

	if( pageURL.includes("/stocksummary") || pageURL.includes("/stock?") || pageURL.includes("/stock/") ){	//custom page
		jQuery(" #cssmenu > ul li > a").filter(function(index) { return $(this).text() === "财经"; }).closest('li').addClass('current-item');
	}

	else if ($('.subcat.submenu').length>0){ //3rd level exist
		var pathArray = pageURL.split( '/' );
		var firstLevelCat = pathArray[4];
		secondLevelCat = pathArray[5];
		if( pageURL.includes("/"+secondLevelCat)  ){
			jQuery(" #cssmenu > ul li > a").filter(function(index) { return $(this).text() === firstLevelCat; }).closest('li').addClass('current-item');
			jQuery("#cssmenu-level-2 > ul li > a").filter(function(index) { return $(this).text() === secondLevelCat; }).closest('li').addClass('current-item');
		}
	}

	if($("#cssmenu #nav > li.current-item .sub-menu").length){
		$("#cssmenu-level-2 > ul").html($("#cssmenu #nav > li.current-item .sub-menu").first().html());
		jQuery('#cssmenu-level-2 a.internalLink:not([target="_blank"])').click(internalLinkRegClickEvent);
		renderCurrentSubMenuItem();
		jQuery("#cssmenu-level-2 > ul li > a").filter(function(index) { return $(this).text() === secondLevelCat; }).closest('li').addClass('current-item');		
	}
	else{
		$("#cssmenu-level-2 > ul").html("");
	}
}


function slideInSideMenu(){
	$(".mobile-side-menu").addClass("slide-in");
	$("body").addClass("disable-scroll");
}

function slideOutSideMenu(){
	$("body").removeClass("disable-scroll");
	$(".mobile-side-menu").removeClass("slide-in");
}

function slideInSearchMenu(){
	$(".mobile-site-search").addClass("slide-in");
	$("body").addClass("disable-scroll");

	retrieve_suggested_keyword();
	retrieve_topic_keyword();
}

function slideOutSearchMenu(){
	$("body").removeClass("disable-scroll");
	$(".mobile-site-search").removeClass("slide-in");

	$(".site-search-mobile-hotkw").css("display","none");
	$(".site-search-mobile-topic").css("display","none");
}

var current_article_page_font = 4;
function initFont(){
	if($( ".article-page" ).length){

		if (typeof(localStorage) !== "undefined") {
			var localStorageFontSize = localStorage.getItem('article_page_font_size_level');
			if(localStorageFontSize){
				current_article_page_font = (localStorageFontSize * 1);
			}
		}

		$( ".article-content-column" ).addClass("font-level-"+ current_article_page_font);
	}
}


function enlargeFont(){
	isStickyNavBar = true;

	var max_font = 9;
	if(current_article_page_font + 1 > max_font) return;

	$( ".article-content-column" ).removeClass("font-level-"+ current_article_page_font);
	$( ".article-content-column" ).addClass("font-level-"+ (++current_article_page_font));

	if (typeof(localStorage) !== "undefined") {
		localStorage.setItem('article_page_font_size_level', current_article_page_font);
	}
	
}

function shrinkFont(){
	isStickyNavBar = true;

	var min_font = 1;
	if(current_article_page_font - 1 < min_font) return;

	$( ".article-content-column" ).removeClass("font-level-"+ current_article_page_font);
	$( ".article-content-column" ).addClass("font-level-"+ (--current_article_page_font));
	
	if (typeof(localStorage) !== "undefined") {
		localStorage.setItem('article_page_font_size_level', current_article_page_font);
	}
}

var arr_bookmark =[];



function loadBookmark(){
	if($( ".article-page" ).length){

		if (typeof(localStorage) !== "undefined") {
			var bookmarklist = localStorage.getItem('bookmarks_list');
			if(bookmarklist){
				arr_bookmark = JSON.parse(bookmarklist);
			}
		}
	}
}


function addBookmark(pid){
	if($(".article-page-bookmark").hasClass("done")) return;
	if (typeof(localStorage) !== "undefined") {
		if(!arr_bookmark.includes(pid)){
			arr_bookmark.push(pid);
			localStorage.setItem('bookmarks_list', JSON.stringify(arr_bookmark));
		}
	}
	$(".article-page-bookmark").html("加入书签 ✔");
	$(".article-page-bookmark").addClass("done");
}
function addBookmarkFromBottomBar(pid){
	if($(".article-page-mobile-bar-bookmark").hasClass("done")) return;
	if (typeof(localStorage) !== "undefined") {
		if(!arr_bookmark.includes(pid)){
			arr_bookmark.push(pid);
			localStorage.setItem('bookmarks_list', JSON.stringify(arr_bookmark));
		}
	}
	$(".article-page-mobile-bar-bookmark").append('<i class="fas fa-check"></i>');
	$(".article-page-mobile-bar-bookmark").addClass("done");

}

function initPostView(elementParent = ''){
	var is_article_page = false;
	if(document.getElementById('single-post-id')){
		is_article_page = true;
	}
	var frontajx_action_prefix = "";
	if(typeof(is_custom_post_view) !== "undefined" && is_custom_post_view == true){
		frontajx_action_prefix = "custom_";
	}
	else{
		frontajx_action_prefix = "";
	}
	if(is_article_page && elementParent == ''){
		var post_id = document.getElementById('single-post-id').getAttribute("data-pid");;
		var post_date = "";
		var items = document.getElementById('single-post-id').children;
		for (var i = items.length - 1; i >= 0; i--)
		{
			if(items[i].className == "single-post-date"){
				post_date = items[i].getAttribute("data-date") ;
			}
			
		}

		if($('.mobile-article').length==0){
			//addReadPostAjx(post_id);
		}

		if (typeof(Storage) !== "undefined") {
            var reactcookies = localStorage.getItem("react_post_"+post_id);
            if(reactcookies == 'Y'){
				$("#emoji-wrapper").addClass("disabled");
				var react = localStorage.getItem("react_post_result_"+post_id);
				$("#emoji_post_"+react+"_count").parent().addClass("voted");
				$("#emoji_post_"+react+"_count").parent().append('<i class="fas fa-check-circle"></i>');
            }
        } 
        else{
            $("#emoji-wrapper").addClass("disabled");
        }

		if (navigator.share) {
			$(".os-share-action").addClass("show");
		}

	}

	
	var post_id_items = "";

	if(elementParent == null || elementParent == ''){
		var items = document.getElementsByClassName('post-view-counter');
	}
	else{
		var items = elementParent.getElementsByClassName('post-view-counter');
	}
	for (var i = items.length - 1; i >= 0; i--)
	{
		$temp_id = items[i].getAttribute("data-pid");
		if(typeof($temp_id) !== "undefined"){
			post_id_items = post_id_items + items[i].getAttribute("data-pid") + ",";
		}
	}
	
	var xmlhttp = new XMLHttpRequest();

    xmlhttp.onreadystatechange = function() {
        if (xmlhttp.readyState == XMLHttpRequest.DONE) {   // XMLHttpRequest.DONE == 4
        	
           if (xmlhttp.status == 200) {
               eval(xmlhttp.responseText);
           }
        }
    };

	

    xmlhttp.open("POST", "/front-ajx.php", true);
    xmlhttp.setRequestHeader('content-type', 'application/x-www-form-urlencoded');
	if(is_article_page  && elementParent == ''){
   		 xmlhttp.send("action="+frontajx_action_prefix+"single_post_view&postidlist="+post_id_items+"&postid="+post_id+'&postdate='+post_date);
	}
	else{


		xmlhttp.send("action="+frontajx_action_prefix+"post_view&postidlist="+post_id_items);
	}
}

function initCustomPostView(elementParent = ''){
	var is_article_page = false;
	if(document.getElementById('custom-post-id')){
		is_article_page = true;
	}
	console.log('Is Article Page: ' + is_article_page);
	console.log('element parent: ' + elementParent);
	if(is_article_page && elementParent == ''){
		var post_id = document.getElementById('custom-post-id').getAttribute("data-pid");
		console.log('post id: ' + post_id);
		var post_date = "";
		var items = document.getElementById('custom-post-id').children;
		for (var i = items.length - 1; i >= 0; i--)
		{
			if(items[i].className == "custom-post-date"){
				post_date = items[i].getAttribute("data-date") ;
			}
			
		}
		console.log('post date:' + post_date);
		if (typeof(Storage) !== "undefined") {
            var reactcookies = localStorage.getItem("react_post_"+post_id);
            if(reactcookies == 'Y'){
				$("#emoji-wrapper").addClass("disabled");
				var react = localStorage.getItem("react_post_result_"+post_id);
				$("#emoji_post_"+react+"_count").parent().addClass("voted");
				$("#emoji_post_"+react+"_count").parent().append('<i class="fas fa-check-circle"></i>');
            }
        } 
        else{
            $("#emoji-wrapper").addClass("disabled");
        }

		if (navigator.share) {
			$(".os-share-action").addClass("show");
		}

	}

	
	var post_id_items = "";

	if(elementParent == null || elementParent == ''){
		var items = document.getElementsByClassName('post-view-counter');
	}
	else{
		var items = elementParent.getElementsByClassName('post-view-counter');
	}
	console.log('items: ' + items);
	console.log('length: ' + items.length);
	for (var i = items.length - 1; i >= 0; i--)
	{
		$temp_id = items[i].getAttribute("data-pid");
		console.log(items[i].getAttribute("data-pid"));
		if((items[i].getAttribute("data-pid") * 1)> 0){
			post_id_items = post_id_items + items[i].getAttribute("data-pid") + ",";
			console.log('post id items: ' + post_id_items);
		}
	}
	
	var xmlhttp = new XMLHttpRequest();

    xmlhttp.onreadystatechange = function() {
        if (xmlhttp.readyState == XMLHttpRequest.DONE) {   // XMLHttpRequest.DONE == 4
        	
           if (xmlhttp.status == 200) {
			//    let r = xmlhttp.responseText.replace(/点阅/g, "");
            //    eval(r);
				console.log('response text: ' + xmlhttp.responseText);
				eval(xmlhttp.responseText);
           }
        }
    };

    xmlhttp.open("POST", "/front-ajx.php", true);
    xmlhttp.setRequestHeader('content-type', 'application/x-www-form-urlencoded');
	if(is_article_page  && elementParent == ''){
		console.log('a');
   		 xmlhttp.send("action=custom_single_post_view&postidlist="+post_id_items+"&postid="+post_id+'&postdate='+post_date);
	}
	else{
		console.log('b');
		xmlhttp.send("action=custom_post_view&postidlist="+post_id_items);
	}
}


function addReadPostAjx(postId){

	var reader = getCookie('reader');
	$.ajax({ url: ax_host+'/ajx-api/article_storage/?reader='+reader+'&action=getpost' })
	.done(function( posts ) {
		var savedata;
		var currentDate = new Date();
		var currDateStr = currentDate.getFullYear()+'-'+pad2(currentDate.getMonth()+1)+'-'+currentDate.getDate();
		// console.log("addReadPostAjx");
		// console.log("posts.length:", posts.length);
		// console.log("string posts.length:", String(posts).length);

		if(posts.length == 0){
			var posts = [{
				'postid':postId,
				'date':currDateStr
			}]
			savedata = JSON.stringify(posts);
		}else{
			var postArray = JSON.parse(posts);
			var newPostList = [];
			var isNewPost = true;
			for(var i=0 ; i <postArray.length; i++){
				var postItem = postArray[i];
				if(postItem.postid == postId){
					postItem.date = currDateStr;
					isNewPost = false;
				}
				newPostList.push(postItem);					
			}
			if(isNewPost){
				newPostList.push({
					'postid':postId,
					'date':currDateStr
				});
			}
			savedata = JSON.stringify(newPostList);
		}
		$.ajax({
			url: ax_host+'/ajx-api/article_storage/?reader='+reader+'&action=addreadpost&data='+savedata
		});
	});
}

function initPurgeOldPost(){

	var today = new Date( new Date().getFullYear().toString(), pad2( new Date().getMonth() ) , pad2( new Date().getDate()) );
	var todayStr = today.getFullYear()+"-"+ pad2(today.getMonth()+1)+"-"+today.getDate();
	if(!cookieExists("postpurgedate")){
		var status= purgeOldPost();
		setCookie('postpurgedate', todayStr);
	}
	else{
		var postLastDateArr = getCookie('postpurgedate').split("-");
		var postLastDate = new Date(postLastDateArr[0],postLastDateArr[1]-1,postLastDateArr[2]);
		if( Date.parse(today)>Date.parse(postLastDate)){
			var status= purgeOldPost();
			setCookie('postpurgedate', todayStr);
		}
	}
}

function purgeOldPost(){
	var reader = getCookie('reader');
	$.ajax({ url: ax_host+'/ajx-api/article_storage/?reader='+reader+'&action=getpost' })
	.done(function( posts ) {
		if(posts.length > 0){
			var postArray = JSON.parse(posts);
			var newPostList = [];
			for(var i=0 ; i <postArray.length; i++){
				var isExpired = false;
				var postItem = postArray[i];
				var postLastDateStr = postItem.date;
				var postLastDateArr = postLastDateStr.split("-");
				isExpired = checkDaysAgo(postLastDateArr,14);					
				if(!isExpired){
					newPostList.push(postItem);	
				}
			}
			var savedata= JSON.stringify(newPostList);
			$.ajax({
				url: ax_host+"/ajx-api/article_storage/?reader="+reader+"&action=purgeoldpost&data="+savedata
			});
			return true;
		}
		return false;
	});
}

function addReaderCookie()
{	
	if(!cookieExists("reader")){
		let rand = randomString(10);
		setCookie('reader', rand);
	}
}
function randomString(len, an) {
	an = an && an.toLowerCase();
	var str = "",
	  i = 0,
	  min = an == "a" ? 10 : 0,
	  max = an == "n" ? 10 : 62;
	for (; i++ < len;) {
	  var r = Math.random() * (max - min) + min << 0;
	  str += String.fromCharCode(r += r > 9 ? r < 36 ? 55 : 61 : 48);
	}
	return str;
}
function cookieExists(name) {
	var cks = document.cookie.split(';');
	for(i = 0; i < cks.length; i++) {
		if (cks[i].split('=')[0].trim() == name) return true;
	}
}
function getCookie(cname) {
	let name = cname + "=";
	let decodedCookie = decodeURIComponent(document.cookie);
	let ca = decodedCookie.split(';');
	for(let i = 0; i <ca.length; i++) {
		let c = ca[i];
		while (c.charAt(0) == ' ') {
			c = c.substring(1);
		}
		if (c.indexOf(name) == 0) {
			return c.substring(name.length, c.length);
		}
	}
	return null;
}
function setCookie(cname, cvalue, exdays=365) {
	const d = new Date();
	d.setTime(d.getTime() + (exdays*24*60*60*1000));
	let expires = "expires="+ d.toUTCString();
	let domain= "domain="+cookie_root;
	document.cookie = cname + "=" + cvalue + ";" + expires + ";path=/;" + domain;
}	

function checkDaysAgo(postLastDateArr, intDays){
	var postLastDate = new Date(postLastDateArr[0],postLastDateArr[1]-1,postLastDateArr[2]);
	var daysAgo = new Date(new Date().setDate(new Date().getDate()-intDays));
	if(Date.parse(postLastDate) < Date.parse(daysAgo)){
		return true;
	}
	return false;
}

function pad2(n) { return n < 10 ? '0' + n : n }

function getParameterByName(name, url = window.location.href) {
	name = name.replace(/[\[\]]/g, '\\$&');
	var regex = new RegExp('[?&]' + name + '(=([^&#]*)|&|#|$)'),
		results = regex.exec(url);
	if (!results) return null;
	if (!results[2]) return '';
	return decodeURIComponent(results[2].replace(/\+/g, ' '));
} 

var curr_history_chain_number = -1;
if (typeof(sessionStorage) !== "undefined") {
	sessionStorage.removeItem("article_chain");
}

function initArticlePrevNextPages(){
	if($(".webview").length) return;
	if($( ".article-page" ).length){
		 if (typeof(sessionStorage) !== "undefined") {
			var post_id =  $("#single-post-id").attr("data-pid"); 
			var permalink_prefix = $("#single-post-id .single-post-permalink-prefix").attr("data-link"); 
			var arr_history = JSON.parse(sessionStorage.getItem('article_chain'));
			curr_history_chain_number++;

			if(!arr_history){
				arr_history = [];
				curr_history_chain_number = 0;
				arr_history[curr_history_chain_number]= post_id; 
			}
			else{
				if(curr_history_chain_number > arr_history.length -1){
					arr_history[curr_history_chain_number] = post_id;
				}

				if(curr_history_chain_number - 1 > -1 && arr_history[curr_history_chain_number -1] ){
					$(".prev-article-action").addClass("show");
					$(".prev-article-action a").attr("href", permalink_prefix+arr_history[curr_history_chain_number -1]);
				}

				if(curr_history_chain_number + 1 <= arr_history.length -1 && arr_history[curr_history_chain_number + 1] ){
					$(".next-article-action").addClass("show");
					$(".next-article-action a").attr("href", permalink_prefix+arr_history[curr_history_chain_number + 1]);
				}
			}

			sessionStorage.setItem('article_chain', JSON.stringify(arr_history));
		}
	}
}


function addClassName(element, name) {
	var  arr;
	if(!element) return;
	arr = element.className.split(" ");
	if (arr.indexOf(name) == -1) {
	  element.className += " " + name;
	}
}


function hotPostListItem(post){

	//type1, desktop vertical, mob hori
	var id = post.ID;
	var link = post.the_permalink;
	var title = post.post_title;
	var img = post.image || defaultCover;
	var date = post.date_diff;
	var elmclass = "";
	var imgstr = "";
	var imgstr_end = "";
	var descstr ="";
	var no_img_inner_frame_start = "";
	var no_img_inner_frame_end= "";
	var catstr = "";
	let is_advertorial = false;
	let play_button = post.play_button==1 ? `<i class='fas fa-play-circle'></i>`: '';

	if(typeof(post.is_advertorial) !== "undefined" && post.is_advertorial == true){
		is_advertorial = true;
	}

	if($('.category-page-editorial').length && post.cat){
		var cat = post.cat;
		var catlink = post.catlink;
		catstr = '<div class="cat">'+
						'<a class="internalLink" data-title="<?php echo $cat; ?>" href="'+catlink+'">'+cat+'</a>'+	
					'</div>';
		descstr = '<div class="desc desc-desktop">'+
		'<a class="internalLink" data-title="'+title+'" href="'+link+'">'+
			post.post_excerpt+
		'</a>'+
		'</div>';
	}
	

	if(!img || img.length == 0){
		elmclass += "no-img-frame";
		descstr = '<div class="desc">'+
					'<a class="internalLink" data-title="'+title+'" href="'+link+'">'+
						post.post_excerpt+
					'</a>'+
				  '</div>';
		no_img_inner_frame_start = '<div class="no-img-frame-inner-div">';
		no_img_inner_frame_end = '</div>';
	}
	else{
		imgstr ='<div class="img-frame">'+
					'<a class="internalLink" data-title="'+title+'" href="'+link+'">'+'<img class="img" src="'+img+'" alt="'+title+'"/>'+'</a>'+
					play_button+
				'</div><div class="post-frame-mobile-right">';
		imgstr_end = '</div>';
	}

	let advertorial_extra_attr = "";
	let adv_cat = "";

	if(typeof(post.cat) !== "undefined" && post.cat != ""){
		adv_cat ='<div class="cat"><a class="internalLink" data-title="'+title+'" href="'+post.catlink+'">'+post.cat+'</a></div>';
	}
	if(is_advertorial){
		elmclass += " adv-post";

		advertorial_extra_attr = " adv-placement='"+post.advcode +"' adv-title='"+id+"_"+post.title_escpbr+"' id='ADV_POST_"+post.advcode+"'";

		if($('.category-page-editorial').length && post.cat){
		}
		else{
			let hide_element_class = post.is_show_shichangqingbao==1? "": " hidden ";
			adv_cat ='<div class="cat'+hide_element_class+'"><a class="internalLink" data-title="'+title+'" href="'+link+'">市场情报</a></div>';
		}
	}

	let liveiconstr = "";
	if(post.live_icon==1){
		liveiconstr = `<span class="live-badge-listing live-badge-listing-red">LIVE</span>`;
	}

	var the_html = '<div class="hot-post desktop-2col type1 vertical-post-frame '+elmclass+'" '+advertorial_extra_attr+'>'+no_img_inner_frame_start+imgstr+catstr+
						'<h2 class="title">'+
							'<a class="internalLink" data-title="'+title+'" href="'+link+'">'+title+'</a>'+
						'</h2>'+descstr+
						'<div class="meta">'+
							'<span class="time">'+date+'</span>'+
							'<span class="counter post-view-counter-parent post-view-counter-parent-'+id+'">'+
								'<i class="far fa-eye"><span data-pid="'+id+'" class="post-view-counter post-view-'+id+'"></span></i>'+
							'</span>'+
						'</div>'+adv_cat+imgstr_end+
						no_img_inner_frame_end+
						'<div class="horizontal-line horizontal-line-40h grey-color "></div>'+
					'</div>';

	return the_html;
}

function hotPostToggle(e){
	var data_range = $(e).attr( 'data-range' );
	var parent = $(e).closest('.hot-posts-frame');
	parent.find(".hot-posts-toggle-item").removeClass("current");
	$(e).addClass("current");

	parent.find(".hot-posts-frame-list").removeClass("current");
	parent.find(".hot-posts-frame-list-"+data_range).addClass("current");
}


function hotPostListItem_Type2(post) {
	//type2 - desktop vertical 2col, mobile vertical

    const id = post.ID;
    const link = post.the_permalink;
    const title = post.post_title;
    const img = post.image || defaultCover;
    const date = post.date_diff;
    let elmclass = "";
    let imgstr = "";
    let imgstr_end = "";
    let descstr = "";
    let catstr = "";
    let is_advertorial = post.is_advertorial === true;
	let catlabel = post.catlabel;
    var catlabelVisibility = is_advertorial || !catlabel ? ' style="visibility:hidden;"' : "";
	let play_button = post.play_button==1 ? `<i class='fas fa-play-circle'></i>`: '';

	if (is_advertorial) {
		if (!$('.category-page-editorial').length || !post.cat) {
			catlabelVisibility = post.is_show_shichangqingbao == 1 ? "" : ' style="visibility:hidden;"';
			catlabel = "市场情报";
		}
	}

    if ($('.category-page-editorial').length && post.cat) {
        const cat = post.cat;
        const catlink = post.catlink;
        catstr = `<div class="cat">
            <a class="internalLink" data-title="${cat}" href="${catlink}">${cat}</a>
        </div>`;
        descstr = `<div class="desc desc-desktop">
            <a class="internalLink" data-title="${title}" href="${link}">${post.post_excerpt}</a>
        </div>`;
    }

	imgstr = `<div class="img-frame">
		<div class="topleft-cat-label"${catlabelVisibility}>${catlabel}</div>
		<a class="internalLink" data-title="${title}" href="${link}">
			<img class="img" src="${img}" alt="${title}" />
		</a>
		${play_button}
	</div><div class="post-frame-mobile-right">`;
	imgstr_end = '</div>';    

    let advertorial_extra_attr = "";
    let adv_cat = "";

	if(typeof(post.cat) !== "undefined" && post.cat != ""){
		adv_cat = `<div class="cat"><a class="internalLink" data-title="${title}" href="${post.catlink}">${post.cat}</a></div>`;
	}
    
    if (is_advertorial) {
        elmclass += " adv-post";
        advertorial_extra_attr = ` adv-placement='${post.advcode}' adv-title='${id}_${post.title_escpbr}' id='ADV_POST_${post.advcode}'`;

        if (!$('.category-page-editorial').length || !post.cat) {
            var hide_element_class = post.is_show_shichangqingbao == 1 ? "" : " hidden ";

			if(catlabel=="市场情报"){
				hide_element_class = " hidden ";
			}

            adv_cat = `<div class="cat${hide_element_class}">
                <a class="internalLink" data-title="${title}" href="${link}">市场情报</a>
            </div>`;
        }
    }

	let liveiconstr = "";
	if(post.live_icon==1){
		liveiconstr = `<span class="live-badge-listing live-badge-listing-red">LIVE</span>`;
	}	

    const the_html = `<div class="hot-post desktop-2col type2 vertical-post-frame margin-20-desktop margin-20-mobile ${elmclass}" ${advertorial_extra_attr}>
        ${imgstr}${catstr}
        <div class="title expandable">
			${liveiconstr}<a class="internalLink" data-title="${title}" href="${link}">${title}</a>
        </div>
        ${descstr}
        <div class="meta">
            <span class="time">${date}</span>
            <span class="counter post-view-counter-parent post-view-counter-parent-${id}">
                <i class="far fa-eye"><span data-pid="${id}" class="post-view-counter post-view-${id}"></span></i>
            </span>
        </div>
        ${adv_cat}${imgstr_end}
    </div>`;

    return the_html;
}


function hotPostListItem_Type4(post) {
	//type4 desktop vertical (4col), mobile same

    const id = post.ID;
    const link = post.the_permalink;
    const title = post.post_title;
    const img = post.image || defaultCover;
    const date = post.date_diff;
    let elmclass = "";
    let imgstr = "";
    let imgstr_end = "";
    let descstr = "";
    let no_img_inner_frame_start = "";
    let no_img_inner_frame_end = "";
    let catstr = "";
    let is_advertorial = post.is_advertorial === true;
	let catlabel = post.catlabel;
    var catlabelVisibility = is_advertorial || !catlabel ? ' style="visibility:hidden;"' : "";
	let play_button = post.play_button==1 ? `<i class='fas fa-play-circle'></i>`: '';

    if ($('.category-page-editorial').length && post.cat) {
        const cat = post.cat;
        const catlink = post.catlink;
        catstr = `<div class="cat">
            <a class="internalLink" data-title="${cat}" href="${catlink}">${cat}</a>
        </div>`;
        descstr = `<div class="desc desc-desktop">
            <a class="internalLink" data-title="${title}" href="${link}">${post.post_excerpt}</a>
        </div>`;
    }

    if (!img || img.length === 0) {
        elmclass += "no-img-frame";
        descstr = `<div class="desc">
            <a class="internalLink" data-title="${title}" href="${link}">${post.post_excerpt}</a>
        </div>`;
        no_img_inner_frame_start = '<div class="no-img-frame-inner-div">';
        no_img_inner_frame_end = '</div>';
    } else {
        imgstr = `<div class="img-frame">
			<div class="topleft-cat-label"${catlabelVisibility}>${catlabel}</div>
            <a class="internalLink" data-title="${title}" href="${link}">
                <img class="img" src="${img}" alt="${title}" />
            </a>
			${play_button}
        </div><div class="post-frame-mobile-right">`;
        imgstr_end = '</div>';
    }

    let advertorial_extra_attr = "";
    let adv_cat = "";

	if(typeof(post.cat) !== "undefined" && post.cat != ""){
		adv_cat = `<div class="cat"><a class="internalLink" data-title="${title}" href="${post.catlink}">${post.cat}</a></div>`;
	}
    
    if (is_advertorial) {
        elmclass += " adv-post";
        advertorial_extra_attr = ` adv-placement='${post.advcode}' adv-title='${id}_${post.title_escpbr}' id='ADV_POST_${post.advcode}'`;

        if (!$('.category-page-editorial').length || !post.cat) {
            const hide_element_class = post.is_show_shichangqingbao == 1 ? "" : " hidden ";
            adv_cat = `<div class="cat${hide_element_class}">
                <a class="internalLink" data-title="${title}" href="${link}">市场情报</a>
            </div>`;
        }
    }

	let liveiconstr = "";
	if(post.live_icon==1){
		liveiconstr = `<span class="live-badge-listing live-badge-listing-red">LIVE</span>`;
	}

    const the_html = `<div class="hot-post desktop-4col-mobile-2col type2 vertical-post-frame margin-20-desktop margin-20-mobile ${elmclass}" ${advertorial_extra_attr}>
        ${no_img_inner_frame_start}${imgstr}${catstr}
        <div class="title">
			${liveiconstr}<a class="internalLink" data-title="${title}" href="${link}">${title}</a>
        </div>
        ${descstr}
        <div class="meta">
            <span class="time">${date}</span>
            <span class="counter post-view-counter-parent post-view-counter-parent-${id}">
                <i class="far fa-eye"><span data-pid="${id}" class="post-view-counter post-view-${id}"></span></i>
            </span>
        </div>
        ${adv_cat}${imgstr_end}${no_img_inner_frame_end}        
    </div>`;

    return the_html;
}



function hotPostListItem_Type3(post){	
	
	//type3 - desktop & mobile  horizontal
	var id = post.ID;
	var link = post.the_permalink;
	var title = post.post_title;
	var img = post.image || defaultCover;
	var date = post.date_diff;
	var elmclass = "";
	var catstr = "";
	var is_advertorial = false;
	let play_button = post.play_button==1 ? `<i class='fas fa-play-circle'></i>`: '';

	const wrapperclassBase = "desktop-horizontal-mobile-horizontal-post";
	const outerwrapperclassBase = "desktop-horizontal-mobile-horizontal-post-frame";
	let wrapperclass = wrapperclassBase;
	let outerwrapperclass = outerwrapperclassBase;
	
	let imageHtml = img && img !== "" ? 
	`<div class="img-frame">
		<a class="internalLink" data-title="${title}" href="${link}">
			<img class="img" src="${img}" onerror="this.src='${defaultCover}'" />
		</a>
		${play_button}
	</div>` : "";
	
	if(typeof(post.is_advertorial) !== "undefined" && post.is_advertorial == true){
		is_advertorial = true;
	}

	if ($('.category-page-editorial').length && post.cat) {
		const cat = post.cat;
		const catlink = post.catlink;
		catstr = `<div class="cat">
					<a class="internalLink" data-title="${cat}" href="${catlink}">${cat}</a>
				</div>`;		
	}
	
	var advertorial_extra_attr = "";
	var adv_cat = "";
	if(typeof(post.cat) !== "undefined" && post.cat != ""){
		adv_cat =`<div class="cat"><a class="internalLink" data-title="${title}" href="${post.catlink}">${post.cat}</a></div>`;
	}
	if(is_advertorial){
		elmclass += " adv-post";
		advertorial_extra_attr = ` adv-placement="${post.advcode}" adv-title="${id}_${post.title_escpbr}" id="ADV_POST_${post.advcode}"`;

		if($('.category-page-editorial').length && post.cat){
		}
		else{
			let hide_element_class = post.is_show_shichangqingbao==1? "": " hidden ";
			adv_cat = `<div class="cat${hide_element_class}"><a class="internalLink" data-title="${title}" href="${link}">市场情报</a></div>`;
		}
	}

	let liveiconstr = "";
	if(post.live_icon==1){
		liveiconstr = `<span class="live-badge-listing live-badge-listing-red">LIVE</span>`;
	}	
	
	var the_html= `<div class="${outerwrapperclass} ${elmclass}" ${advertorial_extra_attr}>
		<div class="${wrapperclass}">
			${imageHtml}
			<div class="title">
				${liveiconstr}<a class="internalLink" data-title="${title}" href="${link}">${title}</a>
			</div>
			<div class="meta">
				<span class="time">${date}</span>
				<span class="counter post-view-counter-parent post-view-counter-parent-${id}">
					<i class="far fa-eye"></i>
					<span  data-pid="${id}" class="post-view-counter post-view-${id}"></span>
				</span>
			</div>
			${adv_cat}
		</div>
	</div>`;
	return the_html;
}



function hotPostListItem_Type5(post, extra_class=""){
		
	//type5 - desktop hori, mobile vertical 2x2
	var id = post.ID;
	var link = post.the_permalink;
	var title = post.post_title;
	var img = post.image || defaultCover;
	var date = post.date_diff;
	var elmclass = "";
	var catstr = "";
	var is_advertorial = false;
	let play_button = post.play_button==1 ? `<i class='fas fa-play-circle'></i>`: '';

	let outerwrapperclass = "hot-post desktop-horizontal-mobile-vertical-post-frame margin-20-mobile";
	let wrapperclass = "desktop-horizontal-mobile-vertical-post vertical-post-frame";
	
	if(typeof(post.is_advertorial) !== "undefined" && post.is_advertorial == true){
		is_advertorial = true;
	}

	let imageHtml = img && img !== "" ? 
	`<div class="img-frame">
		<a class="internalLink" data-title="${title}" href="${link}">
			<img class="img" src="${img}"/>
		</a>
		${play_button}
	</div>` : "";
	
	if ($('.category-page-editorial').length && post.cat) {
		const cat = post.cat;
		const catlink = post.catlink;
		catstr = `<div class="cat">
					<a class="internalLink" data-title="${cat}" href="${catlink}">${cat}</a>
				</div>`;		
	}

	var advertorial_extra_attr = "";
	var adv_cat = "";
	if(typeof(post.cat) !== "undefined" && post.cat != ""){
		adv_cat =`<div class="cat"><a class="internalLink" data-title="${title}" href="${post.catlink}">${post.cat}</a></div>`;
	}
	if(is_advertorial){
		elmclass += " adv-post";
		advertorial_extra_attr = ` adv-placement="${post.advcode}" adv-title="${id}_${post.title_escpbr}" id="ADV_POST_${post.advcode}"`;

		if($('.category-page-editorial').length && post.cat){
		}
		else{
			let hide_element_class = post.is_show_shichangqingbao==1? "": " hidden ";
			adv_cat = `<div class="cat${hide_element_class}"><a class="internalLink" data-title="${title}" href="${link}">市场情报</a></div>`;
		}
	}

	let liveiconstr = "";
	if(post.live_icon==1){
		liveiconstr = `<span class="live-badge-listing live-badge-listing-red">LIVE</span>`;
	}	
	
	var the_html= 
	`<div class="${outerwrapperclass}${elmclass}${extra_class}" ${advertorial_extra_attr}>
		<div class="${wrapperclass}">
			${imageHtml}
			<div class="post-frame-mobile-right">
				<div class="title">
					${liveiconstr}<a class="internalLink" data-title="${title}" href="${link}">${title}</a>
				</div>
				<div class="meta">
					<span class="time">${date}</span>
					<span class="counter post-view-counter-parent post-view-counter-parent-${id}">
						<i class="far fa-eye"></i>
						<span  data-pid="${id}" class="post-view-counter post-view-${id}"></span>
					</span>
				</div>
				${adv_cat}
			</div>
			<div class="horizontal-line horizontal-line-20h grey-color hidden"></div>
		</div>
	</div>`;
	return the_html;
}


function hotPostListItemSidebar(post){
	var id = post.ID;
	var link = post.the_permalink;
	var title = post.post_title;
	var img = post.image || defaultCover;
	var date = post.date_diff;
	var elmclass = "";
	var imgstr = "";
	var descstr ="";
	var no_img_inner_frame_start = "";
	var no_img_inner_frame_end= "";
	var catstr = "";
	var catlabel = post.catlabel;
	let is_advertorial = false;
	let play_button = post.play_button==1 ? `<i class='fas fa-play-circle'></i>`: '';

	if(typeof(post.is_advertorial) !== "undefined" && post.is_advertorial == true){
		is_advertorial = true;
	}

	if($('.category-page-editorial').length && post.cat){
		var cat = post.cat;
		var catlink = post.catlink;
		catstr = `<div class="cat">
			<a class="internalLink" data-title="${cat}" href="${catlink}">${cat}</a>
		</div>`;
		descstr = `<div class="desc desc-desktop">
			<a class="internalLink" data-title="${title}" href="${link}">${post.post_excerpt}</a>
		</div>`;		
	}
	
	if(!img || img.length == 0){
		elmclass += "no-img-frame";
		descstr = `<div class="desc"><a class="internalLink" data-title="${title}" href="${link}">${post.post_excerpt}</a></div>`;
		no_img_inner_frame_start = '<div class="no-img-frame-inner-div">';
		no_img_inner_frame_end = '</div>';
	}
	else{
		imgstr = `<div class="img-frame">
		<a class="internalLink" data-title="${title}" href="${link}">
			<img loading="lazy" class="img" src="${img}" alt="${title}" onerror="this.src='${defaultCover}'"/>
		</a>
		${play_button}
		</div>`;
	}

	let advertorial_extra_attr = "";
	let adv_cat = "";

	if(typeof(post.cat) !== "undefined" && post.cat != ""){
		adv_cat = `<div class="cat"><a class="internalLink" data-title="${title}" href="${post.catlink}">${post.cat}</a></div>`;
	}
	if(is_advertorial){
		elmclass += " adv-post";
		advertorial_extra_attr = `adv-placement='${post.advcode}' adv-title='${id}_${post.title_escpbr}' id='ADV_POST_${post.advcode}'`;

		if($('.category-page-editorial').length && post.cat){
		}
		else{
			let hide_element_class = post.is_show_shichangqingbao==1? "": " hidden ";
			adv_cat = `<div class="cat${hide_element_class}"><a class="internalLink" data-title="${title}" href="${link}">市场情报</a></div>`;
		}
	}

    var catlabelVisibility = is_advertorial || !catlabel ? ' style="visibility:hidden;"' : "";

	var the_html = `<div class="hidden hot-post vertical-post-frame ${elmclass}" ${advertorial_extra_attr}>
		${no_img_inner_frame_start}
		${imgstr}
		${catstr}
		<div class="catrow">
			<div class="catlabel"${catlabelVisibility}>${catlabel}</div>
			<div class="meta">
				<span class="time">${date}</span>
				<span class="counter post-view-counter-parent post-view-counter-parent-${id}">
					<i class="far fa-eye">
						<span data-pid="${id}" class="post-view-counter post-view-${id}"></span>
					</i>
				</span>
			</div>
		</div>
		<div class="title">
			<a class="internalLink" data-title="${title}" href="${link}"><h3 class="skip-default-style">${title}</h3></a>
		</div>
		${descstr}
		${adv_cat}
		${no_img_inner_frame_end}
		<div class="horizontal-line horizontal-line-40h grey-color"></div>
		<div class="horizontal-space-above"></div>
	</div>`;

	return the_html;	
}

function hotPostListItemTop(post){
    var id = post.ID;
    var link = post.the_permalink;
    var title = post.post_title;
    var img = post.image || defaultCover;
    var date = post.date_diff;
    var elmclass = "";
    var catstr = "";
    var catlabel = post.catlabel;

    var is_advertorial = false;
    if (typeof(post.is_advertorial) !== "undefined" && post.is_advertorial == true) {
        is_advertorial = true;
    }

    let advertorial_extra_attr = "";
    let adv_cat = "";
    if(typeof(post.cat) !== "undefined" && post.cat != ""){
		adv_cat ='<div class="cat"><a class="internalLink" data-title="'+title+'" href="'+post.catlink+'">'+post.cat+'</a></div>';
	}
    if(is_advertorial){
        elmclass += " adv-post";
        advertorial_extra_attr = `adv-placement='${post.advcode}' adv-title='${id}_${post.title_escpbr}' id='ADV_POST_${post.advcode}'`;

        let hide_element_class = post.is_show_shichangqingbao==1? "": " hidden ";
		adv_cat ='<div class="cat'+hide_element_class+'"><a class="internalLink" data-title="'+title+'" href="'+link+'">市场情报</a></div>';        
    }

    var catlabelstr = is_advertorial || !catlabel ? "" : `<div class="catlabel">${catlabel}</div>`;

    var newHTML = `
        <div class='hot-post-item ${elmclass}' ${advertorial_extra_attr}>  
            <div class="img-wrapper">
                <a class="internalLink" data-title="${title}" href="${link}">
                    <img loading="lazy" class="img" src="${img}" alt="${title}" onerror="this.src='${defaultCover}'" >
                </a>
            </div>
            <div class="col2">
                <div class="title">
                    <a class="internalLink" href="${link}">${title}</a>
                </div>

                <div class="catrow">
	                ${catlabelstr}
                    ${adv_cat}
                </div>

                <div class="meta">
                    <span class="time">${date}</span>
                    <span class="counter post-view-counter-parent post-view-counter-parent-${id}">
                        <i class="far fa-eye">
                            <span data-pid="${id}" class="post-view-counter post-view-${id}"></span>
                        </i>
                    </span>
                </div>
            </div>            
        </div>`;
    return newHTML;
}

function emojiClicked(element){
	if($(element).parent().hasClass("disabled") || typeof(Storage) == "undefined"){return;}
	$(element).parent().addClass("disabled");
	$(element).find("img").addClass($(element).find("img").data("animation"));

	let is_secondary_article_emoji = false;
	let emoji_parent_id = $(element).parent().attr("id")
	if(emoji_parent_id == "emoji-wrapper_nd"){
		is_secondary_article_emoji = true;
	}

	
	if(is_secondary_article_emoji == true){
		var post_id = secondary_article_id;
		var id_clicked = $(element).find(".feedback-emoji-counter").attr("id");
		var reaction = id_clicked.substring(11,id_clicked.length - 9 );
	}
	else{
		var post_id = document.getElementById('single-post-id').getAttribute("data-pid");
		var id_clicked = $(element).find(".feedback-emoji-counter").attr("id");
		var reaction = id_clicked.substring(11,id_clicked.length - 6 );
	}

	$(element).addClass("voted");
	$(element).find(".feedback-emoji-counter").html($(element).find(".feedback-emoji-counter").html()*1 + 1);	
	$(element).append('<i class="fas fa-check-circle"></i>');


	if (typeof(Storage) !== "undefined") {
		localStorage.setItem("react_post_"+post_id, "Y");
		localStorage.setItem('react_post_result_'+post_id, reaction);
	}

	var xmlhttp = new XMLHttpRequest();

    xmlhttp.onreadystatechange = function() {
        if (xmlhttp.readyState == XMLHttpRequest.DONE) {   // XMLHttpRequest.DONE == 4
        	
           if (xmlhttp.status == 200) {
			   console.log(xmlhttp.responseText);
               eval(xmlhttp.responseText);
           }
        }
    };
	
	var frontajx_action_prefix = "";
	if(typeof(is_custom_post_view) !== "undefined" && is_custom_post_view == true){
		frontajx_action_prefix = "custom_";
	}
	else{
		frontajx_action_prefix = "";
	}
    xmlhttp.open("POST", "/front-ajx.php", true);
    xmlhttp.setRequestHeader('content-type', 'application/x-www-form-urlencoded');
	xmlhttp.send("action="+frontajx_action_prefix+"single_post_react&postid="+post_id+'&react='+reaction);
}

function customEmojiClicked(element){
	if($(element).parent().hasClass("disabled") || typeof(Storage) == "undefined"){return;}
	$(element).parent().addClass("disabled");

	var post_id = document.getElementById('single-post-id').getAttribute("data-pid");;
	var id_clicked = $(element).find(".feedback-emoji-counter").attr("id");
	var reaction = id_clicked.substring(11,id_clicked.length - 6 );

	$(element).addClass("voted");
	$(element).find(".feedback-emoji-counter").html($(element).find(".feedback-emoji-counter").html()*1 + 1);	
	$(element).append('<i class="fas fa-check-circle"></i>');


	if (typeof(Storage) !== "undefined") {
		localStorage.setItem("react_post_"+post_id, "Y");
		localStorage.setItem('react_post_result_'+post_id, reaction);
	}

	var xmlhttp = new XMLHttpRequest();

    xmlhttp.onreadystatechange = function() {
        if (xmlhttp.readyState == XMLHttpRequest.DONE) {   // XMLHttpRequest.DONE == 4
        	
           if (xmlhttp.status == 200) {
			   console.log(xmlhttp.responseText);
               eval(xmlhttp.responseText);
           }
        }
    };

    xmlhttp.open("POST", "/front-ajx.php", true);
    xmlhttp.setRequestHeader('content-type', 'application/x-www-form-urlencoded');
	xmlhttp.send("action=custom_single_post_react&postid="+post_id+'&react='+reaction);
}

function copyShare(el){
	let hasPbClass = $("body").hasClass("pb");
	$("body").removeClass("pb");
	var tempInput = document.createElement("input");
    tempInput.style = "position: absolute; left: -1000px; top: -1000px";

	if(currentStateArticle == 2){
		link = secondary_article_url;
	}else{
		link = $("#single-post-id .single-post-shortlink").attr("data-link");
	}

    tempInput.value = link;
    document.body.appendChild(tempInput);
    tempInput.select();
    document.execCommand("copy");
    document.body.removeChild(tempInput);
	if(hasPbClass == true){
        $("body").addClass("pb");
    }

	$(el).html('<i class="fas fa-check"></i>');

	setTimeout(
		function() 
		{
			$(el).html('<i class="fas fa-link"></i>')
		}, 3000);

}

function weixinShare(){
	if (navigator.share) {
		
		if(currentStateArticle == 2){
			link = secondary_article_url;
			name = secondary_article_title;
		}
		else{
			link = $("#single-post-id .single-post-shortlink").attr("data-link");
			name = $("#single-post-id .single-post-sharename").attr("data-name");
		}

		navigator.share({
		  title:  name,
		  text: name,
		  url: link,
		})
		  .then(() => console.log('Successful share'))
		  .catch((error) => console.log('Error sharing', error));
	  }
}


var hot_topic_retrieved = false;

function retrieve_topic_keyword(){
	if(hot_topic_retrieved == true){
		$(".site-search-desktop-topic").fadeIn();
		$(".site-search-mobile-topic").fadeIn();
		 return;
	 }

	 hot_topic_retrieved = true;
	 $.ajax({
		url: ax_host+'/ajx-api/topic/'
	})
	.done(function( html ) {
		lists = JSON.parse(html);

		if(lists){
			let temp_html1 = "";
			let temp_html2 = "";
			for (i = 0; i < lists.length; i++) {
				let obj = lists[i];

				temp_html1 += ' <div class="site-search-mobile-dashijian-item" ><a class="internalLink" data-title="'+obj.name+'" href="'+obj.path+'"><h2 class="skip-default-style">'+
					(i+1)+'. '+obj.name+
				'</h2></a></div>';
			
				temp_html2 += ' <div class="site-search-desktop-dashijian-item" ><a class="internalLink" data-title="'+obj.name+'" href="'+obj.path+'"><h2 class="skip-default-style">'+
					(i+1)+'. '+obj.name+
				'</h2></a></div>';
			}

			if(temp_html2 != ""){
				$("#site-search-desktop-dashijian-list").html(temp_html2);	
				$(".site-search-desktop-topic").fadeIn();	
				
				$("#site-search-mobile-dashijian-list").html(temp_html1);	
				$(".site-search-mobile-topic").fadeIn();	
			}
		}
		
	});
	 
}

function initHotTopic(){

	if($(".hot-topic-bar-wrapper").length > 0){
		$.ajax({
			url: ax_host+'/ajx-api/topic/'
		})
		.done(function( html ) {
			lists = JSON.parse(html);
	
			if(lists){
				let temp_html = "";
				let temp_html2 = "";
				let temp_html3 = "";
				for (i = 0; i < lists.length; i++) {
					let obj = lists[i];

					if(!jQuery(".webview.article-page.mobile-article").length){
						temp_html += '<a href="' + obj.path + '" class="nav-item internalLink" data-title="' + obj.name + '">'+
						'<span class="nav-text">' + obj.name + '</span>'+
						'</a>';
					}else{
						temp_html += '<a class="nav-item internalLink" data-title="' + obj.name + '" onclick="notifyTag(\'' + obj.term_id + '\', \'' + obj.name + '\', \'' + obj.path + '\')">' +
						'<span class="nav-text">' + obj.name + '</span>' +
						'</a>';
					}

					temp_html2 += ' <div class="site-search-desktop-dashijian-item" ><a class="internalLink" data-title="'+obj.name+'" href="'+obj.path+'"><h2 class="skip-default-style">'+
						(i+1)+'. '+obj.name+
					'</h2></a></div>';

					temp_html3 += ' <div class="site-search-mobile-dashijian-item" ><a class="internalLink" data-title="'+obj.name+'" href="'+obj.path+'"><h2 class="skip-default-style">'+
						(i+1)+'. '+obj.name+
					'</h2></a></div>';
				}
	
				if(temp_html != ""){						
					$(".hot-topic-bar .nav-items").html(temp_html);	//main - mobile bar
					$(".hot-topic-bar-wrapper").addClass("show");

					$(".hot-topic-widget-list").html(temp_html); //main - desktop list
					$(".hot-topic-wrapper").addClass("show");

					$("#site-search-desktop-dashijian-list").html(temp_html2);	
					$("#site-search-mobile-dashijian-list").html(temp_html3);				
				}
			}
			hot_topic_retrieved = true;
		});
	}
		
}

var listingLoading = false;
var listingItemEnded = false;

function categoryNextPage(nooffset = false, videoPost = false, isEditorial = false, postfix =""){
	listingLoading = true;
	$('#category-load-more'+postfix).addClass("hidden");
	$('#category-loading').removeClass("hidden");
	var pageNum = $("#category-page-meta .category-page-paging-counter"+postfix).attr("data-num");
	$("#category-page-meta .category-page-paging-counter"+postfix).attr("data-num",++pageNum);
	var cat = $("#category-page-meta"+postfix).attr("data-catid");
	var editorial = isEditorial == true? 1 : 0;
	var api_url = ax_host+"/ajx-api/category_posts/?cat="+cat+"&page="+pageNum+"&nooffset="+nooffset+"&editorialcat="+editorial+"&posts_per_pages=10";

    var queryType = $("#category-page-meta"+postfix).attr("data-querytype");
    var isVipTopic = queryType === 'vip-topic';	
	if (isVipTopic) {
		api_url = api_url + "&viptopicpost=1";
	}

	$.ajax({
		url: api_url
	})
	.done(function( html ) {
		$('#category-loading').addClass("hidden");
		
		lists = JSON.parse(html);

		if(lists){
			for (i = 0; i < lists.length; i++) {
				let obj = lists[i];
				if(typeof(post_ids_in_listing)  !== "undefined" && post_ids_in_listing){
					if(post_ids_in_listing.includes(obj.ID + '')){
						continue;
					}
				}
				if(videoPost == false){
					var tmp_str = '<div class="horizontal-line horizontal-line-40h grey-color mobile-hidden"></div>\
									<div class="horizontal-space horizontal-space-20h grey-color desktop-hidden"></div>';
					let wrapperclass = "";
					let imageHtml = "";
					if(!obj.image || obj.image == ""){
						wrapperclass  = "no-img-frame";
					}
					else{
						imageHtml = '<div class="img-frame">\
										<a class="internalLink pending-reg-click-event" data-title="'+obj.title+'" href="'+obj.permalink+'">\
											<img class="img" src="'+obj.image+'"/>\
										</a>\
										'+obj.play_button+'\
									</div>';
					}

					let live_icon_class="hidden";
					if(obj.live_icon==1){ live_icon_class= ""; }

					tmp_str +=  '<div class="horizontal-post-frame  mobile-border '+ wrapperclass+'">'+imageHtml+'\
									<div class="cat cat-desktop">\
										<a class="internalLink pending-reg-click-event" data-title="'+obj.cat+'" href="'+obj.catlink+'">'+obj.cat+'</a>\
									</div>\
									<h2 class="title skip-default-style">\
										<span class="live-badge-listing live-badge-listing-red '+live_icon_class+'">LIVE</span>\
										<a class="internalLink pending-reg-click-event" data-title="'+obj.title+'" href="'+obj.permalink+'">'+obj.title+'</a>\
									</h2>\
									<div class="desc desc-desktop">\
										<a class="internalLink pending-reg-click-event" data-title="'+obj.title+'" href="'+obj.permalink+'">\
										'+obj.excerpt+'\
										</a>\
									</div>\
									<div class="meta">\
										<span class="time">'+obj.time_display+'</span>\
											<span class="counter post-view-counter-parent post-view-counter-parent-'+obj.ID+'">\
												<i class="far fa-eye"></i>\
												<span  data-pid="'+obj.ID+'" class="post-view-counter post-view-'+obj.ID+'"></span>\
											</span>\
									</div>\
									<div class="cat cat-mobile">\
										<a class="internalLink pending-reg-click-event" data-title="'+obj.cat+'" href="'+obj.catlink+'">'+obj.cat+'</a>\
									</div>\
								</div>';
				}else{
					let imageHtml = "";
					if(!obj.image || obj.image == ""){
						wrapperclass  = "no-img-frame";
					}
					else{
						imageHtml = '<div class="img-frame">\
										<a class="internalLink pending-reg-click-event" data-title="'+obj.title+'" href="'+obj.permalink+'">\
											<img class="img" src="'+obj.image+'"/>\
										</a>\
										<div class="meta meta-desktop">\
											<span class="time">'+obj.time_display+'</span>\
											<span class="counter post-view-counter-parent post-view-counter-parent-'+obj.ID+'">\
												<i class="far fa-eye"></i>\
												<span  data-pid="'+obj.ID+'" class="post-view-counter post-view-'+obj.ID+'"></span>\
											</span>\
										</div>\
										<i class="fas fa-play-circle"></i>\
									</div>';
					}
					var tmp_str ='<div class="horizontal-space horizontal-space-20h desktop-hidden"></div>\
									<div class="vertical-post-frame mobile-horizontal video-cat-post video-post-frame mobile-border clearfix">\
										<div class="horizontal-space horizontal-space-20h mobile-hidden"></div>\
										'+imageHtml+'\
										<h2 class="title title-mobile">\
											<a class="internalLink pending-reg-click-event" data-title="'+obj.title+'" href='+obj.permalink+'">'+obj.title+'</a>\
										</h2>\
										<div class="meta mobile-meta">\
											<span class="time">'+obj.time_display+'</span>\
											<span class="counter post-view-counter-parent post-view-counter-parent-'+obj.ID+'">\
												<i class="far fa-eye"></i>\
												<span  data-pid="'+obj.ID+'" class="post-view-counter post-view-'+obj.ID+'"></span>\
											</span>\
										</div>\
									</div>';
				}
				$("#cat-post-list"+postfix).append(tmp_str);
			}

			initPostView(document.getElementById("cat-post-list"+postfix));
			jQuery('a.internalLink.pending-reg-click-event:not([target="_blank"])').click(internalLinkRegClickEvent);
			jQuery('a.internalLink.pending-reg-click-event').removeClass("pending-reg-click-event");
			convertTradSimpCN(document.getElementById("cat-post-list"+postfix));

			ga('create', 'UA-33948949-1', 'auto');
			ga('send', 'pageview');
			gtag('event', 'page_view', {
			send_to: 'G-74B2VR88L4'
			});

			gtag('event', 'page_view', {
			send_to: 'G-YBRYTH4EC2'
			});

			gtag('event', 'page_view', {
				send_to: 'AW-11054747425'
			});

			if(lists.length >= 10 ){
				if(autoLoadMoreInListing == true){
					// if(autoLoadMoreInListingCount >= 3){
					// 	$('#category-load-more'+postfix).removeClass("hidden");
					// }
				}
				else{
					$('#category-load-more'+postfix).removeClass("hidden");
				}
			}
			else{
				listingItemEnded = true;
			}
		}

		listingLoading = false;
	});
}


function categoryNextPage_vertical(nooffset = false, videoPost = false, isEditorial = false, postfix =""){
	listingLoading = true;
	$('#category-load-more'+postfix).addClass("hidden");
	$('#category-loading').removeClass("hidden");
	var pageNum = $("#category-page-meta .category-page-paging-counter"+postfix).attr("data-num");
	$("#category-page-meta .category-page-paging-counter"+postfix).attr("data-num",++pageNum);
	var cat = $("#category-page-meta"+postfix).attr("data-catid");;
	var editorial = isEditorial == true? 1 : 0;
	var api_url = ax_host+"/ajx-api/category_posts/?cat="+cat+"&page="+pageNum+"&nooffset="+nooffset+"&editorialcat="+editorial+"&posts_per_pages=10";
    var queryType = $("#category-page-meta"+postfix).attr("data-querytype");
    var isVipTopic = queryType === 'vip-topic';
	if (isVipTopic) {
		api_url = api_url + "&viptopicpost=1";
	}

	$.ajax({
		url: api_url
	})
	.done(function( html ) {
		$('#category-loading').addClass("hidden");
		
		lists = JSON.parse(html);

		if(lists){
			for (i = 0; i < lists.length; i++) {
				let obj = lists[i];
				if(typeof(post_ids_in_listing)  !== "undefined" && post_ids_in_listing){
					if(post_ids_in_listing.includes(obj.ID + '')){
						continue;
					}
				}

				if(!obj.image || obj.image == ""){
					obj.image = cat==3 ? defaultCoverFinance : defaultCover;
				}

				if(videoPost == false){

					let live_icon_class="hidden";
					if(obj.live_icon==1){ live_icon_class= ""; }									
					
					var tmp_str = `
						<div class="horizontal-space horizontal-space-20h grey-color desktop-hidden"></div>

						<div class="desktop-3col-mobile-1col type2 vertical-post-frame mobile-horizontal">
							<div class="img-frame">
								<a class="internalLink pending-reg-click-event" data-title="${obj.title}" href="${obj.permalink}">
									<img class="img" src="${obj.image}" onerror="this.src='${defaultCover}'" />
								</a>
								${obj.play_button}
							</div>

							<div class="post-frame-mobile-right">
								<div class="cat cat-desktop">
									<a class="internalLink" data-title="${obj.cat}" href="${obj.catlink}">${obj.cat}</a>
								</div>
								<div class="title">
									<span class="live-badge-listing live-badge-listing-red ${live_icon_class}">LIVE</span>
									<a class="internalLink pending-reg-click-event" data-title="${obj.title}" href="${obj.permalink}">${obj.title}</a>
								</div>
								<div class="meta">
									<span class="time">${obj.time_display}</span>
									<span class="counter post-view-counter-parent post-view-counter-parent-${obj.ID}">
										<i class="far fa-eye"></i><span data-pid="${obj.ID}" class="post-view-counter post-view-${obj.ID}"></span>
									</span>
								</div>
								<div class="cat cat-mobile">
								<a class="internalLink" data-title="${obj.cat}" href="${obj.catlink}">${obj.cat}</a>
								</div>
							</div>

						</div>`;
				}
				else{

					let imageHtml = `
					<div class="img-frame">
						<a class="internalLink pending-reg-click-event" data-title="${obj.title}" href="${obj.permalink}">
							<img class="img" src="${obj.image}"/>
						</a>
						<div class="meta meta-desktop">
							<span class="time">${obj.time_display}</span>
							<span class="counter post-view-counter-parent post-view-counter-parent-${obj.ID}">
								<i class="far fa-eye"></i>
								<span data-pid="${obj.ID}" class="post-view-counter post-view-${obj.ID}"></span>
							</span>
						</div>
						<i class="fas fa-play-circle"></i>
					</div>`;
					
					let tmp_str = `
						<div class="horizontal-space horizontal-space-20h desktop-hidden"></div>
						<div class="vertical-post-frame mobile-horizontal video-cat-post video-post-frame mobile-border clearfix">
							<div class="horizontal-space horizontal-space-20h mobile-hidden"></div>
							${imageHtml}
							<div class="title title-mobile">
								<a class="internalLink pending-reg-click-event" data-title="${obj.title}" href="${obj.permalink}">${obj.title}</a>
							</div>
							<div class="meta mobile-meta">
								<span class="time">${obj.time_display}</span>
								<span class="counter post-view-counter-parent post-view-counter-parent-${obj.ID}">
									<i class="far fa-eye"></i>
									<span data-pid="${obj.ID}" class="post-view-counter post-view-${obj.ID}"></span>
								</span>
							</div>
						</div>`;
				}

				$("#cat-post-list"+postfix).append(tmp_str);

			}

			initPostView(document.getElementById("cat-post-list"+postfix));
			jQuery('a.internalLink.pending-reg-click-event:not([target="_blank"])').click(internalLinkRegClickEvent);
			jQuery('a.internalLink.pending-reg-click-event').removeClass("pending-reg-click-event");
			convertTradSimpCN(document.getElementById("cat-post-list"+postfix));

			ga('create', 'UA-33948949-1', 'auto');
			ga('send', 'pageview');
			gtag('event', 'page_view', {
			send_to: 'G-74B2VR88L4'
			});

			gtag('event', 'page_view', {
			send_to: 'G-YBRYTH4EC2'
			});

			gtag('event', 'page_view', {
				send_to: 'AW-11054747425'
			});

			//if(lists.length >= 12 ){ //sometimes category_posts return 10 post only.

			if(lists.length >= 10 ){
				if(autoLoadMoreInListing == true){
					// if(autoLoadMoreInListingCount >= 3){
					// 	$('#category-load-more'+postfix).removeClass("hidden");
					// }
				}
				else{
					$('#category-load-more'+postfix).removeClass("hidden");
				}
			}
			else{
				listingItemEnded = true;
			}
		}

		listingLoading = false;
	});
}

function categoryNextPage_anniversary(nooffset = false, videoPost = false, isEditorial = false, postfix =""){
	listingLoading = true;
	$('#category-load-more'+postfix).addClass("hidden");
	$('#category-loading').removeClass("hidden");
	var pageNum = $("#category-page-meta .category-page-paging-counter"+postfix).attr("data-num");
	$("#category-page-meta .category-page-paging-counter"+postfix).attr("data-num",++pageNum);
	var cat = $("#category-page-meta"+postfix).attr("data-catid");;
	var editorial = isEditorial == true? 1 : 0;
	$.ajax({
		url: ax_host+"/ajx-api/category_posts/?cat="+cat+"&page="+pageNum+"&nooffset="+nooffset+"&editorialcat="+editorial+"&posts_per_pages=10"
	})
	.done(function( html ) {
		$('#category-loading').addClass("hidden");
		
		lists = JSON.parse(html);

		if(lists){
			for (i = 0; i < lists.length; i++) {
				let obj = lists[i];
				if(typeof(post_ids_in_listing)  !== "undefined" && post_ids_in_listing){
					if(post_ids_in_listing.includes(obj.ID + '')){
						continue;
					}
				}

				if(!obj.image || obj.image == ""){
					obj.image = defaultCover;
				}

				if(videoPost == false){

					let live_icon_class="hidden";
					if(obj.live_icon==1){ live_icon_class= ""; }									
					
					obj.excerpt = stripContent(obj.excerpt, 60);

					var tmp_str = `
						<div class="horizontal-space horizontal-space-20h mobile-hidden"></div>
						<div class="horizontal-space horizontal-space-20h desktop-hidden"></div>

						<div class="desktop-horizontal-mobile-vertical-post-frame mobile-1col">
						<div class="desktop-horizontal-mobile-vertical-post">

							<div class="img-frame">
								<a class="internalLink pending-reg-click-event" data-title="${obj.title}" href="${obj.permalink}">
									<img class="img" src="${obj.image}" onerror="this.src='${defaultCover}'" />
								</a>
								${obj.play_button}
							</div>
							<div class="title">
								<span class="live-badge-listing live-badge-listing-red ${live_icon_class}">LIVE</span>
								<a class="internalLink pending-reg-click-event" data-title="${obj.title}" href="${obj.permalink}">${obj.title}</a>
							</div>
							<div class="desc">
							<a class="internalLink" data-title="${obj.title}" href="${obj.permalink}">${obj.excerpt}</a>
							</div>							

						</div>
						</div>`;

				}

				$("#cat-post-list"+postfix).append(tmp_str);

			}

			initPostView(document.getElementById("cat-post-list"+postfix));
			jQuery('a.internalLink.pending-reg-click-event:not([target="_blank"])').click(internalLinkRegClickEvent);
			jQuery('a.internalLink.pending-reg-click-event').removeClass("pending-reg-click-event");
			convertTradSimpCN(document.getElementById("cat-post-list"+postfix));

			ga('create', 'UA-33948949-1', 'auto');
			ga('send', 'pageview');
			gtag('event', 'page_view', {
			send_to: 'G-74B2VR88L4'
			});

			gtag('event', 'page_view', {
			send_to: 'G-YBRYTH4EC2'
			});

			gtag('event', 'page_view', {
				send_to: 'AW-11054747425'
			});

			if(lists.length >= 10 ){
				if(autoLoadMoreInListing == true){
					// if(autoLoadMoreInListingCount >= 3){
					// 	$('#category-load-more'+postfix).removeClass("hidden");
					// }
				}
				else{
					$('#category-load-more'+postfix).removeClass("hidden");
				}
			}
			else{
				listingItemEnded = true;
			}
		}

		listingLoading = false;
	});
}

function stripContent(content, length = 45) {
    content = content.replace(/<script.*?<\/script>/gi, "");
    content = content.replace(/\[(\S+)[^\]]*][^\[]*\[\/[^\]]*\]/g, "");
    content = content.replace(']]>', ']]&gt;');
    return textEllipsis(content, false, length);
}
function textEllipsis(string, includePtag = true, limit = 45) {
    string = string.replace('　', '').trim();
    let result = string.substring(0, limit);
    if (result.length < string.length) {
        result += '...';
    }
    return includePtag ? `<p>${result}</p>` : result.replace(/\r|\n/g, "");
}

function categoryMain3NextPage(nooffset = false, videoPost = false, isEditorial = false, postfix =""){
	listingLoading = true;
	$('#category-load-more'+postfix).addClass("hidden");
	$('#category-loading').removeClass("hidden");
	var pageNum = $("#category-page-meta .category-page-paging-counter"+postfix).attr("data-num");
	$("#category-page-meta .category-page-paging-counter"+postfix).attr("data-num",++pageNum);
	var cat = $("#category-page-meta"+postfix).attr("data-catid");;
	var editorial = isEditorial == true? 1 : 0;
	$.ajax({
		url: ax_host+"/ajx-api/category_posts/?cat="+cat+"&page="+pageNum+"&nooffset="+nooffset+"&editorialcat="+editorial+"&posts_per_pages=10"
	})
	.done(function( html ) {
		$('#category-loading').addClass("hidden");
		
		lists = JSON.parse(html);

		if(lists){
			for (i = 0; i < lists.length; i++) {
				let obj = lists[i];
				if(typeof(post_ids_in_listing)  !== "undefined" && post_ids_in_listing){
					if(post_ids_in_listing.includes(obj.ID + '')){
						continue;
					}
				}
				if(videoPost == false){
					// var tmp_str = '<div class="horizontal-line horizontal-line-40h grey-color mobile-hidden"></div>\
					// 				<div class="horizontal-space horizontal-space-20h grey-color desktop-hidden"></div>';

					var tmp_str = "";

					let wrapperclass = "";
					let imageHtml = "";
					if(!obj.image || obj.image == ""){
						wrapperclass  = "no-img-frame-inner-div";
					}
					else{
						imageHtml = '<div class="img-frame">\
										<a class="internalLink pending-reg-click-event" data-title="'+obj.title+'" href="'+obj.permalink+'">\
											<img class="img" src="'+obj.image+'"/>\
										</a>\
										'+obj.play_button+'\
									</div>';
					}

					var cus_classes = "";
					var excerpt = "";
					var cate_desktop = "";
					var cate_mobile = "";

					tmp_str = '<div class="horizontal-line horizontal-line-40h grey-color"></div>';
					cus_classes = "vertical-post-frame ";
					cate_desktop = "";
					cate_mobile = "";
					if(!obj.image || obj.image == ""){
					excerpt = '<div class="desc"><a class="internalLink" data-title="'+obj.title+'" href="'+obj.permalink+'">'+obj.excerpt+'</a></div>';
					}else{
					excerpt = '';
					}
					
					tmp_str +=  '<div class="'+ cus_classes + wrapperclass + '">'+ imageHtml + cate_desktop +'\
									<div class="title">\
										<a class="internalLink pending-reg-click-event" data-title="'+obj.title+'" href="'+obj.permalink+'">'+obj.title+'</a>\
									</div>'+ excerpt +'\
									<div class="meta">\
										<span class="time">'+obj.time_display+'</span>\
											<span class="counter post-view-counter-parent post-view-counter-parent-'+obj.ID+'">\
												<i class="far fa-eye"></i>\
												<span  data-pid="'+obj.ID+'" class="post-view-counter post-view-'+obj.ID+'"></span>\
											</span>\
									</div>'+ cate_mobile +'\
								</div>';
				}else{
					let imageHtml = "";
					if(!obj.image || obj.image == ""){
						wrapperclass  = "no-img-frame";
					}
					else{
						imageHtml = '<div class="img-frame">\
										<a class="internalLink pending-reg-click-event" data-title="'+obj.title+'" href="'+obj.permalink+'">\
											<img class="img" src="'+obj.image+'"/>\
										</a>\
										<div class="meta meta-desktop">\
											<span class="time">'+obj.time_display+'</span>\
											<span class="counter post-view-counter-parent post-view-counter-parent-'+obj.ID+'">\
												<i class="far fa-eye"></i>\
												<span  data-pid="'+obj.ID+'" class="post-view-counter post-view-'+obj.ID+'"></span>\
											</span>\
										</div>\
										<i class="fas fa-play-circle"></i>\
									</div>';
					}
					var tmp_str ='<div class="horizontal-space horizontal-space-20h desktop-hidden"></div>\
									<div class="vertical-post-frame mobile-horizontal video-cat-post video-post-frame mobile-border clearfix">\
										<div class="horizontal-space horizontal-space-20h mobile-hidden"></div>\
										'+imageHtml+'\
										<div class="title title-mobile">\
											<a class="internalLink pending-reg-click-event" data-title="'+obj.title+'" href='+obj.permalink+'">'+obj.title+'</a>\
										</div>\
										<div class="meta mobile-meta">\
											<span class="time">'+obj.time_display+'</span>\
											<span class="counter post-view-counter-parent post-view-counter-parent-'+obj.ID+'">\
												<i class="far fa-eye"></i>\
												<span  data-pid="'+obj.ID+'" class="post-view-counter post-view-'+obj.ID+'"></span>\
											</span>\
										</div>\
									</div>';
				}
				$("#cat-post-list"+postfix).append(tmp_str);
			}

			initPostView(document.getElementById("cat-post-list"+postfix));
			jQuery('a.internalLink.pending-reg-click-event:not([target="_blank"])').click(internalLinkRegClickEvent);
			jQuery('a.internalLink.pending-reg-click-event').removeClass("pending-reg-click-event");
			convertTradSimpCN(document.getElementById("cat-post-list"+postfix));

			ga('create', 'UA-33948949-1', 'auto');
			ga('send', 'pageview');

			if(lists.length >= 10 ){
				if(autoLoadMoreInListing == true){
					// if(autoLoadMoreInListingCount >= 3){
					// 	$('#category-load-more'+postfix).removeClass("hidden");
					// }
				}
				else{
					$('#category-load-more'+postfix).removeClass("hidden");
				}
			}
			else{
				listingItemEnded = true;
			}
		}

		listingLoading = false;
	});
}


function stockNextPage(nooffset = false){
	$('#stock-load-more').addClass("hidden");
	$('#stock-loading').removeClass("hidden");
	var pageNum = $("#stock-page-meta .stock-page-paging-counter").attr("data-num");
	$("#stock-page-meta .stock-page-paging-counter").attr("data-num",++pageNum);
	var cat = $("#stock-page-meta").attr("data-catid");;
	$.ajax({
		url: ax_host+ "/ajx-api/stock-article-api?paged="+pageNum+"&stockid="+stockcode
	})
	.done(function( html ) {
		$('#stock-loading').addClass("hidden");		
		lists = JSON.parse(html);

        if(lists){

            //var tmp_str =``;
            for (i = 0; i < lists.length; i++)
            {
                let tmp_str =``;				
                let obj = lists[i];
                let objID = obj.ID;
                let the_thumb = obj.social_media_cover_image;
                let the_category = obj.cat;
                let the_permalink = obj.the_permalink;
                let the_title = obj.post_title;
                let the_desc = obj.post_excerpt;                
                let the_ago =  getTimeAgo(new Date(obj.post_date));
                let the_counter = obj.pin_post;

                if(i>0)
                {
                    tmp_str += `
                    <div class="horizontal-line horizontal-line-40h grey-color mobile-hidden"></div>
                    <div class="horizontal-space horizontal-space-20h grey-color desktop-hidden"></div>            
                    `;
                }

                let noframeclass='';
                if(!the_thumb || the_thumb == ""){
                    noframeclass = "no-img-frame";
                }else{
                    noframeclass= "";
                }
                
                tmp_str += `<div class="horizontal-post-frame  mobile-border `+noframeclass+`">`;

				if (the_thumb != '') {
					tmp_str += `
						<div class="img-frame">
							<a class="internalLink" data-title="" href="${the_permalink}">
								<img class="img" src="${the_thumb}">
							</a>
						</div>`;
				}

                tmp_str += `
                    <div class="cat cat-desktop">
                        <a class="internalLink" data-title="" href="`+the_permalink+`">`+the_category+`</a>
                    </div>
                    <div class="title">
                        <a class="internalLink" data-title="" href="`+the_permalink+`">`+the_title+`</a>
                    </div>
                    <div class="desc desc-desktop">
                        <a class="internalLink" data-title="" href="`+the_permalink+`">
                            `+the_desc+` </a>
                    </div>
                    <div class="meta">
                        <span class="time">`+the_ago+`</span>
                        <span class="counter post-view-counter-parent post-view-counter-parent-`+objID+` show">
                            <i class="far fa-eye"></i>
                            <span data-pid="`+objID+`" class="post-view-counter post-view-`+objID+`">2点阅</span>
                        </span>
                    </div>
                    <div class="cat cat-mobile">
                        <a class="internalLink" data-title="" href="`+the_permalink+`">`+the_category+`</a>
                    </div>
                `;
                tmp_str += `</div>`;
                $("#stock-post-list").append(tmp_str);				
            }
            //$("#stock-post-list").append(tmp_str);

			initPostView(document.getElementById("stock-post-list"));
			jQuery('a.internalLink.pending-reg-click-event:not([target="_blank"])').click(internalLinkRegClickEvent);
			jQuery('a.internalLink.pending-reg-click-event').removeClass("pending-reg-click-event");
			convertTradSimpCN(document.getElementById("stock-post-list"));

			if(lists.length >= 10 ){
				$('#stock-load-more').removeClass("hidden");
			}

        }

	});
}

function getTimeAgo(date) {
	const MINUTE = 60, HOUR = MINUTE * 60, DAY = HOUR * 24, WEEK = DAY * 7, MONTH = DAY * 30, YEAR = DAY * 365;
	const secondsAgo = Math.round((+new Date() - date) / 1000)
	let divisor = unit = null
	if (secondsAgo < MINUTE) {
	  return secondsAgo + " 秒前"
	} else if (secondsAgo < HOUR) {
	  [divisor, unit] = [MINUTE, '分钟']
	} else if (secondsAgo < DAY) {
	  [divisor, unit] = [HOUR, '小时']
	} else if (secondsAgo < WEEK) {
	  [divisor, unit] = [DAY, '天']
	} else if (secondsAgo < MONTH) {
	  [divisor, unit] = [WEEK, '星期']
	} else if (secondsAgo < YEAR) {
	  [divisor, unit] = [MONTH, '月']
	} else if (secondsAgo > YEAR) {
	  [divisor, unit] = [YEAR, '年']
	}
	count = Math.floor(secondsAgo / divisor)
	return  `${count}${unit}${(count > 1)?'':''}前`
  }

function tagNextPage(){
	listingLoading = true;
	$('#category-load-more').addClass("hidden");
	$('#category-loading').removeClass("hidden");
	var pageNum = $("#category-page-meta .category-page-paging-counter").attr("data-num");
	$("#category-page-meta .category-page-paging-counter").attr("data-num",++pageNum);
	var cat = $("#category-page-meta").attr("data-catid");
	$.ajax({
		url: ax_host+"/ajx-api/tag_posts/?cat="+cat+"&page="+pageNum
	})
	.done(function( html ) { 
		$('#category-loading').addClass("hidden");
		
		lists = JSON.parse(html);

		if(lists){
			for (i = 0; i < lists.length; i++) {
				let obj = lists[i];
				let tmp_str = '<div class="horizontal-line horizontal-line-40h grey-color mobile-hidden"></div>\
                				<div class="horizontal-space horizontal-space-20h grey-color desktop-hidden"></div>';
				let wrapperclass = "";
				let imageHtml = "";
				if(!obj.image || obj.image == ""){
					wrapperclass  = "no-img-frame";
				}
				else{
					imageHtml = '<div class="img-frame">\
									<a class="internalLink pending-reg-click-event" data-title="'+obj.title+'" href="'+obj.permalink+'">\
										<img class="img" src="'+obj.image+'"/>\
									</a>\
									'+obj.play_button+'\
								</div>';
				}
					
				tmp_str +=  '<div class="horizontal-post-frame  mobile-border '+ wrapperclass+'">'+imageHtml+'\
								<div class="cat cat-desktop">\
									<a class="internalLink pending-reg-click-event" data-title="'+obj.cat+'" href="'+obj.catlink+'">'+obj.cat+'</a>\
								</div>\
								<div class="title">\
									<a class="internalLink pending-reg-click-event" data-title="'+obj.title+'" href="'+obj.permalink+'">'+obj.title+'</a>\
								</div>\
								<div class="desc desc-desktop">\
									<a class="internalLink pending-reg-click-event" data-title="'+obj.title+'" href="'+obj.permalink+'">\
									'+obj.excerpt+'\
									</a>\
								</div>\
								<div class="meta">\
									<span class="time">'+obj.time_display+'</span>\
										<span class="counter post-view-counter-parent post-view-counter-parent-'+obj.ID+'">\
											<i class="far fa-eye"></i>\
											<span  data-pid="'+obj.ID+'" class="post-view-counter post-view-'+obj.ID+'"></span>\
										</span>\
								</div>\
								<div class="cat cat-mobile">\
									<a class="internalLink pending-reg-click-event" data-title="'+obj.cat+'" href="'+obj.catlink+'">'+obj.cat+'</a>\
								</div>\
							</div>';
				$("#cat-post-list").append(tmp_str);
			}

			initPostView(document.getElementById("cat-post-list"));
			jQuery('a.internalLink.pending-reg-click-event:not([target="_blank"])').click(internalLinkRegClickEvent);
			jQuery('a.internalLink.pending-reg-click-event').removeClass("pending-reg-click-event");
			convertTradSimpCN(document.getElementById("cat-post-list"));

			ga('create', 'UA-33948949-1', 'auto');
			ga('send', 'pageview');
			gtag('event', 'page_view', {
			send_to: 'G-74B2VR88L4'
			});

			gtag('event', 'page_view', {
			send_to: 'G-YBRYTH4EC2'
			});

			gtag('event', 'page_view', {
				send_to: 'AW-11054747425'
			});

			if(lists.length >= 10 ){
				if(autoLoadMoreInListing == true){
					// if(autoLoadMoreInListingCount >= 3){
					// 	$('#category-load-more').removeClass("hidden");
					// }
				}
				else{
					$('#category-load-more').removeClass("hidden");
				}
			}
			else{
				listingItemEnded = true;
			}
		}

		listingLoading = false;
	});
}

/* v1 legacy start*/
var local_news_preference = [];
var local_news_preference_before_change = null;
function toggleLocalNewsPreference(){
	if($(".local-news-preference").length){

		if(!$(".local-news-preference").hasClass("show")){
			local_news_preference_before_change = local_news_preference;
			if($(window).width() < 768){
				freezeBody();
			}
		}

		$(".local-news-preference").toggleClass("show");

		if(!$(".local-news-preference").hasClass("show")){
			if($(window).width() < 768){
				unFreezeBody();
			}
			
			let changes_applied = false;
			if( local_news_preference_before_change == null ||  local_news_preference_before_change.length < 1){
				changes_applied = true;
			}
			else{
				for (var i = 0; i < local_news_preference.length; i++)
				{
					if(local_news_preference[i] !=  local_news_preference_before_change[i]){
						changes_applied = true;
					}
				}
			}

			if(changes_applied == true){
				if (typeof(localStorage) !== "undefined") {
					localStorage.setItem("local_news_preference", JSON.stringify(local_news_preference));
				}

				rearrangeLocalNewsItem();
			}
		}
	}
}

function startArrangeLocalNewsItem(){
	if(local_news_preference == null || local_news_preference.length == 0){
		if (typeof(localStorage) !== "undefined") {
			local_news_preference = JSON.parse(localStorage.getItem("local_news_preference"));

			if(local_news_preference != null && local_news_preference.length > 0){
				for (var i = 0; i < local_news_preference.length; i++)
				{
					$('#local-news-preference .local-news-preference-item[data-catid='+local_news_preference[i]+']').appendTo('#local-news-preference-choices');
				}
				rearrangeLocalNewsItem();
			}
			else{
				if (navigator.geolocation) {
					initLocalNewsCarousel();
					navigator.geolocation.getCurrentPosition(localPositionGet, rearrangeLocalNewsItem);
				} else { 
					rearrangeLocalNewsItem();
				}
			}
		}
		else{
			rearrangeLocalNewsItem();
		}
	}
	else{
		rearrangeLocalNewsItem();
	}
}
/* v1 legacy end*/

function sectionClicked(element) {
    
    let itemSelector, newsItemSelector, moreLinkSelector;

    if (element.classList.contains('localnews-item')) {
        itemSelector = '#localnews-selections .localnews-item';
        newsItemSelector = '.local-news-items';
        moreLinkSelector = '.moreLocalNewsLink';
    } else if (element.classList.contains('section-title-tab')) {
        itemSelector = '.section-title-group .section-title-tab';
        newsItemSelector = '.caijingGroup';
        moreLinkSelector = '.moreCaijingLink';
    } else {
        return;
    }

    const items = document.querySelectorAll(itemSelector);
    items.forEach(item => {
        item.classList.remove('selected');
    });
    element.classList.add('selected');

    const targetCatId = element.getAttribute('data-catid');
    const targetLink = element.getAttribute('data-link');

    // based on clicked item, hide/show news and update link
    const newsItems = document.querySelectorAll(newsItemSelector);
    newsItems.forEach(newsItem => {
        if (newsItem.getAttribute('data-catid') === targetCatId) {
            newsItem.classList.remove('hidden');
            const moreNewsLink = document.querySelectorAll(moreLinkSelector);
            moreNewsLink.forEach(item => {
                item.href = targetLink;
            });
        } else {
            newsItem.classList.add('hidden');
        }
    });
}

function localPositionGet(position) { 
	var theUrl = "https://nominatim.openstreetmap.org/reverse?format=json&lat="+position.coords.latitude+"&lon="+position.coords.longitude;
	httpGetAsync(theUrl, locationStateGet);

  }

  function locationStateGet(res){
	let state ="";
	let loc_json = "";
	if( res){
		 loc_json = JSON.parse( res);
	   }
	   if(loc_json){
		   if(typeof(loc_json.address) != "undefined"){
			   if(typeof(loc_json.address.state) != "undefined"){
				   state = loc_json.address.state;
			   }
			   else if(typeof(loc_json.address.city) != "undefined" ){
				   state = loc_json.address.city;
			   }
		   }
	   }
	   
	   if(state && arr_state_cat[state.toLowerCase()]){
		   var first_catid = arr_state_cat[state.toLowerCase()];
		   local_news_preference = [];
		   $( "#local-news-preference .local-news-preference-item" ).each(function( i ) {
			   if(first_catid == $(this).attr('data-catid')){
				   local_news_preference.unshift($(this).attr('data-catid'));
			   }
			   else{
				   local_news_preference.push($(this).attr('data-catid'));
			   }
		   });
	   
		   for (var i = 0; i < local_news_preference.length; i++)
		   {
			   $('#local-news-preference .local-news-preference-item[data-catid='+local_news_preference[i]+']').appendTo('#local-news-preference-choices');
		   }

		   if(local_news_preference != null && local_news_preference.length > 0){
				if (typeof(localStorage) !== "undefined") {
					localStorage.setItem("local_news_preference", JSON.stringify(local_news_preference));
				}
			}
		   rearrangeLocalNewsItem();
	   }
	   
  }

  function httpGetAsync(theUrl, callback)
{
	
    var xmlHttp = new XMLHttpRequest();
    xmlHttp.onreadystatechange = function() { 
        if (xmlHttp.readyState == 4){
			if(xmlHttp.status == 200){
            callback(xmlHttp.responseText);
			}
			else{
				callback();
			}
		}
		

    }
    xmlHttp.open("GET", theUrl, true); // true for asynchronous 
    xmlHttp.send(null);
}


function rearrangeLocalNewsItem($error = null){
	if(local_news_carousel != null){
		let tempHeight= $(".local-news-list").height();
		local_news_carousel.trigger('destroy.owl.carousel');

		$(".local-news-list").append('<div id="local-news-list-loading" class="loading-layer">\
											<div class="stage loading-dots">\
												<div class="dot-bricks"></div>\
											</div>\
										</div>');
		$("#local-news-list-loading").height(tempHeight);
	}

	
	if(local_news_preference != null && local_news_preference.length > 0){
	
		for (var i = 0; i < local_news_preference.length; i++)
		{
			$('#local-news-wrapper .local-news-item[data-catid='+local_news_preference[i]+']').appendTo('#local-news-wrapper');
		}
	}
	initLocalNewsCarousel();

	if($("#local-news-list-loading").length){
		setTimeout(() => { 
			$("#local-news-list-loading").remove();
		}, 2000);
	}
}
var bodyScrollPosition = 0;

function freezeBody(){
	scrollPosition = window.pageYOffset;
    $('body').css({'overflow':'hidden','position':'fixed', 'top': `-${scrollPosition}px`, 'width': '100%'});
}

function unFreezeBody(){
	$('body').css({'overflow':'','position':'', 'top': '', 'width': ''});
    window.scrollTo(0, scrollPosition);
}

function initMyFavPreference(){
    if($(".my-fav-cols").length){
      if (typeof(localStorage) !== "undefined") {
        var favcollist = localStorage.getItem('fav_cols');
        if(favcollist){
          arr_favcols = JSON.parse(favcollist);
        }
      }
      if(arr_favcols){
        for (var i = 0; i <arr_favcols.length;  i++)
        {
          $("#myfav_selected" ).append($("#fav_selectable_item_"+arr_favcols[i]));
          $("#fav_selectable_item_"+arr_favcols[i]).children(".fas").removeClass("fa-plus-circle");
          $("#fav_selectable_item_"+arr_favcols[i]).children(".fas").addClass("fa-minus-circle");
        }
        renderFavPrefenceShortcutItem();
      }
      
	  if($(".my-fav-cols.v2").length){
		loadFavList_v2();	
	  }else{
		loadFavList();
	  }
	  
    }
  }

  function renderFavPrefenceShortcutItem(){
    if(arr_favcols){
      $("#favor-selections" ).html("");
        for (var i = 0; i <arr_favcols.length;  i++)
        {

          if( $("#fav_selectable_item_"+arr_favcols[i]).length){
            let favor_item_html = '<div onclick="favorItemClicked(this);" id="favor-item-'+arr_favcols[i]+'" class="favor-item" data-termid='+arr_favcols[i]+'>'+
                                    $("#fav_selectable_item_"+arr_favcols[i]).attr('data-termname')+
                                    '<i class="fas fa-minus-circle"></i>'+
                                  '</div>';
            $("#favor-selections").append(favor_item_html);
          }
          
        }
        if(arr_favcols.length == 0){
          $(".favor-item-plus").addClass("noitem");
        }
      }
      else{
        $(".favor-item-plus").addClass("noitem");
      }
  }
  function favorItemClicked(v){

	if( $('.favor-item').length -1 <6){
		$('.fav-minimum').fadeIn(function () {
			$(this).delay(2500).fadeOut(3000);
		});
		return false;
	}
    let termid = $(v).attr("data-termid");
    $("#myfav_choice").append($("#fav_selectable_item_"+termid));
    $("#fav_selectable_item_"+termid).children(".fas").removeClass("fa-minus-circle");
    $("#fav_selectable_item_"+termid).children(".fas").addClass("fa-plus-circle");
    $(v).remove();

	arr_favcols = [];
    $("#myfav_selected .fav_selectable_item").each(function() {
      arr_favcols.push($( this ).attr( "data-termid" ));
    });

    if (typeof(localStorage) !== "undefined") {
         localStorage.setItem('fav_cols', JSON.stringify(arr_favcols));
    }

  }

  function myFavSelectionClicked(v){
    if($(v).parent().hasClass("selected-box")){
      $("#myfav_choice").append($(v));
      $(v).children(".fas").removeClass("fa-minus-circle");
      $(v).children(".fas").addClass("fa-plus-circle");
     
    }
    else{
      $("#myfav_selected").append($(v));
      $(v).children(".fas").removeClass("fa-plus-circle");
      $(v).children(".fas").addClass("fa-minus-circle");
      
    }
  }

  function openMyFavPreference(){
    freezeBody();
    $( ".my-fav-cols:hidden" ).first().fadeIn( "slow" );

    if($('body').width() > 767){
      $(".my-fav-select-left .box").css("height",($(".my-fav-select-left .box").height()+2)+"px");
    }
  }

  function closeMyFavPreference(){
    unFreezeBody();

    arr_favcols = [];
    $("#myfav_selected .fav_selectable_item").each(function() {
      arr_favcols.push($( this ).attr( "data-termid" ));
    });

    if (typeof(localStorage) !== "undefined") {
         localStorage.setItem('fav_cols', JSON.stringify(arr_favcols));
    }

    renderFavPrefenceShortcutItem();

    $( ".my-fav-cols" ).first().fadeOut( "slow" );
    if($('body').width() > 767){
      $(".my-fav-select-left .box").css("height","");
    }

  }

  function closeMyFavBox(){
    unFreezeBody();
    $( ".my-fav-cols" ).first().fadeOut( "slow" );
    if($('body').width() > 767){
      $(".my-fav-select-left .box").css("height","");
    }
  }


  function loadFavList(){
	$('#myfav-loading').removeClass('hidden');
	$('#favlistmore').addClass('hidden');
    favNewsPageNum++;
	$('#favlistmore').removeClass("trk-home-myfav-more-btn-page-"+favNewsPageNum);
	$('#favlistmore').addClass("trk-home-myfav-more-btn-page-"+(favNewsPageNum+1));
    //console.log("loadFavList  pageNum:" + favNewsPageNum);
	//console.log("favNewsList: ", favNewsList);
    if(favNewsPageNum > maxFavNewsPageNum){
      removeFavListMore();
      return;
    }

    let loadAjxRequired = false;

    if(favNewsPageNum == 1){
      if(favNewsList.length < 9 ){
        loadAjxRequired = true;
      }
    }
    else{
      if(favNewsList.length < 6 ){
        loadAjxRequired = true;
      }
    }

    if(loadAjxRequired == true){
       ajxLoadFavArticle(0);
    }
    else{
      displayFavNews();
    }

}


var favNewsAjaxPage = 1;
function ajxLoadFavArticle(index){
 // console.log("ajxLoadFavArticle  index:" + index + "page=" + favNewsAjaxPage);
  $.ajax({
	  url: ax_host+"/ajx-api/fav_posts/?cat="+arr_favcols[index]+"&page="+favNewsAjaxPage
  })
  .done(function( html ) {
	lists = JSON.parse(html);

	if(lists){
	  for (i = 0; i < lists.length; i++) {
		  let obj = lists[i];
		  if(favNewsListIDs.indexOf(obj.ID) < 0){
			favNewsListIDs.push(obj.ID);
			favNewsList.push(obj);
		  }
	  }
	}

	if(index + 1 < arr_favcols.length){
	  ajxLoadFavArticle(index+1);
	}
	else{
	  favNewsAjaxPage++;
	  favNewsList.sort(function(a, b) {
		  return   b.timestamp - a.timestamp;
	  });

	  displayFavNews();
	}
  
});
}

var favRefresh=false;

function displayFavNews(){
 // console.log("displayFavNews favNewsPageNum:", favNewsPageNum, " favNewsList.length: ",favNewsList.length);

  if(favNewsList.length){
      if(favNewsPageNum == 1){ 
        for (let i = 0; i < 3; i++) {
          if(favNewsList.length){
            let post = favNewsList.shift();
            var add_class = "no-img-frame";
            var img_str = "";
			var no_img_inner_frame_start = "";
			var no_img_inner_frame_end= "";
			var desc_str = "";
            var id = post.ID;
            var link = post.permalink;
            var title = post.title;
            var img = post.image;
            var date = post.time_display;
            var cat = post.cat;
            var catlink = post.catlink;
            var content = post.excerpt;
			
                if(img && img.length > 0){
                  add_class = "";
                  img_str = '<div class="img-frame">'+
                                  '<a  class="internalLink pending-register-onclick" data-title="'+title+'" href="'+link+'">'+'<img class="img" src="'+img+'" alt="'+title+'"/>'+'</a>'+
                             '</div>';
                }
				else{
					desc_str= '<div class="desc desc-desktop">'+
								'<a class="internalLink" data-title="'+title+'" href="'+link+'">'+
									content+
								'</a>'+
							  '</div>';

					no_img_inner_frame_start = '<div class="no-img-frame-inner-div">';
					no_img_inner_frame_end = '</div>';
				}
               
				var live_icon_class="hidden";
				if(post.live_icon==1){ live_icon_class= ""; }
            
                let str_html ='<div class="desktop-3col-mobile-1col vertical-post-frame mobile-horizontal '+add_class+'">'+no_img_inner_frame_start+img_str+
                              '<div class="cat cat-desktop">'+
                                  '<a  class="internalLink pending-register-onclick" data-title="'+cat+'" href="'+catlink+'">'+ 
                                    cat+
                                  '</a>'+
                              '</div>'+
                              '<div class="title">'+
								  '<span class="live-badge-listing live-badge-listing-red '+live_icon_class+'">LIVE</span>'+
                                  '<a  class="internalLink pending-register-onclick" data-title="'+title+'" href="'+link+'">'+title+'</a>'+
                              '</div>'+desc_str+
                              '<div class="meta">'+
                                  '<span class="time">'+date+'</span>'+
                                  '<span class="counter post-view-counter-parent post-view-counter-parent-'+id+'">'+
                                    '<i class="far fa-eye"></i><span data-pid="'+id+'" class="post-view-counter post-view-'+id+'"></span>'+
                                  '</span>'+
                              '</div>'+
                              '<div class="cat cat-mobile">'+
                                '<a  class="internalLink pending-register-onclick" data-title="'+cat+'" href="'+catlink+'">'+ 
                                      cat+
                                '</a>'+
                              '</div>'+no_img_inner_frame_end+
                           '</div>'+
                            '<div class="horizontal-line horizontal-line-40h grey-color desktop-hidden "></div>';
							
              
               $('#div-fav-list-first-3-wrapper').append(str_html);      
			   
          }
        }
		$( "#div-fav-list-first-3-wrapper .no-img-frame-inner-div .desc" ).each(function() {
			adjustNoImgDescClamp($( this ));
		});
		

		$('<div class="favzone horizontal-line  grey-color mobile-hidden"></div>').insertBefore( "#div-fav-list-wrapper" );

		if(screen.width > 767){
			$( '<p class="favzone dfp ad_header desktop-ads-frame">ADVERTISEMENT</p><div id="MBR1_L_REFRESH" style="text-align:center"  class="favzone ads-frame"></div>').insertBefore( "#div-fav-list-wrapper" );
			$('<div class="favzone horizontal-line  grey-color mobile-hidden"></div>').insertBefore( "#div-fav-list-wrapper" );
			if(favRefresh==false){
				googletag.cmd.push(function() { googletag.display('MBR1_L_REFRESH'); });
			}
			else{
				googletag.cmd.push(function() {   googletag.pubads().refresh([st_MBR1_L_REFRESH]); });
			}
		}
      }

	  

      for (let i = 0; i < 6; i++) {
          if(favNewsList.length){
			let is_advertorial = false;
			// if(favNewsPageNum == 1 && i ==0 && json_EC1 != ""){
			// 	var post = JSON.parse(json_EC1);
			// 	is_advertorial = true;
			// } 
			// else if(favNewsPageNum == 1 && i ==3 && json_EC2 != ""){
			// 	var post = JSON.parse(json_EC2);
			// 	is_advertorial = true;
			// }
			// else if(favNewsPageNum == 2 && i ==2 && json_EC != ""){
			// 	var post = JSON.parse(json_EC);
			// 	is_advertorial = true;
			// }
			//else{
           		var post = favNewsList.shift();
			//}
            var add_class = "no-img-frame";
            var img_str = "";
            var id = post.ID;
            var link = post.permalink;
            var title = post.title;
            var img = post.image;
            var date = post.time_display;
            var cat = post.cat;
            var catlink = post.catlink;
            var content = post.excerpt;

            if(img && img.length > 0){
              add_class = "";
              img_str = '<div class="img-frame">'+
                                  '<a  class="internalLink pending-register-onclick" data-title="'+title+'" href="'+link+'">'+'<img class="img" src="'+img+'" alt="'+title+'"/>'+'</a>'+
                             '</div>';
            }

            str_html = "";

			let loadB_L = false;
			if(favNewsPageNum == 2 && i == 2){
				if(screen.width > 767){
					str_html += '<div class="favzone horizontal-line horizontal-line-40h grey-color "></div>';
					str_html += '<p class="favzone dfp ad_header desktop-ads-frame">ADVERTISEMENT</p>';
					str_html += '<div id="MB_L_REFRESH" style="text-align:center"  class="favzone ads-frame"></div>';
					loadB_L = true;
				}
			}
			let MBR1_M = false;
			if(favNewsPageNum == 1 && i == 0){
				if(screen.width < 768){
					str_html += '<p class="favzone dfp ad_header mobile-ads-frame">ADVERTISEMENT</p>';
					str_html += '<div id="MBR1_M_REFRESH" style="text-align:center" class="favzone ads-frame"></div>';
					str_html += '<div class="favzone horizontal-line horizontal-line-40h grey-color "></div>';
					MBR1_M = true;
				}
			}

            if((i == 0 && favNewsPageNum != 1) || i != 0){
              str_html += '<div class="favzone horizontal-line horizontal-line-40h grey-color "></div>';
            }


			let advertorial_extra_attr = "";
			let hide_element_class = "";
			if(is_advertorial){

				hide_element_class = post.is_show_shichangqingbao==1? "": " hidden ";			
				add_class += " adv-post";
				advertorial_extra_attr = " adv-placement='"+post.advcode +"' adv-title='"+id+"_"+post.title_escpbr+"' id='ADV_POST_"+post.advcode+"'";
			}

			var live_icon_class="hidden";
			if(post.live_icon==1){ live_icon_class= ""; }			

            str_html +='<div class="horizontal-post-frame '+add_class+'" '+advertorial_extra_attr+'>'+img_str+
                              '<div class="cat cat-desktop'+hide_element_class+'">'+
                                  '<a  class="internalLink pending-register-onclick" data-title="'+cat+'" href="'+catlink+'">'+ 
                                    cat+
                                  '</a>'+
                              '</div>'+
                              '<div class="title">'+
							  	  '<span class="live-badge-listing live-badge-listing-red '+live_icon_class+'">LIVE</span>'+
                                  '<a  class="internalLink pending-register-onclick" data-title="'+title+'" href="'+link+'">'+title+'</a>'+
                              '</div>'+
                              '<div class="desc desc-desktop">'+
                                  '<a  class="internalLink pending-register-onclick" data-title="'+title+'" href="'+link+'">'+content+'</a>'+
                              '</div>'+
                              '<div class="meta">'+
                                  '<span class="time">'+date+'</span>'+
                                  '<span class="counter post-view-counter-parent post-view-counter-parent-'+id+'">'+
                                    '<i class="far fa-eye"></i><span data-pid="'+id+'" class="post-view-counter post-view-'+id+'"></span>'+
                                  '</span>'+
                              '</div>'+
                              '<div class="cat cat-mobile'+hide_element_class+'">'+
                                '<a  class="internalLink pending-register-onclick" data-title="'+cat+'" href="'+catlink+'">'+ 
                                      cat+
                                '</a>'+
                              '</div>'+
                          '</div>';
              
              $('#div-fav-list-wrapper').append(str_html);

			  if(is_advertorial){
				registerAdvertorialEvent(null,"#ADV_POST_"+post.advcode);
			  }

			  if(loadB_L == true){
				if(favRefresh==false){
					googletag.cmd.push(function() { googletag.display('MB_L_REFRESH'); });
				}
				else{
					googletag.cmd.push(function() { googletag.pubads().refresh([st_MB_L_REFRESH]);  });
				}
			  }
			  if(MBR1_M == true){
				if(favRefresh==false){
					googletag.cmd.push(function() { googletag.display('MBR1_M_REFRESH'); });
				}
				else{
					googletag.cmd.push(function() { googletag.pubads().refresh([st_MBR1_M_REFRESH]);  });					
				}				
			  }
          }
      }

      $('#myfav-loading').addClass('hidden');
	  $('#favlistmore').removeClass('hidden');
      if(favNewsPageNum + 1 > maxFavNewsPageNum)  removeFavListMore();
	  jQuery('#myfav-box a.internalLink.pending-register-onclick:not([target="_blank"])').click(internalLinkRegClickEvent);
	  jQuery('#myfav-box a.internalLink.pending-register-onclick').removeClass("pending-register-onclick");
      initPostView(document.getElementById('myfav-box'));

	  convertTradSimpCN(jQuery('#myfav-box'));

	  favRefresh=false;
  }
  else{
    removeFavListMore();
  }
}

function  removeFavListMore(){
  $('#favlistmore').remove();
}


function loadFavList_v2(){
	$('#myfav-loading').removeClass('hidden');
	favNewsPageNum++;
	ajxLoadFavArticle_v2(0);
}

  var favNewsAjaxPage = 1;
  function ajxLoadFavArticle_v2(index){

	var url = ax_host+"/ajx-api/fav_posts/?cat="+arr_favcols[index]+"&page="+favNewsAjaxPage;
    $.ajax({
		url: url
    })
    .done(function( html ) {
      lists = JSON.parse(html);
      if(lists){
        for (i = 0; i < lists.length; i++) {
            let obj = lists[i];
            if(favNewsListIDs.indexOf(obj.ID) < 0){
              favNewsListIDs.push(obj.ID);
              favNewsList.push(obj);
            }
        }
      }
      if(index + 1 < arr_favcols.length){
        ajxLoadFavArticle_v2(index+1);
      }
      else{
		favNewsAjaxPage++;
        favNewsList.sort(function(a, b) {
            return   b.timestamp - a.timestamp;
        });
        displayFavNews_v2();
      }
  	});
}

var favRefresh_v2=false;

function displayFavNews_v2(){
   
	 if(favNewsList.length){
		   for (let i = 0; i < 6; i++) {
			 if(favNewsList.length){
			   let post = favNewsList.shift();
			   var img_str = "";
			   var desc_str = "";
			   var id = post.ID;
			   var link = post.permalink;
			   var title = post.title;
			   var img = post.image || defaultCover;
			   var date = post.time_display;
			   var cat = post.cat;
			   var catlink = post.catlink;
			   
				if (img && img.length > 0) {
					img_str = `
						<div class="img-frame">
							<div class="topleft-cat-label">${cat}</div>
							<a class="internalLink pending-register-onclick" data-title="${title}" href="${link}">
								<img class="img" src="${img}" alt="${title}" />
							</a>
							${post.play_button}
						</div>`;
				}
				
				var live_icon_class="hidden";
				if(post.live_icon==1){ live_icon_class= ""; }			   

				let str_html = `
				<div class="desktop-3col-mobile-2col vertical-post-frame type2 margin-20-desktop margin-20-mobile mobile-border">${img_str}
					<div class="title">
						<span class="live-badge-listing live-badge-listing-red ${live_icon_class}">LIVE</span>
						<a class="internalLink pending-register-onclick" data-title="${title}" href="${link}">${title}</a>
					</div>${desc_str}
					<div class="meta">
						<span class="time">${date}</span>
						<span class="counter post-view-counter-parent post-view-counter-parent-${id}">
							<i class="far fa-eye"></i><span data-pid="${id}" class="post-view-counter post-view-${id}"></span>
						</span>
					</div>
					<div class="cat cat-mobile hidden">
						<a class="internalLink pending-register-onclick" data-title="${cat}" href="${catlink}">${cat}</a>
					</div>
				</div>
				<div class="horizontal-line horizontal-line-40h grey-color hidden desktop-hidden "></div>`;

				$('#div-fav-list-all-wrapper').append(str_html);
			 }
		   }

		 $('#myfav-loading').addClass('hidden');		 
		 jQuery('#myfav-box a.internalLink.pending-register-onclick:not([target="_blank"])').click(internalLinkRegClickEvent);
		 jQuery('#myfav-box a.internalLink.pending-register-onclick').removeClass("pending-register-onclick");
		 initPostView(document.getElementById('myfav-box'));   
		 convertTradSimpCN(jQuery('#myfav-box'));
   
		 favRefresh_v2=false;
	 }
	 
}


var marqueetop = null;
var isDragging = false;
function loadMarquee(){
	if($("#marquee").length){
		$.ajax({
			url: ax_host+"/ajx-api/marquee/"
		})
		.done(function( html ) {
		  lists = JSON.parse(html);

		  if(lists && lists.length > 0){
			let append_html = "";
			for (i = 0; i < lists.length; i++) {
				let obj = lists[i];

				let addclass = obj.internal_link == "1"? "internalLink" : "";
				addclass += " trk-marquee-item";
				let target_a = obj.newtab == true? 'target="_blank"' : "";
				let link = obj.url;
				let title = obj.title;
				let trackable_advertorial = obj.trackable_advertorial;
				let onclick_str ="";
				if(trackable_advertorial && trackable_advertorial == true){
					if(typeof gatitle !== 'undefined' && gatitle && gatitle != ''){
						ga('send', {
						hitType: 'event',
						eventCategory: "BAR1",
						eventAction: 'Impression',
						eventLabel: title,
						title: gatitle
						
						});
						gtag('event', 'Impression', {
						'event_category' : "BAR1",
						'event_label' : title
						});
					}else{
						ga('send', {
						hitType: 'event',
						eventCategory: "BAR1",
						eventAction: 'Impression',
						eventLabel: title
						
						});
						gtag('event', 'Impression', {
						'event_category' : "BAR1",
						'event_label' : title
						});
					}
					
					onclick_str= ' onclick="if(isDragging) { return; } advertorialOnClick(event, this);" ';
				}
			    let str_html = '<a class="'+ addclass + '" href="'+link+'" '+target_a+' data-title="'+title+'"'+onclick_str+'  advtitle="'+title+'" advcode="BAR1"'+'>'+
									title+
									'<span class="marquee_pipe">|</span>'+
								'</a>';
				append_html += str_html;

				
			}

			$("#marquee").html(append_html);
			$("#marquee").addClass("owl-carousel owl-theme");

			marqueetop = $('#marquee').owlCarousel({
				loop: true,
				autoWidth: true,
				items: 4,
				dots: false,
				autoplay: true,
				autoplayTimeout: 4000,
				autoplayHoverPause: true,
				smartSpeed: 500,
				mouseDrag: true,
				onInitialized: checkItem,
    			onTranslated: checkItem,
				onDrag: function(event) {
					isDragging = true;
					this.trigger('stop.owl.autoplay');
					$('#marquee .owl-item a').css({
						'animation': 'none',
						'animation-play-state': 'paused',
					});
				},
				onDragged: function(event) {
					setTimeout(function() {
						isDragging = false;
					}, 100);
					this.trigger('play.owl.autoplay', [4000]);
					checkItem();
				}
			});

		  }

		  convertTradSimpCN(document.getElementById("marquee"));
		});
	}
	               
}

function checkItem() {
    var $currentItem = $('#marquee .owl-item.active a').first();
    var textWidth = $currentItem.width();
    var screenWidth = $(window).width();
	
	$('#marquee .owl-item a').css({
		'animation': 'none',
		'animation-play-state': 'paused',
	});

    if (screenWidth < textWidth) {
		$("#marquee").trigger('stop.owl.autoplay');

		var duration = (textWidth / screenWidth) * 6000;

		setTimeout(function() {
			if($currentItem.parents('.active').length > 0 && !isDragging) {
				var $currentParentItem = $currentItem.parents('.active');

    			if ($currentParentItem.prevAll('.active').length === 0) {
					$currentItem.css({
						'animation': 'marquee ' + duration + 'ms linear infinite',
						'animation-play-state': 'running',
					});

					var stopPosition = textWidth - screenWidth + 15;
					var isAutoPlayOff = true;

					function stopAnimation() {
						if ($currentItem.position().left <= -stopPosition) {
							$currentItem.css('animation-play-state', 'paused');

							if(isAutoPlayOff) {
								setTimeout(function() {
									if($currentItem.parents('.active').length > 0 && !isDragging && $('#ctrl-ticker').find('.fas.fa-pause').length !== 0) {
										$("#marquee").trigger('next.owl.carousel');
										$("#marquee").trigger('play.owl.autoplay', [4000]);
									}
								}, 3500);

								isAutoPlayOff = false;
							}
						}
					}

					var interval = setInterval(stopAnimation, 100);
				}
				
			}
		}, 1000);
    }
}


var marqueetop_v2 = [];
var isDragging = false;

function loadMarquee_v2() {
    
	if($(".marquee").length)
	{

		if (marqueetop_v2.length > 0) {
			marqueetop_v2.forEach(function(marquee) {
				marquee.trigger('destroy.owl.carousel');
			});
			marqueetop_v2 = [];
		}
	
		var marquee_impr_sent = false;		

		$.ajax({
			url: ax_host + "/ajx-api/marquee/"
		}).done(function(html) {
	
			lists = JSON.parse(html);
	
			$(".marquee").each(function(index, element) {
				var $marquee = $(element);
	
				if(lists && lists.length > 0){
				  let append_html = "";
				  for (i = 0; i < lists.length; i++) {
					  let obj = lists[i];
	  
					  let addclass = obj.internal_link == "1"? "internalLink" : "";
					  addclass += " trk-marquee-item";
					  let target_a = obj.newtab == true? 'target="_blank"' : "";
					  let link = obj.url;
					  let title = obj.title;
					  let trackable_advertorial = obj.trackable_advertorial;
					  let onclick_str ="";
					  if(trackable_advertorial && trackable_advertorial == true){
	
						  if(marquee_impr_sent==false)
						  {
	
							if(typeof gatitle !== 'undefined' && gatitle && gatitle != ''){
								ga('send', {
								hitType: 'event',
								eventCategory: "BAR1",
								eventAction: 'Impression',
								eventLabel: title,
								title: gatitle
								});
								gtag('event', 'Impression', {
								'event_category' : "BAR1",
								'event_label' : title
								});
							}else{
								ga('send', {
								hitType: 'event',
								eventCategory: "BAR1",
								eventAction: 'Impression',
								eventLabel: title							
								});
								gtag('event', 'Impression', {
								'event_category' : "BAR1",
								'event_label' : title
								});
							}
	
						  }
	
						  onclick_str= ' onclick="if(isDragging) { return; } advertorialOnClick(event, this);" ';
					  }
	
					  let processedTitle = obj.title;
					  if (processedTitle.includes('|')) {
						  let splitTitle = processedTitle.split('|');
						  let firstPart = splitTitle.shift().trim();
						  let rest = splitTitle.join('|').trim();
						  processedTitle = '<span class="special_title">' + firstPart + ' |</span> ' + rest;
					  }
					
					  let str_html = '<a class="'+ addclass + '" href="'+link+'" '+target_a+' data-title="'+title+'"'+onclick_str+'  advtitle="'+title+'" advcode="BAR1"'+'>'+
											  processedTitle+
										  '<span class="marquee_pipe hidden">|</span>'+
									  '</a>';
					  append_html += str_html;
				  }
	  
				  marquee_impr_sent = true;
				  $marquee.html(append_html);
				  $marquee.addClass("owl-carousel owl-theme");
	  
				}
	
				var marqueeInstance = $marquee.owlCarousel({
					loop: true,
					// autoWidth: true,
					items: 1,
					dots: false,
					autoplay: true,
					autoplayTimeout: 4000,
					autoplayHoverPause: true,
					smartSpeed: 500,
					mouseDrag: true,
					// responsive: {
					// 	0: {
					// 		dotsEach: 1,
					// 		slideBy: 1,
					// 		nav: false,
					// 		items:1
					// 	},
					// 	768: {
					// 		dotsEach: 1,
					// 		slideBy: 1,
					// 		nav: false,
					// 		items:1
					// 	}
					// },
	
					autoWidth: false,
					
					// onInitialized: checkMarqueeItem_v2,
					// onTranslated: checkMarqueeItem_v2,
					// onDrag: function(event) {
					//     isDragging = true;
					//     this.trigger('stop.owl.autoplay');
					//     $(event.target).find('.owl-item a').css({
					//         'animation': 'none',
					//         'animation-play-state': 'paused',
					//     });                    
					// },
					// onDragged: function(event) {
					//     setTimeout(function() {
					//         isDragging = false;
					//     }, 100);
					//     this.trigger('play.owl.autoplay', [4000]);
					//     checkMarqueeItem_v2();
					// }
	
				});
	
				marqueetop_v2.push(marqueeInstance);
	
				// $('#ctrl-ticker' + index).click(function() {
				//     if($(this).find('.fa-pause').length){
				//         $(this).html('<i class="fas fa-play"></i>');
				//         marqueeInstance.trigger('stop.owl.autoplay');
				//     }
				//     else{
				//         $(this).html('<i class="fas fa-pause"></i>');
				//         marqueeInstance.trigger('play.owl.autoplay', [4000]);
				//     }
				// });
	  
				convertTradSimpCN(document.getElementById("marquee"));
				
			});
	
		});		


	}

}



function checkMarqueeItem_v2(event) {
    var $currentCarousel = $(event.target);
    var $currentItem = $currentCarousel.find('.owl-item.active a').first();
    var textWidth = $currentItem.width();
    var screenWidth = $(window).width();

    $currentCarousel.find('.owl-item a').css({
        'animation': 'none',
        'animation-play-state': 'paused',
    });

    if (screenWidth < textWidth) {
        $currentCarousel.trigger('stop.owl.autoplay');

        var duration = (textWidth / screenWidth) * 6000;

        setTimeout(function() {
            if($currentItem.parents('.active').length > 0 && !isDragging) {
                var $currentParentItem = $currentItem.parents('.active');

                if ($currentParentItem.prevAll('.active').length === 0) {
                    $currentItem.css({
                        'animation': 'marquee ' + duration + 'ms linear infinite',
                        'animation-play-state': 'running',
                    });

                    var stopPosition = textWidth - screenWidth + 15;
					//var stopPosition = textWidth - screenWidth+30;
                    var isAutoPlayOff = true;

                    function stopAnimation() {
                        if ($currentItem.position().left <= -stopPosition) {
                            $currentItem.css('animation-play-state', 'paused');

                            if(isAutoPlayOff) {
                                setTimeout(function() {
                                    if($currentItem.parents('.active').length > 0 && !isDragging && $currentCarousel.siblings('.player').find('.fas.fa-pause').length !== 0) {
                                        $currentCarousel.trigger('next.owl.carousel');
                                        $currentCarousel.trigger('play.owl.autoplay', [4000]);
                                    }
                                }, 3500);

                                isAutoPlayOff = false;
                            }
                        }
                    }

                    var interval = setInterval(stopAnimation, 100);
                }

            }
        }, 1000);
    }
}


function loginpage(){
	let stringQuery = '';

	let option = {};

    option.source_url = encodeURI(window.location.href);

	if (typeof webkit !== 'undefined' && webkit.messageHandlers.myInterface) {
		option.device = 'IOS';
	} 
	else if (typeof AppInterfaceHuawei !== 'undefined') {
		option.device = 'HarmonyOS';
	}
	else if (typeof AppInterface !== 'undefined') {
		option.device = 'Android';
	}
	else {
		option.device = "Web";
	}

	if (option != null) {
        stringQuery = '?' + $.param(option);
    }

	localStorage.setItem('pendingBridgeNotify', 'true');
	
	// console.log("debug: ", `${auth_callback_url}${stringQuery}`); return false;

	window.location.href = `${auth_callback_url}${stringQuery}`;
}

function logoutpage(){
	$.ajax({
		url : `${sso_url}/isUserLogged`,
		type : 'GET',
		xhrFields : {
			withCredentials : true
		},
		success: function(response) {

			if(response.is_auth == true){
				$.ajax({
					url: `${sso_url}/user/logout`,
					type: "POST",
					contentType: 'application/json',
					processData: false,
					xhrFields : {
						withCredentials : true
					},
					data: JSON.stringify({
						sessionId: response.session_id
					}),
					beforeSend: function(xhr) {
						xhr.setRequestHeader("Authorization", `Bearer ${response.access_token}`);
						xhr.setRequestHeader("Accept", "application/json");
					},
					complete: function() {
						location.reload();
					}
				});
			} else {
				location.reload();
			}
		},
	});
}

function profilepage(){
	let stringQuery = '';
	let option = {};

	option.url = encodeURI(window.location.href);

	option.mobile = 0;

	window.open(profile_url + '/profile','_blank');
}

function checkoutpage(elm, require_payment=false, packageslug="vip") {
	var wrapper_type = '';
	if(elm) {
		wrapper_type = $(elm).closest('.prompt-login-wrapper').parent().attr('class');
	}

	let stringQuery = '';
	let option = {};

	option.source_url = encodeURI(window.location.href);

	if(typeof AppInterfaceV2 !== 'undefined'){
		option.device = 'Android';		
	}
	else if (typeof webkit !== 'undefined' && webkit.messageHandlers.myInterface) {
		option.device = 'IOS';
	} 
	else if (typeof AppInterfaceHuawei !== 'undefined') {
		option.device = 'HarmonyOS';
	}
	else if (typeof AppInterface !== 'undefined') {
		option.device = 'Android';
	}
	else {
		option.device = "Web";
	}

	option.require_payment = require_payment;

	if(wrapper_type == "vip-wrapper" && require_payment == true) {
		option.packageslug = packageslug;
	}

	if (option != null) {
        stringQuery = '?' + $.param(option);
    }

	if(require_payment == true) {
		window.open(`${profile_url}/package/paymentSummary${stringQuery}`,'_self');
	}
	else {
		window.open(`${profile_url}/package/paymentSummary${stringQuery}`,'_self');
	}
}

function stockportfoliopage(){
	window.location.href = "/member/stockportfolio";
}

function fixClampText(){
	$( ".no-img-frame-inner-div .desc" ).each(function() {
		adjustNoImgDescClamp($( this ));
	});
}

function adjustNoImgDescClamp(e){
	e.parent( ".no-img-frame-inner-div" ).css("position", "absolute");
	e.css("max-height","unset" );

	let frameHeight = e.height();
	let lines = Math.floor(frameHeight / (17 * 1.3));
	let newFrameHeight = lines * (17 * 1.3);

	if(e.hasClass("local-news-item-desc")){
		lines = Math.floor(frameHeight / (15 * 1.2));
		newFrameHeight = lines * (15 * 1.2);
	}
	e.css("max-height",newFrameHeight+"px" );

	e.parent( ".no-img-frame-inner-div" ).css("position", "relative");

	let achild = e.find("a").first();
	if(achild.height() < newFrameHeight)	{
		e.addClass("nodots");
	}
}

function showAppPromo(){
	if(isMobile.Android()||isMobile.iOS()){
		var app_link = "https://play.google.com/store/apps/details?id=com.sinchewnews";
		if(isMobile.iOS()){
			app_link = "https://apps.apple.com/my/app/sin-chew-%E6%98%9F%E6%B4%B2%E6%97%A5%E6%8A%A5/id1077727843";
		}

		
		const d = new Date();
		let day = d.getDate();
		if(day == 15 || day == 16 || day == 17){
			let faxiandongmeng_icon_html = '<a href="/category/国内/发现东盟" target="_blank"><img src="/public/images/logo-Discover-Asean1.png" alt="发现东盟"/></a>';
			//$(".footer-sticky-icon.test-app-flooting-icon").append(faxiandongmeng_icon_html);

		}
		else{
			let app_icon_html = '<a href="'+app_link+'" target="_blank"><img src="/public/images/app-promo-icon_v1.png" alt="Sinchew App"/></a>';
			//$(".footer-sticky-icon.test-app-flooting-icon").prepend(app_icon_html);
		}

		// let generalelection_icon_html = '<a href="https://myelection.sinchew.com.my/" target="_blank"><img src="/public/images/general-election/ge15-logo.png"/></a>';
		// $(".footer-sticky-icon.test-app-flooting-icon").append(generalelection_icon_html);
	}

	let merdeka_icon_html = '<a id="merdekaIconMob" href="https://myday.sinchew.com.my/" target="_blank"><img src="/public/images/icon-merdeka-web-button.gif" alt="国庆有奖"/></a>';
	//$(".footer-sticky-icon.test-app-flooting-icon").prepend(merdeka_icon_html);

	if(location.hostname.startsWith("scmyelection") || location.hostname.startsWith("myelection")){		
		$(".footer-sticky-icon.test-app-flooting-icon").empty();
		var defaultHtml = '<a href="#body-header-wrapper" id="scroll-up" class="animated bottom-floading-icon fadeIn hidden" style="display: block;"><i class="fa fa-chevron-up"></i></a>';
		//$(".footer-sticky-icon.test-app-flooting-icon").append(defaultHtml);		
	}
}

String.prototype.isCHS = function(i){
	return (this.charCodeAt(i) > 255 || this.charCodeAt(i) < 0);
};

var suggested_keyword_retrieved = false;

	 function retrieve_suggested_keyword(){
		 if (suggested_keyword_retrieved == true) {
			$(".site-search-desktop-hotkw").fadeIn();
			$(".site-search-mobile-hotkw").fadeIn();
			 return;
		 }
		 suggested_keyword_retrieved = true;
		 var arg_body_kw = {id: "hot"};
		 $.ajax({
				type: "POST",
				contentType: "application/json; charset=utf-8",
				url: 'https://searchapi.sinchew.com.my/hot-keyword',
				data: JSON.stringify(arg_body_kw),
				dataType: "json",
				success: function(data) {
					var sug_result = [];
				   if(data.hits && data.hits.hits){
						   var temp_html = "";
						   var temp_html2 = "";
					   for(let i = 0; i < data.hits.hits.length; i++){ 
						   var item = data.hits.hits[i];
						   
						   temp_html += '<div class="site-search-desktop-hotkw-item" ><a href="'+ax_host+'/?s='+item._source.keyword_term+'"><h2 class="skip-default-style">'+item._source.keyword_term+'</h2></a></div>';

						   temp_html2 += '<div class="site-search-mobile-hotkw-item" ><a href="'+ax_host+'/?s='+item._source.keyword_term+'"><h2 class="skip-default-style">'+item._source.keyword_term+'</h2></a></div>';
						}
						$("#site-search-desktop-hotkw-list").html(temp_html);	
						$("#site-search-mobile-hotkw-list").html(temp_html2);	


						$(".site-search-desktop-hotkw").fadeIn();
						$(".site-search-mobile-hotkw").fadeIn();
				   }
				},
				error : function(data) {
					 
				}
			 });
	 }

// function stickyAdsInit() {

// 	var stickyFn  = function(element, parent) {
// 		$(window).scroll(function() {
// 			element = $(element);
// 			parent = $(parent);

// 			let parentId = parent[0].getAttribute( 'id' );
// 			console.log("parentId: ", parentId);
// 			let width = parent.width();

// 			let windowScrollTop = $(window).scrollTop();
// 			let elementHeight = element.height();
// 			let parentOffsetTop = parent.offset().top;
// 			let elementOffsetHeight = parentOffsetTop + parent.height() - elementHeight;
			
// 			if (windowScrollTop > parentOffsetTop && windowScrollTop < elementOffsetHeight) {

// 				var fixTop = '50px';
// 				if(isArticlePage==false){
// 					fixTop = '110px';
// 				}

// 				element.css({
// 				  'position': 'fixed',
// 				  'top': fixTop
// 				});

// 				if(parentId=="lotterysidebar"){
// 					element.css({
// 					'width': width,
// 					});
// 				}
// 			} else if (windowScrollTop > elementOffsetHeight && windowScrollTop > parentOffsetTop + elementHeight) {

// 				if(elementOffsetHeight>0){
// 					element.css({
// 						'position': 'absolute',
// 						'top': elementOffsetHeight + 'px'
// 					  });
// 				}
// 				else{
// 					element.css({
// 						'position': 'relative',
// 						'top': 'auto'
// 					  });
// 				}

// 			} else {
// 				element.css({
// 				  'position': 'relative',
// 				  'top': 'auto'
// 				});
// 			}
// 		});
// 	}

// 	$('.sticky-ads-parent').each( function( index ) {
// 		stickyFn($(this).children(':eq(0)'), this);
// 	});
// }


function stickyAdsInit() {
    var stickyFn = function(childIndex, parent) {
        var element = $(parent).children().eq(childIndex);
        var parentId = $(parent).attr('id');
		
        $(window).scroll(function() {
            let width = parent.width();
            let windowScrollTop = $(window).scrollTop();
            let triggerPoint = element.offset().top;
            let elementHeight = element.height();
            let parentOffsetTop = parent.offset().top;
			let st = $(this).scrollTop();

            if (childIndex === 0) { // existing - sticky at first child
                let elementOffsetHeight = parentOffsetTop + parent.height() - elementHeight;
                if (windowScrollTop > parentOffsetTop && windowScrollTop < elementOffsetHeight) {
                    var fixTop = '50px';
                    if (isArticlePage==false) {
                        fixTop = '110px';
                    }
                    if (isArticlePage==true) {
						if (st > lastScrollTop) {							
							fixTop = '80px';
							//console.log("scroll down");
						} else {
							var baseValue = 0;
							var stickyHeaderHeight = $('.desktop-sticky-header-wrapper.sticky').outerHeight() || 0;
							var breadcrumbHeight = $('#floating-breadcrumb').outerHeight() || 0;
							fixTop = baseValue + stickyHeaderHeight + breadcrumbHeight + 'px';
							//console.log("scroll up");
						}
                    }
                    element.css({
                        'position': 'fixed',
                        'top': fixTop,
                        'width': width
                    });

                    if (parentId == "lotterysidebar") { 
                        element.css({
                            'width': width,
                        });
                    }
                } else if (windowScrollTop > elementOffsetHeight) {
                    if (elementOffsetHeight > 0) {
                        element.css({
                            'position': 'absolute',
                            'top': elementOffsetHeight + 'px'
                        });
                    } else {
                        element.css({
                            'position': 'relative',
                            'top': 'auto'
                        });
                    }
                } else {
                    element.css({
                        'position': 'relative',
                        'top': 'auto'
                    });
                }
            }
            else if (childIndex === 1) { 

				var buffer = 10;
                var parentBottom = parentOffsetTop + parent.height();
                let stickyTopOffset = 160;
                let stickyBottomLimit = parentBottom - elementHeight - stickyTopOffset;

                if (windowScrollTop >= triggerPoint && windowScrollTop <= stickyBottomLimit) {
                    element.css({
                        'position': 'fixed',
                        'top': stickyTopOffset + 'px',
                        'width': width
                    });
                } else if (windowScrollTop > stickyBottomLimit) {
                    element.css({
                        'position': 'absolute',
                        'top': parent.height() - elementHeight + 'px'
                    });
                } 
				else if (windowScrollTop < triggerPoint - buffer) { 
                    element.css({
                        'position': 'relative',
                        'top': 'auto'
                    });
                }
            }

			lastScrollTop = st;
        });
    }

    $('.sticky-ads-parent').each(function() {
        var childIndex = $(this).hasClass('custom-sticky-behavior') ? 1 : 0;
        stickyFn(childIndex, $(this));
    });

}



var sticky_single_hp_offset = 0;

var stickyHpFn = function(element, parent) {
    element = $(element);
    parent = $(parent);
	if (element.length === 0 || parent.length === 0) {
        return;
    }

	if ('scrollRestoration' in history) { history.scrollRestoration = 'manual'; }
    window.scrollTo(0, 0);

    element.addClass("registered-sticky");
    var headerHeight = $(".desktop-sticky-header-wrapper.v2").height() + 10;
    sticky_single_hp_offset = element.offset().top - headerHeight;

    $(window).scroll(function() {
        if ($(window).scrollTop() >= sticky_single_hp_offset) {
            var sticky_single_hp_offset_bottom = parent.offset().top + parent.height() - element.height() - headerHeight;
            if ($(window).scrollTop() >= sticky_single_hp_offset_bottom) {
                element.css("position", "fixed");
                element.css("width", parent.width() + "px");
                var fixedtop = $(window).scrollTop() - sticky_single_hp_offset_bottom - headerHeight;
                element.css("top", "-" + fixedtop + "px");
            } else {
                element.css("position", "fixed");
                element.css("width", parent.width() + "px");
                element.css("top", headerHeight + "px");
            }
        } else {
            element.css("position", "relative");
            element.css("top", "unset");
            element.css("width", "100%");
            sticky_single_hp_offset = element.offset().top - headerHeight;
        }
    });
}


function initAutoLoadMoreInListing(){
	//load-more-click-element
	$( window ).scroll(function() {
		if(listingLoading == false && listingItemEnded == false && $("#category-load-more-indicator").isInViewport()){
				autoLoadMoreInListingCount++;
				if($("#load-more-click-element").length){
					$("#load-more-click-element").click();
				}
		}
	});

}

$.fn.isInViewport = function() {
    var elementTop = $(this).offset().top;
    var elementBottom = elementTop + $(this).outerHeight();

    var viewportTop = $(window).scrollTop();
    var viewportBottom = viewportTop + $(window).height()+100;


    return elementBottom > viewportTop && elementTop < viewportBottom;
};

function refreshFavNews(){
	//window.location.reload();
	favRefresh=true;
	favNewsListIDs = [];
	favNewsList = [];
	$('#div-fav-list-first-3-wrapper').html("");
	$('#div-fav-list-wrapper').html("");
	$('.favzone').remove();
	$('#myfav-loading').removeClass('hidden');
	favNewsPageNum=1;
	favNewsAjaxPage=1;
	ajxLoadFavArticle(0);
}

function nextFavNews_v2(){
	favNewsPageNum++;
	// if(favNewsPageNum==6){
	// 	window.location.reload();
	// }

	favRefresh_v2=true;
	$('#div-fav-list-all-wrapper').html("");
	$('.favzone').remove();
	$('#myfav-loading').removeClass('hidden');

	if (favNewsList.length > 0) {
		displayFavNews_v2();
	} else {
		favNewsListIDs = [];
		favNewsList = [];			
		favNewsPageNum = 1;
		favNewsAjaxPage = 1;
		ajxLoadFavArticle_v2(0);
	}
}

function loadStockMarquee()
{
    $.ajax({
        type: "GET",
        url: ax_host+"/ajx-api/marquee_stock",
        dataType: "json",
        success: function (data) {
            $('#marquee_stock').html(data.stock.html);
            $('#marquee_stock').marquee({
                duration: 5000,
                gap: 50,
                delayBeforeStart: 0,
                direction: 'left',
                pauseOnHover: true,
                duplicated: true,
                startVisible: true,    
                speed: 20,
            });
        }
    });
}

function loadPetrolMarquee()
{
    $.ajax({
        type: "GET",
        url: ax_host+"/ajx-api/marquee_petrol",
        dataType: "json",
        success: function (data) {
            $('.petrol_marquee_wrapper').html(data.petrol.html);
            $('#marquee_petrol').marquee({
                duration: 5000,
                gap: 50,
                delayBeforeStart: 0,
                direction: 'left',
                pauseOnHover: true,
                duplicated: true,
                startVisible: true,    
                speed: 20,
            });
        }
    });
}

function sendBannerClickEvent(e,advpost)
{
	e.preventDefault();
	let advcode = advpost.attr("advcode");
	let advtitle = advpost.attr("advtitle");
	var href = advpost.attr('href');
	console.log("sendBannerClickEvent ", advcode, ' ',advtitle);
	ga('send', {
		hitType: 'event',
		eventCategory: advcode,
		eventAction: 'Click',
		eventLabel: advtitle
	});
	gtag('event', 'Click', {
						'event_category' : advcode,
						'event_label' : advtitle
						});
	window.location.href = href;
}
function sendBannerImpressionEvent(selector,sendImpression)
{
	advpost = $(selector);
	let advcode = advpost.attr("advcode");
	let advtitle = advpost.attr("advtitle");
	if(sendImpression == true)
	{
		console.log("sendBannerImpressionEvent ", advcode, ' ',advtitle);
		ga('send', {
			hitType: 'event',
			eventCategory: advcode,
			eventAction: 'Impression',
			eventLabel: advtitle
		});
		gtag('event', 'Impression', {
						'event_category' : advcode,
						'event_label' : advtitle
						});
	}
}

function sendPageView(){
    ga('create', 'UA-33948949-1', 'auto');
    ga('send', 'pageview');
    gtag('event', 'page_view', {
    send_to: 'G-74B2VR88L4'
    });	

    gtag('event', 'page_view', {
	send_to: 'G-YBRYTH4EC2'
	});

    gtag('event', 'page_view', {
		send_to: 'AW-11054747425'
	});
}

function showDonateFAB(){
	if (document.getElementById('single-post-id')) {
		let articleId = document.getElementById('single-post-id').getAttribute('data-pid');	
		if(articleId){
			let donateHtml = `<a style="margin:10px auto; width:45px;" href="${window.location.origin}/buyusacoffee/?article-id=${articleId}" target="_blank"><img src="/public/images/donation/donation-icon-3.png"/></a>`;
			$(".footer-sticky-icon.test-app-flooting-icon").prepend(donateHtml);
		}
	}
}

function readMoreContent(){
	jQuery(".read-more-wrapper").addClass("released");
	jQuery(".read-more-msg").addClass("done");

	if(typeof read_more_released_ads_unit !== 'undefined' && read_more_released_ads_unit.length > 0){
		read_more_released_ads_unit.forEach(function (item, index) {
                            googletag.cmd.push(function() {
                                var st = googletag.defineSlot(item[1],item[2],item[0]).addService(googletag.pubads());

								googletag.pubads().refresh([st]);
                            });
		});
	}

	var resizeEvent = window.document.createEvent('UIEvents'); 
	resizeEvent.initUIEvent('resize', true, false, window, 0); 
	window.dispatchEvent(resizeEvent);

	if (!jQuery('.reader-redeem-code-section:first').hasClass('nodata')) {
		jQuery('.reader-redeem-code-section:first').removeClass('hidden');
	}

	sendReadMoreClickEvent();
}


function readMoreBudget2023Content(){
	if(typeof read_more_budget2023_released_ads_unit !== 'undefined' && read_more_budget2023_released_ads_unit.length > 0){
		read_more_budget2023_released_ads_unit.forEach(function (item, index) {
				googletag.cmd.push(function() {
					var st = googletag.defineSlot(item[1],item[2],item[0]).addService(googletag.pubads());
					googletag.pubads().refresh([st]);
				});
		});
	}
	var resizeEvent = window.document.createEvent('UIEvents'); 
	resizeEvent.initUIEvent('resize', true, false, window, 0); 
	window.dispatchEvent(resizeEvent);
}


function makeid(length) {
    var result           = '';
    var characters       = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
    var charactersLength = characters.length;
    for ( var i = 0; i < length; i++ ) {
      result += characters.charAt(Math.floor(Math.random() * 
 charactersLength));
   }
   return result;
}

function replaceCdnPrefix(url) {
    return url.replace('https://www.sinchew.com.my/', 'https://cdn.sinchew.com.my/');
}

function getBudget2023RepeatAds(container, postfix, adunit, size){
	var mobile_mode = true;	
	if(container.endsWith('_L')){
		mobile_mode = false;
	}
	var screen_condition = " if(screen.width > 767){";
	if(mobile_mode){
		screen_condition = " if(screen.width < 768){";
	}
	var wrapclass = "";
	if( !mobile_mode){
		wrapclass = "desktop-ads-frame";
	}
	else{
		wrapclass = "mobile-ads-frame";
	}
	var dfp_ad_header = "<p class='dfp ad_header'>ADVERTISEMENT</p>";
	wrapper_container_head = "<div style='text-align:center; margin-top:20px !important' class='QQ ads-frame "+wrapclass+"' >";
	wrapper_container_end = "</div>";

	header_html = wrapper_container_head + dfp_ad_header + `<div id='${container}${postfix}' ></div><script>${screen_condition}
	read_more_budget2023_released_ads_unit.push(['${container}${postfix}','${adunit}',${size}]);
	}
	</script>` + wrapper_container_end;

	header_html = wrapper_container_head +dfp_ad_header+"<div id='"+container+postfix+"' ></div><script>"+screen_condition+"read_more_budget2023_released_ads_unit.push(['"+container+postfix+"','"+adunit+"',"+size+"]); }</script>" +wrapper_container_end;
	return header_html;	
}

function categoryNextPageBudget(nooffset = false, budgetYear="", videoPost = false, isEditorial = false, postfix =""){
	listingLoading = true;
	$('#category-load-more'+postfix).addClass("hidden");
	$('#category-loading').removeClass("hidden");
	var pageNum = $("#category-page-meta .category-page-paging-counter"+postfix).attr("data-num");
	$("#category-page-meta .category-page-paging-counter"+postfix).attr("data-num",++pageNum);
	var cat = $("#category-page-meta"+postfix).attr("data-catid");;
	var editorial = isEditorial == true? 1 : 0;
	$.ajax({
		url: ax_host+"/ajx-api/category_posts/?cat="+cat+"&page="+pageNum+"&nooffset="+nooffset+"&editorialcat="+editorial+"&posts_per_pages=10"
	})
	.done(function( html ) {
		$('#category-loading').addClass("hidden");
		
		lists = JSON.parse(html);

		if(lists){
			for (i = 0; i < lists.length; i++) {
				let obj = lists[i];
				if(typeof(post_ids_in_listing)  !== "undefined" && post_ids_in_listing){
					if(post_ids_in_listing.includes(obj.ID + '')){
						continue;
					}
				}

				if(budgetYear==""){					
					if(i==2 || i==5 || i==8){
						var rand =  makeid(3);
						var budgetslotpostfix = "_RPT_"+i+rand;
	
						var adunit_L = "/2365395/SC3_Lead_(Budget)";
						var adsize_L = "[ [970, 90] ]";
						var budgetAdsContent_L = getBudget2023RepeatAds('BL1_L', budgetslotpostfix, adunit_L, adsize_L);
						$("#cat-post-list"+postfix).append(budgetAdsContent_L);
	
						var adunit_M = "/2365395/SC3_Lead_(Budget)_Mob";
						var adsize_M = "[ [320, 50] ]";
						var budgetAdsContent_M = getBudget2023RepeatAds('BL1_M', budgetslotpostfix, adunit_M, adsize_M);					
						$("#cat-post-list"+postfix).append(budgetAdsContent_M);
	
						readMoreBudget2023Content();
						read_more_budget2023_released_ads_unit = [];
					}
				}

				if(videoPost == false){
					var tmp_str = '<div class="horizontal-line horizontal-line-40h grey-color mobile-hidden"></div>\
									<div class="horizontal-space horizontal-space-20h grey-color desktop-hidden"></div>';
					let wrapperclass = "";
					let imageHtml = "";
					if(!obj.image || obj.image == ""){
						wrapperclass  = "no-img-frame";
					}
					else{
						imageHtml = '<div class="img-frame">\
										<a class="internalLink pending-reg-click-event" data-title="'+obj.title+'" href="'+obj.permalink+'">\
											<img class="img" src="'+obj.image+'"/>\
										</a>\
									</div>';
					}
						
					tmp_str +=  '<div class="horizontal-post-frame  mobile-border '+ wrapperclass+'">'+imageHtml+'\
									<div class="cat cat-desktop">\
										<a class="internalLink pending-reg-click-event" data-title="'+obj.cat+'" href="'+obj.catlink+'">'+obj.cat+'</a>\
									</div>\
									<div class="title">\
										<a class="internalLink pending-reg-click-event" data-title="'+obj.title+'" href="'+obj.permalink+'">'+obj.title+'</a>\
									</div>\
									<div class="desc desc-desktop">\
										<a class="internalLink pending-reg-click-event" data-title="'+obj.title+'" href="'+obj.permalink+'">\
										'+obj.excerpt+'\
										</a>\
									</div>\
									<div class="meta">\
										<span class="time">'+obj.time_display+'</span>\
											<span class="counter post-view-counter-parent post-view-counter-parent-'+obj.ID+'">\
												<i class="far fa-eye"></i>\
												<span  data-pid="'+obj.ID+'" class="post-view-counter post-view-'+obj.ID+'"></span>\
											</span>\
									</div>\
									<div class="cat cat-mobile">\
										<a class="internalLink pending-reg-click-event" data-title="'+obj.cat+'" href="'+obj.catlink+'">'+obj.cat+'</a>\
									</div>\
								</div>';
				}else{
					let imageHtml = "";
					if(!obj.image || obj.image == ""){
						wrapperclass  = "no-img-frame";
					}
					else{
						imageHtml = '<div class="img-frame">\
										<a class="internalLink pending-reg-click-event" data-title="'+obj.title+'" href="'+obj.permalink+'">\
											<img class="img" src="'+obj.image+'"/>\
										</a>\
										<div class="meta meta-desktop">\
											<span class="time">'+obj.time_display+'</span>\
											<span class="counter post-view-counter-parent post-view-counter-parent-'+obj.ID+'">\
												<i class="far fa-eye"></i>\
												<span  data-pid="'+obj.ID+'" class="post-view-counter post-view-'+obj.ID+'"></span>\
											</span>\
										</div>\
										<i class="fas fa-play-circle"></i>\
									</div>';
					}
					var tmp_str ='<div class="horizontal-space horizontal-space-20h desktop-hidden"></div>\
									<div class="vertical-post-frame mobile-horizontal video-cat-post video-post-frame mobile-border clearfix">\
										<div class="horizontal-space horizontal-space-20h mobile-hidden"></div>\
										'+imageHtml+'\
										<div class="title title-mobile">\
											<a class="internalLink pending-reg-click-event" data-title="'+obj.title+'" href='+obj.permalink+'">'+obj.title+'</a>\
										</div>\
										<div class="meta mobile-meta">\
											<span class="time">'+obj.time_display+'</span>\
											<span class="counter post-view-counter-parent post-view-counter-parent-'+obj.ID+'">\
												<i class="far fa-eye"></i>\
												<span  data-pid="'+obj.ID+'" class="post-view-counter post-view-'+obj.ID+'"></span>\
											</span>\
										</div>\
									</div>';
				}
				$("#cat-post-list"+postfix).append(tmp_str);
				
			}

			initPostView(document.getElementById("cat-post-list"+postfix));
			jQuery('a.internalLink.pending-reg-click-event:not([target="_blank"])').click(internalLinkRegClickEvent);
			jQuery('a.internalLink.pending-reg-click-event').removeClass("pending-reg-click-event");
			convertTradSimpCN(document.getElementById("cat-post-list"+postfix));

			ga('create', 'UA-33948949-1', 'auto');
			ga('send', 'pageview');
			gtag('event', 'page_view', {
			send_to: 'G-74B2VR88L4'
			});

			gtag('event', 'page_view', {
			send_to: 'G-YBRYTH4EC2'
			});

			gtag('event', 'page_view', {
				send_to: 'AW-11054747425'
			});

			if(lists.length >= 10 ){
				if(autoLoadMoreInListing == true){

				}
				else{
					$('#category-load-more'+postfix).removeClass("hidden");
				}
			}
			else{
				listingItemEnded = true;
			}
		}

		listingLoading = false;
	});
}

function copyShareRollingNews(el){
	var tempInput = document.createElement("input");
	tempInput.style = "position: absolute; left: -1000px; top: -1000px";
	tempInput.value = $(el).attr("data-link");
	document.body.appendChild(tempInput);
	tempInput.select();
	document.execCommand("copy");
	document.body.removeChild(tempInput);
	$(el).html('<i class="fas fa-check"></i>');
	setTimeout(
		function() {
			$(el).html('<img src="/public/images/share.png">')
		}, 3000);
}


//election - rolling news - like click
function customElectionPostLikeClicked(element){
	if($(element).parent().hasClass("disabled") || typeof(Storage) == "undefined"){return;}
	$(element).parent().addClass("disabled");
	$(element).addClass("liked");
    var post_id = element.data('pid');
    var objLikeCount = element.find('span.rollingnews-post-view-counter');    
    var n = parseInt(objLikeCount.text())+1 || 1;   //if nan, set to 1
    objLikeCount.text(n);
	var reaction = "like";
	// if (typeof(Storage) !== "undefined") {
	// 	localStorage.setItem("react_post_"+post_id, "Y");
	// 	localStorage.setItem('react_post_result_'+post_id, reaction);
	// }
	var xmlhttp = new XMLHttpRequest();
    xmlhttp.onreadystatechange = function() {
        if (xmlhttp.readyState == XMLHttpRequest.DONE) {        	
           if (xmlhttp.status == 200) {
			   console.log("resp:", xmlhttp.responseText);
               eval(xmlhttp.responseText);
           }
        }
    };
    xmlhttp.open("POST", "/front-ajx.php", true);
    xmlhttp.setRequestHeader('content-type', 'application/x-www-form-urlencoded');
	xmlhttp.send("action=custom_single_post_react&postid="+post_id+'&react='+reaction);
}
 
//election - add count to all grid
function initPostView_RollingNewsCustomPost(){
    var post_id_items = "";
    var items = document.getElementsByClassName('rollingnews-post-view-counter');
	//console.log("counter: ",items.length);
    if(items.length>0)
    {		
        for (var i = items.length - 1; i >= 0; i--){
            post_id_items = post_id_items + items[i].getAttribute("data-pid") + ",";
        }
        var xmlhttp = new XMLHttpRequest();
        xmlhttp.onreadystatechange = function() {
            if (xmlhttp.readyState == XMLHttpRequest.DONE) {
                if (xmlhttp.status == 200) {
                        //console.log("resp:", xmlhttp.responseText);
                        eval(xmlhttp.responseText);
                }
            }
        };
        xmlhttp.open("POST", "/front-ajx.php", true);
        xmlhttp.setRequestHeader('content-type', 'application/x-www-form-urlencoded');
        xmlhttp.send("action=custom_multiple_post_like_view&custompostidlist="+post_id_items+'&lang=');
    }
}

function tagClick(e){
	var event_label = "tag/" + e.getAttribute("tag") + "/?"+ e.getAttribute("ref");
	ga('send', {
		hitType: 'event', eventCategory: "keyword_tagging", eventAction: 'Click', eventLabel: event_label
	});
	gtag('event', 'Click', {
		'event_category' : "keyword_tagging", 'event_label' : event_label
	});

    var tagID = e.getAttribute("tagID");
    var tagName = e.getAttribute("tag");
    var tagLink = e.getAttribute("href");

	if (jQuery(".webview.article-page.mobile-article").length > 0) {
		notifyTag(tagID, tagName, tagLink);
	}
}

function onLoadBanner(height = null) {
	if (isMobile.any()) {
		gaTrack('Impression');
	}
}

function onClickBanner(event) {
	gaTrack('Click');
}

function gaTrack(eventAction) {
	let eventCategory = 'Banner 600 x 160px';
	let title = 'Mobile Web Banner';

	ga('send', {
		hitType: 'event',
		eventCategory: eventCategory,
		eventAction: eventAction,
		eventLabel: title,
	});

	gtag('event', eventAction, {
		'event_category' : eventCategory,
		'event_label' : title
	});
}

$(document).ready(function() {
	if($('map').length){
		$('img[usemap]').rwdImageMaps();
	}
});

var openCCConverter =  null;
var openCCRootNode =  null;
var openCCHTMLConvertHandler =  null;

function toggleTradSimplifiedCN(){
	if (typeof openCCHTMLConvertHandler === 'undefined' || openCCHTMLConvertHandler == null) {
	  	openCCConverter = OpenCC.Converter({ from: 'cn', to: 'tw' });
        openCCRootNode = document.documentElement;
        openCCHTMLConvertHandler = OpenCC.HTMLConverter(openCCConverter, openCCRootNode, 'zh-CN', 'zh-TW');
	}

	//$(openCCRootNode).find("img").addClass("ignore-opencc");
    var imageMap = new Map();
    $("img").each(function(index) {
        var key = `__IMG_${index}__`;
        imageMap.set(key, $(this).attr('src'));
        $(this).attr('src', key);
    });

	if($("body").attr('lang') == 'zh-TW' && !isZhHant){
		openCCHTMLConvertHandler.restore();
		if (typeof(localStorage) !== "undefined") {
			localStorage.setItem('cn_type', "simp");
		}
		$(".translation-btn span").text('简');
	}

	else if( $("body").hasClass('no-translate') && $("body").attr('lang') == 'zh-CN'){
		openCCHTMLConvertHandler.restore();
		if (typeof(localStorage) !== "undefined") {
			localStorage.setItem('cn_type', "simp");
		}
		$(".translation-btn span").text('简');
	}

	else{
	 	openCCHTMLConvertHandler.convert();
		if (typeof(localStorage) !== "undefined" && !isZhHant) {
			localStorage.setItem('cn_type', "trad");
			$(".translation-btn span").text('繁');
		}

		if (isZhHant) {
			localStorage.setItem('cn_type', "simp");

			const url = new URL(window.location.toString());

			if (url.searchParams.has('variant') && url.searchParams.get('variant') == 'zh-hant') {
				url.searchParams.delete('variant');
			}

			window.location.href = url.href;
			
		}
	}

    $("img").each(function(index) {
        var key = `__IMG_${index}__`;
        if (imageMap.has(key)) {
            $(this).attr('src', imageMap.get(key));
        }
    });
}

$(document).ready(function() {
	const url = new URL(window.location.toString());

	if (url.searchParams.has('variant') && url.searchParams.get('variant') == 'zh-hant') {
		isZhHant = true;
		if (typeof(localStorage) !== "undefined") {
			localStorage.setItem('cn_type', "trad");
		}
	}

	convertTradSimpCN();
});

function resetCnTypeExpiryDate() {
	if (typeof(localStorage) !== "undefined"){
		var cnTypeExpiry = localStorage.getItem('cn_type_expiry');
		var now = new Date().getTime();
		var expiryDuration = 30 * 60 * 1000	//30 mins
		if (cnTypeExpiry) {
			if (now > parseInt(cnTypeExpiry)) {
				localStorage.removeItem('cn_type');
				localStorage.setItem('cn_type_expiry', now+expiryDuration);
			}
		}
		else{
			localStorage.setItem('cn_type_expiry', now+expiryDuration);
		}
	}
}

function convertTradSimpCN(relatedParentNode = null){
	if(typeof OpenCC === 'undefined') return;
	
	var prefCn = localStorage.getItem("cn_type");
	if(typeof prefCn !== 'undefined' && prefCn == "trad"){
		let converter = null;
		let imageMap = new Map();

		if(relatedParentNode != null){
				if(relatedParentNode instanceof jQuery) {
					relatedParentNode = relatedParentNode.get(0);
				}
				$(relatedParentNode).attr("lang", 'zh-CN');
				//$(relatedParentNode).find("img").addClass("ignore-opencc");
				$(relatedParentNode).find("img").each(function(index) {
					var key = `__IMG_${index}__`;
					imageMap.set(key, $(this).attr('src'));
					$(this).attr('src', key);
				});				
				openCCConverterTmp = OpenCC.Converter({ from: 'cn', to: 'tw' });
				openCCHTMLConvertHandlerTmp = OpenCC.HTMLConverter(openCCConverterTmp, relatedParentNode, 'zh-CN', 'zh-TW');
				converter = openCCHTMLConvertHandlerTmp;
		}
		else{
			if (typeof openCCHTMLConvertHandler === 'undefined' || openCCHTMLConvertHandler == null) {
				openCCConverter = OpenCC.Converter({ from: 'cn', to: 'tw' });
				openCCRootNode = document.documentElement;
				//$(openCCRootNode).find("img").addClass("ignore-opencc");
                $(openCCRootNode).find("img").each(function(index) {
                    var key = `__IMG_${index}__`;
                    imageMap.set(key, $(this).attr('src'));
                    $(this).attr('src', key);
                });
				openCCHTMLConvertHandler = OpenCC.HTMLConverter(openCCConverter, openCCRootNode, 'zh-CN', 'zh-TW');
				
			}
			converter = openCCHTMLConvertHandler;
		}
		converter.convert();

        $("img").each(function(index) {
            var key = `__IMG_${index}__`;
            if (imageMap.has(key)) {
                $(this).attr('src', imageMap.get(key));
            }
        });
	}
	else if((typeof prefCn === 'undefined' || prefCn == null) && relatedParentNode == null) {
		var ipgeo = localStorage.getItem("ip_geolocation");
		if(typeof ipgeo === 'undefined' || ipgeo == null) {
			$.ajax({
				type: "GET",
				url: ax_host+"/ajx-api/ipgeo",
				dataType: "text",
				success: function (data) {
					ipgeo = data.toLowerCase();
					if (typeof(localStorage) !== "undefined") {
						localStorage.setItem('ip_geolocation', ipgeo);
					}
					convertCNTypeForSpecificIP(ipgeo);
				}
			});
		}
		else {
			convertCNTypeForSpecificIP(ipgeo);
		}
	}
}


function getShareThisConfig(url, title) {
	let config = window.__sharethis__.config["inline-share-buttons"];

	config.url = url;
	config.title = title;
	config.description = `${url} ${title}`;

	delete config['updated_at'];
	delete config['ts'];

	return config;
}
function convertCNTypeForSpecificIP(ipgeo) {
	if(ipgeo === "hk" || ipgeo === "mo" || ipgeo === "tw") {
		openCCConverter = OpenCC.Converter({ from: 'cn', to: 'tw' });
		openCCRootNode = document.documentElement;
		openCCHTMLConvertHandlerTmp = OpenCC.HTMLConverter(openCCConverter, openCCRootNode, 'zh-CN', 'zh-TW');
		$(openCCRootNode).find("img").addClass("ignore-opencc");
		openCCHTMLConvertHandlerTmp.convert();
	}
}


function getShareLink(platform, link, name){

	name =  name.replace(/<br\W*?>/, "");
	encoded_name = encodeURIComponent(name);
	encoded_link = encodeURIComponent(link);
	switch(platform){
		case "facebook":
			return "https://www.facebook.com/sharer/sharer.php?u="+encoded_link+"&t="+encoded_name+"&quote="+encoded_name;
			break;
		case "twitter":
			return "https://twitter.com/intent/tweet?text="+encodeURIComponent(name+" "+link);
			break;
		case "mail":
			return "mailto:?subject=" + encoded_name + "&body=" + encodeURIComponent(name+" "+link);
			break;
		case "whatsapp":
			return "https://api.whatsapp.com/send?text="+encodeURIComponent(name+" "+link);
			break;
		case "evernote":
			return "https://www.evernote.com/clip.action?url="+encoded_link+"&title="+encoded_name;
			break;
		case "gmail":
			return "https://mail.google.com/mail/?view=cm&fs=1&su="+encoded_name+"&body="+encoded_link;
			break;
		case "iorbix":
			return "https://iorbix.com/m-share?url="+encoded_link+"&title="+encoded_name;
			break;			
		case "kakao":
			return "https://story.kakao.com/share?url="+encoded_link;
			break;
		case "kindleit":
			return "https://pushtokindle.fivefilters.org/send.php?url="+encoded_link;
			break;
		case "kooapp":
			return "https://www.kooapp.com/create?link="+encoded_link+"&title="+encoded_name;
			break;
		case "linkedin":
			return "https://www.linkedin.com/shareArticle?url="+encoded_link+"&title="+encoded_name;
			break;
		case "line":
			return "https://lineit.line.me/share/ui?url="+encoded_link+"&text="+encoded_name;
			break;
		case "messenger":
			return "https://www.messenger.com/t/me?text="+encoded_link;
			break;
		case "messenger_mob":
			return "fb-messenger://share?link="+encoded_link;
			break;
		case "outlook":
			return "https://outlook.live.com/mail/0/deeplink/compose?subject="+encoded_name+"&body="+encoded_link;
			break;
		case "pinterest":
			return "https://pinterest.com/pin/create/button/?url="+encoded_link+"&description="+encoded_name;
			break;
		case "reddit":
			return "https://www.reddit.com/submit?url="+encoded_link+"&title="+encoded_name;
			break;
		case "skype":
			return "https://web.skype.com/share?url="+encoded_link+"&text="+encoded_name;
			break;			
		case "telegram":
			return "https://t.me/share/url?url="+encoded_link+"&text="+encoded_name;
			break;
		case "tencentqq":
			return "https://sns.qzone.qq.com/cgi-bin/qzshare/cgi_qzshare_onekey?url="+encoded_link+"&title="+encoded_name;
			break;			
		case "trello":
			return "https://trello.com/add-card?source=trello.com&mode=popup&url="+encoded_link+"&name="+encoded_name;
			break;
		case "tumblr":
			return "https://www.tumblr.com/widgets/share/tool?canonicalUrl="+encoded_link+"&title="+encoded_name;
			break;
		case "viber":
			return "viber://forward?url="+encoded_link+"&text="+encoded_name;
			break;			
		case "weibo":
			return "http://service.weibo.com/share/share.php?url="+encoded_link+"&title="+encoded_name;
			break;
		case "wordpress":
			return "http://wordpress.com/press-this.php?u="+encoded_link+"&t="+encoded_name+"&s="+encoded_name;
			break;
		case "yahoomail":
			return "http://compose.mail.yahoo.com/?to=&subject="+encoded_name+"&body="+encoded_link;
			break;
		case "yummly":
			return "https://www.yummly.com/urb/verify?url="+encoded_link+"&urbtype=bookmarklet&type=agg&title="+encoded_name;
			break;
		default:
			return "";
	}
}
function inAppWebviewPermalink(url){
	if(url == null || url == "") return url;

	if(url.indexOf("?") > -1){
		return url + "&inapp=1";
	}

	return url+"?inapp=1";
}

function shareAnalytics(platform_share, source=""){

	if(source==""){
		let post_id = document.getElementById('single-post-id').getAttribute("data-pid");
		if (currentStateArticle == 2) {
			post_id = secondary_article_id;
		}
		var xmlhttp = new XMLHttpRequest();
		xmlhttp.onreadystatechange = function() {
			if (xmlhttp.readyState == XMLHttpRequest.DONE) {        	
				if (xmlhttp.status == 200) {
					// eval(xmlhttp.responseText);
				}
			}
		};
		xmlhttp.open("POST", "/front-ajx.php", true);
		xmlhttp.setRequestHeader('content-type', 'application/x-www-form-urlencoded');
		xmlhttp.send("action=single_post_share&postid="+post_id+'&platform_share='+platform_share);

		let contentTitle= currentStateArticle == 2 ? secondary_article_gatitle: gatitle;
        ga('send', {
            hitType: 'event',
            eventCategory: `${platform_share}_share`,
            eventAction: 'Click',
            eventLabel: contentTitle
        });
		gtag('event', `${platform_share}_share_clicked`, {
			event_label: contentTitle
		});
		
	}
	
	const shareSources = ["budget2025", "budget2026", "sabahprn2025", "game"];
	if (shareSources.includes(source)) {
		var xmlhttp = new XMLHttpRequest();
		xmlhttp.onreadystatechange = function () {
			if (xmlhttp.readyState === XMLHttpRequest.DONE && xmlhttp.status === 200) {
				eval(xmlhttp.responseText);
			}
		};
		xmlhttp.open("POST", "/front-ajx.php", true);
		xmlhttp.setRequestHeader("content-type", "application/x-www-form-urlencoded");
		xmlhttp.send("action=&platform=" + platform_share);
		console.log(`shareAnalytics ${source} ended`);
	}

}

function display_share_view_count(viewCount) {
	let shareCount = document.querySelector('#post-share-count');

	if (shareCount) {
		if (viewCount) {
			shareCount.style.display = 'flex';
			shareCount.querySelector('.post_share_count_total').textContent = viewCount;
		} else {
			shareCount.style.display = 'none';
			shareCount.querySelector('.post_share_count_total').textContent = '';
		}
	}
}

function init_share_view_count(post_id) {

	if($('body').hasClass("page-template-video-baige")) {
        return;
	}

	let initViewCount = false;

	switch (currentStateArticle) {
		case 1:
			if (primary_article_id == post_id) {
				initViewCount = true;
				init_article_url = primary_article_url;
				init_article_id = primary_article_id;
				init_article_title = primary_article_title;
				init_article_date = primary_article_date;
				init_article_cover_image = primary_article_cover_image;
			}
			break;
		case 2:
			if (secondary_article_id == post_id) {
				initViewCount = true;
				init_article_url = secondary_article_url;
				init_article_id = secondary_article_id;
				init_article_title = secondary_article_title;
				init_article_date = secondary_article_date;
				init_article_cover_image = secondary_article_cover_image;
			}
			break;
	}
	
	if (initViewCount) {
		let view_count = 0;

		if (window['post_share_count_' + post_id] !== undefined) {
			view_count = window['post_share_count_' + post_id];
		}

		if (jQuery(".webview.article-page.mobile-article").length) {
			let app_sharing_url_message = {
				event: "articleurl", 
				currentState: currentStateArticle, 
				sharing_url: init_article_url,
				post_id: init_article_id,
				post_title: init_article_title,
				post_date: init_article_date,
				post_cover_image: init_article_cover_image,
				share_count: view_count
			};
			
			if(typeof AppInterfaceV2 !== 'undefined'){
				AppInterfaceV2.postMessage(JSON.stringify(app_sharing_url_message));
			}
			if (typeof AppInterface === 'undefined') {
				if (typeof window.webkit != 'undefined') {
					window.webkit.messageHandlers.share.postMessage(JSON.stringify(app_sharing_url_message));
				}
			}
			else {
				AppInterface.articleurl(JSON.stringify(app_sharing_url_message));
			}

		} else {
			display_share_view_count(view_count);
		}
	}
}

function get_share_view_count(post_id) {
	let view_count = 0;

	if (window['post_share_count_' + post_id] !== undefined) {
		view_count = window['post_share_count_' + post_id];
	}

	return view_count;
}


$(document).ready(function() {

    var isMobile = /iPhone|iPad|iPod|Android/i.test(navigator.userAgent);

	$(document).on('click', '.socialshare[platform="shareall"]', function(e) {
        e.preventDefault();
        
        if(isMobile && navigator.share) {
            if(currentStateArticle == 2){
                link = secondary_article_url;
                name = secondary_article_title;
            }
            else{
                link = $("#single-post-id .single-post-shortlink").attr("data-link");
                name = $("#single-post-id .single-post-sharename").attr("data-name");
            }
            navigator.share({
                title: name,
                text: name,
                url: link,
            })
            .then(() => console.log('Successful share'))
            .catch((error) => console.log('Error sharing', error));
        } else {		
			if(!isMobile){
				//console.log('normal browser');
			}
            $('body').addClass('st-body-no-scroll');
            $('#shareall').removeClass('hidden').animate({opacity: 1, top: 0}, 300);
        }
    });

    $('#shareall .st-close').click(function(e) {
        e.preventDefault();        
        $('body').removeClass('st-body-no-scroll');
        $('#shareall').animate({opacity: 0, top: '100%'}, 300, function() {
            $(this).addClass('hidden');
        });
    });

	$(document).on('click', '#shareall.share-article .st-btn', function() {
        var platform = $(this).data('network');
		if(currentStateArticle == 2){
			link = secondary_article_url;
			name = secondary_article_title;
		}
		else{
			link = $("#single-post-id .single-post-shortlink").attr("data-link");
			name = $("#single-post-id .single-post-sharename").attr("data-name");
		}
        var openlink = getShareLink(platform, link, name);
        window.open(openlink, '_blank');
    });

});

$(document).ready(function() {

	//initNotifyAppArticlePageIDS();

	if(jQuery("#secondary_article").length){
		let lastStateArticle;	
		$( window ).scroll(function() {
			if(currentStateArticle != lastStateArticle){

				//temporary turn off
				if(currentStateArticle == 1){
					$('.scroll-to-primary').addClass('hidden');
					$('.scroll-to-secondary').removeClass('hidden');
				}
				else{
					$('.scroll-to-primary').removeClass('hidden');
					$('.scroll-to-secondary').addClass('hidden');
				}
				lastStateArticle = currentStateArticle;
				notifyMobileArticlePosition(currentStateArticle);

			}
		});
	}

	$('.scroll-article').on('click', function(event) {
		event.preventDefault();
		var headerHeight = $('.desktop-sticky-header-wrapper').outerHeight(true);
		var targetElement;

		var title_source = "";
		if($(this).hasClass('scroll-to-primary')){
			targetElement = '#primary_article_header';
			title_source = primary_article_title;
		} else if($(this).hasClass('scroll-to-secondary')) {
			targetElement = '#secondary_article';
			title_source = secondary_article_title;
		}

		if(title_source!=""){
			gtag('event', '12clcik', {
			'send_to': 'G-F7SFM6LR17',
			'page_title': title_source
			});
		}

		var targetOffset = $(targetElement).offset().top - headerHeight;
		$('html, body').animate({ scrollTop: targetOffset }, 500);
	});

	$(document).on('click', '.redeem-box-content .floating-box-close-icon', function(e) {
		$('.redeem-box-content-minimized').removeClass('hidden');
		$('.redeem-box-content').addClass('hidden');
		$('.reader-redeem-code-section').css('width', 'unset');
	});
	$(document).on('click', '.redeem-box-content-minimized', function() {
		$(this).addClass('hidden');
		$(this).prev('.redeem-box-content').removeClass('hidden');
		$('.reader-redeem-code-section').css('width', '300px');
	});
	
    if ($('.reader-redeem-code-section').length > 0) {
        updateRedeemCode('.reader-redeem-code-section:first', "95anniv");
    }

	function setRightProperty(targetSelector) {
        if ($(targetSelector).length) {
			if($(window).width() > 768){
				var borderRightDistance = $(window).width() - $('.article-content-column').offset().left - $('.article-content-column').outerWidth();
				$(targetSelector).css('right', borderRightDistance + 'px');
			}else{
				$(targetSelector).css('right', '10px');
			}
        }
    }
    setRightProperty('.reader-redeem-code-section:first');

    $(window).resize(function() {
        setRightProperty('.reader-redeem-code-section:first');
    });

    $(document).on('click', '#copy-button', function(e) {
        e.preventDefault();
        var copyText = document.querySelector("#copy-me > div");
        navigator.clipboard.writeText(copyText.textContent).then(function() {
            var button = $(e.target);
            var originalText = button.text();
            button.text('Copied!');
			button.prev('#copy-me').addClass('highlighted');

            setTimeout(function() {
                button.text(originalText);
				button.prev('#copy-me').removeClass('highlighted');
            }, 4000);

        }, function(err) {
            console.error('Error copying: ', err);
        });
	});

});


function setWebViewDeepLink(segment) {
	if (jQuery(".webview.article-page.mobile-article").length > 0) {
		if(segment=='reel'){		
			var reelLink = jQuery(".bottom-floading-icon.reel");
			if (reelLink.length > 0) {
			  var deeplink = "https://www.sinchew.com.my/screel";
			  reelLink.attr("href", deeplink);
			}
		}
	}
}

function updateRedeemCode(targetSelector, grouping) {
    if (grouping == "95anniv") {
		var deeplink = "https://bit.ly/4bRYGYo";
		
		if(jQuery(".webview.article-page.mobile-article").length){
			deeplink = "https://www.sinchew.com.my/sc95reward";
		}

        $.ajax({
            type: "GET",
            contentType: "application/json; charset=utf-8",
            url: '/ajx-api/95_game_redeemcode/',
            dataType: "json",
            success: function(data) {
                var redeemCodeFound = false;
                var today = new Date();
                var todayStart = new Date(today.getFullYear(), today.getMonth(), today.getDate(), 0, 0, 0);
                var todayEnd = new Date(today.getFullYear(), today.getMonth(), today.getDate(), 23, 59, 59);                
                data.forEach(function(code) {
                    var fromDate = new Date(code.from_date + 'T00:00:00');
                    var toDate = new Date(code.to_date + 'T23:59:59');                    
                    if (todayStart <= toDate && todayEnd >= fromDate) {
												
						var redeemCodeCookie = getCookie('redeem95_' + code.redeem_code);
						if (redeemCodeCookie === null) {

							var redeem_styling = "";
							if(code.usage_count >= code.redeem_cap){
								redeem_styling = "grey-out";
							}

							var redeemCodeHtml = `
							<div class="redeem-box-content">
								<div class="redeem-layer ${redeem_styling}"></div>
								<div class="top-left-label"><img class="image" style="width:60px;" src="/public/images/95game/redeem_new.png?v=0.2" /></div>

								<div class="floating-box-close-icon floating-box-close"></div>
								<div class="fbox">
									<div class="fcontent code">
										<div class="htitle"><img class="image" style="width:180px;" src="/public/images/95game/redeem_logo.png" /></div>
										<div class="offer-container">
											<div class="offer-code">
												<div class="code-box code" aria-describedby="copy-button" id="copy-me">
													<div>${code.redeem_code}</div>
												</div>
												<button id="copy-button" data-clipboard-target="#copy-me">Copy</button>
											</div>
										</div>
										<div class="offer-actions"><a href="${deeplink}" class="link" target="_blank">前往游戏兑换额外抽奖机会 ></a>
											<div class="terms hidden"><span class="c-terms-button">Terms</span> <i class="df-arrow-gen-down"></i></div>
										</div>
									</div>
								</div>
							</div>
							<div class="redeem-box-content-minimized hidden">
								<div class="minimized-content"><img class="image" style="width:120px;" src="/public/images/95game/redeem_logo.png" /></div>
							</div>
							`;
							$(targetSelector).html(redeemCodeHtml);
							redeemCodeFound = true;
							return false;
						}
                    }
                });

                if (!redeemCodeFound) {
                    $(targetSelector).addClass('hidden').addClass('nodata');
                }
            }
        });
    }
}


function initNotifyAppArticlePageIDS(){
	if(jQuery(".webview.article-page.mobile-article").length){
		let app_article_message = {
			event: "articleurl", 
			primary_article_id: primary_article_id,
			secondary_article_id: secondary_article_id || 0
		};
		
		if(typeof AppInterfaceV2 !== 'undefined'){
			AppInterfaceV2.postMessage(JSON.stringify(app_article_message));
		}
		if(typeof webkit !== 'undefined'){	//safari
			window.webkit.messageHandlers.share.postMessage(JSON.stringify(app_article_message));
		}
		else if (typeof AppInterface !== 'undefined') { //android
			AppInterface.articleurl(JSON.stringify(app_article_message));
		}
	}	
}

function notifyMobileArticlePosition(currentStateArticle){
	if(currentStateArticle==1){
		articleposition = "first";
		init_article_url = primary_article_url;
		init_article_id = primary_article_id;
		init_article_title = primary_article_title;
		init_article_date = primary_article_date;
		init_article_cover_image = primary_article_cover_image;		
	}
	else{
		articleposition = "second";
		init_article_url = secondary_article_url;
		init_article_id = secondary_article_id;
		init_article_title = secondary_article_title;
		init_article_date = secondary_article_date;
		init_article_cover_image = secondary_article_cover_image;		
	}
	if(jQuery(".webview.article-page.mobile-article").length){

		let view_count = 0;
		if (window['post_share_count_' + init_article_id] !== undefined) {
			view_count = window['post_share_count_' + init_article_id];
		}

		let app_article_message = {
			event: "articleurl", 
			action: articleposition+"_article",
			currentState: currentStateArticle, 
			sharing_url: init_article_url,
			post_id: init_article_id,
			post_title: init_article_title,
			post_date: init_article_date,
			post_cover_image: init_article_cover_image,
			share_count: view_count
		};
		
		if(typeof AppInterfaceV2 !== 'undefined'){
			AppInterfaceV2.postMessage(JSON.stringify(app_article_message));
		}
		if(typeof webkit !== 'undefined'){
			window.webkit.messageHandlers.share.postMessage(JSON.stringify(app_article_message));
		}
		else if (typeof AppInterface !== 'undefined') {
			AppInterface.articleurl(JSON.stringify(app_article_message));
		}
	}
}

function getMobileArticleClickNotification(mobileStateArticle){
	if(jQuery(".webview.article-page.mobile-article").length){
		currentStateArticle = mobileStateArticle;
		var targetElement;
		if(currentStateArticle==1){
			targetElement = '#primary_article_header';
		}
		else if(currentStateArticle==2){
			targetElement = '#secondary_article';
		}

		scrollToTarget(targetElement);
		
		if(currentStateArticle==2){	//prevent duplicate sending when click button back to first article
			notifymobileapp_sharecount(currentStateArticle);
		}
	}
}

const scrollToTarget = (targetElement) => {
	var targetOffset = $(targetElement).offset().top;  
	$('html, body').animate({ scrollTop: targetOffset}, 500);  
}

function notifymobileapp_sharecount(article_pos){
	if(article_pos==2)
	{
		if(jQuery(".webview.article-page.mobile-article").length){
			//avoid url change in webview
			currentSharingUrl = secondary_article_url;
			let app_sharing_url_message = {event: "articleurl", sharing_url: currentSharingUrl, post_id: secondary_article_id, post_title: secondary_article_title, post_date:secondary_article_date, post_cover_image:secondary_article_cover_image,share_count: get_share_view_count(secondary_article_id)};
			
			if(typeof AppInterfaceV2 !== 'undefined'){
				AppInterfaceV2.postMessage(JSON.stringify(app_sharing_url_message));
			}
			if (typeof AppInterface === 'undefined') {
				if(typeof window.webkit != 'undefined'){
					window.webkit.messageHandlers.share.postMessage(JSON.stringify(app_sharing_url_message));
				}
			}
			else{	
				AppInterface.articleurl(JSON.stringify(app_sharing_url_message));
			}
		}
		document.title = secondary_article_title;
		currentStateArticle = 2;
	}
	else
	{
		if(jQuery(".webview.article-page.mobile-article").length){
			//avoid url change in webview
			currentSharingUrl = primary_article_url;
			let app_sharing_url_message = {event: "articleurl", sharing_url: currentSharingUrl, post_id: primary_article_id, post_title: primary_article_title, post_date:primary_article_date, post_cover_image:primary_article_cover_image,share_count:get_share_view_count(primary_article_id)};

			if(typeof AppInterfaceV2 !== 'undefined'){
				AppInterfaceV2.postMessage(JSON.stringify(app_sharing_url_message));
			}
			if (typeof AppInterface === 'undefined') {
				if(typeof window.webkit != 'undefined'){
					window.webkit.messageHandlers.share.postMessage(JSON.stringify(app_sharing_url_message));
				}
			}
			else{	
				AppInterface.articleurl(JSON.stringify(app_sharing_url_message));
			}
		}
		document.title = primary_article_title;
		currentStateArticle = 1;
	}
}

/*
document.addEventListener("DOMContentLoaded", function() {

    if(document.querySelector('.hot-posts-frame-list') && document.querySelector('.homepage-headline-news-wrapper-outer')) 
    {
        if (window.innerWidth >= 768) {            
            var SliderSectionHeight = document.querySelector('.homepage-headline-news-wrapper-outer').offsetHeight + document.querySelector('.link-more-headline').offsetHeight;
            var boxCol1Height = SliderSectionHeight;
            var boxCol2_Header = document.querySelector('.sc-flex-row .box-col--40 .hot-posts-frame-title').offsetHeight;
            var boxCol2_Footer = document.querySelector('.sc-flex-row .box-col--40 .link-more').offsetHeight;
            document.querySelectorAll('.sc-flex-row .box-col--40 .hot-posts-frame-list').forEach(element => { element.style.maxHeight = `${boxCol1Height - boxCol2_Header - boxCol2_Footer}px`; });
            document.querySelectorAll('.sc-flex-row .box-col--40 .hot-posts-frame-list').forEach(element => element.style.visibility = "visible");
        }
    }
    resizeHotpost();
    window.addEventListener('resize', resizeHotpost);
});


function resizeHotpost() {

	if(document.querySelector('.hot-posts-frame-list') && document.querySelector('.homepage-headline-news-wrapper-outer')) 
	{
		const boxCol2 = document.querySelector('.sc-flex-row .box-col--40 .hot-posts-frame-list');
		if (window.innerWidth >= 768) {   
			console.log("resizeHotpost > 768");
			var SliderSectionHeight = document.querySelector('.homepage-headline-news-wrapper-outer').offsetHeight + document.querySelector('.link-more-headline').offsetHeight;
			var boxCol1Height = SliderSectionHeight;
			var boxCol2_Header = document.querySelector('.sc-flex-row .box-col--40 .hot-posts-frame-title').offsetHeight;
			var boxCol2_Footer = document.querySelector('.sc-flex-row .box-col--40 .link-more').offsetHeight;
			document.querySelectorAll('.sc-flex-row .box-col--40 .hot-posts-frame-list').forEach(element => { element.style.maxHeight = `${boxCol1Height - boxCol2_Header - boxCol2_Footer}px`; });
			document.querySelectorAll('.sc-flex-row .box-col--40 .hot-posts-frame-list').forEach(element => element.style.visibility = "visible");
		} else {
			console.log("resizeHotpost <= 768");
			document.querySelectorAll('.sc-flex-row .box-col--40 .hot-posts-frame-list').forEach(element => {
				element.style.maxHeight = '320px';
				element.style.overflowY = 'scroll';
				element.style.visibility = "visible";
			});
		}
	}
}
*/

function backToTop(){
	return jQuery("body,html").animate({scrollTop: 0}, 800), !1
}


function scrollProgressBar() {
	var getMax = function getMax() {
	  	return $(document).height() - $(window).height();
	};
  
	var getValue = function () {
	  	return $(window).scrollTop();
	};
  
	var max = getMax();
	var value;
	var width;
  
	var getWidth = function () {
		value = getValue();
		width = (value / max) * 100;
		width = width + "%";
		return width;
	};
  
	var setWidth = function () {
		max = getMax();
		$(".scroll-progress-bar").css({ width: getWidth() });
	};
  
	$(document).on("scroll", setWidth);
	$(window).on("resize", setWidth);
}

function showSearchForm(event) {
	var desktopForm = document.querySelector('.site-search-desktop-form');		
	if (desktopForm.contains(event.target)) {
		return;
	}
	if (desktopForm) {
		if (desktopForm.style.display === "none" || desktopForm.style.display === "") {
			desktopForm.style.display = "block";
			retrieve_suggested_keyword();
			retrieve_topic_keyword();
			$(".site-search-desktop-hover").show();
		} else {
			desktopForm.style.display = "none";
		}
	}
}

document.addEventListener("DOMContentLoaded", function() {
    function enableDragScroll(selector) {
        const container = document.querySelector(selector);
        if (!container) return;

        let isDown = false;
        let startX;
        let scrollLeft;

        container.addEventListener('mousedown', (e) => {
            isDown = true;
            startX = e.pageX - container.offsetLeft;
            scrollLeft = container.scrollLeft;
            container.style.cursor = 'grabbing';
        });
        container.addEventListener('mouseleave', () => {
            isDown = false;
            container.style.cursor = 'grab';
        });
        container.addEventListener('mouseup', () => {
            isDown = false;
            container.style.cursor = 'grab';
        });
        container.addEventListener('mousemove', (e) => {
            if (!isDown) return;
            e.preventDefault();
            const x = e.pageX - container.offsetLeft;
            const walk = (x - startX);
            container.scrollLeft = scrollLeft - walk;
        });
    }

    enableDragScroll('.favor-selections-bar-scroll');
    enableDragScroll('.localnews-selections-bar-scroll');
});


$(document).ready(function() {

    if($(window).width() >= 768) {
        $('.title.expandable').hover(function() {
            $(this).removeClass('expandable').addClass('expanded');
        });
    }

    var applyMaxHeight = function() {
        if($(window).width() >= 768) {
            var maxHeight = 0;
            $('#homepage_2 .post-frame-mobile-right').each(function(){
                $(this).css('height', 'auto');
                var thisHeight = $(this).height();
                if(thisHeight > maxHeight) {
                    maxHeight = thisHeight;
                }
            });
            $('#homepage_2 .post-frame-mobile-right').height(maxHeight);
        } else {
            $('#homepage_2 .post-frame-mobile-right').css('height', 'auto');
        }
    };
    applyMaxHeight();

    var debounce;
    $(window).resize(function(){
        clearTimeout(debounce);
        debounce = setTimeout(applyMaxHeight, 200);
    });


	if ($('.fukanGroup[data-catid]').length > 0) 
	{
		function moveAdvertorialToAfterDataCnt($container, targetCnt) {
			var $advPost = $container.find('.adv-post');
			var $targetPost = $container.find(`.vertical-post-frame[data-cnt="${targetCnt}"]`);
			$advPost.insertAfter($targetPost);
	
			if (targetCnt === 0) { // mobile mode
				$container.find('.vertical-post-frame:nth-child(1), .vertical-post-frame:nth-child(2)').removeClass('mobile-hidden');
				$container.find('.vertical-post-frame:nth-child(n+3)').addClass('mobile-hidden');
			} else { // desktop mode
				$container.find('.vertical-post-frame').removeClass('mobile-hidden');
			}
		}
	
		function rearrangeAdvertorial($container) {
			var screenWidth = $(window).width();
			if (screenWidth <= 768) {
				moveAdvertorialToAfterDataCnt($container, 0); //to after first place
			} else {
				moveAdvertorialToAfterDataCnt($container, 1); //to after second place
			}
		}
	
		function handleResize() {
			clearTimeout(window.resizingFinished);
			window.resizingFinished = setTimeout(function(){
				$('.fukanGroup[data-catid]').each(function() {
					rearrangeAdvertorial($(this));
				});
			}, 500);
		}
	
		$('.fukanGroup[data-catid]').each(function() {
			rearrangeAdvertorial($(this));
		});
	
		$(window).resize(handleResize);
	}

	$('.acceptCookies').click(function() {
		setCookie('cookieConsent', true, 365);
		$('.cookie-consent-banner').addClass('hidden');
	});

});


function initViewAndShareStatistic(){
    var xmlhttp = new XMLHttpRequest();
    xmlhttp.onreadystatechange = function() {
        if (xmlhttp.readyState == XMLHttpRequest.DONE) {
            if (xmlhttp.status == 200) {
                eval(xmlhttp.responseText);
            }
        }
    };
    xmlhttp.open("POST", "/front-ajx.php", true);
    xmlhttp.setRequestHeader('content-type', 'application/x-www-form-urlencoded');
    xmlhttp.send("action=site_view&domain="+share_domain+"&url="+page_url);
}
function updateSiteShare(){
	var xmlhttp = new XMLHttpRequest();
	xmlhttp.onreadystatechange = function() {
		if (xmlhttp.readyState == XMLHttpRequest.DONE) {
			if (xmlhttp.status == 200) {
				eval(xmlhttp.responseText);
			}
		}
	};
	xmlhttp.open("POST", "/front-ajx.php", true);
	xmlhttp.setRequestHeader('content-type', 'application/x-www-form-urlencoded');
    xmlhttp.send("action=site_share&domain="+share_domain);
}

function updateAnalyticShare(){
	var xmlhttp = new XMLHttpRequest();
	xmlhttp.onreadystatechange = function() {
		if (xmlhttp.readyState == XMLHttpRequest.DONE) {
			if (xmlhttp.status == 200) {
				eval(xmlhttp.responseText);
			}
		}
	};
	xmlhttp.open("POST", "/front-ajx.php", true);
	xmlhttp.setRequestHeader('content-type', 'application/x-www-form-urlencoded');
	xmlhttp.send("action=page_share&url="+page_url+'&platform_share='+platform_share);
}

function initializePhotoSwipe(gallerySelector, pswpElementSelector) {    
    const elements = document.querySelectorAll(gallerySelector);
    const items = Array.from(elements).map(el => {
        const src = el.getAttribute('data-pswp-src');
        const width = parseInt(el.getAttribute('data-pswp-width'), 10);
        const height = parseInt(el.getAttribute('data-pswp-height'), 10);
		const caption = el.getAttribute('data-pswp-caption');
        return {
            src: src,
            w: width,
            h: height,
            title: caption			
        };
    });
    elements.forEach((el, index) => {
        el.addEventListener('click', function (e) {
            e.preventDefault();
            openPhotoSwipe(items, index, pswpElementSelector);
        });
    });
}
function openPhotoSwipe(items, index, pswpElementSelector) {
    const pswpElement = document.querySelector(pswpElementSelector);
    if (!pswpElement) {
        return;
    }
    const options = {
        index: index,
        bgOpacity: 0.7,
        showHideOpacity: true,
    };
    const gallery = new PhotoSwipe(pswpElement, PhotoSwipeUI_Default, items, options);
    gallery.init();
}

function articleContentProgressTracker() {
    if (!isArticlePage) { return; }

    const thresholds = [25, 50, 75, 100];
    const articles = [];

    if ($('.article-page-content').length) {
        articles.push({
            content: $('.article-page-content'),
            hiddenContent: $('.read-more-wrapper').length ? $('.read-more-wrapper') : $(),
            title: gatitle,
            scrollEvents: Object.fromEntries(thresholds.map(threshold => [threshold, false])),
            hasHiddenContent: $('.read-more-wrapper').length ? true : false
        });
    }

    if ($('#secondary_article_content').length && secondary_article_gatitle != '') {		
        articles.push({
            content: $('#secondary_article_content'),
            hiddenContent: $(''),
            title: secondary_article_gatitle,
            scrollEvents: Object.fromEntries(thresholds.map(threshold => [threshold, false])),
            hasHiddenContent: false
        });
    }

	console.log("movingon");
    function getArticleDimensions(article) {
        const maxHeight = article.content.outerHeight(true);
        
        if (!article.hasHiddenContent) {
            return [maxHeight, 9999];
        }
        
        if (!article.hiddenContent.hasClass('released')) {
            article.hiddenContent.addClass('released');
            hiddenHeight = 100 - ((article.hiddenContent.outerHeight(true) / maxHeight) * 100);
            article.hiddenContent.removeClass('released');
        }
        
        return [maxHeight, hiddenHeight];
    }

    function getScrollProgress(article) {
        return (($(window).scrollTop() + $(window).height() - article.content.offset().top) / article.maxHeight) * 100;
    }

    function updateArticleDimensions(article) {
        const [maxHeight, hiddenHeight] = getArticleDimensions(article);
        article.maxHeight = maxHeight;
        article.hiddenHeight = hiddenHeight;
    }

    function checkScrollProgress() {
        articles.forEach((article) => {
            const scrollPercent = getScrollProgress(article);

            const hiddenThreshold = article.hasHiddenContent && 
			article.hiddenContent.hasClass('released') ? 9999 : article.hiddenHeight;
            
            thresholds.forEach(threshold => {
                if (scrollPercent >= threshold && !article.scrollEvents[threshold] && threshold <= hiddenThreshold) {
                    sendArticleContentProgressEvent(article.title, threshold);
                    article.scrollEvents[threshold] = true;
                }
            });
        });
    }

    let scrollTimeout;

    $(document).on('scroll', function() {
        clearTimeout(scrollTimeout);
        scrollTimeout = setTimeout(function() {
            articles.forEach(updateArticleDimensions);
            checkScrollProgress();
        }, 200);
    });

    articles.forEach(updateArticleDimensions);
}

function articlePageProgressTracker() {
    if (!isArticlePage) return;

    const thresholds = [25, 50, 75, 100];
    const scrollEvents = Object.fromEntries(thresholds.map(threshold => [threshold, false]));

    function getScrollProgress() {
        return ($(window).scrollTop() + $(window).height()) / $(document).height() * 100;
    }

    function checkScrollProgress() {
        const scrollPercent = getScrollProgress() + 0.01;
        thresholds.forEach(threshold => {
            if (scrollPercent >= threshold && !scrollEvents[threshold]) {
                const titleToSend = (threshold <= 50) 
                    ? gatitle 
                    : ($('#secondary_article_content').length ? secondary_article_gatitle : gatitle);
                    
                sendArticlePageProgressEvent(titleToSend, threshold);
                scrollEvents[threshold] = true;
            }
        });
    }

    let scrollTimeout;

    $(document).on('scroll', function() {
        clearTimeout(scrollTimeout);
        scrollTimeout = setTimeout(checkScrollProgress, 200);
    });
}

function updateChartbeatVirtualPageChange(current_state_article, primary_article_title, secondary_article_title, url) {
	let cb_article_section = "";
	let article_author_meta_tag = document.querySelector('meta[property="article:author"]');
	let cb_article_author = article_author_meta_tag ? article_author_meta_tag.getAttribute("content") : null;
	let canonical_url = document.querySelector('link[rel="canonical"]');
	let canonical_path = canonical_url ? new URL(canonical_url.getAttribute("href")).pathname : null;

	switch (current_state_article) {
		case 1:
			cb_article_section = "2article";
			cb_article_title = secondary_article_title;
			path = url.pathname;
			break;
		case 2:
			cb_article_section = "1article";
			cb_article_title = primary_article_title;
			path = canonical_path || url.pathname;
			break;
		default:
			console.error("Unimplemented current_state_article value.");
			return;
	}

	pSUPERFLY.virtualPage({
		sections: cb_article_section,
		authors: cb_article_author,
		path: path,
		title: cb_article_title
	});

	console.log("Sent virtualPage data:", {
        sections: cb_article_section,
        authors: cb_article_author,
        path: path,
        title: cb_article_title
    });
}

document.addEventListener('DOMContentLoaded', () => {

    if (document.body.classList.contains('page-template-video-baige')) {
        return;
    }

    function updateHeroVideoBottomPosition() {
        const elements = document.querySelectorAll('[id^="vr-"][class*="vr-"]');
        const overlayElement = document.querySelector('.ats-overlay-bottom-wrapper-rendered');
        const overlayHeight = overlayElement ? overlayElement.offsetHeight + 10 : 20;
        elements.forEach((el) => {	
            const classListStr = Array.from(el.classList).join(' ');
            if (classListStr.includes('-bottom-right-position')) {
                // Only apply bottom positioning when in dynamic floating mode
                if (overlayHeight > 0) {
                    el.style.setProperty('bottom', `${overlayHeight}px`, 'important');
                } else {
                    el.style.setProperty('bottom', '20px', 'important');
                }
            } else {
				el.style.setProperty('bottom', '0px', 'important');
            }
        });
    }

    const ivs_observer = new MutationObserver(updateHeroVideoBottomPosition);
    if (document.body) {
        ivs_observer.observe(document.body, { childList: true, subtree: true });
    } else {
        console.error("document.body is not available for observation.");
    }
	updateHeroVideoBottomPosition();
});

function fetchAndDisplayLockedContent() {
    const placeholder = $('#locked-content-placeholder');

    if (placeholder.length) {
        const postId = placeholder.data('postid');

        $.ajax({
            url: `/ajx-api/locked-content?postid=${postId}`,
            type: 'GET',
            dataType: 'json',
            success: function(response) {
                if (response && response.locked_content) {
                    placeholder.html(response.locked_content);

                    convertTradSimpCN(placeholder);
                }
            },
            error: function(err) {
                console.error("Failed to load locked content.", err);
                placeholder.html("<p>文章剩余内容加载失败，请刷新页面重试。</p>");
            }
        });
    }
}