$(function(){ CUtils.init(); AUtils.init(); MUtils.init(); PUtils.init(); PTUtils.init(); }); var fr_opts = {autoLoad:false}; var THA_VARS = THA_VARS || {}; function _th_trackEvent(category,action, label){ CUtils.gevent(category,action,label); } function _th_trackPageView(url){ var url = url || window.location.pathname; CUtils.gpview(url); } var CUtils = { _ap:"/trends", iHost:"https://cdn.trendhunterstatic.com", init:function(){ $.support.cors = true; CUtils.bind(); }, bind:function(){ $('body') .on('click','a.ctft__cont',function(e){ e.preventDefault(); var act = $('.th__magazine').length ? 'mag-click' : 'trend-click'; CUtils.gevent('ctfad',act,null,$(this).attr('href')); }); }, gpview:function(url){ //ga('send','pageview',url); //console.log('send pageview'); gtag('event','page_view'); }, trackSponsored:function(url){ gtag('event','page_view',{'page_location':url}); }, loadFreeReport:function(autoLoad){ THFormUserLoad(); }, gevent:function(category,action,label, url){ CPage.gevent(category,action,label,url); /*label = label == null ? '' : label; category = category+""; action = action+""; label = label+""; if(!url){ ga('send','event',category, action, label); }else{ ga('send','event',category, action, label,{ 'hitCallback':function(){ window.location.href = url; } }); }*/ }, ajax:function(params,type, cache){ var params = params || {}, type = type || 'GET', cache = cache || false; params['aj'] = 1; if(!params['eid'] && !params['cid']){ params['eid'] = $(".tha[data-eid]").data('eid'); } var _ap = params['_ap'] ? params['_ap'] : CUtils._ap; delete params['_ap']; var $req = $.ajax({ url:_ap, data:params, dataType:'json', type:type, cache:cache, xhrFields:{withCredentials:true}, crossDomain:true }); $req.fail(function(arg1,arg2){ Prompt.alert('There was an error performing your request'); console.log("p:",params); }); return $req; }, getImageSrc:function(eid,num,format,domain,okk){ var domain = domain || CUtils.iHost, okk = typeof okk == 'undefined' || okk == null ? "" : "_"+okk, webp = THA_VARS['webp'] ? "?auto=webp" : "", src = domain+"/phpthumbnails/"+Math.floor(eid/1000)+"/"+eid+"/"+eid+"_"+num+"_"+format+okk+".jpeg"+webp; return src; } } var PActions = { btnMap:{ 'more':'loadPage', 'switchindexpage':'switchIndexPage', 'freereport':'loadFreeReport' }, buttonClick:function(btn,item){ var fname = PActions.btnMap[btn] ? PActions.btnMap[btn] : false; if(!fname){ return; } PActions[fname](item); }, loadFreeReport:function(){ CUtils.loadFreeReport(false); }, switchIndexPage:function(item){ var $item = $(item), page = $item.data('page'); $('.thp__indexBtn').removeClass('thp__indexBtn--selected'); $item.addClass('thp__indexBtn--selected'); $('.thp__indexPage--visible').removeClass('thp__indexPage--visible'); if(page != 'new' && !$('.thp__indexPage').length){ PActions.loadIndexPages(); return; } $('.thp__indexPage[data-page="'+page+'"]').addClass('thp__indexPage--visible'); }, loadIndexPages:function(){ var $req = CUtils.ajax({act:'lip'},'GET',true); $req.done(function(r){ if(!r.success){ error('There was an error loading the index pages'); return; } $('.thp__indexPages').empty().html(r.data); var page = $('.thp__indexBtn--selected').data('page'); $('.thp__indexPage[data-page="'+page+'"]').addClass('thp__indexPage--visible'); }); }, loadPage:function(){ if(!$('.tha__btn--more:visible').length){ return; } $('.tha__btn--more').hide(); $('.tha__moreLoader').show(); var page = PUtils.page, nextPage = page + 1, params = { act:'lp', p:nextPage }; if($('.th__pro').data('cig')){ params['ci'] = $('.th__pro').data('cig'); } if($('.th__pro').data('cat')){ params['c'] = $('.th__pro').data('cat'); } if($('.th__pro').data('type')){ params['t'] = $('.th__pro').data('type'); } var $req = CUtils.ajax(params,'GET',true); $req .done(function(r){ if(!r.success){ error(r.data); return false; } if(r.data.length == ""){ $('.tha__btn--more').remove(); $('.tha__moreLoader').remove(); return; } PUtils.page = PUtils.page + 1; $('.thp__page:eq(0)').append(r.data); Lazy.reveal(); }) .fail(function(r){ error('There was an error loading the next page'); }) .always(function(){ $('.tha__btn--more').show(); $('.tha__moreLoader').hide(); }); } } var PUtils = { page:1, init:function(){ if(!$('.th__pro').length){ return; } CUtils._ap = "/pro"; setTimeout(Lazy.reveal,200); setTimeout(function(){ PUtils.initialScrollPos = $('html').scrollTop(); },500); PUtils.bind(); window.memberInfoCallback = PUtils.memberInfoCallback; }, bind:function(){ $(document,window).on('scroll',PUtils.handleScroll); $(window).on('resize',PUtils.handleResize); $('body') .on('click','[data-btn]',function(){ PActions.buttonClick($(this).data('btn'), this); }) /*.on('mouseenter','.thar',function(){ CActions.rotateImages(this); }) .on('mouseleave','.thar',function(){ CActions.stopRotation(); })*/ }, memberInfoCallback:function(info){ if(info.g){ if(info.g != 3){ $('.tha__btn--login').animate({'opacity':0}); } if([1,6,14,15,16,18,19,21,22].indexOf(info.g) != -1){ $('.tha__btn--subscribe').animate({'opacity':0}); $('.tha__subscribeLink').remove(); $('.tha__btn--trial').animate({'opacity':0}); $('.tha__btn--more').show(); }else{ $('.tha__btn--more').remove(); } } }, lastScroll:new Date().getTime(), initialScrollPos:-1, handleScroll:function(e){ var currTime = new Date().getTime(), diff = currTime - PUtils.lastScroll; if(diff < 100){ return; } PUtils.lastScroll = currTime; if( window.scrollY > PUtils.initialScrollPos && PUtils.initialScrollPos == 0 && $('.thp__top--first').length && $('.thp__top--second').length && window.innerWidth > 767 ){ e.preventDefault(); var scrollVal = $('#thp__frame').offset().top - 30; PUtils.initialScrollPos = -1; // window.scrollTo(0, scrollVal); $('#thp__frame').get(0).contentWindow.location.reload() $("html,body") .stop().animate( {scrollTop:scrollVal}, 500, 'swing', function(){ } ); return false; } PUtils.checkIframeAnimation(); Lazy.reveal(); if($('[data-btn="more"]:visible').length && $(window).scrollTop() + $(window).height() > $(document).height() - 500){ PActions.loadPage(); } }, checkIframeAnimation:function(){ var iframe = document.getElementById('thp__frame'); if(!iframe){ return; } var pos = iframe.getBoundingClientRect(), top = pos.top, bottom = pos.bottom, height = pos.height, tollerance = height + 100, min = 0 - tollerance, wHeight = parseInt(window.innerHeight), max = wHeight + tollerance; if(iframe && typeof iframe.contentWindow.Particles == 'object'){ if((top > min && bottom < max)){ iframe.contentWindow.Particles.startMovement(); }else{ iframe.contentWindow.Particles.stopMovement(); } } }, handleResize:function(){ Lazy.reveal(); } }; var PTUtils = { init:function(){ if(!$('.th__pt.tpt').length){ return false; } CUtils._ap = "/protrends"; setTimeout(Lazy.reveal,200); PTUtils.bind(); window.memberInfoCallback = PTUtils.memberInfoCallback; }, bind:function(){ $(document,window).on('scroll',PTUtils.handleScroll); $(window).on('resize',PTUtils.handleResize); $('body') .on('click','[data-btn]',function(){ // PActions.buttonClick($(this).data('btn'), this); }) /*.on('mouseenter','.thar',function(){ CActions.rotateImages(this); }) .on('mouseleave','.thar',function(){ CActions.stopRotation(); })*/ .on('click','.tpt__paywallInner',function(e){ e.stopPropagation(); }) .on('click','.tpt__paywall',function(){ window.location.href = '/trendreports'; }); }, lastScroll:new Date().getTime(), handleScroll:function(){ var currTime = new Date().getTime(), diff = currTime - PTUtils.lastScroll; if(diff < 100){ return; } PTUtils.lastScroll = currTime; Lazy.reveal(); }, handleResize:function(){ Lazy.reveal(); }, memberInfoCallback:function(info){ if(TH_BPC){ return; } if((!info.g || [19,18,16].indexOf(info.g) == -1) && !info.tg){ $('.tpt__subscribe').slideDown(); PTUtils.tryCookie(); }else{ console.log('THP-HA'); } }, showpaywall:function(){ console.log('show paywall'); var paywallHtml = [ "
", "
", "
", "", "
", "
", "
Upgrade to PRO
", "", "
", "
", "
" ].join(""); $('body').append(paywallHtml); setTimeout(function(){ $('.tpt__paywall').fadeIn(); $('.tpt').addClass('tpt--blur'); },200); }, tryCookie:function(){ try{ var check = PTUtils.checkCookie(); if(!check && !TH_BPC){ PTUtils.showpaywall(); return; } }catch(err){ if(!TH_BPC){ PTUtils.showpaywall(); } return; } }, launchWall:function(){ console.log('launch wall'); THFormUserLoad('insights',true); $('body').addClass('body--nohcamp'); }, popfilled:function(){ console.log('in pop filled'); //now they should be able to view 10 free insights PTUtils.updateCookie(); console.log('cookie set'); }, cookie_array:[], checkCookie:function(){ var cookie = PTUtils.readCookie("th_trak"); if(cookie == null){ PTUtils.launchWall() return true; } var urlList = decodeURIComponent(cookie); PTUtils.cookie_array = urlList.split(","); if(PTUtils.cookie_array.indexOf(window.location.pathname) != -1 ){ return true; } if(PTUtils.cookie_array.length >= 10){ return false; } PTUtils.updateCookie(); return true; }, updateCookie:function(){ var d = new Date(); var t = d.getTime(); t += 86400000; d.setTime(t); PTUtils.cookie_array.push(window.location.pathname); var cookieString = PTUtils.cookie_array.join(","), cookieStringFull = "th_trak="+cookieString+";expires="+d.toUTCString(); document.cookie = cookieStringFull; return true; }, readCookie:function(name){ name += '='; var parts = document.cookie.split(/;\s*/); for (var i = 0; i < parts.length; i++){ var part = parts[i]; if (part.indexOf(name) == 0) return part.substring(name.length) } return null; } }; var AUtils = { page:0, id:false, startUrl:false, exitIntentLaunched:false, okIds:[], mOK:false, init:function(){ if(!$('.th__article').length){ return; } CUtils._ap = "/trends"; if(window.location.pathname && window.location.pathname.indexOf('/apps/') != -1){ CUtils._ap = window.location.pathname; } setTimeout(Lazy.reveal,200); AUtils.startUrl = $('.th[data-url]').data('url'); AUtils.id = $('.th[data-id]').data('id'); AUtils.bind(); AUtils.colorizeBackground(); AGallery.init(); CGallery.init(); AUtils.trackLandingView(); AUtils.checkAmazon(); AUtils.checkOK(); AUtils.checkCTSBanners(); //AUtils.checkBanners(); // AUtils.fixGalleryImage(); }, checkCTSBanners:function(){ const $banners = $('.cts__banner:visible'); $banners.each((i,v)=>{ const $banner = $(v), bn = $banner.data('bn'); CUtils.gevent('cts-banner','banner-track',bn); }); }, checkBanners:function(){ $('.th__adsbygoogle:not(:visible)').remove(); var adsbygoogle = window.adsbygoogle || [], numBanners = $('.th__adsbygoogle').length; for(var i = 0; i < numBanners; i ++){ console.log('push banner'); adsbygoogle.push({}); } }, trackLandingView:function(){ CUtils.ajax({eid:AUtils.id,act:'tlv'},'POST',false); }, trackInternal:function(id){ var id = id || AUtils.id; if($('.trackingPixels').length == 0){ $('.tha__articleBody').before("
"); } var img = new Image(); img.src = 'https://www.trendhunter.com/trackingpixel?entry_id='+id+'&_t='+new Date().getTime()+"&_r="+Math.round(Math.random()*1000); $('.trackingPixels').append(img); }, lastScroll:new Date().getTime(), bind:function(){ $(document,window).on('scroll',AUtils.handleScroll); $(window).on('resize',AUtils.handleResize); $('body') .on('click','[data-btn]',function(){ ArticleActions.buttonClick($(this).data('btn'), this); }) .on('mouseenter','.tha__tgLink',function(){ CActions.rotateImages(this); }) .on('mouseleave','.tha__tgLink',function(){ CActions.stopRotation(); }) .on('mouseenter','.tha__tg',function(){ ATGallery.loadTopGallery(); }) .on('mouseenter','.gal__main',function(){ if($('.gal__buffer img').length == 0){ AGallery.preload(); } }) .on('click','.tha__tgLink',function(){ _th_trackEvent('trends','top-gallery-click'); }) .on('click','.tha--idea .tha__relPage .thar,.tha--keynote .tha__relPage .thar',function(){ _th_trackEvent('trends','rel-bottom-click'); }) .on('click','.tha--toplist .tha__relPage[data-page="0"] .thar',function(){ _th_trackEvent('trends','slideshow-item-click'); }) .on('click','.tha--toplist .tha__relPage[data-page!="0"] .thar',function(){ _th_trackEvent('trends','slideshow-rel-click'); }) .on('click','.tha__socialItem',function(){ _th_trackEvent('trends','social-share',$(this).data('social')); }) .on('click','.tha__sbb',function(e){ console.log('ad click'); var imgSrc = $(this).find('.tha__sbbImg').data('src').split("/"), imgName = imgSrc[imgSrc.length - 1], href = $(this).attr('href'); if(href.indexOf('http') != -1){ e.preventDefault(); CPage.gevent('trends', 'sidebarad-click', imgName, href); }else{ CPage.gevent('trends', 'sidebarad-click', imgName); } }) .on('click','.tha__freeReportLink', function(e){ e.preventDefault(); CUtils.loadFreeReport(false); }) .on('click','.tha__loginDialogJoin',function(){ window.scrollTo(0,0); THFormUserLoad('trendwall',true); }); }, popfilled:function(){ AUtils.mOK = false; AUtils.removeLoginDialog(); AUtils.loadActualImages(); }, checkPopCookie:function(){ var cookieStr = document.cookie, cookies = cookieStr.split(";"); for(var i in cookies){ var cookie = cookies[i].trim(), parts = cookie.split("="); if(parts.length < 2){ continue; } if(parts[0] == 'TH-trendwall'){ console.log('has pop cookie'); return true; } } return false; }, checkOK:function(){ //check if any of the gallery data has ok var $thisArticle = $('.th__article[data-ok]'), thisArticle = $('.th__article[data-ok]').length, isTopList = $thisArticle.hasClass('tha--toplist'), ids = []; if(isTopList){ AUtils.checkOKTopList(); } for(var id in AGallery.data){ if(AGallery.data[id].ok){ ids.push(parseInt(id)); } } var topGalleryIds = $('.tha__tgLink[data-ok="1"]').map(function(){return $(this).data('id')}).get(); ids = ids.concat(topGalleryIds); if(!ids.length){ return; //do nothing } AUtils.okIds = ids; if(typeof window.memberInfoHooks == 'undefined'){ window.memberInfoHooks = []; } window.memberInfoHooks.push(function(mi){ if(!mi.u && !mi.ok){ AUtils.mOK = true; if(thisArticle){ AUtils.loginDialog(); } //THFormUserLoad('trendwall',true); return; } AUtils.loadActualImages(); }); }, checkOKTopList:function(){ var okIds = $('[data-oki]').map(function(){return $(this).data('oki')}).get(); if(!okIds.length){ return; } okIds = okIds.filter(function(item,index){ return okIds.indexOf(item) === index; }); AUtils.okIds = okIds; if(typeof window.memberInfoHooks == 'undefined'){ window.memberInfoHooks = []; } window.memberInfoHooks.push(function(mi){ if(!mi.u && !mi.ok){ AUtils.mOK = true; AUtils.loginDialog(); //THFormUserLoad('trendwall',true); return; } AUtils.loadActualImagesTopList(); }); }, loadActualImagesTopList:function(){ var ids = AUtils.okIds; //console.log('Load actual images ',ids); var $req = CUtils.ajax({act:'gok',ids:ids, _ap:'https://www.trendhunter.com/trends'},'POST',false); $req.done(function(r){ if(!r.success){ console.log(r.data); return; } for(var eid in r.data){ var item = r.data[eid], key = item.k, imgSrcSmall = CUtils.getImageSrc(eid,1,'230c',CUtils.iHost,key), imgSrc = CUtils.getImageSrc(eid,1,'800',CUtils.iHost,key), $imgSmall = $('.tha__tlSquare img[data-oki="'+eid+'"]'), $img = $('.thar__img[data-oki="'+eid+'"]'); if($imgSmall.length){ $imgSmall.attr('src',imgSrcSmall); $imgSmall.attr('data-src',imgSrcSmall); } if($img.length){ $img.attr('src',imgSrc); $img.attr('data-src',imgSrc); } } }); }, loginDialog:function(){ var html = [ "
", "
Join FREE to View the Full Article
", "
", "
", "", "
", "
", "", "
", "
", "
" ].join(""); if($('.th__article').hasClass('tha--toplist')){ $('.tha__articleText').after(html); }else{ $('.gal__main').append(html); } }, removeLoginDialog:function(){ $('.tha__loginDialog').remove(); }, checkLoginDialog:function(){ AUtils.removeLoginDialog(); if(AUtils.okIds.indexOf(AGallery.id) != -1 && AUtils.mOK == true){ AUtils.loginDialog(); } }, loadActualImages:function(){ if($('.th__article').hasClass('tha--toplist')){ AUtils.loadActualImagesTopList(); return; } var ids = AUtils.okIds; //console.log('Load actual images ',ids); var $req = CUtils.ajax({act:'gok',ids:ids,_ap:'https://www.trendhunter.com/trends'},'POST',false); $req.done(function(r){ if(!r.success){ console.log(r.data); return; } for(var id in r.data){ var item = r.data[id]; if(AGallery.data[id]){ AGallery.data[id]['okk'] = item.k; AGallery.data[id]['pc'] = item.c; if(AGallery.id == id && $('.gal__mainImage').length && AGallery.num == 1){ var imgSrc = CUtils.getImageSrc(id,1,'800',CUtils.iHost,item.k); $('.gal__mainImage').attr('src', imgSrc); $('.gal__mainImage').removeAttr('srcset'); } } console.log('converting id: ',id); //update header bar images var $topGalleryItem = $('.tha__tgLink[data-id="'+id+'"]'); if($topGalleryItem.length){ var imgSrc = CUtils.getImageSrc(id,1,'230c',CUtils.iHost,item.k); var $img = $topGalleryItem.find('.tha__tgImg'); $img.attr('src',imgSrc); $img.attr('data-src',imgSrc); } //update thumb images var $thumbImage = $('.gal__thumb[data-id="'+id+'"]'); if($thumbImage.length){ var imgSrc = CUtils.getImageSrc(id,1,'80',CUtils.iHost,item.k); var $img = $thumbImage.find('.gal__thumbImage'); $img.attr('src',imgSrc); $img.attr('data-src',imgSrc); } } }); }, checkTHPopUpCookie:function(){ var name = 'TrendhunterPopup=', parts = document.cookie.split(/;\s*/); var cFound = null; for(var i = 0; i < parts.length; i++){ if(parts[i].indexOf(name) == 0){ cFound = parts[i].substring(name.length); break; } } if(cFound != null){ return true; } var d = new Date(), t = d.getTime(); t += 86400000*3; d.setTime(t); document.cookie = name+"1;path=/;expires="+d.toUTCString()+";SameSite=None; Secure"; return false; }, handleScroll:function(){ var currTime = new Date().getTime(), diff = currTime - AUtils.lastScroll; if(diff < 100){ return; } Lazy.reveal(); AUtils.lastScroll = currTime; if($('[data-btn="more"]:visible').length && $(window).scrollTop() + $(window).height() > $(document).height() - 500){ ArticleActions.loadPage(); } }, handleResize:function(){ Lazy.reveal(); if($('.tha__tgArticlesInner').length){ $('.tha__tgArticlesInner').css('left','0px'); } }, colorizeBackground:function(){ if(!$('.gal__main').length){ return; } if(window.location.origin.indexOf('trendhunter.com') == -1){ $('.gal__main').css('background-color','rgb(128,128,128)'); return; } var eid = $(".tha[data-eid]").data('eid'), src = CUtils.getImageSrc(eid,1,"110",'https://www.trendhunter.com/images'), img = document.createElement("img"); img.crossOrigin = "Anonymous"; img.onload = function(){ var rgb = AUtils.getAverageRGB(this); $('.gal__main').css('background-color','rgb('+rgb.r+','+rgb.g+','+rgb.b+')'); }; img.src = src; }, getColorIndicesForCoord:function(x, y, width) { var red = y * (width * 4) + x * 4; return [red, red + 1, red + 2, red + 3]; }, getAverageRGB:function(imgEl) { var blockSize = 5, defaultRGB = {r:0,g:0,b:0}, canvas = document.createElement('canvas'), context = canvas.getContext && canvas.getContext('2d'), data, width, height, i = -4, length, rgb = {r:0,g:0,b:0}, count = 0; if (!context) { console.log('default rgb'); return defaultRGB; } height = canvas.height = imgEl.naturalHeight || imgEl.offsetHeight || imgEl.height; width = canvas.width = imgEl.naturalWidth || imgEl.offsetWidth || imgEl.width; context.drawImage(imgEl, 0, 0); try { data = context.getImageData(0, 0, width, height); } catch(e) { console.log(e); return defaultRGB; } length = data.data.length; var indices = {}; indices['tl'] = AUtils.getColorIndicesForCoord(0,0,canvas.width); indices['tr'] = AUtils.getColorIndicesForCoord(canvas.width - 1 ,0,canvas.width); indices['bl'] = AUtils.getColorIndicesForCoord(0,canvas.height - 1,canvas.width); indices['br'] = AUtils.getColorIndicesForCoord(canvas.width - 1,canvas.height - 1,canvas.width); var vals = []; for(var x in indices){ var ind = indices[x]; r = data.data[ind[0]], g = data.data[ind[1]], b = data.data[ind[2]]; vals.push(r); vals.push(g); vals.push(b); } var valsLength = vals.length, num250 = 0; for(var y in vals){ if(vals[y] > 250){ num250 += 1; } } if(num250 > valsLength / 2){ return {r:255,g:255,b:255}; } while ( (i += blockSize * 4) < length ) { ++count; rgb.r += data.data[i]; rgb.g += data.data[i+1]; rgb.b += data.data[i+2]; } // ~~ used to floor values rgb.r = ~~(rgb.r/count); rgb.g = ~~(rgb.g/count); rgb.b = ~~(rgb.b/count); return rgb; }, checkAmazon:function(){ $('.tha__amazonButton').remove(); if($('.tha--idea').length){ AUtils.checkAmazonIdea(); return; } }, checkAmazonIdea:function(){ var links = $('.tha__referenceLinks a').map(function(){return $(this).attr('href');}).get(); for(var i in links){ var l = links[i]; if(l.indexOf('tag=trenhunt0f-20') !== -1){ AUtils.addAmazonBtn(l); break; } } }, addAmazonBtn:function(l){ var btnHtml = ""; $('.gal__main').append(btnHtml); } } var CGallery = { cid:null, data:null, order:null, init:function(){ if(!$(".tha--course #tha__relData").length){ return; } this.cid = $('.tha__courseItem:eq(0)').data('id'); this.data = JSON.parse($(".tha #tha__relData").get(0).innerHTML); this.order = $(".tha[data-relorder]").data('relorder'); this.bind(); }, bind:function(){ $(document) .on('keyup',function(e){ if($('.lp__formPop').length){ return; } if(e.which == 37){ //left CGallery.prev(); }else if(e.which == 39){ //right CGallery.next(); } }); }, selectItem:function(item){ var cid = $(item).data('id'); this.cid = cid; this.placeVideo(); }, next:function(){ var cid = this.cid, o = this.order, currIndex = o.indexOf(cid), nextIndex = !this.order[currIndex + 1] ? 0 : currIndex + 1, nextId = this.order[nextIndex]; this.cid = nextId; this.placeVideo(); }, prev:function(){ var cid = this.cid, o = this.order, currIndex = o.indexOf(cid), prevIndex = !this.order[currIndex - 1] ? this.order.length - 1 : currIndex - 1, prevId = this.order[prevIndex]; this.cid = prevId; this.placeVideo(); }, placeVideo:function(){ var cid = this.cid, d = this.data[cid]; var video = d.video, o = this.order, oNum = o.length, index = o.indexOf(cid), currNum = oNum - index; $('.tha__courseVideo').html(video); $('.tha__courseTopNumber').html(currNum); $('.tha__courseTopTitle1').html(d.t1); $('.tha__courseTopTitle2').html(d.t2); $('.tha__courseTopLink').attr('href',d.u); var $item = $('.tha__courseItem[data-id="'+cid+'"]'), left = $item.get(0).offsetLeft; $('.tha__courseGallery').get(0).scrollTo(left,0); _th_trackPageView(); AUtils.trackInternal(); } } var AGallery = { num:null, id:null, data:null, okk:null, order:null, init:function(){ if(!$(".tha--idea.tha #tha__relData").length && !$(".tha--keynote.tha #tha__relData").length){ return; } this.num = 1; this.id = $(".tha[data-eid]").data('eid'); this.data = JSON.parse($(".tha #tha__relData").get(0).innerHTML); this.order = $(".tha[data-relorder]").data('relorder'); this.bind(); }, bind:function(){ $(document) .on('keyup',function(e){ if($('.lp__formPop').length){ return; } if(e.which == 37){ //left AGallery.prev(); }else if(e.which == 39){ //right AGallery.next(); } }); }, next:function(){ var cid = this.id, d = this.data[cid], pc = parseInt(d.pc), n = parseInt(this.num), nn = n+1; this.num = nn; this.okk = d.okk; if(nn > pc){ this.nextArticle(); } this.changeImage(); }, prev:function(){ var cid = this.id, d = this.data[cid], pc = parseInt(d.pc), n = parseInt(this.num), nn = n-1; this.num = nn; this.okk = d.okk; if(nn < 1){ this.prevArticle(); } this.changeImage(); }, changeImage:function(){ var imgSrc = CUtils.getImageSrc(this.id,this.num,'800',CUtils.iHost,this.okk); $('.gal__mainImage').attr('src', imgSrc); $('.gal__mainImage').removeAttr('srcset'); $('.gal__main').css('background-color','white'); $('.gal__thumbs').remove(); _th_trackPageView(AUtils.startUrl); AUtils.trackInternal(this.id); _th_trackEvent('trends','main-gallery-click'); }, updateArticleContent:function(){ var id = this.id, d = this.data[id]; $('.tha__articleBody').html(d.ab); $('.tha__bcLink--category').html(d.cn).attr('href','/'+d.cu); $('.tha__title1').html(d.t1); AUtils.checkLoginDialog(); var host = "https://"+window.location.host; window.history.replaceState({}, "",host+d.u); document.title = d.t; AUtils.checkAmazon(); }, nextArticle:function(){ var cid = this.id, o = this.order, currIndex = o.indexOf(cid), nextIndex = !this.order[currIndex + 1] ? 0 : currIndex + 1, nextId = this.order[nextIndex], d = this.data[nextId]; this.id = nextId; this.num = 1; this.okk = d.okk; this.updateArticleContent(); this.preload(); }, prevArticle:function(){ var cid = this.id, o = this.order, currIndex = o.indexOf(cid), prevIndex = !this.order[currIndex - 1] ? this.order.length - 1 : currIndex - 1, prevId = this.order[prevIndex], d = this.data[prevId]; this.id = prevId; this.okk = d.okk; this.num = parseInt(d.pc); this.updateArticleContent(); }, preloadTracker:[], preload:function(nextId){ var doNext = nextId ? false : true; var cid = nextId ? nextId : this.id, d = this.data[cid], pc = parseInt(d.pc), o = this.order, currIndex = o.indexOf(cid), nextIndex = !this.order[currIndex + 1] ? 0 : currIndex + 1, nextId = this.order[nextIndex], okk = d.okk ? d.okk : null; if(this.preloadTracker.indexOf(cid) != -1){ return; } this.preloadTracker.push(cid); for(var i = 2; i <= pc; i++){ var imgSrc = CUtils.getImageSrc(cid,i,'800',CUtils.iHost,okk); var img = new Image(); img.src = imgSrc; } if(doNext){ this.preload(nextId); } } }; var ATGallery = { topGalleryLoaded:false, isScrolling:false, doScroll:function(direction){ if(ATGallery.isScrolling){ return; } var offset = parseInt($('.tha__tgArticlesInner').css('left')), contWidth = parseInt($('.tha__tgArticlesInner').width()), itemWidth = $('.tha__tgLink:eq(0)').outerWidth(true), itemCount = $('.tha__tgLink').length, totalWidth = itemWidth*itemCount, itemsPerCont = contWidth / itemWidth; ATGallery.isScrolling = true; var newOffset = direction == 'forward' ? offset-contWidth : offset+contWidth; if(direction == 'forward' && (newOffset*-1 + contWidth >= totalWidth)){ //go back to the start newOffset = 0; }else if(direction == 'backward' && offset == 0){ //go to last full section var itemsPerCont = contWidth / itemWidth, newOffset = (Math.floor(itemCount / itemsPerCont) - 1) * contWidth * -1; } $('.tha__tgArticlesInner').animate({'left':(newOffset)+"px"},{ complete:ATGallery.scrollDone }); ATGallery.lazy(); _th_trackEvent('trends','top-gallery-scroll'); }, scrollDone:function(){ ATGallery.isScrolling = false; // ATGallery.lazy(); }, loadTopGallery:function(){ if(ATGallery.topGalleryLoaded){ return; } ATGallery.topGalleryLoaded = true; var $req = CUtils.ajax({act:'ltg'},'GET',true); $req .done(function(r){ if(!r.success){ return; } $('.tha__tgArticlesInner').append(r.data); return; var contWidth = parseInt($('.tha__tgArticlesInner').width()); $('.tha__tgLink').each(function(){ if($(this).offset().left > contWidth){ $('.tha__tgLink img.thai').removeClass('thai'); } }); ATGallery.lazy(); }) .fail(function(){ console.log('failed to load top gallery'); }) }, lazy:function(){ return; var contWidth = parseInt($('.tha__tgArticlesInner').width()); $('.tha__tgLink img:not(.thai)').each(function(){ var $item = $(this).parents('.tha__tgLink'); if($item.offset().left < contWidth*3){ $(this).addClass('thai'); } }); Lazy.reveal(); } } var ArticleActions = { btnMap:{ 'more':'loadPage', 'popvideo':'popvideo', 'gallerynext':'galleryNext', 'galleryprev':'galleryPrev', 'galthumb':'galleryThumb', 'tgforward':'topGalleryForward', 'tgback':'topGalleryBackward', 'morestats':"loadMoreStats", 'coursenext':'courseNext', 'courseprev':'coursePrev', 'gocourse':'goCourse', 'freereport':'loadFreeReport' }, buttonClick:function(btn,item){ var fname = ArticleActions.btnMap[btn] ? ArticleActions.btnMap[btn] : false; if(!fname){ return; } ArticleActions[fname](item); }, loadFreeReport:function(){ CUtils.loadFreeReport(false); }, loadMoreStats:function(item){ if($('.tha__advancedStats--loaded').length){ $('.tha__advancedStats').toggle(); if($('.tha__advancedStats:visible').length){ $("[data-btn='morestats'] i").html('expand_less'); }else{ $("[data-btn='morestats'] i").html('expand_more'); } return; } var $req = CUtils.ajax({act:'lms',eid:$(item).data('eid')},'GET',true); $req .done(function(r){ if(!r.success){ error(r.data); return false; } $('.tha__advancedStats').html(r.data).addClass('tha__advancedStats--loaded').show(); $("[data-btn='morestats'] i").html('expand_less'); }) .fail(function(){ error('There was an error loading more stats.'); }) .always(function(){ }); }, goCourse:function(item){ CGallery.selectItem(item); }, topGalleryBackward:function(){ ATGallery.doScroll('backward'); }, topGalleryForward:function(){ ATGallery.doScroll('forward'); }, courseNext:function(){ CGallery.next(); }, coursePrev:function(){ CGallery.prev(); }, galleryThumb:function(item){ AGallery.id = $(item).data('id'); AGallery.num = $(item).data('pn'); var oldId = AGallery.id, d = AGallery.data[AGallery.id], okk = d.okk ? d.okk : null; AGallery.okk = okk; if(oldId != AGallery.id){ AGallery.updateArticleContent(); } AGallery.changeImage(); }, galleryNext:function(){ AGallery.next(); }, galleryPrev:function(){ AGallery.prev(); }, popvideo:function(){ var eid = $('.tha[data-eid]').data('eid'); var url = "http://live.trendhunter.com/video-pop?id="+eid; window.open(url); }, loadPage:function(){ $('.tha__btn--more').hide(); $('.tha__moreLoader').show(); var page = AUtils.page, nextPage = page + 1, catId = $(".th__article[data-cid]").data('cid'), params = {act:'lp',p:nextPage}; if(nextPage > 1){ params['cid'] = catId; } var $req = CUtils.ajax(params,'GET',true); $req .done(function(r){ if(!r.success){ error(r.data); return false; } if(r.data.length == 0){ $('.tha__btn--more').remove(); } AUtils.page = AUtils.page + 1; $('.tha__bottom').append(r.data); Lazy.reveal(); _th_trackPageView(AUtils.startUrl); }) .fail(function(){ error('There was an error loading the next page'); }) .always(function(){ $('.tha__btn--more').show(); $('.tha__moreLoader').hide(); }); } }; var MUtils = { page:1, type:'trends', score:'all', init:function(){ if(!$('.th__magazine').length){ return; } CUtils._ap = "/"; setTimeout(Lazy.reveal,200); MUtils.bind(); MGallery.init(); MUtils.trackSponsored(); }, lastScroll:new Date().getTime(), bind:function(){ $(document,window).on('scroll',MUtils.handleScroll); $(window).on('resize',MUtils.handleResize); $('body') .on('click','[data-btn]',function(){ MActions.buttonClick($(this).data('btn'), this); }) .on('click','.thm__advisoryBtn,.thm__bookBtn',function(e){ e.preventDefault(); CUtils.gevent('mag-btns','mag-btn-click',$(this).text(), $(this).attr('href')); }); /*.on('mouseenter','.thar',function(){ CActions.rotateImages(this); }) .on('mouseleave','.thar',function(){ CActions.stopRotation(); })*/ }, handleScroll:function(){ var currTime = new Date().getTime(), diff = currTime - MUtils.lastScroll; if(diff < 100){ return; } setTimeout(function(){ Lazy.reveal(); },100); MUtils.lastScroll = currTime; if($('[data-btn="more"]:visible').length && $(window).scrollTop() + $(window).height() > $(document).height() - 1000){ MActions.loadPage(); } }, handleResize:function(){ Lazy.reveal(); }, trackSponsored:function(){ if(!$('.spn.thm__sponsored').length){ return; } var $spn = $('.spn.thm__sponsored'), id = $spn.data('id'); var url = $spn.data('url'); var img = new Image(); img.src = 'https://www.trendhunter.com/trackingpixel?entry_id='+id+'&type=trend&_t='+new Date().getTime(); $('.trackingPixels').append(img); CUtils.trackSponsored(url) } } var MGallery = { data:null, ind:0, p:null, init:function(){ if(!$("#thmg__data").length){ return; } this.p = $('.thmg').data('p'); this.data = JSON.parse($("#thmg__data").get(0).innerHTML); this.bind(); }, next:function(){ var p = this.p, d = this.data, ok = Object.keys(d), okInd = ok.indexOf(p), ind = this.ind, nextInd = ind + 1; if(!d[p][nextInd]){ nextInd = 0; if(p != 0){ var okNext = okInd + 1 > ok.length -1 ? 0 : okInd + 1; p = ok[okNext]; } } this.p = p; this.ind = nextInd; this.change(); }, prev:function(){ var p = this.p, d = this.data, ok = Object.keys(d), okInd = ok.indexOf(p), ind = this.ind, prevInd = ind - 1; if(prevInd < 0){ prevInd = d[p].length - 1; if(p != 0){ var okNext = okInd - 1 < 0 ? ok.length - 1 : okInd - 1; p = ok[okNext]; prevInd = d[p].length - 1; } } this.p = p; this.ind = prevInd; this.change(); }, change:function(){ var d = this.data, p = this.p, ind = this.ind, item = d[p][ind]; var num = ind + 1, t1 = "#"+num+": "+item.t1, t2 = item.t2+" FULL ARTICLE", imgSrc = CUtils.getImageSrc(item.id,1,"800"); $('.thmg__controls .thmg__controlItem').removeClass('thmg__controlItem--selected'); if(p != 0){ $('.thmg__controlItem[data-period="'+p+'"]').addClass('thmg__controlItem--selected'); } $('.thmg__controlItem--lbl').html("TOP "+d[p].length); $('.thmg__title1').html(t1); $('.thmg__title2').html(t2); $('.thmg__img').attr('src',imgSrc); _th_trackEvent('magazine','top-gallery-click'); }, selectPeriod:function(period){ this.p = period; this.ind = 0; this.change(); }, bind:function(){ } } var MActions = { btnMap:{ 'more':'loadPage', 'switchgallery':'switchGallery', 'gallerynext':'galleryNext', 'galleryprev':'galleryPrev', 'switchview':'switchView', 'switchtype':'switchType', 'switchscore':'switchScore' }, buttonClick:function(btn,item){ var fname = MActions.btnMap[btn] ? MActions.btnMap[btn] : false; if(!fname){ return; } MActions[fname](item); }, galleryNext:function(){ MGallery.next(); }, galleryPrev:function(){ MGallery.prev(); }, loadPage:function(){ if(MUtils.page == 0){ $('.thm__endLink').remove(); $('.tha__btn--more').show(); } if(!$('.tha__btn--more:visible').length){ return; } $('.tha__btn--more').hide(); $('.tha__moreLoader').show(); var page = MUtils.page, nextPage = page + 1, params = { act:'lp', p:nextPage, pt:$('.thm[data-ptype]').data('ptype'), v:$('.thm[data-v]').data('v'), t:MUtils.type }; if(MUtils.score != 'all'){ params['s'] = MUtils.score; } var $req = CUtils.ajax(params,'GET',true); $req .always(function(){ $('.tha__btn--more').show(); $('.tha__moreLoader').hide(); }) .done(function(r){ if(!r.success){ error('There was an error loading the next page'); console.log(r.data); return false; } if(r.data.length == ""){ $('.thm__bottom').append(""); $('.tha__btn--more').hide(); $('.tha__moreLoader').hide(); return; } MUtils.page = MUtils.page + 1; $('.thm__page:eq(0)').append(r.data); Lazy.reveal(); _th_trackPageView(); var view = $('.thm__view--selected').data('view'), type = $('.thm__type--selected').data('type'); if(view == 'mag' && type == 'trends'){ $('.thm__pagebreak').show(); }else{ $('.thm__pagebreak').hide(); } }) .fail(function(r){ error('There was an error loading the next page'); }); }, switchGallery:function(item){ var p = $(item).data('period'); MGallery.selectPeriod(p); }, switchView:function(item){ var view = $(item).data('view'); $('.thm__view').removeClass('thm__view--selected'); $('.thm__view[data-view="'+view+'"]').addClass('thm__view--selected'); if(view == 'vr'){ window.location.href = "https://www.trendhunter.com/vr"; return; } if($('.rnk__cont').length){ if(view != 'mag'){ $('.rnk__cont').hide(); }else{ $('.rnk__cont').show(); } } $('.thm__content').removeClass(function(index,className){ return (className.match (/(^|\s)thm__content--view\S+/g) || []).join(' '); }) $('.thm__content').addClass('thm__content--view'+view); setTimeout(function(){ Lazy.reveal(); if($('[data-btn="more"]:visible').length && $(window).scrollTop() + $(window).height() > $(document).height() - 1000){ MActions.loadPage(); } },500); }, switchType:function(item){ var type = $(item).data('type'); $('.thm__type').removeClass('thm__type--selected'); $('.thm__type[data-type="'+type+'"]').addClass('thm__type--selected'); if(type == 'pro'){ window.location.href = "https://www.trendhunter.com/pro"; return; } $('.thm__page').empty(); MUtils.page = 0; MUtils.type = type; MActions.loadPage(); }, switchScore:function(item){ var score = $(item).data('score'); $('.thm__scoreBtn').removeClass('thm__scoreBtn--selected'); $('.thm__scoreBtn[data-score="'+score+'"]').addClass('thm__scoreBtn--selected'); MUtils.score = score; $('.thm__page').empty(); MUtils.page = 0; MActions.loadPage(); } } var CActions = { rotateInterval:null, rotateItem:null, rotateImages:function(item){ if($(item).data('pc') == 1){ return; } if($(item).hasClass('thar--toplist') && !$(item).data('rel')){ return; } if(!$(item).data('ci')){ $(item).data('ci',1); } CActions.rotateItem = item; clearInterval(CActions.rotateInterval); CActions.rotateInterval = setInterval(CActions.doRotation,1000); }, doRotation:function(){ var item = CActions.rotateItem, $item = $(item), id = $item.data('id'), pc = $item.data('pc'), ci = $item.data('ci'), is = $item.data('is'); if(is == '230c'){ is = '468'; } ci += 1; if(ci > pc){ ci = 1; } $item.data('ci',ci); if($item.hasClass('thar--toplist')){ var index = ci - 1, rel = $item.data('rel'), eid = parseInt(rel[index]); var imageSrc = CUtils.getImageSrc(eid,1,is); }else{ var imageSrc = CUtils.getImageSrc(id,ci,is); } $item.find('img').attr('src',imageSrc); }, stopRotation:function(){ clearInterval(CActions.rotateInterval); CActions.rotateItem = false; } } var YTD = { yt_player:null, playingTime:0, playingInterval:null, stateMap:{ '-1':'unstarted', '0':'ended', '1':'playing', '2':'paused', '3':'buffering', '5':'cueued' }, init:function(){ YTD.loadAPI(); }, bind:function(){ }, loadAPI:function(){ var tag = document.createElement('script'); tag.src = "https://www.youtube.com/iframe_api"; var firstScriptTag = document.getElementsByTagName('script')[0]; firstScriptTag.parentNode.insertBefore(tag, firstScriptTag); }, log:function(msg){ if(typeof msg == 'object'){ msg = JSON.stringify(msg); } console.log("YTD: ",msg); }, sendTracking:function(){ var params = { tid:AUtils.id, yid:YTD.yt_player.getVideoData().video_id, s:YTD.playingTime, act:'yt-track' }; CUtils.ajax(params,'POST',false); }, onPlayerStateChange:function(event){ var state = event.data, stateLbl = YTD.stateMap[state]; YTD.log("Video state changed: "+stateLbl); if(state == 1){ YTD.playingInterval = setInterval(function(){ YTD.playingTime += 1; var s = YTD.playingTime == 1 ? '' : 's'; YTD.log("Playing time: "+YTD.playingTime+" second"+s); if(YTD.playingTime % 5 == 0){ YTD.sendTracking(); } },1000); if(YTD.playingTime == 0){ YTD.sendTracking(); } }else{ clearInterval(YTD.playingInterval); } }, onPlayerError:function(event){ // console.log('player error'); }, onPlayerReady:function(event){ // console.log('player ready'); } } if(document.getElementById('th-youtube-iframe')){ YTD.init(); } function onYouTubeIframeAPIReady(){ YTD.log('API Ready. Start playing the video to view tracking data.'); YTD.yt_player = new YT.Player('th-youtube-iframe', { events : { 'onReady' : YTD.onPlayerReady, 'onStateChange' : YTD.onPlayerStateChange, 'onError' : YTD.onPlayerError } }); }