window.TimesApps = window.TimesApps || {}; TimesApps.VideoShow = (function(){ "use strict"; var cache, fn, api, bindInitialEvents, util, moduleData; cache = { jInfoCard : $(".jInfoCard"), jSocialICons : $(".jSocialICons"), jVidEmbedUrlBox : $(".jVidEmbedUrlBox"), overlayBgDiv : $(".vid_overlay"), rhsWidget : $(".videoshow .column2 .related-list"), description : $('.jInfoCard .jdescription'), readmore : $('.jInfoCard .readmore-btn'), topVideoIframe : $("#topVideoIframe") }; moduleData = { msid: '', defaultEmbedCode: '' }; bindInitialEvents = function(){ cache.jInfoCard.on("click", fn._handleInfoCardClick); cache.overlayBgDiv.on('click', function(){ fn._toggleDim(true); }); $(document).on('VOD_EVENTS', function(event, obj, eventType) { eventType = ( eventType ? eventType.toUpperCase() : "" ); if( eventType == "DIM_TOGGLE" ){ fn._toggleDim(); return; }else if( eventType == 'VIDEOREADY' ){ fn._videoInitActions(obj); return; }else if( !(eventType === "ONNEXTVIDEODATAFETCH") ){ return; } fn._refreshCard(obj); fn._refreshRelatedKeywords(obj); // fn._refreshRelatedStories(obj); // fn._refreshTrendingStories(obj); fn._refreshBreadCrumb(obj); }); $('.close').on("click",function(){ $('section').toggleClass('hidden'); }) cache.readmore.on('click', function(e) { e.stopPropagation(); var $this = $(this); if(cache.description.hasClass('content-collapse')) { $this.html('Read Less'); cache.description.removeClass('content-collapse'); } else { $this.html('Read More'); cache.description.addClass('content-collapse'); } }); require(["event"], function(eventBus){ eventBus.subscribe("onNextVideoDataFetch", fn._refreshPage) }) cache.rhsWidget.mCustomScrollbar({ theme: "dark", scrollButtons: { enable: false }, scrollInertia: 0, mouseWheel: { enable: true, scrollAmount: 52 }, advanced: { updateOnContentResize: true } }); cache.rhsWidget.find('li').on('click', fn._loadVideo); cache.rhsWidget.find('li a').on('click', function(e) { e.preventDefault() }); }; fn = { _handleInfoCardClick: function(e){ var clickedEle = $(e.target).closest('li'); //toggle social icons if( clickedEle.hasClass('jMore')){ var text = cache.jSocialICons.hasClass("active") ? "more" : "less"; cache.jInfoCard .find(".jToggleSocial>a") .text(text); cache.jSocialICons .toggleClass("active"); cache.jInfoCard .find(".jInfo") .toggleClass("active"); } else if(clickedEle.hasClass('embed')){ fn._showEmbedCodeBox(); }else if( clickedEle.closest('.jSocialICons').length > 0 ){ var pgtrack = require("pgtrack"); pgtrack.evtCap(event); } }, _showEmbedCodeBox: function(){ var embedSrc = moduleData.defaultEmbedCode; embedSrc = embedSrc.replace('$msid$', moduleData.msid); cache.jVidEmbedUrlBox .removeClass('hidden') .find("textarea") .val(embedSrc) .select(); }, _initRedirection : function(){ var canonicalURL = document.querySelector("link[rel='canonical']"), canonicalURL = canonicalURL && canonicalURL.getAttribute("href"), userURL = window.location.href; if(canonicalURL){ canonicalURL = canonicalURL.toLowerCase(); userURL = userURL.toLowerCase(); if( userURL != canonicalURL && userURL.indexOf('?') == -1 && userURL.indexOf('jeetwin-gaming.com')>=0 && canonicalURL.indexOf('jeetwin-gaming.com')>=0 ){ document.location.href = canonicalURL+"?"; } } }, _loadVideo : function(event){ var clickedVideo = $(event.currentTarget); var msid = clickedVideo.attr("data-msid"); if( !msid ){ return; } fn._getVideoDetails(msid); var source = 'video-show'; var params = { 'classNames' : '', 'msid' : msid, 'videosection' : source, 'source' : 'videoshow', 'version' : 5 }; var iframeHtml = TimesApps.VideoCore.createVideoIframe(params); cache.topVideoIframe.attr('src', $(iframeHtml).attr('src')); cache.rhsWidget.find('li').removeClass('playing'); clickedVideo.addClass('playing'); }, _videoInitActions: function(obj){ cache.rhsWidget.find('li').removeClass('playing'); cache.rhsWidget .find("[data-msid='" + obj.id + "']") .addClass('playing'); //console.log("*** _videoInitActions", cache.rhsWidget.find("[data-msid='" + obj.id + "']")[0] ); fn._setNextVideo(); }, _setNextVideo: function(){ var nextVideo = cache.rhsWidget.find('.playing').next('li'); var iframeWindow = cache.topVideoIframe[0].contentWindow; var nextVideoMsid = nextVideo.attr("data-msid") || ""; //console.log("*** _setNextVideo", nextVideo[0]); if( iframeWindow.TimesApps && iframeWindow.TimesApps.Vod_Player && iframeWindow.TimesApps.Vod_Player.addNextVideoToList ){ iframeWindow.TimesApps.Vod_Player.addNextVideoToList(nextVideoMsid); } }, _checkAndSetDescription: function() { // Reset settings if(cache.description.hasClass('content-collapse')) { cache.description.removeClass('content-collapse'); cache.readmore.hide(); } if(cache.description.length === 1 && cache.description.height() > 60) { cache.description.addClass('content-collapse'); cache.readmore.show(); } }, _init: function(){ moduleData.msid = $("#msid").val(); fn._initRedirection(); bindInitialEvents(); fn._getVideoDetails($("#msid").val(), true); // fn._updateRelatedStories(); // fn._updateTrendingStories(); fn._checkAndSetDescription(); // fn._callTimesTrendService(); moduleData.defaultEmbedCode = cache.jVidEmbedUrlBox.find("textarea").val(); }, _getVideoDetails: function(msid, updateViewsOnly){ if( !(msid && msid.trim().length) ){ return; } /* * fetches only * mediaaudiovideo data * using param type=no_meta */ var url = ""; $.ajax({ url : "/videomediainfo_v1/" + msid + ".cms?feedtype=json&type=no_meta", type: 'GET' }).done(function(data){ var eventData = data.item || {}; eventData.updateViewsOnly = !!updateViewsOnly; require(["event"], function(eventBus){ eventBus.publish('onNextVideoDataFetch', eventData); }); }); }, _refreshCard: function(obj){ if (typeof(buildAdsAj) == "function") { buildAdsAj(); } moduleData.msid = obj.msid || obj.id, fn._changeURL(obj); fn._renderData(obj); fn._analyticsCalls(obj); fn._updateAttributes(obj); fn._checkAndSetDescription(); $('footer .js-watchLater').removeClass('added'); $('footer').data('data-msid',obj.id); }, _refreshPage: function(obj) { if(!obj.updateViewsOnly) { fn._refreshCard(obj); fn._refreshBreadCrumb(obj); } fn._updateViews(obj); }, _updateAttributes: function(obj){ if( !( obj && obj.seopath && obj.title && obj.msid ) ){ return; } var pgFbConstant = 'VideoShare#videoshow#2~fb', pgTwitterConstant = 'VideoShare#videoshow#2~twitter', pgGooglePlusConstant = 'VideoShare#videoshow#2~google+', pglinkedinConstant = 'VideoShare#videoshow#2~linkedin', pgStoryVariable = obj.seopath; cache.jSocialICons .find('.fb a') .attr('pg',pgFbConstant + pgStoryVariable); cache.jSocialICons .find('.twitter a') .attr('pg',pgTwitterConstant + pgStoryVariable); cache.jSocialICons .find('.g-plus a') .attr('pg',pgGooglePlusConstant + pgStoryVariable); cache.jSocialICons .find('.linkedin a') .attr('pg',pglinkedinConstant + pgStoryVariable); var imgUrl = '//' + document.location.hostname + '/photo/' + obj.msid + '.cms'; cache.jSocialICons .find('.fb a, .twitter a, .g-plus a, .linkedin a') .attr('data-social-img', imgUrl); cache.jSocialICons .find('.fb a, .twitter a, .g-plus a, .linkedin a') .attr('data-title', obj.title); cache.jSocialICons .find('.fb a') .attr('data-url','/'+pgStoryVariable+'/videoshow/'+obj.msid+'.cms?utm_source=facebook.com&utm_medium=social&utm_campaign=TOIDesktop'); cache.jSocialICons .find('.twitter a') .attr('data-url','/'+pgStoryVariable+'/videoshow/'+obj.msid+'.cms?utm_source=twitter.com&utm_medium=social&utm_campaign=TOIDesktop'); cache.jSocialICons .find('.g-plus a') .attr('data-url','/'+pgStoryVariable+'/videoshow/'+obj.msid+'.cms?utm_source=plus.google.com&utm_medium=social&utm_campaign=TOIDesktop'); cache.jSocialICons .find('.linkedin a') .attr('data-url','/'+pgStoryVariable+'/videoshow/'+obj.msid+'.cms?utm_source=linkedin.com&utm_medium=social&utm_campaign=TOIDesktop'); }, _analyticsCalls: function(obj){ fn._gaHandling(obj); //fn._handleIbeat(obj); if (typeof(fireComscore) == "function"){ fireComscore(); } }, _updateViews: function(dataObj){ var $views = $('.video_meta .views'); var currentViewCount = ( $views.text() && !!$views.text().match(/\d+/) ) ? $views.text().match(/\d+/)[0] : 0; var updatedViews = (dataObj && dataObj.totalcount) ? parseInt(dataObj.totalcount) : 0; if( dataObj.msid == moduleData.msid && updatedViews >= 100 && ( updatedViews >= parseInt(currentViewCount) ) ){ $views .html(updatedViews + ' views') .removeClass('hidden'); }else if(parseInt(currentViewCount) < 100){ $views.addClass('hidden'); }else{ $views .html(updatedViews + ' views') .removeClass('hidden'); } }, _renderData: function(obj){ if( typeof obj!= "undefined" && obj.title ){ $('.jheading') .html(obj.title); } if( typeof obj != "undefined" && obj.description ){ $('.jdescription') .html(obj.description); } if(typeof obj != "undefined" && obj.videodatetime ){ $('.desc-timestamp') .html(obj.videodatetime); } if( !( obj && obj.videodatetime ) ){ return; } var trimmmedResult = obj.videodatetime.substr(0, obj.videodatetime.search('PM')) || obj.videodatetime.substr(0, obj.videodatetime.search('AM')); var time = obj.videodatetime; var meridian = (time.search('PM') > 0) ? 'PM':'AM'; time = trimmmedResult + " " + meridian; $('.video_meta') .find('[rodate]') .html(obj.videodatetime) .attr('rodate',time); fn._updateViews(obj); TimesApps.Utils.convertHoursToAgo(); }, _changeURL: function(obj){ var msid = obj.msid || obj.id, url = "/"+obj.seopath+"/videoshow/"+ msid +".cms"; history.replaceState({},'',url); document.title = obj.title; }, /*_handleIbeat: function(obj){ if( !( obj.section && obj.keywords && obj.msid && obj.videodatetime ) ){ return; } _page_config.articleId = obj.msid; _page_config.subcat = obj.section; _page_config.url = window.location.href; _page_config.contenttag = obj.keywords; _page_config.articledt = obj.videodatetime; if (typeof iBeatPgTrend != "undefined") { iBeatPgTrend.init(); } },*/ _gaHandling: function(obj){ if (typeof(ga) == "function") { ga('send', { 'hitType': 'pageview', 'page': "/"+obj.seopath+"/videoshow/"+obj.id+".cms", 'title': document.title, 'location': location.href }); } }, _refreshRelatedStories: function(obj){ if(fn._checkIfMsidIsDefined(obj)){ return; } var msid = obj.msid, url = "/wdt_list.cms?config.perpage=8&tmpl=videoshow&img=280&tag=relmediaobj&msid=" + msid +"&byline=totalcnt|viewed|urcount|mediadate&pg=Videoshow_VideoClick@Related_Videos~position-geturl&config.ignorepl=1"; $.ajax({ url: url, }).done(function(data) { $('.ulWrapper').html(data); $('#relsec').attr('data-licount',$('#relsec li').length); fn._updateRelatedStories(); TimesApps.Utils.convertHoursToAgo(); }); }, _refreshRelatedKeywords: function(obj){ if(fn._checkIfMsidIsDefined(obj)){ return; } var msid = obj.msid, url = "/related_keywords.cms?msid=" + msid; $.ajax({ url: url, }).done(function(data) { if(data.search('
  • ') > 0){ $('.jRelatedKeywords') .html(data) .removeClass("hidden"); } else{ $('.jRelatedKeywords').addClass("hidden"); } }); }, _refreshTrendingStories: function(obj){ if(fn._checkIfMsidIsDefined(obj)){ return; } var msid = obj.msid, url = "/trendingvideosupdate.cms?msid=" + msid; $.ajax({ url: url, }).done(function(data) { $("#trendingsec>ul").html(data); $('#trendingsec').attr('data-licount',$('#trendingsec>ul li').length); }); }, _refreshBreadCrumb: function(obj){ if(fn._checkIfMsidIsDefined(obj)){ return; } var msid = obj.msid, url = "/nextvideo_nav.cms?msid=" + msid; url += "&ver=1"; $.ajax({ url: url, }).done(function(data) { $(".jbreadcrumb").html(data); }); }, _checkIfMsidIsDefined: function(obj){ if( !( obj && obj.msid ) ){ return true; }else{ return false; } }, _updateTrendingStories : function(){ var $trendingSection =$('#trendingsec'); if($trendingSection.data('licount') < 3){ //add trending videos var url = "/wdt_list.cms?v=1256&msid=3812890&config.perpage=10&tmpl=videoshow&img=280&tag=videolistroot&byline=totalcnt|viewed|urcount|mediadate|strupd|art_date| strlastupd|watchlater&config.ignorepl=1&pg=Videoshow_VideoClick@Trending_Videos~position-geturl"; $.ajax({ url: url, }).done(function(data) { $trendingSection.find('ul').remove(); $trendingSection.append(data); $trendingSection.attr('data-licount',$trendingSection.find('ul>li').length); TimesApps.Utils.convertHoursToAgo(); }); } }, _updateRelatedStories : function(){ var $relatedSection = $('#relsec'), $trendingSection =$('#trendingsec'); if($('#main-top-stories').length > 0){ $('#main-top-stories').remove(); } if($relatedSection.data('licount') < 3 || $trendingSection.data('licount') < 5){ //add top videos var url = "/wdt_list.cms?v=1238&msid=4762524&config.perpage=10&tmpl=videoshow&img=msid&tag=pllistnew&byline=totalcnt|viewed|urcount|mediadate|strupd|art_date| strlastupd|watchlater&config.ignorepl=1&pg=Videoshow_VideoClick@Top_Videos~position-geturl"; $.ajax({ url: url, }).done(function(data) { var $cloneElem = $relatedSection.clone(); $cloneElem.find('ul').remove(); $cloneElem.find('h2>span').text('Top'); $cloneElem.append(data); $cloneElem.attr('id', 'main-top-stories'); $cloneElem.attr('data-licount',$cloneElem.find('ul>li').length); $cloneElem.addClass('videolist wrapper'); $($cloneElem).insertBefore('.video_ads'); TimesApps.Utils.convertHoursToAgo(); }); } }, _toggleDim : function(forceClose){ if( !forceClose && !$(".vid_overlay").is(":visible")){ $('.vid_overlay').fadeIn(); $("body").addClass('dim'); } else{ $('.vid_overlay').fadeOut(); $("body").removeClass('dim'); } } // _callTimesTrendService: function(){ // var msid = $("#msid").val(); // var times_trend_subsec_info = $("#times_trend_subsec_info").val(); // var url = 'http://cmstrendslog.jeetwin-gaming.com/cmslog.dll?'; // url += 'cms-msid='+ msid; // url += '&'+ times_trend_subsec_info; // url += '&cmsurtype=viewed'; // url += '&randomno='+ Math.random(); // var pixel1 = new Image(); // pixel1.src = url; // var pixel2 = new Image(); // pixel2.src = "http://timeslog.jeetwin-gaming.com/timeslog.dll/topcnt?CHUR=jeetwin-gaming.com&randomno="+ Math.random() +""; // } }; api = { init: function(){ return fn._init(); }, toggleDim : function(){ return fn._toggleDim(); } }; return api; }()); if(typeof(_geo) === "undefined"){ var _geo = (typeof(geolocation) !== "undefined")?geolocation:100; }else{ _geo = (typeof geolocation !== "undefined")?geolocation:_geo; } var toiprops = toiprops || {}; toiprops.createCookie = function(name, value, days) { var expires; if (days) { var date = new Date(); date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000)); expires = "; expires=" + date.toGMTString(); } else { expires = ""; } document.cookie = name + "=" + value + expires + "; path=/"; }; toiprops.chkGeo = function(callback,ad_geo){ if(typeof Get_Ckie_str === "function" && Get_Ckie_str('_countrygeo')){_countrygeo=Get_Ckie_str('_countrygeo');} else if(typeof Set_Ckie_str === "function"){ $.getScript( "http://geoapi.jeetwin-gaming.com/?cb=1", function() { Set_Ckie_str('_countrygeo', geoinfo.CountryCode, 365, '/', '.indiatimes'); Set_Ckie_str('_continentgeo', geoinfo.Continent, 365, '/', '.indiatimes'); _countrygeo=geoinfo.CountryCode }) } }; toiprops.chkGeo(); var crtg_nid = '4306'; var crtg_cookiename = 'crtg_rta'; var crtg_varname = 'crtg_content'; function crtg_getCookie(c_name){ var i,x,y,ARRCookies=document.cookie.split(";");for(i=0;i0)document.getElementsByTagName("head")[0].appendChild(crtg_script); else if(document.getElementsByTagName("body").length>0)document.getElementsByTagName("body")[0].appendChild(crtg_script); } })(); } }); window.isPwtLoaded=false; var tgtkeys={}; var PWT={}; //Initialize Namespace PWT.jsLoaded = function(){ //PubMatic pwt.js on load callback is used to load GPT window.isPwtLoaded=true; } function loadPWT() { var purl = window.location.href; var url = '//ads.pubmatic.com/AdServer/js/pwt/23105/7403'; var profileVersionId = ''; if (purl.indexOf('pwtv=') > 0) { var regexp = /pwtv=(.*?)(&|$)/g; var matches = regexp.exec(purl); if (matches.length >= 2 && matches[1].length > 0) { profileVersionId = '/' + matches[1]; } } var wtads = document.createElement('script'); wtads.async = true; wtads.type = 'text/javascript'; wtads.src = url + profileVersionId + '/pwt.js'; var node = document.getElementsByTagName('script')[0]; node.parentNode.insertBefore(wtads, node); } // ************************************************************* // ***************** start UAM Implementation *************** // ************************************************************* if(typeof toiprops != "undefined" && toiprops.hasOwnProperty("toiprebid") && toiprops.toiprebid == 1){ !function(a9,a,p,s,t,A,g){if(a[a9])return;function q(c,r){a[a9]._Q.push([c,r])}a[a9]={init:function(){q("i",arguments)},fetchBids:function(){q("f",arguments)},setDisplayBids:function(){},targetingKeys:function(){return[]},_Q:[]};A=p.createElement(s);A.async=!0;A.src=t;g=p.getElementsByTagName(s)[0];g.parentNode.insertBefore(A,g)}("apstag",window,document,"script","//c.amazon-adsystem.com/aax2/apstag.js"); // initialize apstag with global settings apstag.init({ pubID: '5025', adServer: 'googletag', bidTimeout: 2000, simplerGPT: true }); } // define apstag slots var apstagSlots = []; function _getGPTSlots(apstagSlots) { // get all of the slot IDs that were requested // var slotIDs = apstagSlots.map(slot => slot.slotID); var slotIDs = apstagSlots.map(function (slot) { return slot.slotID; }); // return the slot objects corresponding to the gpt slotIDs return window.googletag .pubads() .getSlots() .filter( function(slot){ // return true if the ID of the slot object is in the gpt slotIDs array return slotIDs.indexOf(slot.getSlotElementId()) > -1 } ); } // fetch apstag bids, set bid targting, then call headerBidderBack // to get the ads for the first time function doAmazonHeaderBidding(apstagSlotsArr) { var gptSlotsToRefresh = _getGPTSlots(apstagSlotsArr); googletag.cmd.push(function() { apstag.fetchBids({ slots: gptSlotsToRefresh }, function(bids) { apstag.setDisplayBids(); googletag.pubads().refresh(gptSlotsToRefresh); }); }) } // ************************************************************* // ***************** End Prebid Implementation *************** // ************************************************************* function removeAds(adtype,t) { var targetElement = (t) ? t : 'body'; $(targetElement).find('.gds').hide(); } $( document ).ready(function() { if(!(typeof toiprops && typeof toiprops.toipr!="undefined")){ if(typeof toiprops != "undefined" && toiprops.hasOwnProperty("toiprebid") && toiprops.toiprebid == 1){ if(window._geo == 1 || window._geo == 2 || window._geo == 3){ loadPWT(); } }else{ loadPWT(); } (function() { var gads = document.createElement('script'); gads.async = true; gads.type = 'text/javascript'; var useSSL = 'https:' == document.location.protocol; gads.src = 'http://securepubads.g.doubleclick.net/tag/js/gpt.js'; var node = document.getElementsByTagName('script')[0]; node.parentNode.insertBefore(gads, node); })(); }else{ typeof removeAds =="function" && removeAds('gpt'); $('.colombia,.ad1,.ctn_ads_rhs,.colombia,.ad,.ads,.ad-widget').hide(); } }); function getCookie(name){ var re = new RegExp(name + "=([^;]+)"); var value = re.exec(document.cookie); return (value != null) ? unescape(value[1]) : null; } var googletag = googletag || {}; googletag.cmd = googletag.cmd || []; var PPIDFlag = null; var PPIDCookieVal = getCookie('_col_uuid'); if (PPIDCookieVal) { PPIDFlag = PPIDCookieVal ? 'true' : 'false'; } var _fic; if (document.referrer && document.referrer.search(/timesofindia|jcmsdev|toidev/) == -1) { var _ficarr = document.cookie.match(/(?:\s)?fic=(\w+);?/); _fic = (_ficarr && _ficarr[1])?parseInt(_ficarr[1], 10)+1:1; document.cookie="fic="+_fic+"; path=/"; }else{ _fic=0; } var adsthrottle = function(limit,func) { var inThrottle = void 0; var lastFunc = void 0; var lastRan = void 0; return function () { var context = this; var args = arguments; if (!inThrottle) { func.apply(context, args); lastRan = Date.now(); inThrottle = true; } else { clearTimeout(lastFunc); lastFunc = setTimeout(function () { if (Date.now() - lastRan >= limit) { func.apply(context, args); lastRan = Date.now(); } }, limit - (Date.now() - lastRan)); } }; }; var dfpFallbackAdsLoad = function(){ if($( "[data-adsSlot][data-fallback-ad-for]" ).length > 0){ adsReadTag('default', true); } }; var dfpadsLoad = function(){ if($( "[data-adsSlot]" ).length > 0){ adsReadTag('default'); } }; var trackGArequest = function(reqevent , reqtemp, reqads){ //ga('send', 'event', reqtemp, "req_" + reqevent, reqads); } var SCP = 0, addListner=0, _SCN, _Tmpl, _Tmpl_SCN; var inViewCtr = 0; var slotObj = Object(), trackGA = Object(), fallbackAds = { /*adID: { toBeChecked: true/false, // to be checked for empty response toBeLoaded: true/false, // fallback ad to be loaded for these ads, as they were rendered empty $el: adDomObj }*/ }, slotObj_all = Object(), etJSONObj; var adsSlotToUniqueKey = function(adSlot){ return adSlot.toString().split("").reduce(function(a,b){a=((a<<5)-a)+b.charCodeAt(0);return a&a},0); } var adsReadTag = function(msid, fallbackAdsOnly){ _fn_execute = function(dfpads,isactive){ var _auds = ""; if(typeof(colaud) !='undefined' && typeof(colaud.aud) !='undefined' && colaud.aud != "") { _auds = colaud.aud; } else if(typeof localStorage != "undefined" && typeof(localStorage.getItem('colaud')) != "undefined" ){ _auds = localStorage.getItem('colaud'); } var _HDL = ''; var _ARC1 = ''; var _Tmpl = (typeof toiprops != "undefined" && toiprops.hasOwnProperty("_Tmpl_pg") && typeof toiprops._Tmpl_pg != "undefined") ? toiprops._Tmpl_pg : ''; var _PGT = (typeof _PGT_pg != "undefined") ? _PGT_pg : ((typeof toiprops != "undefined" && toiprops.hasOwnProperty("_PGT_pg") && typeof toiprops._PGT_pg != "undefined") ? toiprops._PGT_pg : ''); var _BL = (typeof toiprops != "undefined" && toiprops.hasOwnProperty("_BL_pg") && typeof toiprops._BL_pg != "undefined") ? 1 : 0; var _article = ''; var _MetaKey = (typeof toiprops != "undefined" && toiprops.hasOwnProperty("_MetaKey_pg") && typeof toiprops._MetaKey_pg != "undefined") ? toiprops._MetaKey_pg : $('meta[name=keywords]').attr("content"); // try{ var pathList = window.location.pathname.split('/'); if(pathList[3] == 'budget'){ _SCN = pathList[1]; _SubSCN = pathList[2] _LastSubSCN = _LastSubSCN ? _LastSubSCN : pathList[3]; // if(pathList.length > 4 && !toiprops.Keyword){ toiprops.Keyword = pathList[3] + '_'+ pathList[4] } } }catch(e){ console.log(e); } var _tval = function(v) { if(typeof(v)=='undefined') return ''; if(v.length>100) return v.substr(0,100); return v; } var _prc_Cookie = document.cookie.match(new RegExp('prc=([^#]+)')); var _prc_val = parseInt((_prc_Cookie && _prc_Cookie[1]) ? _prc_Cookie[1] : 0); // var __prime_user_val = [1,3,4,5,8]; var _non_prime_user_val = [0,2,6,7]; var is_prime_targeted = (_non_prime_user_val.indexOf(_prc_val) > -1) ? true : false; var _Msid = (typeof toiprops != "undefined" && toiprops.hasOwnProperty("msid") && typeof toiprops.msid != "undefined") ? toiprops.msid : ''; var _Hyp1 = (typeof toiprops != "undefined" && toiprops.hasOwnProperty("hyp1") && typeof toiprops.hyp1 != "undefined") ? toiprops.hyp1 : ''; var _Channel = (typeof toiprops != "undefined" && toiprops.hasOwnProperty("_Channel") && typeof toiprops._Channel != "undefined") ? toiprops._Channel : ''; var _SCN = (typeof toiprops != "undefined" && toiprops.hasOwnProperty("_SCN") && typeof toiprops._SCN != "undefined") ? toiprops._SCN : ''; var _Tmpl_SCN = (typeof toiprops != "undefined" && toiprops.hasOwnProperty("_Tmpl_SCN") && typeof toiprops._Tmpl_SCN != "undefined") ? toiprops._Tmpl_SCN : ''; var _SubSCN = (typeof toiprops != "undefined" && toiprops.hasOwnProperty("_SubSCNs") && typeof toiprops._SubSCNs != "undefined") ? toiprops._SubSCNs : ''; var _LastSubSCN = (typeof toiprops != "undefined" && toiprops.hasOwnProperty("_LastSubSCN") && typeof toiprops._LastSubSCN != "undefined") ? toiprops._LastSubSCN : ''; var _LastSubSCN_Child_1 = (typeof toiprops != "undefined" && toiprops.hasOwnProperty("_LastSubSCN_Child_1") && typeof toiprops._LastSubSCN_Child_1 != "undefined") ? toiprops._LastSubSCN_Child_1 : ''; var _LastSubSCN_Child_2 = (typeof toiprops != "undefined" && toiprops.hasOwnProperty("_LastSubSCN_Child_2") && typeof toiprops._LastSubSCN_Child_2 != "undefined") ? toiprops._LastSubSCN_Child_2 : ''; var _LastSubSCN_Child_3 = (typeof toiprops != "undefined" && toiprops.hasOwnProperty("_LastSubSCN_Child_3") && typeof toiprops._LastSubSCN_Child_3 != "undefined") ? toiprops._LastSubSCN_Child_3 : ''; var _LastSubSCN_Child_4 = (typeof toiprops != "undefined" && toiprops.hasOwnProperty("_LastSubSCN_Child_4") && typeof toiprops._LastSubSCN_Child_4 != "undefined") ? toiprops._LastSubSCN_Child_4 : ''; var _LastSubSCN_Child_5 = (typeof toiprops != "undefined" && toiprops.hasOwnProperty("_LastSubSCN_Child_5") && typeof toiprops._LastSubSCN_Child_5 != "undefined") ? toiprops._LastSubSCN_Child_5 : ''; var _LastSubSCN_Child_6 = (typeof toiprops != "undefined" && toiprops.hasOwnProperty("_LastSubSCN_Child_6") && typeof toiprops._LastSubSCN_Child_6 != "undefined") ? toiprops._LastSubSCN_Child_6 : ''; var _LastSubSCN_Child_7 = (typeof toiprops != "undefined" && toiprops.hasOwnProperty("_LastSubSCN_Child_7") && typeof toiprops._LastSubSCN_Child_7 != "undefined") ? toiprops._LastSubSCN_Child_7 : ''; var _LastSubSCN_Child_8 = (typeof toiprops != "undefined" && toiprops.hasOwnProperty("_LastSubSCN_Child_8") && typeof toiprops._LastSubSCN_Child_8 != "undefined") ? toiprops._LastSubSCN_Child_8 : ''; var _LastSubSCN_Child_9 = (typeof toiprops != "undefined" && toiprops.hasOwnProperty("_LastSubSCN_Child_9") && typeof toiprops._LastSubSCN_Child_9 != "undefined") ? toiprops._LastSubSCN_Child_9 : ''; var _Article_ID = (typeof toiprops != "undefined" && toiprops.hasOwnProperty("_Article_ID") && typeof toiprops._Article_ID != "undefined") ? toiprops._Article_ID : ''; var _Meta_Keywords = (typeof toiprops != "undefined" && toiprops.hasOwnProperty("_Meta_Keywords") && typeof toiprops._Meta_Keywords != "undefined") ? toiprops._Meta_Keywords : ''; var _Content_URL = (typeof toiprops != "undefined" && toiprops.hasOwnProperty("_Content_URL") && typeof toiprops._Content_URL != "undefined") ? toiprops._Content_URL : ''; tgtkeys = { 'FIC': _fic, 'Channel': 'toi', 'Tmpl_SCN': _Tmpl_SCN, 'SubSCN': _SubSCN, 'SCN': _SCN, 'LastSubSCN': _LastSubSCN, 'SCP': SCP, 'Arc1': _ARC1, 'BL': _BL, 'PGT': _PGT, 'Hyp1': _Hyp1, 'crtotoi': '', 'rpmid':'', 'pagecolor':'', 'ctnkeyword': _MetaKey, 'templatetype' : _Tmpl, 'primeusertype' : (is_prime_targeted === true) ? _prc_val : '', 'msid' : _Msid, 'LastSubSCN_Child_1':_LastSubSCN_Child_1, 'LastSubSCN_Child_2':_LastSubSCN_Child_2, 'LastSubSCN_Child_3':_LastSubSCN_Child_3, 'LastSubSCN_Child_4':_LastSubSCN_Child_4, 'LastSubSCN_Child_5':_LastSubSCN_Child_5, 'Article_ID':_Article_ID, 'Meta_Keywords':_Meta_Keywords, 'Content_URL':_Content_URL } googletag.cmd.push(function() { dfpads['len'] = dfpads.containers.length; dfpads['arr'] = []; var slot = ''; var adsid = []; var exc = function(ele,msid){ try{ //adsid=$ele.attr('id'); var adsSlot = ele.data('adsSlot')||$ele.data('adsslot'); if(adsSlot=='#' || adsSlot=='') return true; if(!(adsSlot.match(/^7176/))){ adsSlot = "/7176/"+adsSlot; } var adssize=ele.data('size'); adsid=ele.attr('id'); if(msid!='' && msid!='default' && !adsid.match(new RegExp(msid,'g'))) { return true; } if($ele.css('display')!='none'){ if(adssize){ slot = googletag.defineSlot(adsSlot, adssize, adsid).addService(googletag.pubads()); }else{ slot = googletag.defineOutOfPageSlot(adsSlot, adsid).addService(googletag.pubads()); } if(ele.data('ga')){ trackGArequest(ele.data('ga'), _Tmpl_SCN, adsSlot); trackGA[adsSlotToUniqueKey(adsSlot)] = ele.data('ga'); } if(typeof toiprops != "undefined" && toiprops.hasOwnProperty("toiprebid") && toiprops.toiprebid == 1){ apstagSlots.push({"slotID": adsid, "sizes": adssize, "slotName": adsSlot}); } if(ele.data('adsrefresh') && ele.data('adsrefresh')!='all') slotObj[adsid]=slot; if(ele.data('adsrefresh') && ele.data('adsrefresh')=='all') slotObj_all[adsid]=slot; dfpads['arr'].push(adsid); } if (PPIDCookieVal) { googletag.pubads().setPublisherProvidedId(PPIDCookieVal); } }catch(ex){ console.log(ex); } }; var chkGeoLogic = function(cas, geo){ var c = (cas+"").split("|"); if((cas+"").indexOf("!") >= 0){//Not case if(c.indexOf("!" + geo) >= 0){ return true; }else{ return false; } }else{ if(c.indexOf('' + geo) >= 0){ return false; }else{ return true; } } }; for(var i=0; i ad_fic || _fic==0){ $('#'+adsid).removeAttr('data-adsSlot').removeAttr('data-adsslot'); continue; } } /********* end check Fisrt Impression Cound **************/ /********* check ******************/ var ad_in = $ele.data('inview'); if(ad_in && ad_in!=''){ if( !dfp_inView( $ele, true, 500) ) { continue; } $('#'+adsid).removeAttr('data-adsSlot').removeAttr('data-adsslot'); $('#'+adsid).removeAttr('data-inview'); inViewCtr--; } /********* end check cookies **************/ /********* Geo targetted ads **************/ var ad_geo = $ele.data('geo'); if(ad_geo && ad_geo!='' ){ if(_geo!=''){ //if(ad_geo!=_geo){continue;} if(chkGeoLogic(ad_geo,_geo)){//(ad_geo+"").split('|').indexOf(_geo)==-1){ $('#'+adsid).removeAttr('data-adsSlot').removeAttr('data-adsslot'); continue; } exc($ele,msid); } }else{ exc($ele,msid); //if(_geo=='' && i==0)toiprops.chkGeo(); } /********* end Geo targetted ads **************/ } var getUniqueKeywords = function(kwsstr){ if(kwsstr && typeof kwsstr === 'string'){ var arr = kwsstr.split(","); var result = []; arr.forEach(function(str, i) { if(str){ if(!result.includes(str) && i!=0){ result.push(str); }else if(!result.includes(str) && i==0){ result.push(str); } } }); return result.toString(); } } if(PPIDFlag){ googletag.pubads().setTargeting('sg', _auds).setTargeting('HDL', _tval(_HDL)) .setTargeting('ARC1', _tval(_ARC1)).setTargeting('fic',_fic + '').setTargeting('SCP', SCP + '') .setTargeting('Hyp1', _tval(_Hyp1)).setTargeting('article', _tval(_article)) .setTargeting('Tmpl_SCN', _Tmpl_SCN + '') .setTargeting('PGT', _PGT + '').setTargeting('BL', _BL + '') .setTargeting('aud_flag', PPIDFlag+ '').setTargeting('col_key',PPIDCookieVal + ''); } else{ googletag.pubads().setTargeting('sg', _auds).setTargeting('HDL', _tval(_HDL)) .setTargeting('ARC1', _tval(_ARC1)).setTargeting('fic',_fic + '').setTargeting('SCP', SCP + '') .setTargeting('Hyp1', _tval(_Hyp1)).setTargeting('article', _tval(_article)) .setTargeting('Tmpl_SCN', _Tmpl_SCN + '') .setTargeting('PGT', _PGT + '').setTargeting('BL', _BL + '') .setTargeting('aud_flag', PPIDFlag+ ''); } if(toiprops && toiprops.Keyword && toiprops.Keyword!="''"){ googletag.pubads().setTargeting("keyword", toiprops.Keyword); }else if(window.Keyword!=undefined && window.Keyword!="''"){ googletag.pubads().setTargeting("keyword", window.Keyword); } googletag.pubads().setTargeting('Channel', _Channel); if(_SCN){ googletag.pubads().setTargeting('SCN', _SCN); } if(_SubSCN){ googletag.pubads().setTargeting('SubSCN', _SubSCN); } if(_LastSubSCN){ googletag.pubads().setTargeting('LastSubSCN', _LastSubSCN); } if(_LastSubSCN_Child_1){ googletag.pubads().setTargeting('LastSubSCN_Child_1', _LastSubSCN_Child_1); } if(_LastSubSCN_Child_2){ googletag.pubads().setTargeting('LastSubSCN_Child_2',_LastSubSCN_Child_2); } if(_LastSubSCN_Child_3){ googletag.pubads().setTargeting('LastSubSCN_Child_3', _LastSubSCN_Child_3) } if(_LastSubSCN_Child_4){ googletag.pubads().setTargeting('LastSubSCN_Child_4',_LastSubSCN_Child_4) } if(_LastSubSCN_Child_5){ googletag.pubads().setTargeting('LastSubSCN_Child_5', _LastSubSCN_Child_5) } if(_Meta_Keywords){ googletag.pubads().setTargeting('Meta_Keywords', getUniqueKeywords(_Meta_Keywords)); } if(_Content_URL){ googletag.pubads().setTargeting('Content_URL', _Content_URL) } if(_Article_ID && _Tmpl_SCN != "listing"){ googletag.pubads().setTargeting('Article_ID', _Article_ID) } if(_Tmpl_SCN){ googletag.pubads().setTargeting('Tmpl_SCN', _Tmpl_SCN) } var crtg_split= (crtg_content|| '').split(';'); var pubads = googletag.pubads(); var cto_values= []; if(crtg_split.length > 0 & _geo!=1){ for (var i=1;i -1 && $('body').hasClass('bgImg')){ // console.log(adSlot + ' ad rendered but returned empty in slotRenderEnded callback.'); if(fallbackAds[d].$fallbackEls.length){ $.each(fallbackAds[d].$fallbackEls, function(){ this.remove(); }); } fallbackAds[d] = null; return; } fallbackAds[d].toBeLoaded = true; dfpFallbackAdsLoad(); } }); addListner++; } googletag.enableServices(); for(var i=0; i 0)adRefresh(msid); if($("[data-adsrefresh][data-adsrefresh='all']:not([data-adsslot])").length > 0)adRefresh_all(); } adsReadTag(msid); } else{ typeof removeAds =="function" && removeAds('gpt'); } }; var dfp_inView = function (elem, partial, skew) { skew = skew || 0; var $w = $(window), $e = $(elem), docViewTop,docViewBottom,elemTop,elemBottom,in_view; if($e.is(":hidden")){ // Element is hidden so its not in the view return false; } docViewTop = $w.scrollTop() - skew; //todo - skew docViewBottom = $w.scrollTop() + $w.height() + skew;//todo + skew elemTop = $e.offset()?$e.offset().top:0; elemBottom = elemTop + $e.height(); in_view = false; if (partial === true) { in_view = ((elemBottom > docViewTop ) && (elemTop <= docViewBottom )); } else { in_view = ((elemBottom <= docViewBottom) && (elemTop >= docViewTop)); } return in_view; }; var dfp_throttle = function ( delay, callback ) { var _timeout; var _exec = 0; return function callable() { var elapsed = +new Date() - _exec; var tthis = this; var args = arguments; function run() { _exec = +new Date(); callback.apply( tthis, args ); } _timeout && clearTimeout( _timeout ); if( elapsed > delay ) run(); else _timeout = setTimeout( run, delay - elapsed ); }; } var dfp_scrollT = dfp_throttle(100, function(){ if($("[data-inview]").length > 0){buildAdsAj();} }); $( document ).ready(function() { if(!(typeof toiprops && typeof toiprops.toipr!="undefined")){ dfpadsLoad('default'); inViewCtr = $("[data-inview]").length; $(window).scroll(dfp_scrollT); } else{ typeof removeAds =="function" && removeAds('gpt'); } }); window.TimesApps = window.TimesApps || {}; TimesApps.VideoListManager = (function(){ "use strict"; var cache, fn, api, config, data, bindInitialEvents; cache = { jRow : $(".jRow"), jSectionRow : $(".jSectionRow") } config = { shouldCheckGeoAndRenderCity : true, cityData : undefined, sectionsForGeoData : [] } bindInitialEvents = function(){ require(["tiljs/event"], function(eventBus){ eventBus.subscribe("window.scroll", fn._chooseUserPrefferedData); }); cache.jSectionRow.on("click", 'a', fn._handleSubSectionClick); } fn = { _init : function(){ bindInitialEvents(); fn._chooseUserPrefferedData(); fn._selectFirstCatIfNoSelected(); }, _selectFirstCatIfNoSelected: function(){ for(var i=0; i < cache.jSectionRow.length; i++){ var activeCatCount = cache.jSectionRow.eq(i).find(".active").length; if( !activeCatCount ){ cache.jSectionRow .eq(i) .find('.sub-section') .eq(0).addClass("active"); } } }, _sortSectionByGeo : function(){ var catkey = $("#catkey").val(); var catsWithGeoData = { 3812908 : "ent", 3813445 : "trailers", 59192346 : "city" }; if( catsWithGeoData[catkey] ){ require(["tiljs/event"], function(eventBus){ eventBus.subscribe("VideosGeoPreferredMsidsFound", function(data){ var key = catsWithGeoData[catkey] || ""; var id = data[key] || data[key]; $(".jRow[data-id='" + id + "']").insertBefore($(".jRow").eq(0)); }); fn._getMsidsFromCityName(); }); } }, _chooseUserPrefferedData : function(){ if( !config.shouldCheckGeoAndRenderCity ){ //selection upon geo has been //already done return; } fn._renderUserPrefferedCat(); config.shouldCheckGeoAndRenderCity = false; }, _getMsidsFromCityName : function(){ require(['cookie'], function(cookie){ var cityName = cookie.get("geolocation"); if( !cityName ){ return; } $.ajax({ url: "/vidpef.cms", data: { city : cityName } }).done(function(json) { var data = TimesApps.Utils.parseJson(json); config.cityData = data; require(["tiljs/event"], function(pubSub){ pubSub.publish('VideosGeoPreferredMsidsFound', this.data); }.bind({data})); for( var i in config.cityData ){ if( config.cityData.hasOwnProperty(i) ){ var msid = config.cityData[i]; } $("[data-msid=" + msid +"]") .trigger("click"); } }); }) }, _renderUserPrefferedCat : function(type){ var preferences = fn._getUserSectionPreference(); config.sectionsForGeoData = []; $(".jRow").each(function(i, row){ var sectionId = $(row).data("id") || ""; if( preferences.subsecPreference && preferences.subsecPreference[sectionId]){ var msid = preferences.subsecPreference[sectionId]["preferredSubsection"]; $("[data-msid=" + msid +"]") .trigger("click"); }else{ config.sectionsForGeoData.push(sectionId); } }); if( config.sectionsForGeoData.length == 0 ){ return; } fn._getMsidsFromCityName(); }, _saveUserSectionPreference : function(sectionRowId, preferredSubsection){ var data = TimesApps.Utils.getData() || {}; data["subsecPreference"] = data["subsecPreference"] || {}; data["subsecPreference"][sectionRowId] = { preferredSubsection : preferredSubsection }; TimesApps.Utils.storeData("subsecPreference", data["subsecPreference"]); }, _getUserSectionPreference : function(){ return TimesApps.Utils.getData("subsecPreference"); }, _handleSubSectionClick: function(e){ var $subSection = $(this), msid = $subSection.data('msid'), tag = $subSection.data('tag'), href = $subSection.data('href'), $subSectionsParent = $subSection.closest(".jSectionRow"), $subSections = $subSectionsParent.find('.sub-section'), $subSectionMore = $subSectionsParent.find('.sub-section-more'), subSectionsId = $subSectionsParent.data('id'), $moreBtn = $subSectionsParent.prev('.title-section').find('.jviewmore'); if( !$subSection.closest('.sub-section').hasClass('active') ){ fn._loadSelectedSectionsVideos(msid, tag, $subSectionsParent); } $subSections.removeClass('active'); $subSectionMore.removeClass('active'); $subSection.closest('.sub-section').addClass('active'); $subSection.closest('.sub-section-more').addClass('active'); //change more buttons href $moreBtn.attr('href', href); fn._saveUserSectionPreference(subSectionsId, msid); }, _loadSelectedSectionsVideos: function(msid, tag, $subSections){ var baseUrl = '/wdt_list.cms?tmpl=videoshow&byline=totalcnt|viewed|urcount|mediadate|strupd|art_date|strlastupd|watchlater' + '&msid=' + msid + '&tag=' + tag + '&img=' + (msid == 4762524 ? 'msid': 280) + '&config.ignorepl=1', url = baseUrl + '&config.perpage=10', nextUrl = baseUrl + '&config.perpage=30&exclude_top=10', $existingVideoSectionSlider = $subSections.next('.videos-section-slider'); $existingVideoSectionSlider.addClass('loading'); $.ajax({ "url": url, success: function(response){ var $html = $('
    ').html(response).html(), $videoSectionSlider = '
    ' + '
    ' + response + '
    ' + '
    '; $existingVideoSectionSlider.replaceWith($videoSectionSlider); $existingVideoSectionSlider = $subSections.next('.videos-section-slider'); videos_section_slider.init($existingVideoSectionSlider); require( ['tiljs/plugin/lazy', 'toicommonjs/rodate'], function(lazy, rodate){ lazy.load(); rodate.uptime(); //WatchLaterManger is initialized on window load if(TimesApps.WatchLaterManager.getInitStatus()){ TimesApps.WatchLaterManager.updateStatus($existingVideoSectionSlider); } else{ $(window).load(function(){ TimesApps.WatchLaterManager.updateStatus($existingVideoSectionSlider); }); } }); } }); } } api = { init: function(){ return fn._init(); }, sortSectionByGeo : function(){ return fn._sortSectionByGeo(); } } return api; }()); var TimesApps = window.TimesApps || {}; TimesApps.VideoSearch = (function(){ "use strict"; var cache, fn, api, util, config, state, bindInitialEvents, constants, templates; constants = { AUTO_SUGGESTOR : "AUTO_SUGGESTOR", SEARCH_PAGE : "SEARCH_PAGE" }; config = { searchApi : "/video_search_api.cms", searchFrom : "", sortOrder : { relevance : "score desc", date : "effectivedate desc" }, maxSearchPageToShow : 6, maxResultsPerPage : 20, relatedstoriesurl : "/wdt_list.cms?msid=4762524&tag=videopllist&config.perpage=5&tmpl=videoshow&byline=totalcnt|viewed|urcount|mediadate|strupd|art_date|%20strlastupd" } state = { searchType : constants.AUTO_SUGGESTOR, sortOrder : config.sortOrder.relevance, pageNum : 1, isAutoSuggestorOpen : false } cache = { jSearchListingContainer : $(".jSearchListingContainer"), jSearchLens : $(".jSearchLens"), jAutoSuggestorBox : $(".jAutoSuggestorBox"), jAutoSuggestorInput : $(".jAutoSuggestorInput"), jAutoSuggestorBoxClose : $(".jAutoSuggestorBoxClose"), jSearchPage : $(".jSearchPage"), jBody : $("body"), jSearchSubmit : $('.jSearchSubmit') } /* *caching templates *for in memory dom manipulation */ templates = { jSearchListing : cache.jSearchListingContainer.clone() } bindInitialEvents = function(){ cache.jSearchLens.on("click", fn._showCloseSearchBox); cache.jAutoSuggestorInput.on("keyup", fn._fetchResults); cache.jSearchSubmit.on('click', fn._fetchResults); //cache.jAutoSuggestorBoxClose.on("click", fn._closeAutoSuggestorBox); //search results event require(["tiljs/event"], function(eventBus){ eventBus.subscribe("searchResultsFound", fn._showResults); }); cache.jSearchPage .on("click", ".jSortOrder", function(){ fn._changeSortOrder(event, fn._callApi); }); cache.jSearchPage .on("click", ".jPagination", fn._paginate); } util = { _setSearchType : function(searchType){ state.searchType = searchType; }, _getDescriptionFromXml : function(xml){ var tempDiv = document.createElement("div"); tempDiv.innerHTML = xml; var description = tempDiv.querySelectorAll("largedescription")[0].innerText; return description; }, _getElapsedTimeFromDate : function(date){ if(!date){ return; } var timeStamp = new Date(date).getTime(); var rodate = require("rodate"); var elapsedTime = rodate.elapsedTime(timeStamp, { minute: "min", second: "sec" }, true); return elapsedTime; }, _getTemplates : function(id){ var tpl = templates[id]; return tpl ? tpl.clone() : false; }, _incrementPageCount : function(){ var pageNum = state.pageNum; if( pageNum < state.maxCount ){ pageNum += 1; } state.pageNum = pageNum; }, _getCurrentPageNum: function(count){ return count == state.pageNum; }, _setMaxPageCount: function(count){ state.maxCount = count; } }; fn = { _init: function(){ bindInitialEvents(); }, _showCloseSearchBox : function(event){ if( state.isAutoSuggestorOpen ){ fn._closeAutoSuggestorBox(event); }else{ fn._showSearchBox(event); } }, _showSearchBox : function(event){ $(".search-form") .addClass("active"); cache.jAutoSuggestorBox .removeClass("hidden") .find(".jAutoSuggestorInput") .val(""); cache.jBody .toggleClass("overlay"); cache.jAutoSuggestorInput.trigger("focus"); state.isAutoSuggestorOpen = true; }, _closeAutoSuggestorBox: function(e){ var clickedEle = $(e.target); var pressedKey = e.key ? e.key.toUpperCase() : e.keyCode; /* if( !( clickedEle.closest(".jAutoSuggestorBoxClose").length > 0 ) && clickedEle.hasClass("jAutoSuggestorInput") && !( pressedKey == "ENTER" || pressedKey == 13 ) || clickedEle.hasClass("jSearchLens") ){ return; }*/ if( ( state.isAutoSuggestorOpen && !clickedEle.hasClass("jSearchLens") ) && !clickedEle.hasClass("jSearchSubmit") && clickedEle.closest(".search-form").length && !( pressedKey == "ENTER" || pressedKey == 13 ) ){ return; } state.isAutoSuggestorOpen = false; $(".search-form") .removeClass("active"); cache.jAutoSuggestorBox .addClass("hidden") .find(".jAutoSuggestorInput") .trigger("keyup"); cache.jBody .removeClass("overlay"); }, _callApi : function(event){ var sortOrder = state.sortOrder; var searchType = state.searchType; var query = cache.jAutoSuggestorInput.val() || ""; var placeholder = cache.jAutoSuggestorInput.attr("placeholder"); if( query.trim().length == 0 || placeholder == query ){ return; } var ajaxReq = $.ajax({ url : config.searchApi, data : { feedtype: "sjson", sortOrder: sortOrder, query: query, page: state.pageNum } }); ajaxReq.done(function(json){ require(["tiljs/event"], function(eventBus){ eventBus.publish("searchResultsFound", {json:json, searchType: searchType}); }); }.bind({searchType: searchType})); }, _getTopStories : function(){ //check tag again $.ajax({ url: config.relatedstoriesurl, }).done(function(response){ $('.related-stories .box1').html(response) }) }, _showAutoSuggestor : function(data){ var list = data.Documents; //limiting results to max 7 for auto suggestor list.length = ( list.length >= 7 ) ? list.length = 7 : list.length; var jsrender = require(["jsrender"], function(){ var template = $.templates("#autosuggestionTpl"); var htmlOutput = template.render(this.list); $(".searchSuggestions").html(htmlOutput); }.bind({list:list})) }, _showSearchListing : function(data){ if(!data.Documents){ return; } if( data.Documents instanceof Array ){ var list = data.Documents; }else{ var list = []; list.push(data.Documents.Document); } var helperFunctions = { getDescriptionFromXml : util._getDescriptionFromXml, convertMsToReadableTime : TimesApps.Utils.convertMsToReadableTime, getElapsedTimeFromDate : util._getElapsedTimeFromDate } var searchTemplate = util._getTemplates("jSearchListing"); var jsrender = require("jsrender"); var jsRenderTemplate = $.templates("#searchListingTpl"); var htmlOutput = jsRenderTemplate.render(list, helperFunctions); searchTemplate .find(".jSearchList") .html(htmlOutput); var searchMeta = data.Header; if( searchMeta.numFound > 2000 ){ var text = "Your search returned a large number of results."; text += " Showing top 2000 results.
    Narrow your search results by refining your search criteria."; searchTemplate .find(".jSearchMeta") .html(text); }else{ searchTemplate .find(".jResultCount") .text(searchMeta.numFound || 0); searchTemplate .find(".jSearchTerm") .text(searchMeta.Params.q || ""); } /*pagination template*/ var jsRenderTemplate = $.templates("#searchPaginationTpl"); var pageCountJson = fn._getSearchPageCount(state.pageNum, searchMeta.numFound); var htmlOutput = jsRenderTemplate.render(pageCountJson); var previousNextHtml = ""; var previous = '
  • '; var next = ''; var maxResultsShown = 0; if( pageCountJson.length > 0 ){ maxResultsShown = pageCountJson[pageCountJson.length-1].pageNum ; } if( state.pageNum === 1 && state.pageNum != maxResultsShown ){ previousNextHtml += next; }else if( state.pageNum === maxResultsShown && state.pageNum != 1 ){ previousNextHtml += previous; }else if( state.pageNum > 1 && state.pageNum < maxResultsShown ){ previousNextHtml += previous + next; } searchTemplate .find(".jPagination") .html(previousNextHtml); if( state.pageNum > 1 ){ searchTemplate .find(".jPagination li") .eq(0) .after(htmlOutput); }else if( maxResultsShown == 1 ){ //there is only 1 search page //prev, next not shown searchTemplate .find(".jPagination") .html(htmlOutput); }else{ //both prev & next shown searchTemplate .find(".jPagination li") .eq(0) .before(htmlOutput); } //mark current page active searchTemplate .find(".pagination [data-page-num=" + state.pageNum +"]") .closest("li") .addClass("active"); if( state.sortOrder == config.sortOrder.relevance ){ searchTemplate .find(".jSortOrder [data-sort-ordrer='relevance']") .addClass("active"); searchTemplate .find(".jSortOrder [data-sort-ordrer='date']") .removeClass("active"); }else{ searchTemplate .find(".jSortOrder [data-sort-ordrer='date']") .addClass("active"); searchTemplate .find(".jSortOrder [data-sort-ordrer='relevance']") .removeClass("active"); } if( list.length == 0 ){ searchTemplate .find(".jNoResultsFound") .removeClass("hidden"); searchTemplate .find(".jPagination") .addClass("hidden"); } cache.jSearchListingContainer .html( searchTemplate.html() ); fn._showSearchPage(); }, _showResults: function(obj){ var searchData = TimesApps.Utils.parseJson(obj.json); if( !searchData ){ return; } var ajaxSentForSearchType = obj.searchType; if( ajaxSentForSearchType != state.searchType ){ return; } searchData.Documents = searchData.Documents || []; if( searchData.Documents.length <= 0 ){ searchData.Documents = []; } if( state.searchType == constants.AUTO_SUGGESTOR ){ fn._showAutoSuggestor(searchData); }else{ $(".jPageDataContainer").addClass("hidden"); //stop video player $("#topVideoIframe").attr("src",""); fn._showSearchListing(searchData); fn._getTopStories(); require(["tiljs/event"], function(eventBus){ // errorMsg eventBus.publish("renderingSearch"); }); } var searchKey = cache.jAutoSuggestorInput.val() || ""; fn._fireAnalytics(searchKey); }, _fetchResults : function(e){ e.preventDefault(); var pressedKey = e.key ? e.key.toUpperCase() : e.keyCode; if( ! (pressedKey || $(e.target).hasClass('jSearchSubmit') ) ){ return; } //state.pageNum = state.pageNum || 1; state.pageNum = 1; if( pressedKey == "ENTER" || pressedKey == 13 || $(e.target).hasClass('jSearchSubmit') ){ util._setSearchType(constants.SEARCH_PAGE); fn._callApi(e); fn._closeAutoSuggestorBox(e); }else{ util._setSearchType(constants.AUTO_SUGGESTOR); debounce( fn._callApi, 150 )(); } }, _changeSortOrder : function(e, searchApi){ var clickedEle = $(e.target); if( clickedEle.closest(".jSortOrder").length > 0 ){ var sortOrder = clickedEle.data("sort-ordrer") ? clickedEle.data("sort-ordrer").toUpperCase() : ""; if( sortOrder == "RELEVANCE" ){ state.sortOrder = config.sortOrder.relevance; }else if( sortOrder == "DATE"){ state.sortOrder = config.sortOrder.date; } } if( typeof searchApi == "function"){ searchApi(e, state.sortOrder, constants.SEARCH_PAGE); } }, _getSearchPageCount: function(startIndex, resultCount){ var pageCountArray = []; if( resultCount == 0 ){ return pageCountArray; } /* *maxResultsPerPage is controlled from video_search_api.cms *this var is just to calculate num of pages */ var maxResultsPerPage = config.maxResultsPerPage; var maxPagesCount = resultCount / maxResultsPerPage; maxPagesCount = Math.ceil(maxPagesCount); maxPagesCount = ( maxPagesCount > 100 ) ? 100 : maxPagesCount; util._setMaxPageCount(maxPagesCount); var pageCountToShow = (maxPagesCount < config.maxSearchPageToShow) ? maxPagesCount : config.maxSearchPageToShow; pageCountToShow = ( pageCountToShow + startIndex ) < maxPagesCount ? (pageCountToShow + startIndex) : maxPagesCount; for( var i = startIndex; i <= pageCountToShow; i++ ){ pageCountArray.push({ pageNum: i}); } return pageCountArray; }, _showSearchPage : function(){ cache.jSearchPage.removeClass("hidden"); require(["tiljs/event"], function(eventBus){ eventBus.publish("updateWatchLaterStatus", {$container: cache.jSearchPage}); }); }, _paginate : function(e){ e.preventDefault(); var clickedELe = $(e.target); var jPrevious = cache.jSearchPage .find(".jPrevious"); var jNext = cache.jSearchPage .find(".jNext"); if( e.target == jPrevious[0] ){ if(state.pageNum > 1){ state.pageNum -= 1; fn._callApi(); } }else if( e.target == jNext[0] ){ util._incrementPageCount(); fn._callApi(); }else if( clickedELe.hasClass("jPageNum") ){ var pageNum = clickedELe.data("page-num"); state.pageNum = pageNum; fn._callApi(); } }, _fireAnalytics: function(searchKeyword){ var pageName = cache.jBody .find("#pageName") .val() || ""; pageName = pageName ? pageName : cache.jBody .find("#pageType") .val(); ga('send', { hitType: 'event', eventCategory: "VideoSearch", eventAction: searchKeyword, eventLabel: pageName }); } }, api = { init : function(){ fn._init(); }, closeAutoSuggestorBox : function(e){ fn._closeAutoSuggestorBox(e); } } return api; }()); //source - http://davidwalsh.name/javascript-debounce-function // Returns a function, that, as long as it continues to be invoked, will not // be triggered. The function will be called after it stops being called for // N milliseconds. If `immediate` is passed, trigger the function on the // leading edge, instead of the trailing. function debounce(func, wait, immediate) { var timeout; return function() { var context = this, args = arguments; var later = function() { timeout = null; if (!immediate) func.apply(context, args); }; var callNow = immediate && !timeout; clearTimeout(timeout); timeout = setTimeout(later, wait); if (callNow) func.apply(context, args); }; }; window.TimesApps = window.TimesApps || {}; (function(MODULE){ var _constants = { configSelectors: { // configs will be picked using these seletors on the $listContainer passed to the init function watchLaterElementSelector: 'data-watchlater-selector', msidElementSelector: 'data-msid-selector', updateStatusOnLoad: 'data-update-watchlater-status-onload' }, urls: { //dynamic params for watchLater // after=true for first load, false for viewMore watchLaterStatus: 'http://myt.jeetwin-gaming.com/mytimes/video/activity/?activityType=WishList&appKey=TOI&entity=false&grouping=false&after=true&lastSeenId=0', //dynamic params for addToWatchLater //activityId : _id of the video to be removed // url : teu // uniqueAppID : msid addToWatchLater: 'http://myt.jeetwin-gaming.com/mytimes/addActivityDdup/?appKey=TOI&baseEntityType=VIDEO&objectType=B&activityType=WishList&_=1487317571900', //dynamic params for removeFromWatchLater //activityId : _id of the video to be removed // url : teu // uniqueAppID : msid removeFromWatchLater: 'http://myt.jeetwin-gaming.com/mytimes/removeActivity?appKey=TOI&baseEntityType=VIDEO&objectType=B&activityType=WishList&_=1487317571900' }, cssClasses: { updated: 'js-updated' } }, _defaults = { domSelectors: { watchLater: '.js-watchLater', msid: '[data-msid]', }, groupSize: 10, updateStatusOnLoad: true }, _dom = { }, _state = { processing: false }, _config, _initialized = false; function getFinalConfig($container) { var $updateStatusOnLoad = $('[' + _constants.configSelectors.updateStatusOnLoad + ']'), $watchLaterSelector = $('[' + _constants.configSelectors.watchLaterElementSelector + ']'), $msidSelector = $('[' + _constants.configSelectors.msidElementSelector + ']'), finalConfig = { domSelectors: { watchLater: $watchLaterSelector.attr(_constants.configSelectors.watchLaterElementSelector), msid: $msidSelector.attr(_constants.configSelectors.msidElementSelector) }, updateStatusOnLoad: ($updateStatusOnLoad.length && $updateStatusOnLoad.attr(_constants.configSelectors.updateStatusOnLoad) === 'no') ? false : true }; return $.extend(true, _defaults, finalConfig); } function populateDOMVariables($container){ _dom.$container = $container; } function updateVideosWatchLaterStatus(container){ var $container = container || _dom.$container, $watchLaterElements = $container.find(_config.domSelectors.watchLater + ":not(."+ _constants.cssClasses.updated +")"), msids = [], msidGroups, elementsMap = {}; $watchLaterElements.each(function(i, item){ var $item = $(item), msid = $item.closest(_config.domSelectors.msid).data('msid'); if(msid){ //this map will be used to update the status in DOM elementsMap[msid] = elementsMap[msid] || []; elementsMap[msid].push($item); //this array will be used to make server calls to get watch ater status (msids.indexOf(msid) < 0) && msids.push(msid); } }); if(!msids.length){ return; } //split msids array into chunks/groups of required size msidGroups = MODULE.Utils.createGroupedArray(msids, _config.groupSize); //get status for each group and render status $.each(msidGroups, function(i, msidGroup){ getVideosWatchLaterStatus(function(statusData){ var processedStatusData; if(!statusData){ return; } processedStatusData = getProcessedStatusData(statusData); renderVideosWatchLaterStatus(processedStatusData, elementsMap); },{ "msids": msidGroup.join(',') }); }); } function getProcessedStatusData(statusData){ var processedData = {}; statusData = statusData.filter(function(item){ return item.msid; }); statusData.reduce(function(prev,curr){ //_id in the status object is used in the remove call later prev[curr.msid] = curr._id; return prev; }, processedData); return processedData; } function getVideosWatchLaterStatus(successCB, data){ MODULE.Utils.ajax(_constants.urls.watchLaterStatus, successCB, null, null, data, 'jsonp'); } function renderVideosWatchLaterStatus(statusData, elementsMap){ for(var key in elementsMap){ $.each(elementsMap[key], function(i, el){ el.addClass(_constants.cssClasses.updated); //presense in statusData object means video is in watch later list if(statusData[key]){ el.addClass('added'); el.closest(_config.domSelectors.msid).data('id', statusData[key]); } }); } } function attachEventHandlers(){ _dom.$container.on('click', _config.domSelectors.watchLater, watchLaterClicked); require(["tiljs/event"], function(eventBus){ eventBus.subscribe("updateWatchLaterStatus", function(data){ TimesApps.WatchLaterManager.updateStatus(data.$container); }); }); } function watchLaterClicked(e){ var $target = $(e.target), $video = $target.closest(_config.domSelectors.msid), id = $video.data('id'), msid = $video.data('msid'), url = $video.data('url'), action = 'add'; if(_state.processing){ return; } var href = $video.find('[href]').attr('href'), videoSeo = href.substring(0,href.search('videoshow')-1); ga('send', { hitType: 'event', eventCategory: 'WatchLater', eventAction: videoSeo, eventLabel: document.getElementById("pageType").value }); //check login status before making the call require(['event', 'cookie'], function(event, cookie){ var userLoggedin = cookie.get('ssoid'); if(!userLoggedin){ require("login").login(); return; } if($target.hasClass('added')){ action = 'remove'; }else{//id argument is needed only for remove Activity id = undefined; } _state.processing = true; modifyWatchLaterStatus(action, msid, id, url, function(){ if(action === 'remove'){ $target.removeClass('added'); } else{ $target.addClass('added'); } _state.processing = false; }) }); } function modifyWatchLaterStatus(action, msid, id, url, successCB){ var api = 'addToWatchLater'; if(action === 'remove'){ api = 'removeFromWatchLater'; } MODULE.Utils.ajax(_constants.urls[api], function(response){ typeof successCB === 'function' && successCB(response); }, null, null, { "activityId" : id, "url" : url, "uniqueAppID" : msid }, 'jsonp'); } MODULE.WatchLaterManager = { init: function($container){ $container = $container || $(document); _config = getFinalConfig($container); populateDOMVariables($container); attachEventHandlers(); require(['event', 'cookie'], function(event, cookie){ var userLoggedin = cookie.get('ssoid'); if(!userLoggedin){ return; } if(_config.updateStatusOnLoad){ updateVideosWatchLaterStatus($container); } _initialized = true; }); }, updateStatus: updateVideosWatchLaterStatus, getInitStatus: function(){ return _initialized; } } })(window.TimesApps, window, jQuery); /*$(function(){ window.TimesApps.WatchLaterManager.init(); });*/ $(window).load(function(){ window.TimesApps.WatchLaterManager.init(); }) /***************************************Ask someone to fix ads_perfectmarket JS, Temporary fix******************************************/ window._ls_set = window._ls_set || function(){}; /*********************************************************************************/ window.TimesApps = window.TimesApps || {}; TimesApps.Utils = (function(){ var fn, api, constants, data, config; config = { dataStorageKey : "VideosData", }, constants = { seondsInOneMinute : 60, msInOneSecond : 1000 } fn = { _getData : function(){ var data; try{ data = JSON.parse( localStorage.getItem(config.dataStorageKey) || "{}" ); }catch(e){ data = {}; } return data; }, _storeData : function(prop, value){ if( typeof prop == "undefined" || prop.trim().length == 0 ){ return; } var data = fn._getData(); data[prop] = value; var dataJson; try{ dataJson = JSON.stringify(data); }catch(e){ return false; } localStorage.setItem(config.dataStorageKey, dataJson); return data; }, _getClientHeight: function(){ return $(window).height(); }, _isIpad: function(){ if(typeof navigator.userAgent == "undefined" ){ return; } return navigator.userAgent.match(/iPad/i) != null; }, _getDocumentHeight: function(){ return $(document).height(); }, _getScrolledHeight: function(){ return $(window).scrollTop(); }, _convertMsToReadableTime : function(miliSeconds){ var readableTime; if( !miliSeconds || isNaN(miliSeconds) || miliSeconds < 0 ){ readableTime = ""; } var totalSeonds = miliSeconds / constants.msInOneSecond; var minutes = totalSeonds / constants.seondsInOneMinute; var seconds = totalSeonds % constants.seondsInOneMinute; seconds = parseInt(seconds) > 9 ? seconds : "0" + seconds; readableTime = parseInt(minutes) + ":" + seconds; return readableTime; }, _parseJson : function(json){ var data; if(!json){ data = {}; } try{ if( typeof json != "object" ){ data = JSON.parse(json); }else{ data = json; } }catch(e){ data = {}; } return data; }, _ajax: function(url, successCB, errorCB, alwaysCB, data, type) { if (!url) { return; } var ajaxRequest = $.ajax({ "url": url, "dataType": type || 'json', "jsonp": type === 'jsonp' ? "callback" : undefined, "data": data ? data : { format: "json" } }); ajaxRequest.done(function(json) { typeof successCB === 'function' && successCB(json); }); ajaxRequest.fail(function(error) { typeof errorCB === 'function' && errorCB(error); }); ajaxRequest.always(function(response) { typeof alwaysCB === 'function' && alwaysCB(response); }); return ajaxRequest; }, _createGroupedArray: function(arr, chunkSize) { var groups = [], i; for (i = 0; i < arr.length; i += chunkSize) { groups.push(arr.slice(i, i + chunkSize)); } return groups; }, _checkFirstViewPort: function(){ return (fn._getScrolledHeight() > fn._getClientHeight()) ? true : false; }, _getSeolocation: function(){ var pagetype = $('#pageType').val() || ""; pagetype = pagetype.toUpperCase(); var seolocation = ""; if(pagetype == "VIDEOSHOW"){ var pathname = location.href.replace(location.origin,""), index = pathname.indexOf('videoshow'); seolocation = pathname.substring(0,index - 1); }else if(pagetype == "VIDEOLIST" || pagetype == "VIDEOHOME" || pagetype == "VIDEO" || pagetype == "AUDIO" ){ seolocation = location.href.replace(location.origin,""); } return seolocation; }, _convertHoursToAgo: function(){ require(["rodate"], function(rodate){ rodate.uptime(); $('[rodate]').filter(function(){ return $(this).text() == '1 day ago' }).text('Yesterday'); }); }, _getUserCity : function(){ require('cookie').get("geolocation"); } }; api = { convertMsToReadableTime : function(miliSeconds){ return fn._convertMsToReadableTime(miliSeconds); }, parseJson : function(json){ return fn._parseJson(json); }, ajax : function(url, successCB, errorCB, alwaysCB, data, type){ return fn._ajax(url, successCB, errorCB, alwaysCB, data, type); }, createGroupedArray : function(arr, chunkSize){ return fn._createGroupedArray(arr, chunkSize); }, checkFirstViewPort: function(){ return fn._checkFirstViewPort(); }, getSeolocation: function(){ return fn._getSeolocation(); }, getClientHeight: function(){ return fn._getClientHeight(); }, getDocumentHeight: function(){ return fn._getDocumentHeight(); }, getScrolledHeight: function(){ return fn._getScrolledHeight(); }, isIpad : function(){ return fn._isIpad(); }, convertHoursToAgo : function(){return fn._convertHoursToAgo(); }, getUserCity : function(){ return fn._getUserCity(); }, getData : function(){ return fn._getData(); }, storeData : function(prop, value){ return fn._storeData(prop, value); } } return api; }()); /* * TODO - rename module VideoHome * to VideoCommons */ TimesApps.VideoHome = (function(){ "use strict"; var cache, fn, api, config, data, bindInitialEvents; cache = { jNavigation : $(".jNavigation"), jNavClose : $('.jNavClose'), hamburgerMenuIcon : $(".hamburgerMenuIcon"), jVideoNav : $(".jVideoNav"), jVideohomeLink : $('.header_left .jVideohomeLink'), errorMsg : $(".errorMsg"), backToTop : $('.jBackToTop') } bindInitialEvents = function(){ cache.hamburgerMenuIcon.on("click", fn._showMenu); cache.jNavClose.on("click", fn._hideMenu); //cache.jVideohomeLink.on("click", fn._toggleVideohomeMenu); //cache.jVideoNav.on("mouseleave", fn._) $('.arrow').on("click", fn._toggleVideohomeMenu); $(document).on("click", fn._closeOpenWidgets); cache.backToTop.on('click',fn._scrollToTop); require(["tiljs/event"], function(eventBus){ eventBus.subscribe("renderingSearch", fn._hideErrorMsgs); eventBus.subscribe("liveTvChannelChanged", TimesApps.setpgAttributes.attachPgAttributes); eventBus.subscribe("window.scroll", fn._displayCheckForBackToTop); }); }, fn = { _init: function(){ bindInitialEvents(); TimesApps.Utils.convertHoursToAgo(); fn._hideVideoViews(); }, _showMenu: function(){ $(".leftNav").animate({left: "0px"},"ease-in"); /*cache.jNavigation .addClass("slide-in") .removeClass("slide-out");*/ }, _hideMenu: function(){ $(".leftNav").animate({left: "-297px"},"ease-in"); /*cache.jNavigation .removeClass("slide-in") .addClass("slide-out");*/ }, _toggleVideohomeMenu: function(e){ e.preventDefault(); cache.jVideohomeLink .toggleClass("active_dropdown"); $('.video_nav_list').slideToggle("ease-in"); $('.arrow').toggleClass('active'); /*cache.jVideohomeLink .toggleClass('active'); cache.jVideoNav .slideToggle("ease-in") .removeClass("hidden");*/ }, _closeOpenWidgets: function(e){ var clickedEle = $(e.target); if(!clickedEle.hasClass("jHamburgerMenuIcon")){ fn._hideMenu(); } /*if(!clickedEle.hasClass("jVideohomeLink")){ $('.video_nav_list').slideUp("ease-in"); cache.jVideohomeLink .removeClass("active_dropdown"); }*/ if(!clickedEle.hasClass("arrow")){ $('.video_nav_list').slideUp("ease-in"); cache.jVideohomeLink .removeClass("active_dropdown"); $('.arrow').removeClass('active'); } if( !clickedEle.hasClass("jSearchLens") ){ TimesApps.VideoSearch.closeAutoSuggestorBox(e); } }, _hideErrorMsgs: function(){ cache.errorMsg .addClass("hidden"); }, _styleTimeStamp: function(){ require(['tiljs/string'], function(){ $('[rodate]').each(function(i){ //copied from toijs var plugin = $(this); var time = plugin.attr( "rodate" ); var match = time.match( /^(\d+)-(\d+)-(\d+) (\d+)\:(\d+)\:(\d+)$/ ); var rod = {}; if( !!time && !match ) { time = !isNaN(time) ? parseInt(time) : time; var timeObj = new Date( time ); if( !isNaN( timeObj.getTime() ) ){ rod = timeObj; }else{ if( time.indexOf("hrs IST") != -1 ){ time = time.replace( " hrs IST", "" ); if(time.search(":") < 0){ time = time.splice( -2, 0, ":" ); //21 Apr, 2014, 16:31 } } time = time.replace( "IST", "" ); time = time.replace( "hrs", "" ); time = time.replace( "AM", " AM" ); time = time.replace( "PM", " PM" ); rod = new Date( time ); } match = [ '', rod.getYear() + 1900, rod.getMonth() + 1, rod.getDate(), rod.getHours(), rod.getMinutes(), rod.getSeconds() ]; } if( match && match instanceof Array && match.length >= 5 ){ var videoTimestamp = new Date( match[ 1 ], match[ 2 ] - 1, match[ 3 ], match[ 4 ], match[ 5 ], match[ 6 ] ).getTime(); var interval = new Date().getTime() - videoTimestamp; //interval less than an hour if( interval < 60*60*1000 ){ $(this).addClass('redColor'); } } }) }); }, _truncateTitle: function(){ if( navigator.userAgent.indexOf('AppleWebKit') >= 0 ){ return; } var titles = $(".w_tle a"); for(var i=0; i < titles.length; i++){ if( titles.eq(i).text().length > 55 ){ var truncated = titles.eq(i).text().substr(0, 55); titles.eq(i).text(truncated+"..."); } } }, _scrollToTop: function(){ $('html, body').animate({ scrollTop: 0 }, 1250); }, _displayCheckForBackToTop: function(){ if(TimesApps.Utils.checkFirstViewPort()){ cache.backToTop .addClass('active'); }else{ cache.backToTop .removeClass('active'); } }, _hideVideoViews : function(){ var videoViewNodes = $(".urcount"); for(var i = 0; i < videoViewNodes.length; i++){ var videoViews = videoViewNodes.eq(i).text() ? videoViewNodes.eq(i).text().match(/\d+/)[0] : 0; if( parseInt(videoViews) < 100 ){ videoViewNodes.eq(i).addClass("hidden"); } } }, } api = { init : function(){ return fn._init(); }, styleTimeStamp: function(){ fn._styleTimeStamp(); }, truncateTitle: function(){ fn._truncateTitle(); } } return api; }()); TimesApps.setpgAttributes = (function(){ var fn, api, cache; cache = { jHamburgerMenuIcon : $('.jHamburgerMenuIcon'), jDropMenu : $('.jDropMenu'), jSwitchvideo : $('.jSwitchvideo'), jSwitchaudio : $('.jSwitchaudio'), jVideohomeLink : $('.jVideohomeLink'), jBackToTop : $('.jBackToTop'), jviewmoreButtons : $('.jviewmore') }; fn = { _attachPgAttributes: function(){ var seolocation = TimesApps.Utils.getSeolocation(); cache.jHamburgerMenuIcon .attr('pg','HamburgerClick#NA~'+seolocation); cache.jDropMenu .attr('pg','VideoNavClick#VideosMenu~'+seolocation); cache.jSwitchvideo .attr('pg','VideoNavClick#LiveTV~'+seolocation); cache.jSwitchaudio .attr('pg','VideoNavClick#LiveAudio~'+seolocation); cache.jVideohomeLink .attr('pg','VideoNavClick#Videos~'+seolocation); cache.jBackToTop .attr('pg','BackToTop#NA~'+seolocation); cache.jviewmoreButtons.each(function(){ var category = 'MoreVideosClick', action = TimesApps.Utils.getSeolocation(), label = $(this).attr('href'), pgAttribute = category + '#' + label + '~' + action; $(this).attr('pg',pgAttribute); }) } }; api = { attachPgAttributes: function(){ return fn._attachPgAttributes(); } }; return api; }()); $(document).ready(function(){ TimesApps.VideoHome.init(); TimesApps.VideoHome.styleTimeStamp(); TimesApps.VideoHome.truncateTitle(); var pageType = $('#pageType').val() || ""; var source = $("#source").val() || ""; pageType = pageType.toUpperCase(); if(pageType == 'VIDEOHOME' || pageType == 'VIDEOLIST' || source == "LIVEHOME_LIVE_TV"){ TimesApps.scrollEventsModule.init(); } if( pageType == 'VIDEOHOME' || source == "LIVEHOME_LIVE_TV" ){ TimesApps.VideoListManager.init(); }else if( pageType == 'VIDEOLIST' ){ TimesApps.VideoListManager.sortSectionByGeo(); } TimesApps.VideoSearch.init(); var pageName = $("#pageName").val() || ""; pageName = pageName.toUpperCase(); switch(pageName){ case "VIDEOSHOW": TimesApps.VideoShow.init(); break; } TimesApps.setpgAttributes.attachPgAttributes(); $(".jfeedback").click(function(){ $(this).addClass("active"); return false; }); $(".jfeedback-close").click(function(){ $(".jfeedback").removeClass("active"); }) }); TimesApps.scrollEventsModule = (function(){ var fn, api, constants, data, jsonConfig; jsonConfig = [ { limit: 100, count: 0 }, { limit: 75, count: 0 }, { limit: 50, count: 0 }, { limit: 25, count: 0 } ] data = { previous_scroll : 0 } bindInitialEvents = function(){ require(["tiljs/event"], function(eventBus){ eventBus.subscribe("window.scroll", fn._onScrollEvents); }); } fn = { _checkScrollDirection: function(){ var diff = TimesApps.Utils.getScrolledHeight() - data.previous_scroll; data.previous_scroll = TimesApps.Utils.getScrolledHeight(); return diff; }, _onScrollEvents: function(){ var scrolledHeight = TimesApps.Utils.getScrolledHeight(); var documentHeight = TimesApps.Utils.getDocumentHeight(); var heightTillVisibleBottom = scrolledHeight + TimesApps.Utils.getClientHeight(); var scrolledPercentage = ( heightTillVisibleBottom / documentHeight ) * 100; scrolledPercentage = parseInt(scrolledPercentage); if(fn._checkScrollDirection() > 0){ fn._traverseJsonConfig(scrolledPercentage); } }, _traverseJsonConfig : function(scrolledPercentage){ for(var i=0 ; i < jsonConfig.length ; i++){ var value = jsonConfig[i]; if(scrolledPercentage >= value.limit && value.count == 0){ value.count = value.count + 1; if(value.count == 1){ fn._fireGaEvents(value.limit); } } } }, _fireGaEvents: function(scrolledPercentage){ var ga = window.ga; var eventCat = 'ScrollDepth'; var eventAction = scrolledPercentage + '%'; var eventLabel = TimesApps.Utils.getSeolocation(); if( typeof ga == "undefined" ){ return; } ga('send', { hitType: 'event', eventCategory: eventCat, eventAction: eventAction, eventLabel: eventLabel }); }, _init: function(){ bindInitialEvents(); } } api = { init: function(){ return fn._init(); } } return api; }())