').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 = '
Previous';
var next = '
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;
}())