(function($){
$.fn.ticker = function(options) {
// Extend our default options with those provided.
// Note that the first arg to extend is an empty object -d
// this is to keep from overriding our "defaults" object.
var opts = $.extend({}, $.fn.ticker.defaults, options);
// check that the passed element is actually in the DOM
if ($(this).length == 0) {
if (window.console && window.console.log) {
window.console.log('Element does not exist in DOM!');
}
else {
alert('Element does not exist in DOM!');
}
return false;
}
/* Get the id of the UL to get our news content from */
var newsID = '#' + $(this).attr('id');
/* Get the tag type - we will check this later to makde sure it is a UL tag */
var tagType = $(this).get(0).tagName;
return this.each(function() {
// get a unique id for this ticker
var uniqID = getUniqID();
/* Internal vars */
var settings = {
position: 0,
time: 0,
distance: 0,
newsArr: {},
play: true,
paused: false,
contentLoaded: false,
dom: {
contentID: '#ticker-content-' + uniqID,
titleID: '#ticker-title-' + uniqID,
titleElem: '#ticker-title-' + uniqID + ' SPAN',
tickerID : '#ticker-' + uniqID,
wrapperID: '#ticker-wrapper-' + uniqID,
revealID: '#ticker-swipe-' + uniqID,
revealElem: '#ticker-swipe-' + uniqID + ' SPAN',
controlsID: '#ticker-controls-' + uniqID,
prevID: '#prev-' + uniqID,
nextID: '#next-' + uniqID,
playPauseID: '#play-pause-' + uniqID
}
};
// if we are not using a UL, display an error message and stop any further execution
if (tagType != 'UL' && tagType != 'OL' && opts.htmlFeed === true) {
debugError('Cannot use <' + tagType.toLowerCase() + '> type of element for this plugin - must of type
or ');
return false;
}
// set the ticker direction
opts.direction == 'rtl' ? opts.direction = 'right' : opts.direction = 'left';
// lets go...
initialisePage();
/* Function to get the size of an Object*/
function countSize(obj) {
var size = 0, key;
for (key in obj) {
if (obj.hasOwnProperty(key)) size++;
}
return size;
};
function getUniqID() {
var newDate = new Date;
return newDate.getTime();
}
/* Function for handling debug and error messages */
function debugError(obj) {
if (opts.debugMode) {
if (window.console && window.console.log) {
window.console.log(obj);
}
else {
alert(obj);
}
}
}
/* Function to setup the page */
function initialisePage() {
// process the content for this ticker
processContent();
// add our HTML structure for the ticker to the DOM
$(newsID).wrap('');
// remove any current content inside this ticker
$(settings.dom.wrapperID).children().remove();
$(settings.dom.wrapperID).append('
');
$(settings.dom.wrapperID).removeClass('no-js').addClass('ticker-wrapper has-js ' + opts.direction);
// hide the ticker
$(settings.dom.tickerElem + ',' + settings.dom.contentID).hide();
// add the controls to the DOM if required
if (opts.controls) {
// add related events - set functions to run on given event
$(settings.dom.controlsID).live('click mouseover mousedown mouseout mouseup', function (e) {
var button = e.target.id;
if(!button){
button = $(e.target).closest('[id]').attr('id');
}
if (e.type == 'click') {
switch (button) {
case settings.dom.prevID.replace('#', ''):
// show previous item
settings.paused = true;
$(settings.dom.playPauseID).addClass('paused');
manualChangeContent('prev');
break;
case settings.dom.nextID.replace('#', ''):
// show next item
settings.paused = true;
$(settings.dom.playPauseID).addClass('paused');
manualChangeContent('next');
break;
case settings.dom.playPauseID.replace('#', ''):
// play or pause the ticker
if (settings.play == true) {
settings.paused = true;
$(settings.dom.playPauseID).addClass('paused');
pauseTicker();
}
else {
settings.paused = false;
$(settings.dom.playPauseID).removeClass('paused');
restartTicker();
}
break;
}
}
else if (e.type == 'mouseover' && $('#' + button).hasClass('controls')) {
$('#' + button).addClass('over');
}
else if (e.type == 'mousedown' && $('#' + button).hasClass('controls')) {
$('#' + button).addClass('down');
}
else if (e.type == 'mouseup' && $('#' + button).hasClass('controls')) {
$('#' + button).removeClass('down');
}
else if (e.type == 'mouseout' && $('#' + button).hasClass('controls')) {
$('#' + button).removeClass('over');
}
});
// add controls HTML to DOM
$(settings.dom.wrapperID).append('
');
}
if (opts.displayType != 'fade') {
//Anurag - Commented mouse over and mouse out events on displayType:Reveal
// add mouse over on the content
/* $(settings.dom.contentID).mouseover(function () {
if (settings.paused == false) {
pauseTicker();
}
}).mouseout(function () {
if (settings.paused == false) {
restartTicker();
}
}); */
}
// we may have to wait for the ajax call to finish here
if (!opts.ajaxFeed) {
//settings.nextnewslock = 0;
setupContentAndTriggerDisplay();
}
}
/* Start to process the content for this ticker */
function processContent() {
// check to see if we need to load content
if (settings.contentLoaded == false) {
// construct content
if (opts.ajaxFeed) {
if (opts.feedType == 'xml') {
$.ajax({
url: opts.feedUrl,
cache: false,
dataType: opts.feedType,
async: true,
success: function(data){
count = 0;
// get the 'root' node
for (var a = 0; a < data.childNodes.length; a++) {
if (data.childNodes[a].nodeName == 'rss') {
xmlContent = data.childNodes[a];
}
}
// find the channel node
for (var i = 0; i < xmlContent.childNodes.length; i++) {
if (xmlContent.childNodes[i].nodeName == 'channel') {
xmlChannel = xmlContent.childNodes[i];
}
}
// for each item create a link and add the article title as the link text
for (var x = 0; x < xmlChannel.childNodes.length; x++) {
if (xmlChannel.childNodes[x].nodeName == 'item') {
xmlItems = xmlChannel.childNodes[x];
var title, link = false;
for (var y = 0; y < xmlItems.childNodes.length; y++) {
if (xmlItems.childNodes[y].nodeName == 'title') {
title = xmlItems.childNodes[y].lastChild.nodeValue;
}
else if (xmlItems.childNodes[y].nodeName == 'link') {
link = xmlItems.childNodes[y].lastChild.nodeValue;
}
if ((title !== false && title != '') && link !== false) {
settings.newsArr['item-' + count] = { type: opts.titleText, content: '' + title + '' }; count++; title = false; link = false;
}
}
}
}
// quick check here to see if we actually have any content - log error if not
if (countSize(settings.newsArr < 1)) {
debugError('Couldn\'t find any content from the XML feed for the ticker to use!');
return false;
}
settings.contentLoaded = true;
setupContentAndTriggerDisplay();
}
});
}
else {
debugError('Code Me!');
}
}
else if (opts.htmlFeed) {
if($(newsID + ' LI').length > 0) {
$(newsID + ' LI').each(function (i) {
// maybe this could be one whole object and not an array of objects?
settings.newsArr['item-' + i] = { type: opts.titleText, content: $(this).html()};
});
}
else {
debugError('Couldn\'t find HTML any content for the ticker to use!');
return false;
}
}
else {
debugError('The ticker is set to not use any types of content! Check the settings for the ticker.');
return false;
}
}
}
function setupContentAndTriggerDisplay() {
settings.contentLoaded = true;
settings.nextnewslock = 0;//anurag - my default variable to stop animation
//settings.noAniforFirst = 0;
// update the ticker content with the correct item
// insert news content into DOM
$(settings.dom.titleElem).html(settings.newsArr['item-' + settings.position].type);
$(settings.dom.contentID).html(settings.newsArr['item-' + settings.position].content);
var dataLen = $(settings.dom.contentID).text();
$('.ticker-content').css('margin-left','0px');
$('.ticker-content span').css('margin-left','0px');
var desk_data_len = 90;
// var iOS = ( navigator.userAgent.match(/(iPad)/g) ? true : false );
// if(iOS){$('.ticker-content span').css('font-size','55%');
// $('.ticker-title span').css('font-size','80%');
// $('.ticker-title').css('width','180px');
//desk_data_len = 45;
// }
var win_outer_wid= window.innerWidth;
if(win_outer_wid >= 768 && win_outer_wid <= 999) {
desk_data_len = 40;
// $('.ticker-content span').css('font-size','75%');
// $('.ticker-title span').css('font-size','80%');
// $('.ticker-title').css('width','180px');
}
// console.log(dataLen.length);
var abc =1;
if((dataLen.length > desk_data_len) && abc==1){
//console.log('News');
settings.nextnewslock = 1;
var iOS = ( navigator.userAgent.match(/(iPad)/g) ? true : false );
if(iOS){timer = 3000;}
else{timer = 6500;}
//timer = 6500;//(90/13)*1000;
shift=0;
setTimeout(function(){
mycount = function(len,shift) {
//var iOS = ( navigator.userAgent.match(/(iPad)/g) ? true : false );
//if(iOS){shift+=12.5;}
//else{shift+=9.5;}
//console.log(iOS);
var win_outer_wid= window.innerWidth;
if(win_outer_wid >= 768 && win_outer_wid <= 999) {
shift+=8.5;
}else{
shift+=11.5;
}
len++;
// console.log(shift +" :"+ len);
// $('.ticker-content span').css('margin-left','-'+shift+'px');
if((dataLen.length- desk_data_len) >= len ){
shift = mycount(len++,shift);
}
return shift;
};
var shift_main = mycount(1,0);
if(settings.nextnewslock == 1 )
{
//console.log(settings.noAniforFirst);
// if(settings.noAniforFirst == 0){
$(".ticker-content span").css('margin-left', '').delay(1).animate( {marginLeft:'-'+shift_main+'px'}, ((dataLen.length-desk_data_len)*310),'linear',function(){try{if(homeObj.breakingNewsPause == 1){$('.ticker-content span').css('margin-left','0px');}}catch(e){console.log(e);}});
// }
}
// settings.noAniforFirst++;
// $(".ticker-content span").animate( {marginLeft:'-'+shift_main+'px'}, 6000,'linear',function(){try{if(homeObj.breakingNewsPause == 1){$('.ticker-content span').css('margin-left','0px');}}catch(e){console.log(e);}});
// $(".ticker-content span").animate( {marginLeft:'-'+shift_main+'px'}, 5000,'linear',function(){});
}, timer);
}
// set the next content item to be used - loop round if we are at the end of the content
if (settings.position == (countSize(settings.newsArr) -1)) {
settings.position = 0;
}
else {
settings.position++;
}
// get the values of content and set the time of the reveal (so all reveals have the same speed regardless of content size)
distance = $(settings.dom.contentID).width();
time = distance / opts.speed;
// start the ticker animation
revealContent();
}
// slide back cover or fade in content
function revealContent() {
//console.log('reveal content');
$(settings.dom.contentID).css('opacity', '1');
if(settings.play) {
// get the width of the title element to offset the content and reveal
var offset = $(settings.dom.titleID).width() + 45;
$(settings.dom.revealID).css(opts.direction, offset + 'px');
// show the reveal element and start the animation
if (opts.displayType == 'fade') {
//console.log('reveal content if');
// fade in effect ticker
$(settings.dom.revealID).hide(0, function () {
$(settings.dom.contentID).css(opts.direction, offset + 'px').fadeIn(opts.fadeInSpeed, postReveal);
});
}
else if (opts.displayType == 'scroll') {
// to code
}
else {
//console.log('reveal content else');
// default bbc scroll effect
$(settings.dom.revealElem).show(0, function () {
$(settings.dom.contentID).css(opts.direction, offset + 'px').show();
// set our animation direction
animationAction = opts.direction == 'right' ? { marginRight: distance + 'px'} : { marginLeft: distance + 'px' };
$(settings.dom.revealID).css('margin-' + opts.direction, '0px').delay(20).animate(animationAction, time, 'linear', postReveal);
});
}
}
else {
return false;
}
};
// here we hide the current content and reset the ticker elements to a default state ready for the next ticker item
function postReveal() {
if(settings.play) {
// we have to separately fade the content out here to get around an IE bug - needs further investigation
//console.log('a:'+opts.pauseOnItems);
$(settings.dom.contentID).delay(2500).fadeOut(opts.fadeOutSpeed);
// $(settings.dom.contentID).fadeOut(opts.fadeOutSpeed);//anurag-removing delay
// deal with the rest of the content, prepare the DOM and trigger the next ticker
if (opts.displayType == 'fade') {
$(settings.dom.contentID).fadeOut(opts.fadeOutSpeed, function () {
$(settings.dom.wrapperID)
.find(settings.dom.revealElem + ',' + settings.dom.contentID)
.hide()
.end().find(settings.dom.tickerID + ',' + settings.dom.revealID)
.show()
.end().find(settings.dom.tickerID + ',' + settings.dom.revealID)
.removeAttr('style');
setupContentAndTriggerDisplay();
});
}
else {
$(settings.dom.revealID).hide(0, function () {
$(settings.dom.contentID).fadeOut(opts.fadeOutSpeed, function () {
$(settings.dom.wrapperID)
.find(settings.dom.revealElem + ',' + settings.dom.contentID)
.hide()
.end().find(settings.dom.tickerID + ',' + settings.dom.revealID)
.show()
.end().find(settings.dom.tickerID + ',' + settings.dom.revealID)
.removeAttr('style');
//console.log('2');
setupContentAndTriggerDisplay();
});
});
}
}
else {
$(settings.dom.revealElem).hide();
}
}
// pause ticker
function pauseTicker() {
//console.log("Breaking News:Pause the Breaking News Ticker");
//Pause the Breaking News AJAX Call and Refresh
homeObj.breakingNewsPause = 1;
settings.play = false;
// stop animation and show content - must pass "true, true" to the stop function, or we can get some funky behaviour
$(settings.dom.tickerID + ',' + settings.dom.revealID + ',' + settings.dom.titleID + ',' + settings.dom.titleElem + ',' + settings.dom.revealElem + ',' + settings.dom.contentID).stop(true, true);
$(settings.dom.revealID + ',' + settings.dom.revealElem).hide();
$(settings.dom.wrapperID)
.find(settings.dom.titleID + ',' + settings.dom.titleElem).show()
.end().find(settings.dom.contentID).show();
}
// play ticker
function restartTicker() {
settings.nextnewslock = 0;
//$( ".ticker-content span" ).stop();
//console.log("Breaking News:Play the Breaking News Ticker");
settings.play = true;
settings.paused = false;
//Play the Breaking News AJAX Call and Refresh
homeObj.breakingNewsPause = 0;
// start the ticker again
postReveal();
}
// change the content on user input
function manualChangeContent(direction) {
pauseTicker();
//Pause the Breaking News AJAX Call and Refresh
homeObj.breakingNewsPause = 1;
//Set margin to zero when next/previous is clicked while news is scrolling
$('.ticker-content span').css('margin-left','0px');
switch (direction) {
case 'prev':
if (settings.position == 0) {
settings.position = countSize(settings.newsArr) -2;
}
else if (settings.position == 1) {
settings.position = countSize(settings.newsArr) -1;
}
else {
settings.position = settings.position - 2;
}
$(settings.dom.titleElem).html(settings.newsArr['item-' + settings.position].type);
$(settings.dom.contentID).html(settings.newsArr['item-' + settings.position].content);
break;
case 'next':
$(settings.dom.titleElem).html(settings.newsArr['item-' + settings.position].type);
$(settings.dom.contentID).html(settings.newsArr['item-' + settings.position].content);
break;
}
// set the next content item to be used - loop round if we are at the end of the content
if (settings.position == (countSize(settings.newsArr) -1)) {
settings.position = 0;
}
else {
settings.position++;
}
}
});
};
// plugin defaults - added as a property on our plugin function
$.fn.ticker.defaults = {
speed: 0.10,
ajaxFeed: false,
feedUrl: '',
feedType: 'xml',
displayType: 'reveal',
htmlFeed: true,
debugMode: true,
controls: true,
titleText: 'Breaking News',
direction: 'ltr',
pauseOnItems: 3000,
fadeInSpeed: 600,
fadeOutSpeed: 300
};
})(jQuery);
var timesTop10popup_callbacks;
var coronapopup_callbacks;
require({'config':{'version':{'vtime':1447750589885,'vdate':'Tue Nov 17 2015 14:26:29 GMT+0530 (India Standard Time)'}}});
( function () {
var shim = {};
var paths = {};
var deps = [];
var min = ".min";
// var min = "";
var preload = [
{
module: "json",
variable: "JSON",
js: "//cdnjs.cloudflare.com/ajax/libs/json2/20121008/json2" + min
}
,
{
module: "jquery",
variable: "jQuery",
js: [ "//ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery" + min
, "//cdnjs.cloudflare.com/ajax/libs/jquery/1.8.2/jquery" + min ]
}
];
for( var i = 0; i < preload.length; i++ ) {
var pre = preload[ i ];
if( !window[ pre.variable ] ) {
paths[ pre.module ] = pre.js;
shim[ pre.module ] = {
"exports": pre.variable
};
deps.push( pre.module );
} else {
define( pre.module, ( function ( pre, min ) {
return function () {
return window[ pre.variable ]
};
}( pre, min ) ) );
}
}
require( {
deps: deps,
shim: shim,
paths: paths
} );
}() );
define("preload", function(){});
require( {
shim: {
// "jquery": {"exports":"jQuery"},
// "json": {"exports":"JSON"} ,
"jsrender": {
"exports": "jQuery.fn.render",
deps: [ 'jquery' ]
}
},
paths: {
// times: 'apps/times', //used so that app module name looks nice
// toi: 'apps/toi', //used so that app module name looks nice
// jquery: [
// "//jeetbetwin.com/jquery_toi.cms?minify=1",
// "//ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js",
// "//cdnjs.cloudflare.com/ajax/libs/jquery/2.0.3/jquery.min"
// ],
// json: "//cdnjs.cloudflare.com/ajax/libs/json2/20121008/json2",
jsrender: "/jsrender.cms?"
},
config: {
"tiljs/page": {
channel: "TOI",
// siteId:"ef55d27920fbf01f58c0da43430f5c6a",
siteId: "541cc79a8638cfd34bdc56d1a27c8cd7",
domain: "jeetbetwin.com"
},
"tiljs/plugin/lazy": {
skew: 0,
error_image: $('[data-default-image-msid]').length ? ("/photo/" + $('[data-default-image-msid]').attr('data-default-image-msid') + ".cms") : "/photo/34824568.cms"
},
"tiljs/social/facebook": {
xfbml: true,
parse: false,
appid: 117787264903013,
load_js: false,
init:false
},
"tiljs/social/twitter": {
parse: false,
load_js: false,
init:false
},
"tiljs/analytics/mytimes": {
"appKey": "TOI"
},
"tiljs/apps/times/comments": {
loadCommentFromMytimes: true,
commentType:"comments_agree"
},
"tiljs/apps/times/api": {
post_comment: {
url: "/postro2.cms",
params: {
medium: 'WEB'
}
},
comments: {
url: "/commentsdata.cms",
// url:"http://192.168.27.159/mytimes/getFeed/Activity",
type: "json",
params: {
appkey: "TOI",
msid: window.msid,
sortcriteria: "CreationDate",
order: "asc",
size: 25,
lastdeenid: 123,
after: true,
withReward: true
}
},
comments_oldest: {
url: "/commentsdata.cms",
type: "json",
params: {
appkey: "TOI",
msid: window.msid,
sortcriteria: "CreationDate",
order: "desc",
size: 25,
lastdeenid: 123,
after: true,
withReward: true
}
},
comments_agree: {
url: "/commentsdata.cms",
type: "json",
params: {
appkey: "TOI",
msid: window.msid,
sortcriteria: "AgreeCount",
order: "desc",
size: 25,
lastdeenid: 123,
after: true,
withReward: true,
medium: 'WEB'
}
},
comments_disagree: {
url: "/commentsdata.cms",
type: "json",
params: {
appkey: "TOI",
msid: window.msid,
sortcriteria: "DisagreeCount",
order: "desc",
size: 25,
lastdeenid: 123,
after: true,
withReward: true
}
},
comments_discussed: {
url: "/commentsdata.cms",
type: "json",
params: {
appkey: "TOI",
msid: window.msid,
sortcriteria: "discussed",
order: "desc",
size: 25,
lastdeenid: 123,
after: true,
withReward: true
}
}
}
}
} );
define('config',[],function(){return {};});
define('compatibility',[],function(){return {};});
define("ajax", ["tiljs/ajax"], function (m) {
return m;
});
define("localstorage", ["tiljs/localstorage"], function (m) {
return m;
});
define("util", ["tiljs/util"], function (m) {
return m;
});
define("is", ["tiljs/is"], function (m) {
return m;
});
define("ui", ["tiljs/ui"], function (m) {
return m;
});
define("cookie", ["tiljs/cookie"], function (m) {
return m;
});
define("event", ["tiljs/event"], function (m) {
return m;
});
define("plugin/lazy", ["tiljs/plugin/lazy"], function (m) {
return m;
});
define("load", ["tiljs/load"], function (m) {
return m;
});
define("toicommonjs/rodate", ["rodate"], function (m) {
return m;
});
define("logger", ["tiljs/logger"], function (m) {
return m;
});
define("page", ["tiljs/page"], function (m) {
return m;
});
define("user", ["tiljs/user"], function (m) {
return m;
});
define("times/comments", ["comments"], function (m) {
return m;
});
define("authorcomments", ["tiljs/apps/times/authorcomments"], function (m) {
return m;
});
//define("personalisation", ["./personalisation"], function (m) {
// return m;
//});
/**
* 'cookie' module.
*
* @module cookie
*/
define( 'tiljs/cookie',[], function () {
var mod_cookie = {};
// var default_config = {
// localstorage : false //use localstorage if available or else cookie
// };
//
// var config = $.extend({}, default_config, module.config());
/**
* Get value of a cookie
*
* @memberOf module:cookie#
* @function get
*
* @param name {String} name of the cookie for which value is required,
* if name is not provided an object with all cookies is returned
* @returns value {String | Array} value of the requested cookie / Array of all cookies
*
* @example
*
* require(['cookie'],function(cookie){
* var abc_cookie = cookie.get("abc");
* });
*/
mod_cookie.get = function ( name ) {
var result = name ? undefined : {};
var cookies = document.cookie ? document.cookie.split( '; ' ) : [];
for( var i = 0, l = cookies.length; i < l; i++ ) {
var parts = cookies[ i ].split( '=' );
var nameK = decodeURIComponent( parts.shift() );
var cookie = parts.join( '=' );
cookie = mod_cookie._parseCookieValue( cookie );
if( name && name === nameK ) {
result = cookie;
break;
}
if( !name && cookie !== undefined ) {
result[ nameK ] = cookie;
}
}
return result;
};
/**
* Cookie Set,Get,Delete
*/
mod_cookie.getAll = function () {
return mod_cookie.get();
};
/**
* Remove a cookie
*
* @memberOf module:cookie#
* @function remove
*
* @param {String} name name of the cookie to be removed
* @param {String} [path] path of the cookie
* @param {String} [domain] domain of the cookie
*
* @example
*
* require(['cookie'],function(cookie){
* cookie.remove("abc");
* });
*/
mod_cookie.remove = function ( name, path, domain ) {
if( name ) {
domain = ( domain || document.location.host ).split( ":" )[ 0 ];
path = path || document.location.pathname;
mod_cookie.set( name, null, -1, path, domain );
}
};
/**
* Set a cookie
*
* @param {String} name name of the cookie to be set
* @param {String} value value of the cookie to be set
* @param {Number} days number of days for which the cookie is to be set
* @param {String} path path of the cookie to be set
* @param {String} domain domain of the cookie to be set
* @param {Boolean} secure true if the cookie is to be set on https only
*/
mod_cookie.set = function ( name, value, days, path, domain, secure ) {
var expires = '';
days = ( days !== undefined ) ? days : 30;
var date = new Date();
date.setTime( date.getTime() + ( days * 24 * 60 * 60 * 1000 ) );
expires = '; expires=' + date.toGMTString();
domain = ( domain || document.location.host ).split( ":" )[ 0 ]; //removing port
path = path || document.location.pathname;
//Removing file name, fix for IE11
if( /\/.*\..*/.test( path ) ) { //if path contains file name
path = path.split( "/" );
path.pop();
path = path.join( "/" );
}
document.cookie = name + '=' +
value + expires +
( ( path ) ? ';path=' + path : '' ) +
( ( domain && domain !='localhost' ) ? ';domain=' + domain : '' ) +
( ( secure ) ? ';secure' : '' );
};
mod_cookie._parseCookieValue = function ( s ) {
if( s.indexOf( '"' ) === 0 ) {
// This is a quoted cookie as according to RFC2068, unescape...
s = s.slice( 1, -1 ).replace( /\\"/g, '"' ).replace( /\\\\/g, '\\' );
}
try {
// If we can't decode the cookie, ignore it, it's unusable.
// Replace server-side written pluses with spaces.
return decodeURIComponent( s.replace( /\+/g, ' ' ) );
} catch( e ) {}
};
return mod_cookie;
} );
/**
* 'event' module.
*
* @module event
*/
define( 'tiljs/event',[], function () {
var mod_event = {},
pubsub = {},
onsubscribe_prefix = "__on_",
generateUid = ( function () {
var id = 0;
return function () {
return id++;
};
} )();
/**
* Publish subscribed events
*
* @param name Method name for the event to be published
* @param data data to be passed to the subscribed event
* @returns null
*/
mod_event.publish = function ( name, data ) {
if( !name ) {
return null;
}
if( pubsub[ name ] ) {
for( var e in pubsub[ name ] ) {
if( pubsub[ name ].hasOwnProperty( e ) ) {
var eventCallback = pubsub[ name ][ e ];
try { //try catch done to keep publisher running in case of error in event callback
eventCallback( data );
} catch( err ) {
mod_event.publish( "logger.error", err.stack );
}
}
}
}
};
mod_event.subscribeAll = function ( name, eventCallback, options ) {
if( name instanceof Array ) {
var eventIds = [];
var responses = [];
for( var i = 0; i < name.length; i++ ) {
eventIds.push( mod_event.subscribe( name[ i ], function ( response ) {
responses.push( response );
if( eventIds.length === responses.length ) { // todo fix, call even when first event is called twice
if( eventCallback ) {
eventCallback( responses );
}
responses = [];
}
}, options ) );
}
return eventIds;
}
return mod_event.subscribe( name, eventCallback, options );
};
/**
* Subscribe custom events
*
* @param name Method name for the event to be subscribed
* @param eventCallback(data) Function to be called when the event is published with the data
* @options options
* @returns eventId unique id generated for every subscription
*/
mod_event.subscribe = function ( name, eventCallback, options ) {
if( name instanceof Array ) {
var eventIds = [];
for( var i = 0; i < name.length; i++ ) {
eventIds.push( mod_event.subscribe( name[ i ], eventCallback, options ) );
}
return eventIds;
}
if( !name || !eventCallback ) {
return null;
}
if( !pubsub[ name ] ) {
pubsub[ name ] = {};
}
var eventId = name + ":" + generateUid();
pubsub[ name ][ eventId ] = eventCallback;
//TODO find better way
//Setting callback in options so that it can be used in onsubscribe event.
if( options ) {
options.__callback = eventCallback;
}
//Calling onsubscribe events
mod_event.publish( onsubscribe_prefix + name, options );
return eventId;
};
/**
* Unsubscribe an event
*
* @param eventId id of the event to be unsubscribed
* @returns boolean true if event is successfully unsubscribed,else false
*/
mod_event.unsubscribe = function ( eventId ) {
if( !eventId ) {
return null;
}
var eventArr = eventId.split( ":" );
if( eventArr.length === 2 ) {
var eventName = eventArr[ 0 ];
// var eventNum = eventArr[1];
if( pubsub[ eventName ][ eventId ] ) {
delete pubsub[ eventName ][ eventId ];
return true;
}
}
return false;
};
/**
* Get all the subscribed events in an object
*
*
* @param name Event name for which all events are required
* @returns Event object for the provided event name
*/
mod_event.getSubscriptions = function ( name ) {
if( !name ) {
return pubsub; //todo return cloned object istead of original
}
return pubsub[ name ];
};
/**
* Used to subscribe to subscribe events, onsubscribe('method1') is called when subscribe('method1') is called
* This can be used to setup data / setup publish events
*
* @param name
* @param eventCallback
* @returns {string}
*/
mod_event.onsubscribe = function ( name, eventCallback ) {
if( !name || !eventCallback ) {
return null;
}
name = onsubscribe_prefix + name;
if( !pubsub[ name ] ) {
pubsub[ name ] = {};
}
var eventId = name + ":" + generateUid();
pubsub[ name ][ eventId ] = eventCallback;
return eventId;
};
return mod_event;
} );
define( 'tiljs/logger',[ "./cookie", "module", "./event", "jquery" ], function ( cookie, module, event, $ ) {
var mod_logger = {}, logCache = [];
var types = [ "log", "debug", "info", "warn", "error" ];
var default_config = {
cookieName: "d",
hashString: "#debugdsfgw456g", //change to url param / use cookie
prefix: "[times_log] ",
//linenum: false,
time: false, //todo to be implemented
handleWindowError: true,
handleJqueryError: true,
logModuleLoad: true,
log: false //can be overridden by cookie or hash when it is false
};
var config = $.extend( {}, default_config, module.config() ); //todo remove jquery dependency
/**
* Returns the stack details for method that calls log
* @param stack
* @returns {string}
* @private
*/
function getStackDetails( stack ) {
var regex = new RegExp( "\/(.*):([0-9]*)\:([0-9]*)", "g" );
//done thrice to get the main calling method and line number
var res = regex.exec( stack );
res = regex.exec( stack );
res = regex.exec( stack );
if( res ) {
res.shift();
}
return res ? res.join( ":" ).replace( config.hashString, "" ) : null;
}
/**
* times.debug
*
* times.log/info/error
*/
mod_logger = {};
mod_logger.disable = function () {
config.log = false;
cookie.remove( config.cookieName, "/" );
var i, type;
for(i in types ) {
if( types.hasOwnProperty( i ) ) {
type = types[ i ];
mod_logger[ type ] = (function(type) {
return function() {
logCache.push.apply(logCache,arguments);
};
})(type);
}
}
return "Logging Disabled";
};
mod_logger.enable = function () {
config.log = true;
cookie.set( config.cookieName, config.hashString, 30, "/" );
var i, type;
for(i in types ) {
if( types.hasOwnProperty( i ) ) {
type = types[ i ];
function fun(){
console.log.apply(this,arguments);
}
mod_logger[ type ] = (function(type) {
var noop = function() {};
var log;
var context = config.prefix;
if (console.log.bind === 'undefined') { // IE < 10
log = Function.prototype.bind.call(console[type], console, context);
}
else {
log = console[type].bind(console, context);
}
//log = console[type].bind(console);
//log = fun.bind(console);
//log = (window.console === undefined) ? noop
// : (Function.prototype.bind !== undefined) ? Function.prototype.bind.call(console[type], console)
// : function() {Function.prototype.apply.call(console[type], console, arguments);};
return log;
})(type);
(function ( type ) {
event.subscribe( "logger." + type, function ( data ) {
Function.prototype.apply.call(mod_logger[type],console, arguments);
});
}( type ));
}
}
return "Logging Enabled";
};
mod_logger.isEnabled = function () {
return config.log || ( window.location.hash.length > 0 && window.location.hash === ( config.hashString ) ) || ( cookie.get( config.cookieName ) === config.hashString );
};
mod_logger.handleWindowError = function () {
window.onerror = function ( msg, url, linenumber, colno, error ) {
mod_logger.error.apply(this,
['Error message: ' + msg +
'\n\tURL: ' + url + ( linenumber ? ":" + linenumber + ":" + colno : "" ) +
'\n\tLine Number: ' + linenumber + ":" + colno +
'\n\tError: ' + error] );
return true;
};
};
mod_logger.handleJqueryError = function () {
$( document ).ajaxError( function ( event, jqxhr, settings, exception ) {
if( exception === "timeout" ) {
mod_logger.error.apply(this, [exception + ": " + settings.url] );
} else {
mod_logger.error.apply(this, [exception] );
}
} );
$( document ).error( function ( event ) {
mod_logger.error.apply(this, event );
} );
};
/**
window.require.onResourceLoad = function (context, map, depArray) {
console.log(map.name);
};
*/
function init_log() {
config.log = mod_logger.isEnabled();
if(config.log){
mod_logger.enable();
}else{
mod_logger.disable();
}
if( config.handleWindowError === true ) {
mod_logger.handleWindowError();
//Doing it again on window load
event.subscribe( "window.load", function () {
mod_logger.handleWindowError();
});
}
if( config.handleJqueryError === true ) {
mod_logger.handleJqueryError();
}
}
/**
* As of date we are saving only logs which are not being cached.
*
* //TODO save all logs to cache
*/
mod_logger.getLogs = function(){
return logCache.slice(0);//slice to create a new reference
};
mod_logger.getLogsStr = function(){
return mod_logger.getLogs().join("\n");
};
init_log();
return mod_logger;
});
/** 'is' module.
* @module is
* @exports is
*/
define( 'tiljs/is',[], function () {
var mod_is = {};
/**
* Checks if the param is a number.
*
* @memberOf module:is#
* @function number
* @param ele {object} Any element which is to be checked
* @returns {boolean}
* @example
*
* require(['is'],function(is){
* is.number(1); //returns true
* is.number('abc'); //returns false
* });
*/
mod_is.number = function ( ele ) {
return typeof ele === "number";
};
/**
* Checks if the param is a string.
*
* @memberOf module:is#
* @function string
* @param ele {object} Any element which is to be checked
* @returns {boolean}
* @example
*
* require(['is'],function(is){
* is.number(1); //returns false
* is.number('abc'); //returns true
* });
*/
mod_is.string = function ( ele ) {
return typeof ele === "string";
};
mod_is.funct = mod_is.method = function ( ele ) {
return typeof ele === "function";
};
mod_is.object = function ( ele ) {
return ele !== null && typeof ele === "object"; //&& !(ele instanceof Array);
};
mod_is.array = Array && Array.isArray ? Array.isArray : function ( ele ) {
return ele instanceof Array;
};
mod_is.undefined = function ( ele ) {
return typeof ele === "undefined";
};
mod_is.defined = function ( ele ) {
return typeof ele !== "undefined";
};
mod_is.exists = function ( ele ) {
return mod_is.defined( ele ) || ele === "";
};
mod_is.empty = function ( ele ) {
if( !mod_is.defined( ele ) ) {
return true;
} else if( mod_is.string( ele ) || mod_is.array( ele ) ) {
return ele.length === 0;
} else if( mod_is.object( ele ) ) {
var i = 0,
e;
for( e in ele ) {
if( ele.hasOwnProperty( e ) ) {
i++;
}
}
return i === 0;
} else if( mod_is.number( ele ) ) {
return false;
} else {
return true;
}
};
mod_is.alphaOnly = function ( str ) {
return /^[A-z\s]+$/.test( str );
};
mod_is.numberOnly = function ( str ) {
return /^[0-9]+$/.test( str );
};
mod_is.mobile = function () {
return( function ( a ) {
return /(android|bb\d+|meego).+mobile|avantgo|bada\/|blackberry|blazer|compal|elaine|fennec|hiptop|iemobile|ip(hone|od)|iris|kindle|lge |maemo|midp|mmp|mobile.+firefox|netfront|opera m(ob|in)i|palm( os)?|phone|p(ixi|re)\/|plucker|pocket|psp|series(4|6)0|symbian|treo|up\.(browser|link)|vodafone|wap|windows (ce|phone)|xda|xiino/i.test( a ) || /1207|6310|6590|3gso|4thp|50[1-6]i|770s|802s|a wa|abac|ac(er|oo|s\-)|ai(ko|rn)|al(av|ca|co)|amoi|an(ex|ny|yw)|aptu|ar(ch|go)|as(te|us)|attw|au(di|\-m|r |s )|avan|be(ck|ll|nq)|bi(lb|rd)|bl(ac|az)|br(e|v)w|bumb|bw\-(n|u)|c55\/|capi|ccwa|cdm\-|cell|chtm|cldc|cmd\-|co(mp|nd)|craw|da(it|ll|ng)|dbte|dc\-s|devi|dica|dmob|do(c|p)o|ds(12|\-d)|el(49|ai)|em(l2|ul)|er(ic|k0)|esl8|ez([4-7]0|os|wa|ze)|fetc|fly(\-|_)|g1 u|g560|gene|gf\-5|g\-mo|go(\.w|od)|gr(ad|un)|haie|hcit|hd\-(m|p|t)|hei\-|hi(pt|ta)|hp( i|ip)|hs\-c|ht(c(\-| |_|a|g|p|s|t)|tp)|hu(aw|tc)|i\-(20|go|ma)|i230|iac( |\-|\/)|ibro|idea|ig01|ikom|im1k|inno|ipaq|iris|ja(t|v)a|jbro|jemu|jigs|kddi|keji|kgt( |\/)|klon|kpt |kwc\-|kyo(c|k)|le(no|xi)|lg( g|\/(k|l|u)|50|54|\-[a-w])|libw|lynx|m1\-w|m3ga|m50\/|ma(te|ui|xo)|mc(01|21|ca)|m\-cr|me(rc|ri)|mi(o8|oa|ts)|mmef|mo(01|02|bi|de|do|t(\-| |o|v)|zz)|mt(50|p1|v )|mwbp|mywa|n10[0-2]|n20[2-3]|n30(0|2)|n50(0|2|5)|n7(0(0|1)|10)|ne((c|m)\-|on|tf|wf|wg|wt)|nok(6|i)|nzph|o2im|op(ti|wv)|oran|owg1|p800|pan(a|d|t)|pdxg|pg(13|\-([1-8]|c))|phil|pire|pl(ay|uc)|pn\-2|po(ck|rt|se)|prox|psio|pt\-g|qa\-a|qc(07|12|21|32|60|\-[2-7]|i\-)|qtek|r380|r600|raks|rim9|ro(ve|zo)|s55\/|sa(ge|ma|mm|ms|ny|va)|sc(01|h\-|oo|p\-)|sdk\/|se(c(\-|0|1)|47|mc|nd|ri)|sgh\-|shar|sie(\-|m)|sk\-0|sl(45|id)|sm(al|ar|b3|it|t5)|so(ft|ny)|sp(01|h\-|v\-|v )|sy(01|mb)|t2(18|50)|t6(00|10|18)|ta(gt|lk)|tcl\-|tdg\-|tel(i|m)|tim\-|t\-mo|to(pl|sh)|ts(70|m\-|m3|m5)|tx\-9|up(\.b|g1|si)|utst|v400|v750|veri|vi(rg|te)|vk(40|5[0-3]|\-v)|vm40|voda|vulc|vx(52|53|60|61|70|80|81|83|85|98)|w3c(\-| )|webc|whit|wi(g |nc|nw)|wmlb|wonu|x700|yas\-|your|zeto|zte\-/i.test( a.substr( 0, 4 ) );
} )( navigator.userAgent || navigator.vendor || window.opera );
};
mod_is.tablet = function () {
return( function ( a ) {
return /(?:ipad|tab)/i.test( a );
} )( navigator.userAgent || navigator.vendor || window.opera );
};
mod_is.desktop = function () {
return !mod_is.mobile() && !mod_is.tablet();
};
mod_is.touch = function () {
return (('ontouchstart' in window) || ('DocumentTouch' in window));
};
mod_is.IE = function () {
var ua = window.navigator.userAgent;
var msie = ua.indexOf( "MSIE " );
if( msie > 0 || !!navigator.userAgent.match( /Trident.*rv\:11\./ ) ) { // If Internet Explorer, return version number
return true;
} else { // If another browser, return 0
return false;
}
};
mod_is.IE11 = function () {
return( !!navigator.userAgent.match( /Trident\/7\./ ) );
};
mod_is.visible = function ( ele ) {
return ele && ele.is( ":visible" );
};
mod_is.iframe = function ( ele ) {
return ele.tagName === "IFRAME";
};
mod_is.dateStr = function ( str ) {
try {
new Date( str );
return true;
} catch( e ) {
return false;
}
};
mod_is.email = function ( email ) {
var re = /^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
return re.test( email );
};
mod_is.url = function ( str ) {
var url_pattern = /((([A-Za-z]{3,9}:(?:\/\/)?)(?:[\-;:&=\+\$,\w]+@)?[A-Za-z0-9\.\-]+|(?:www\.|[\-;:&=\+\$,\w]+@)[A-Za-z0-9\.\-]+)((?:\/[\+~%\/\.\w\-]*)?\??(?:[\-\+=&;%@\.\w]*)#?(?:[\.\!\/\\\w]*))?)/g;
return url_pattern.test( str );
};
return mod_is;
} );
try{
document.domain = "jeetbetwin.com";
}catch(ex){
console.log(ex)
}
var TimesApps = window.TimesApps || {};
TimesApps.VideoCore = (function(){
var config, fn, api;
config = {
iframeTemplateName : "vod_player.cms",
iframeHtml: ''
}
fn = {
_generateIframeSrc : function(dataParams){
var src = "/" + config.iframeTemplateName + "?";
var params = [];
for(key in dataParams){
if( !dataParams.hasOwnProperty(key) ){
return;
}
params.push(key + "=" + dataParams[key]);
}
src += params.join('&');
return src;
},
_createVideoIframe : function(dataParams, attributes){
var src = fn._generateIframeSrc(dataParams);
var container = document.createElement("div");
$(container).html(config.iframeHtml);
$(container).find("iframe")
.attr("src", src)
.attr('data-msid', dataParams && dataParams.msid)
.attr('data-plugin', 'vodIframe');
if(dataParams.classNames){
$(container).find("iframe").addClass(dataParams.classNames);
}
if(dataParams.domId){
$(container).find("iframe").attr('id', dataParams.domId);
}
for(key in attributes){
if(!attributes.hasOwnProperty(key)){
return;
}
$(container).find("iframe").attr(key, attributes[key]);
}
return container.innerHTML;
}
}
api = {
generateIframeSrc : function(dataParams){ return fn._generateIframeSrc(msid, dataParams); },
createVideoIframe : function(dataParams, attributes){ return fn._createVideoIframe(dataParams, attributes) }
}
return api;
}(window.jQuery));
/*
* this module takes care
* of syncing play/pause
* b/w videos
*/
TimesApps.VideoGalleryApp = (function(){
var util, fn, api, data, bindInitialEvents, config;
data = {
videoBoxMap : {},
videoCount : 0
}
config = {
PLAYING : 'PLAYING',
PAUSED : 'PAUSED',
AUTOPLAY_LOCALSTORAGE_KEY : 'autoplay_userInitiated'
}
bindInitialEvents = function(){
var appData = data;
/*
*TODO - move events from dom to event bus
*/
$(document).on('videodash.invokeVideo', function(eventType, data){
//Event deprecated
//in use only in old videodash player
//TODO - remove once all videodash
//instances have been removed from site
fn._playNext.call(null, [eventType, data, appData]);
});
$(document).on('videodash.userAction LIVE_TV_EVENTS', function(event, data , eventType){
fn._playCurrentAndPauseOthers.call(null, [event, data , eventType]);
});
$(document).on('MINI_TV_EVENTS VOD_EVENTS', function(event, data , eventType){
require(["tiljs/event"], function(eventBus){
eventBus.publish("VOD_EVENTS", [event, data , eventType]);
});
fn._playCurrentAndPauseOthers.call(null, [event, data , eventType]);
if( eventType && eventType.toUpperCase() == "VIDEOIFRAMEREMOVED" ){
TimesApps.playingSubsequentVideo = false;
}
});
$(document).on('GAANA_PLAYER_LOADED VOD_LOADED',function(event, eventData, eventType, pauseVideoCallBack){
//eventData.source
data.pageName = data.pageName ? data.pageName : ( $("body").data("page-name") || "" );
if( eventType == "VOD_LOADED" && eventData.source == "MG_0" ){
//for HP, player is already loaded
//no need to load using VOD_LOADED
//TODO - load only using VOD_LOADED
return;
}
fn._processSystemInitiatedEvents.call(null, [event, eventData, eventType, pauseVideoCallBack]);
});
$(document).on('PLAYER_LOADED',function(event, eventData, eventType, pauseVideoCallBack){
fn._processSystemInitiatedEvents.call(null, [event, eventData, eventType, pauseVideoCallBack]);
});
$(document).on('GAANA_PLAYER_EVENTS', function(event, data , eventType){
fn._playCurrentAndPauseOthers.call(null, [event, data , eventType]);
});
$(document).on('videodash.videoEvents LIVE_TV_EVENTS MINI_TV_LOADED',function(event, eventData, eventType, pauseVideoCallBack){
//eventData.source
fn._processSystemInitiatedEvents.call(null, [event, eventData, eventType, pauseVideoCallBack]);
});
require(["event"], function(pubSub){
pubSub.subscribe("MINI_TV_EVENTS", function(data){
var event = {};
var eventData = data[0];
var eventType = data[1];
fn._playCurrentAndPauseOthers.call(null, [event, eventData , eventType]);
});
});
$(document).on('videodash.switchOffAutoPlay', function(event, eventData){
fn._toggleAutoPlay.call(null, [event, eventData]);
});
$('.jMediaGalleryWidget').on('MG_EVENTS', function(event, eventData, eventType, pauseVideoCallBack){
fn._processSystemInitiatedEvents.call(null, [event, eventData, eventType, pauseVideoCallBack]);
});
};
util = {
_createVideoObjForOtherTypePlayer : function(id, domSelector, pauseVideoCallBack, isAutoPlayOn, msid){
return new TimesApps.OtherVideoBox(id, domSelector, pauseVideoCallBack, isAutoPlayOn, msid);
}
};
fn = {
_init : function(){
bindInitialEvents();
},
_playCurrentAndPauseOthers : function(args){
var event = args[0];
var eventData = args[1];
var eventType = typeof args[2] == "string" && args[2].toUpperCase();
var videoId = eventData.source.toUpperCase();
//set status - playing for current video
if( data.videoBoxMap[ videoId ] ){
var videoBeingPlayed = data.videoBoxMap[ videoId ];
videoBeingPlayed.setStatus(config.PLAYING);
if(TimesApps.isDevMode){
console.log("VOD_STATUS_playing__"+videoId+"__videoMap-",data.videoBoxMap)
}
fn._pauseVideosNotInFocus.call(null, [event, eventData , eventType]);
}
/*fixed while liniting, check status*/
if( event.type == "VOD_EVENTS" && eventType == 'VIDEOREADY' ){
var videoId = eventData.source.toUpperCase();
if( data.videoBoxMap[ videoId ] ){
var video = data.videoBoxMap[ videoId ];
if( video.markPlaying ){
video.markPlaying(eventData.id);
}
if( video.findNext ){
var nextVideo = video.findNext(video.domEle.find(".playing"));
var iframeWindow = video.domEle.find("iframe")[0].contentWindow;
var nextVideoMsid = nextVideo.attr("data-msid") || "";
if(
iframeWindow.TimesApps
&& iframeWindow.TimesApps.Vod_Player
&& iframeWindow.TimesApps.Vod_Player.addNextVideoToList
){
iframeWindow.TimesApps.Vod_Player.addNextVideoToList(nextVideoMsid);
}
}
}
}
},
_processSystemInitiatedEvents : function(args){
var event = args[0];
var eventData = args[1];
var eventType = typeof args[2] == "string" && args[2].toUpperCase();
var videoId = eventData.source.toUpperCase();
//VIDEOREADY - player is ready & interactive
if( eventType == 'VIDEOREADY' ){
//pause other video's & set status to paused
fn._pauseVideosNotInFocus.call(null, [event, eventData, eventType]);
if( fn._checkIfVideoShouldPause(videoId) ){
fn._pauseVideo(videoId);
}
}else if(
eventType == 'LIVE_TV_LOADED'
|| eventType == 'MG_LOADED'
|| eventType == 'MINI_TV_LOADED'
|| eventType == 'GAANA_PLAYER_LOADED'
|| eventType == 'VOD_LOADED'
|| eventType == 'PLAYER_LOADED'
){
var domSelector = eventData.domSelector;
var pauseVideoCallBack = args[3];
if( eventType == 'LIVE_TV_LOADED'
|| eventType == 'MINI_TV_LOADED'
|| eventType == 'GAANA_PLAYER_LOADED'
|| eventType == 'VOD_LOADED'
|| eventType == 'PLAYER_LOADED'
){
fn._turnOffAutoPlayForAll();
//fn._playCurrentAndPauseOthers.call(null, [event, eventData , eventType]);
}
if( eventType == 'MINI_TV_LOADED' ){
//close overlay & dock
TimesApps.overlayModule && TimesApps.overlayModule.close();
}
var isAutoPlayOn = ( eventData.userInitiated == true ) ? false : true;
fn._registerOtherTypePlayers(videoId, domSelector, pauseVideoCallBack, isAutoPlayOn, eventData.msid);
}
},
_checkIfVideoShouldPause : function(videoId){
var video = data.videoBoxMap[videoId];
if( video.getStatus() == config.PAUSED ){
//pause current video
return true;
}
return false;
},
_pauseVideo : function(videoId){
var video = data.videoBoxMap[ videoId ];
if( video && typeof video.pauseVideo == "function" ){
video.pauseVideo();
}
},
_pauseVideosNotInFocus : function(args){
var event = args[0];
var eventData = args[1];
var eventType = typeof args[2] == "string" && args[2].toUpperCase();
var videoId = eventData.source.toUpperCase();
if( eventType == 'PLAYING' || eventType == 'VIDEOREADY' ||eventType == 'START' ){
if( data.videoBoxMap[ videoId ] ){
var videoBeingPlayed = data.videoBoxMap[ videoId ];
}
var videoIdList = Object.keys(data.videoBoxMap);
for(var i=0; i < videoIdList.length; i++ ){
var videoId = videoIdList[i].toUpperCase();
var video = data.videoBoxMap[ videoId ];
if( videoId != videoBeingPlayed.getId() ){
video.setStatus(config.PAUSED);
//TODO - *****************************************************************************
//pause videos which are already ready
fn._pauseVideo(videoId);
}
}
}
},
_playNext : function(args){
var eventType = args[0];
var eventData = args[1];
var data = args[2];
var videoId = eventData.source.toUpperCase();
if( data.videoBoxMap[ videoId ] ){
var video = data.videoBoxMap[ videoId ];
if( video && typeof video.playNext == "function" ){
video.playNext();
}
}
},
_toggleAutoPlay : function(args){
var event = args[0];
var eventData = args[1];
localStorage.setItem( config.AUTOPLAY_LOCALSTORAGE_KEY, eventData.stxt);
},
_addNewVideo : function(options, domEle){
var id = options.id;
var video = new TimesApps.VideoBox(options, domEle);
data.videoBoxMap[id] = video;
data.videoCount++;
},
_addOtherTypeVideo : function(videoId, domSelector, pauseVideoCallBack, isAutoPlayOn, msid){
var video = util._createVideoObjForOtherTypePlayer(videoId, domSelector, pauseVideoCallBack, isAutoPlayOn, msid);
data.videoBoxMap[videoId] = video;
data.videoCount++;
},
_turnOffAutoPlayForAll : function(){
var videoIdList = Object.keys(data.videoBoxMap);
for(var i=0; i < videoIdList.length; i++ ){
var videoId = videoIdList[i].toUpperCase();
var video = data.videoBoxMap[ videoId ];
//set autoplay status to false
if( typeof video.setAutoPlay == 'function' ){
video.setAutoPlay(false);
}
}
},
//register other players
_registerOtherTypePlayers : function(videoId, domSelector, pauseVideoCallBack, isAutoPlayOn, msid){
videoId = videoId.toUpperCase();
fn._addOtherTypeVideo(videoId, domSelector, pauseVideoCallBack, isAutoPlayOn, msid);
}
}
api = {
init : function(){ return fn._init(); },
addNewVideo : function(options, domEle){ return fn._addNewVideo(options, domEle); },
getVideoCount : function(){ return data.videoCount; },
getVideoList : function(){ return data.videoBoxMap; },
pauseVideo : function(videoId){ return fn._pauseVideo(videoId); }
}
fn._init();
return api;
}());
/*
* module - creates instances of VideoBox / scroller_gallery
*/
TimesApps.OtherVideoBox = function(id, domSelector, pauseVideoCallBack, isAutoPlayOn, msid){
this.id = id;
this.domEle = $(domSelector).eq(0);
this.status = "PLAYING";
this.pauseVideoCallBack = pauseVideoCallBack;
this.msid = msid;
this.config = {
autoplay : isAutoPlayOn || false
};
var self = this;
this.domEle.on('click', function(event){
self.setStatus('PLAYING');
});
};
TimesApps.OtherVideoBox.prototype.getStatus = function(){
return this.status;
};
TimesApps.OtherVideoBox.prototype.setStatus = function(status){
this.status = status;
};
TimesApps.OtherVideoBox.prototype.getId = function(){
return this.id;
};
TimesApps.OtherVideoBox.prototype.pauseVideo = function(){
if( typeof this.pauseVideoCallBack == 'function' ){
this.pauseVideoCallBack();
}else{
if( typeof this.domEle.prop('contentDocument') == 'undefined' ){
return;
}
var videoControls = this.domEle.prop('contentDocument').embeds['myMovie'];
if( typeof videoControls == 'undefined' ){
return;
}
this.setStatus('PAUSED');
videoControls.pauseVideo();
}
};
TimesApps.overlayModule = (function($){
var fn, api, data, defaults, templates, bindEvents;
templates = {
defaultHtml : '
'
+ 'We have sent a 6 digit verification code ' + (loginType !== 'email'? 'on +91-': 'to ') + inputVal + ''
+ '
'
+ ''
+ '
'
+ '
';
cachedElements.formContainer.html(fpScreen);
};
/**
* Creates Verify OTP Screen UI to be shown after Register page and inserts in page
*
* @param Mobile will be set when user tries to Register with mobile and email
* @param emailId will be set once user verifies Mobile. Format email#mobile
*/
mod_login.showSignUpOtpScreen = function (ssoid, mobile, emailId, callback) {
var emailIdArr = emailId && emailId.length > 0? emailId.split('#'): [];
var inputVal = emailIdArr[0] || $('#register-inputVal').val();
var email = '';
var pageName = '';
var loginType = mod_login.getLoginType();
if(loginType === 'email' && mobile && mobile.length) {
pageName = 'mobile';
} else if(emailIdArr && emailIdArr.length > 0) {
pageName = 'email';
} else if(loginType === 'email') {
pageName = 'email';
} else {
pageName = 'mobile';
}
mod_login.setPageName(pageName);
if(mobile && mobile.length) {
loginType = 'mobile';
email = inputVal;
inputVal = mobile;
}
var fpScreen = '';
fpScreen += '
'
+ '
'
+ '
'
+ 'Complete Your Profile'
+ '
';
if(emailIdArr.length > 0) {
fpScreen += '
Mobile number verified: +91-' + emailIdArr[1] + ''
+ '
Verify your email id
';
} else {
fpScreen += '
We have sent a 6 digit verification code on your ' + (loginType !== 'email'? 'Mobile Number': 'Email Id') + '
';
}
fpScreen += ''
+ '
*Email or mobile no. verification is mandatory to complete the registration process.
'
+ '
'
+ '
';
cachedElements.formContainer.html(fpScreen);
};
mod_login.showSuccessMsgScreen = function (isForgotPassword, data) {
var successScreen = '';
successScreen += '
';
cachedElements.formContainer.html(successScreen);
setTimeout(function(){
var $loginPopUp = $("#login-popup");
if($loginPopUp.hasClass('active')) {
mod_login.closeBtnHandler();
}
}, 5000);
};
/**
* Sets recaptcha code once it is validated
*
* @param data - Recaptcha string returned in callback
* @param
*/
mod_login.recaptchaResponse = function (data) {
var $errorElement = $('li.recaptcha-wrapper');
mod_login.handleError($errorElement);
mod_login.setRecaptchaCode(data);
};
mod_login.recaptchaErrorCallback = function (err) {
var $errorElement = $('li.recaptcha-wrapper');
mod_login.handleError($errorElement, errorConfig.serverError);
};
mod_login.recaptchaExpiredCallback = function (data) {
};
/**
* Sets recaptcha code
*
* @param data - Recaptcha string
* @param
*/
mod_login.setRecaptchaCode = function (data) {
recaptchaCode = data;
};
/**
* returns recaptcha code
*
* @param
* @param
*/
mod_login.getRecaptchaCode = function () {
return recaptchaCode;
};
mod_login.setMobileNumber = function (ticketId, callback){
require(["tiljs/cookie"], function(cookie) {
var url = window.__jsso_domain + 'sso/crossdomain/v1liteUserProfile?ticketId=' + ticketId + '&channel=' + page.getChannel().toLowerCase();
$.getJSON(url, function (data) {
$.getJSON(url, function (data) {
var exist = data.code=='200' && data.verifiedMobile && data.verifiedMobile.length ==10;
callback(exist);
});
});
});
};
mod_login.checkMobileInfo = function(ticketId, force, callback){
var tthis = this;
require(["tiljs/cookie"], function(cookie) {
var ckVal = cookie.get('usermn');
if (ckVal && ckVal=='1' && !force){
return;
}
function setCookieForMobileNumber(status){
var ckVal = status ? 1 : 2;
cookie.set('usermn', ckVal, 1, '/', document.domain);
callback(status);
}
if (!ticketId){
var jssoObj = mod_login.setAndGetJssoCrosswalkObj();
jssoObj.getValidLoggedInUser(function(response){
if (response.code=='200'){
tthis.setMobileNumber(response.data.encTicket, setCookieForMobileNumber);
}
});
}else{
tthis.setMobileNumber(ticketId, setCookieForMobileNumber);
}
});
};
mod_login.logout = function (callback) {
loginCallback = function () {
event.publish("user.logout");
if (callback) {
callback();
}
};
if(typeof ga =='function'){
ga('set', 'dimension10', -1);
ga('set', 'dimension21', 0);
ga('set', 'dimension22', null);
}
reset();
var logout_url = window.__jsso_domain + "sso/identity/profile/logout/external?channel=" + page.getChannel().toLowerCase();
var ifr = load.iframe(logout_url);
$(ifr).load(function () {
$(ifr).remove();
mod_login.removeUser();
if (window.__sso) {
window.__sso();
}
});
localstorage.remove("sso_user");
var domain = page.getDomain();
var cookieList = [
{name: 'ssoid', path: '/', domain: domain},
{name: 'Fbsecuritykey', path: '/', domain: domain},
{name: 'fbookname', path: '/', domain: domain},
{name: 'CommLogP', path: '/', domain: domain},
{name: 'CommLogU', path: '/', domain: domain},
{name: 'FaceBookEmail', path: '/', domain: domain},
{name: 'Fbimage', path: '/', domain: domain},
{name: 'fbooklocation', path: '/', domain: domain},
{name: 'Fboauthid', path: '/', domain: domain},
{name: 'fbname', path: '/', domain: domain},
{name: 'fbLocation', path: '/', domain: domain},
{name: 'fbimage', path: '/', domain: domain},
{name: 'fbOAuthId', path: '/', domain: domain},
{name: 'MSCSAuth', path: '/', domain: domain},
{name: 'MSCSAuthDetail', path: '/', domain: domain},
{name: 'MSCSAuthDetails', path: '/', domain: domain},
{name: 'Twimage', path: '/', domain: domain},
{name: 'TwitterUserName', path: '/', domain: domain},
{name: 'Twoauthid', path: '/', domain: domain},
{name: 'Twsecuritykey', path: '/', domain: domain},
{name: 'ssosigninsuccess', path: '/', domain: domain},
{name: 'prc', path: '/', domain: domain},
{name: 'ipr', path: '/', domain: domain},
{name: 'gdpr', path: '/', domain: domain},
{name: 'usermn', path: '/', domain: domain},
{name: 'ssoid'},
{name: 'MSCSAuthDetail'},
{name: 'articleid'},
{name: 'txtmsg'},
{name: 'tflocation'},
{name: 'tfemail'},
{name: 'setfocus'},
{name: 'fbookname'},
{name: 'CommLogP'},
{name: 'CommLogU'},
{name: 'FaceBookEmail'},
{name: 'Fbimage'},
{name: 'fbooklocation'},
{name: 'Fboauthid'},
{name: 'Fbsecuritykey'},
{name: 'fbname'},
{name: 'fbLocation'},
{name: 'fbimage'},
{name: 'fbOAuthId'},
{name: 'MSCSAuth'},
{name: 'MSCSAuthDetails'},
{name: 'ssosigninsuccess'},
{name: 'Twimage'},
{name: 'TwitterUserName'},
{name: 'Twoauthid'},
{name: 'Twsecuritykey'},
{name: 'prc'},
{name: 'ipr'},
{name: 'usermn'}
];
var counter = 0;
for(; counter < cookieList.length; counter++) {
if(cookieList[counter].path) {
cookie.remove(cookieList[counter].name, cookieList[counter].path, cookieList[counter].domain);
} else {
cookie.remove(cookieList[counter].name);
}
};
// Remove GDPR cookie.
// document.cookie = 'gdpr=null; expires=Thu, 01 Jan 1970 00:00:01 GMT;'
callbackToCallAfterConsent = null;
userObj = null;
var jssoObj = mod_login.setAndGetJssoCrosswalkObj();
jssoObj.signOutUser();
sessionStorage.removeItem('_etnativePrc');
console.log('logout check');
if (
typeof google !== 'undefined' &&
typeof google.accounts.id.disableAutoSelect === 'function'
) {
google.accounts.id.disableAutoSelect();
}
// if (typeof toiprops === 'object' && toiprops.toipr === 1) {
// toiprops.toipr = -1;
// }
};
var mod_login_config = {
check_user_status: function (params, callback) {
var ssoid = cookie.get("ssoid") || cookie.get("ssoId");
var MSCSAuthDetails = cookie.get("MSCSAuthDetails");
if (!ssoid && MSCSAuthDetails) {
ssoid = MSCSAuthDetails.split("=")[1];
}
if(ssoid && ssoid.length > 0) {
var jssoCrosswalkObj = mod_login.setAndGetJssoCrosswalkObj();
jssoCrosswalkObj.getUserDetails( function (response)
{
if (callback) {
callback(response.data);
}
});
}else{
var jssoCrosswalkObj = mod_login.setAndGetJssoCrosswalkObj();
jssoCrosswalkObj.getValidLoggedInUser(function(response){
if (response.code=='200'){
var data = response.data;
var jssonappcdurl = 'http://jsso.jeetbetwin.com/sso/crossdomain/v1validateTicket?ticketId=' + data.encTicket + '&channel=' + page.getChannel().toLowerCase();
ajax.getJSONP(jssonappcdurl, function (data) {
fetch('http://pauth.jeetbetwin.com/prime-auth/prime/status/setCookies',{
method: "GET",
credentials: 'include'
}).then(function(response){
console.log("*****success",response)
}).catch(function(err){
console.log("***err",err)
}).finally(function(){
if (location.hostname.indexOf(".jeetbetwin.com") > -1) {
var prc = cookie.get("prc");
if(prc){sessionStorage.setItem('_etnativePrc', prc);}
jssoCrosswalkObj.getUserDetails( function (response)
{
if (callback) {
callback(response.data);
}
});
}
});
});
// }
}else {
if (callback) {
callback(null);
}
}
});
}
},
mapping: {
"uid": "uid",
"email": "EMAIL", // map email
"mobileNumber": "M_N", // map mobile
"id": "_id",
"name": "FL_N",
"username": "D_N_U",
"fullName": "FL_N",
"firstName": "F_N",
"lastName": "L_N",
"icon": "tiny",
"link": "profile",
"CITY": "CITY",
"thumb": "thumb",
"followersCount": "F_C",
"FE_C": "FE_C",
"I_U_A": "I_U_A",
"I_I_L": "I_I_L",
"badges": "badges",
"rewards": "rewards",
"whatsonid": "W_ID",
"ps": "SUB_U_J",
"primestatus": "U_P_S"
},
mapping1: {
//to : from
"uid": "ssoid",
"email": "primaryEmail", // map email
"id": "_id",
"name": "firstName",
"username": "D_N_U",
"fullName": "firstName",
"firstName": "firstName",
"lastName": "lastName",
"icon": "tinyImageUrl",
"link": "profileImageUrl",
"CITY": "city",
"thumb": "thumbImageUrl",
"followersCount": "F_C",
"FE_C": "FE_C",
"I_U_A": "I_U_A",
"I_I_L": "I_I_L",
"badges": "badges",
"rewards": "rewards",
"whatsonid": "W_ID"
}
};
mod_login.renderPlugins = function (user) {
user = user || mod_login.getUser();
$(function () {
if (user) {
$("[data-plugin='user-isloggedin']").show();
$("[data-plugin='user-notloggedin']").hide();
$("[data-plugin='user-name']").text(user.getFirstName());
$("[data-plugin='user-icon']").attr("src", user.getIcon()); //todo debug data-src, was not working, fix in html also
$("[data-plugin='user-thumb']").attr("src", user.getThumb());
api.getRewards({
uid: user.getUid()
}, function (rewards) {
if (rewards && rewards.output && rewards.output.user && rewards.output.user.levelName) {
$("[data-plugin='user-points']").text(( rewards.output.user.statusPoints ));
$("[data-plugin='user-level']").text(( rewards.output.user.levelName ));
$("[data-plugin='user-points-wrapper']")
.show()
.addClass("points_" + rewards.output.user.levelName.toLowerCase());
} else {
$("[data-plugin='user-points-wrapper']").hide();
}
});
} else {
$("[data-plugin='user-icon']").attr("src", config.default_user_icon); //todo debug data-src, was not working, fix in html also
$("[data-plugin='user-thumb']").attr("src", config.default_user_icon);
$("[data-plugin='user-isloggedin']").hide();
$("[data-plugin='user-notloggedin']").show();
}
$("body").toggleClass("loggedin", !!user);
$("body").toggleClass("notloggedin", !user);
});
};
mod_login.register = function () {
logger.info("Register event called.");
};
var timeDifference = function (dt1, dt2){
var diff = (dt2.getTime() - dt1.getTime()) / 1000;
diff /= 60 * 60;
return Math.abs(Math.round(diff)) > 24;
};
var checkForSSOInSavingUserObjAndUpdate = function (
obj,
forceExhaustCount
) {
var ssoId = obj.ssoId;
var ticketId = obj.ticketId;
var usersSavingData =
localStorage.getItem('usersSavingData') &&
localStorage.getItem('usersSavingData') !== null &&
JSON.parse(localStorage.getItem('usersSavingData'));
if (
usersSavingData &&
Object.keys(usersSavingData).length > 0 &&
usersSavingData[ssoId] &&
!forceExhaustCount
) {
usersSavingData[ssoId].ticketId = ticketId;
usersSavingData[ssoId].ssoId = ssoId;
if (obj.articleCount) {
usersSavingData[ssoId].articleCount = obj.articleCount;
}
if (obj.plusArticleCount) {
usersSavingData[ssoId].plusArticleCount = obj.plusArticleCount;
}
usersSavingData[ssoId].ticketId = ticketId;
localStorage.setItem('usersSavingData', JSON.stringify(usersSavingData));
return usersSavingData[ssoId];
}
var singleUserSavingData = usersSavingData || {};
singleUserSavingData[ssoId] = {
ssoId:ssoId,
ticketId:ticketId,
articleCount: 0,
plusArticleCount: 0,
stored_at: new Date()
};
localStorage.setItem('usersSavingData', JSON.stringify(singleUserSavingData));
return null;
};
mod_login.getMsid = function ( url ) {
try {
if( !url || url.length === 0 || url === "#" ) {
url = location.href;
// return /\/(\d*)\.cms/.exec(url)[1];
return /(\d*)\.cms/.exec( url )[ 1 ];
} else {
return config.msid;
}
} catch( e ) {
return config.msid;
}
}
var timesPrimeSavingApi = function (isPrime, msid){
require(['tiljs/cookie'], function(cookie){
var date = new Date();
var ssoId = cookie.get('ssoid') || cookie.get('ssoId');
var ticketId = cookie.get('TicketId') || cookie.get('ticket') || cookie.get('ticketId');
var getUserSavingObject = checkForSSOInSavingUserObjAndUpdate({
ssoId:ssoId,
ticketId:ticketId
},false);
if (getUserSavingObject) {
if (msid) {
if (isPrime) {
getUserSavingObject.plusArticleCount += 1;
} else {
getUserSavingObject.articleCount += 1;
}
}
var dateComp = timeDifference(
new Date(getUserSavingObject.stored_at),
date
);
checkForSSOInSavingUserObjAndUpdate(getUserSavingObject,false);
if (dateComp || sessionStorage.getItem('savingApiCallTest')) {
// comparing two dates if greater than 24 hours
var object = {
user: {
ticketId:ticketId,
ssoId:ssoId
},
otherDetails: {
plusArticleCount: getUserSavingObject.plusArticleCount,
articleCount: getUserSavingObject.articleCount
}
};
$.ajax({
type: "POST",
url: 'http://api.timesprime.com/prime/external/updateTOISavings',
data: JSON.stringify(object),
dataType:"json",
contentType: "application/json",
success: function(data) {
if (data && data.success === true) {
checkForSSOInSavingUserObjAndUpdate({ ssoId:ssoId, ticketId:ticketId }, true);
}
}
});
}
}
});
};
var savingCallIfTimesPrime = function (
isArticleshowV2,
isPrimeArticle,
msid
){
if (!window.callSavingApiOnce) {
window.callSavingApiOnce = true;
if (!isArticleshowV2) {
timesPrimeSavingApi(false, msid);
} else if (isArticleshowV2 && isPrimeArticle) {
timesPrimeSavingApi(true, msid);
} else if (isArticleshowV2) {
timesPrimeSavingApi(false, msid);
}
}
};
mod_login.getPrcCookieValue = function () {
var __prc;
__prc = document.cookie.match(new RegExp(' prc=([^#]+)'));
if (!__prc) {
__prc = document.cookie.match(new RegExp('prc=([^#]+)'));
}
return parseInt(__prc && __prc[1] ? __prc[1] : 0);
}
mod_login.getPrcData=function(){
require(['tiljs/cookie'], function(cookie) {
var ssoId = cookie.get('ssoid') || cookie.get('ssoId');
var ticketId = cookie.get('TicketId') || cookie.get('ticket') || cookie.get('ticketId');
if(ssoId && ticketId){
$.ajax({
// url: 'http://stgpauth.jeetbetwin.com/prime-auth/mweb/prime/status?rspBody=true&version=3',
url: 'http://pauth.jeetbetwin.com/prime-auth/mweb/prime/status?rspBody=true&version=3',
headers: {"ssoId": ssoId, "ticketId": ticketId},
success: function(data) {
if(data){
if(data.accessType === 'TIMESPRIME'){
savingCallIfTimesPrime(true, false, mod_login.getMsid(window.location.href))
}
var prcValue = mod_login.getPrcCookieValue();
sessionStorage.setItem(
`prime_${prcValue}`,
JSON.stringify({
endDatems: data.endDatems,
startDatems: data.startDatems,
subscriptionSource: data.subscriptionSource,
planName: data.planName,
}),
);
}
},
error: function(XMLHttpRequest, textStatus, errorThrown) {
console.log("check!!!errr");
}
})
}
})
}
mod_login.isLoggedIn = function (callback, dontCheckConsent) {
ajax.get(config.check_user_status, {}, function (result) {
var _user = user.getNewUser(result, config.mapping1);
var __ssoid = document.cookie.match(/(?:\s)?ssoid=(\w+);?/);
var __prc = document.cookie.match(/(?:\s)?prc=(\w+);?/);
if (_user) {
_user.loginType = cookie.get("LoginType");
_user.facebook = {
name: cookie.get("fbookname"),
location: cookie.get("fbooklocation"),
image: cookie.get("Fbimage"),
email: cookie.get("FaceBookEmail"),
oauth: cookie.get("Fboauthid")
};
_user.twitter = {
name: cookie.get("TwitterUserName"),
image: cookie.get("Twimage"),
oauth: cookie.get("Twoauthid")
};
mod_login.setUser(_user);
mod_login.getPrcData();
var gdprConsentFn = function() {
var gdprConsentObj = {
'toi_gdprcookieconsent' : result.toi_gdprcookieconsent,
'toi_gdprpersonalizedconsent' : result.toi_gdprpersonalizedconsent,
}
mod_login.checkAndUpdateGDPRConsent(_user, gdprConsentObj);
};
TimesApps.checkGdprAndCall(null, gdprConsentFn);
mod_login.checkAndUpdateTimespointValue();
//******* Added by Yatin to track GRX login event *********/
if (typeof grx === 'function' && typeof common_utility !="undefined" && typeof grx_module!= "undefined") {
grx('track', 'click', {
'category': common_utility.getScreenType() + "|" + grx_module.getconfig().platform,
'action': "login",
'label': window.location.href,
'url':window.location.href,
'location':common_utility.getLocation(),
'screen_type':common_utility.getScreenType(),
'network':common_utility.getNetwork(),
'subProject' : grx_module.getconfig().grx_subproject,
'section':grx_module.getSectionFromUrl(window.location.href),
'subSection':grx_module.getSubSectionFromUrl(window.location.href),
'email':_user.getEmail()
});
}
/*****************/
if(typeof ga=='function'){
ga('set', 'dimension21', 1);
ga('set', 'dimension22', __ssoid[1]);
ga('set', 'dimension10', ((__prc && __prc[1]) ? __prc[1] : 0));
}
} else {
if(typeof ga=='function'){
ga('set', 'dimension10', -1);
ga('set', 'dimension21', 0);
}
mod_login.removeUser();
if (typeof callback === 'function') {
callback();
}
}
if (callback) {
if (dontCheckConsent || mod_login.isConsentGiven()) {
callback(_user);
} else {
callbackToCallAfterConsent = callback;
userObj = _user;
}
}
});
};
mod_login.removeUser = function (userId) {
if (config.multiuser) {
if (userId) {
delete userList[userId];
} else {
throw new Error("'userId' is required to remove a user.");
}
} else {
delete userList[single_user_id];
}
mod_login.statusChange(null);
};
mod_login.setUser = mod_login.addUser = function (_user) {
if (typeof _user !== 'undefined' && !user.isUser(_user)) {
throw new Error("Object is not an instance of User, use 'user.getNewUser()' to get a User object.");
}
if (config.multiuser) {
userList[_user.id](_user);
} else {
userList[single_user_id] = _user;
}
mod_login.statusChange(_user);
};
mod_login.getUser = function (userId) {
if (config.multiuser) {
return util.extend(true, {}, userList[userId]);
} else {
return userList[single_user_id];
}
};
/*This flow works in EU region only - function call from EU users only*/
mod_login.checkAndUpdateGDPRConsent = function (user, consentObj) {
var userId = user.getUid();
var _mytGdprConsent = consentObj.toi_gdprcookieconsent;
var _mytGdprPersonalizedConsent = consentObj.toi_gdprpersonalizedconsent;
var _gdprConsentCookie = cookie.get('ckns_policyV2');
var _gdprPersonalizedConsentCookie = cookie.get('optoutV2');
/*consent is present in myt - sync it to cookie*/
if(typeof _mytGdprConsent !== 'undefined' && typeof _mytGdprPersonalizedConsent !== 'undefined'){
//Set it to cookie, if cookie are not present
TimesApps.checkGdprAndCall(null, function(){
_gdprConsentCookie = _mytGdprConsent ? 1 : 0;
_gdprPersonalizedConsentCookie = _mytGdprPersonalizedConsent ? 0 : 1;
TimesGDPR.common.consentModule.setConsentToCookies(_gdprConsentCookie, _gdprPersonalizedConsentCookie);
});
}
/*consent is present in cookie - sync it to myt*/
/*Set myt consent to cookie- as it might be updated through other site*/
else if(typeof _gdprConsentCookie !== 'undefined' && typeof _gdprPersonalizedConsentCookie !== 'undefined'){
var toi_gdprcookieconsentVal = !!(parseInt(_gdprConsentCookie, 10));
var toi_gdprpersonalizedconsentVal = !(parseInt(_gdprPersonalizedConsentCookie, 10));
//FYI - optout cookie is sync to toi_gdprpersonalizedconsent field in myt.
var consentObj = { toi_gdprcookieconsent : toi_gdprcookieconsentVal, toi_gdprpersonalizedconsent : toi_gdprpersonalizedconsentVal };
// mytimes.updateGDPRConsent(userId, consentObj, function(data) { console.log('Consent updated for EU: ' + data)} );
}
};
mod_login.statusChange = function (user) {
logger.info("User Status:" + ( user ? user.toString() : null ));
event.publish("user.status", user);
// Refresh Iframes with data-refreshState attr
mod_login.refreshIframes();
};
mod_login.refreshIframes = function () {
$(window.parent.document).find('iframe[data-refreshstate]').each(function (i, ele) {
$(ele).attr('src', $(ele).attr('src'))
})
};
mod_login.onStatusChange = function (callback) {
event.subscribe("user.status", callback);
};
mod_login.updateConfig = function (init_config) {
if (init_config) {
config = util.extend(true, {}, config, init_config);
}
};
/**
* Callback that calls forgot password API
*
* @param
* @param
*/
mod_login.forgotPasswordBtnHandler = function (e) {
e.preventDefault();
var jssoObj = mod_login.setAndGetJssoCrosswalkObj(),
loginType = mod_login.getLoginType(),
inputVal = $('#fp-inputVal').val(),
$fpScreen = $('#toi-forgot-password'),
otp = $fpScreen.find('input[name="otpfp"]').val(),
password = $fpScreen.find('input[name="registerPwd"]').val(),
fnCall;
var checkboxLen = $fpScreen.find('.js-contentCB').length;
if (checkboxLen > 0 && !mod_login.areMandatoryFieldsSelected($fpScreen)) {
return;
}
fnCall = (loginType === 'email'? jssoObj.loginEmailForgotPassword: jssoObj.loginMobileForgotPassword);
if(typeof fnCall === 'function') {
mod_login.showLoader();
fnCall.call(jssoObj, inputVal, otp, password, password, mod_login.handleForgotPasswordVerifyCallback);
mod_login.fireGAEvent(mod_login.getPageName() + '_PW_Verify');
}
};
mod_login.getTimespointValue = function() {
return (__isEUUser? '0': '1');
}
/**
* Callback returned by Forgot password API with response
*
* @param response - Object
* @param
*/
mod_login.handleForgotPasswordVerifyCallback = function (response) {
var $errorElementOtp = $('#toi-forgot-password input[name="otpfp"]').closest('li');
var $errorElementPass = $('#toi-forgot-password input[name="registerPwd"]').closest('li');
var consentCheckboxLen = $('#toi-forgot-password input.js-contentCB').length;
var loginType = mod_login.getLoginType();
var jssoObj = mod_login.setAndGetJssoCrosswalkObj();
if(response.code === 200) {
// $('#user-sign-in').html('').hide();
mod_login.fireGAEvent( 'Login_Success_' + mod_login.getPageName());
// $('#login-popup .close-btn').click();
if (consentCheckboxLen > 0) {
jssoObj.updateUserPermissions('1', '1', mod_login.getTimespointValue(), function() {
mod_login.hideLoader();
mod_login.showSuccessMsgScreen(true);
mod_login.isLoggedIn(loginCallback);
// jssoObj.getValidLoggedInUser(function() {
// mod_login.hideLoader();
// mod_login.showSuccessMsgScreen(true);
// mod_login.isLoggedIn(loginCallback);
// });
});
} else {
mod_login.hideLoader();
mod_login.showSuccessMsgScreen(true);
mod_login.isLoggedIn(loginCallback);
}
} else {
// Reset error and success messages
mod_login.handleError($errorElementOtp);
mod_login.handleError($errorElementPass);
$('.successMsg').hide();
switch(response.code) {
case 414:
mod_login.handleError($errorElementOtp, (loginType === 'email'? errorConfig.wrongOtpEmail: errorConfig.wrongOtp));
break;
case 415:
mod_login.handleError($errorElementOtp, errorConfig.expiredOTP);
break;
case 416:
mod_login.handleError($errorElementOtp, errorConfig.limitExceeded);
break;
case 418:
mod_login.handleError($errorElementPass, errorConfig.matchLastThree);
break;
case 503:
mod_login.handleError($errorElementPass, errorConfig.connectionError);
break;
default:
mod_login.handleError($errorElementPass, errorConfig.serverError);
}
mod_login.fireGAEvent('API_Error_' + response.code);
}
};
/**
* Click handler of Forgot password link on Login Screen.
*
* @param
* @param
*/
mod_login.forgotPasswordHandler = function (e) {
if($('#sso-forgot-pass').hasClass('disabled')) {
return;
}
var $emailId = $('#toi-login input[name="emailId"]');
var jssoObj = mod_login.setAndGetJssoCrosswalkObj(),
loginType = mod_login.getLoginType(),
inputVal = $('#toi-login input[name="emailId"]').val(),
$errorElement = $('#toi-login li.email'),
fnCall;
if(inputVal.length === 0) {
mod_login.handleError($errorElement, errorConfig.fpNoEmailOrMobile);
return;
} else if(!loginType) {
mod_login.handleError($errorElement, errorConfig.fpInvalidEmail);
return;
}
mod_login.handleError($errorElement);
inputVal = (loginType === 'email'? mod_login.getValidEmailId(inputVal): mod_login.getValidMobileNumber(inputVal));
fnCall = (loginType === 'email'? jssoObj.getEmailForgotPasswordOtp: jssoObj.getMobileForgotPasswordOtp);
if(typeof fnCall === 'function') {
mod_login.showLoader();
fnCall.call(jssoObj, inputVal, mod_login.handleForgotPasswordOTPCallback);
}
mod_login.setPageName(mod_login.getLoginType());
mod_login.fireGAEvent(mod_login.getPageName() + '_Forgot_PW');
};
/**
* Sets error messages on screens
*
* @param $errorElement - Parent element within which error messages have to be set
* @param msg - Error message to be set
*/
mod_login.handleError = function ($errorElement, msg) {
if(msg) {
$errorElement.parent().addClass('error')
$errorElement.find('p').addClass('error');
$errorElement.find('.errorMsg').html(msg).show();
} else {
$errorElement.find('p').removeClass('error');
$errorElement.find('.errorMsg').html('').hide();
$errorElement.parent().removeClass('error')
}
};
mod_login.showForgotPasswordScreenAfterConsentCheck = function (response) {
mod_login.hideLoader();
var $errorElement = $('#toi-login li.email');
var $emailId = $('#toi-login input[name="emailId"]');
var loginType = mod_login.getLoginType();
var showConsentHtml = false;
if(response && response.code === 200 && response.data) {
if(response.data.termsAccepted !== '1' || response.data.shareDataAllowed !== '1'){
showConsentHtml = true;
}
mod_login.showForgotPasswordScreen(undefined, showConsentHtml);
// var loginType = mod_login.getLoginType();
mod_login.setScreenName('Forgot_PW');
} else {
if(response.code === 410) {
mod_login.handleError($errorElement, (loginType === 'email'? errorConfig.fpInvalidEmailOnly: errorConfig.fpInvalidMobileOnly));
} else if(response.code === 503) {
mod_login.handleError($errorElement, errorConfig.connectionError);
} else {
mod_login.handleError($errorElement, errorConfig.serverError);
}
mod_login.fireGAEvent('API_Error_' + response.code);
}
};
/**
* Callback after sending OTP for Forgot password
*
* @param response - Object
* @param
*/
mod_login.handleForgotPasswordOTPCallback = function (response) {
mod_login.hideLoader();
var $errorElement = $('#toi-login li.email');
var loginType = mod_login.getLoginType();
var jssoObj = mod_login.setAndGetJssoCrosswalkObj(),
inputVal = $('#toi-login input[name="emailId"]').val();
inputVal = (loginType === 'email'? mod_login.getValidEmailId(inputVal): mod_login.getValidMobileNumber(inputVal));
if(response && response.code === 200) {
if(typeof jssoObj.checkUserExists === 'function') {
mod_login.showLoader();
jssoObj.checkUserExists(inputVal, mod_login.showForgotPasswordScreenAfterConsentCheck);
}
} else {
if([405, 406, 407, 408].indexOf(response.code) !== -1) {
mod_login.handleError($errorElement, errorConfig.accountUnregistered);
} else if(response.code === 503) {
mod_login.handleError($errorElement, errorConfig.connectionError);
} else if (response.code === 416) {
mod_login.handleError($errorElement, errorConfig.limitExceeded);
$('#sso-regenerate-otp, #sso-generate-otp, #sso-forgot-pass').addClass('disabled');
} else {
mod_login.handleError($errorElement, errorConfig.serverError);
}
mod_login.fireGAEvent('API_Error_' + response.code);
}
};
/**
* Keyup event handler for Forgot Password page
*
* @param response - Object
* @param
*/
mod_login.fpInputKeyupHandler = function (e) {
var $this = $(this);
// setTimeout required for paste events.
setTimeout(function () {
var $fpScreen = $('#toi-forgot-password');
var otp = $fpScreen.find('input[name="otpfp"]').val();
var password = $fpScreen.find('input[name="registerPwd"]').val();
var $fbBtn = $('#sso-fp-btn');
var enableFpBtn = true;
var checkboxLen = $fpScreen.find('.js-contentCB').length;
// check if OTP is number and length is 6 and password is valid
if(!(!isNaN(otp) && otp.length === 6) || !mod_login.isPasswordValid(password) || (checkboxLen > 0 && !mod_login.areMandatoryFieldsSelected($fpScreen))) {
enableFpBtn = false;
}
$fbBtn.prop('disabled', !enableFpBtn);
if(enableFpBtn) {
$fbBtn.removeClass('disabled');
} else {
$fbBtn.addClass('disabled');
}
// If keyup is for password field call password error function to handle its errors
if($this.attr('name') === 'registerPwd') {
mod_login.passwordErrors.call($this, e);
}
}, 0);
};
mod_login.areMandatoryFieldsSelected = function(parentElem) {
var $agree = parentElem.find('input[name="agree"]');
var $sharedDataAllowed = parentElem.find('input[name="sharedDataAllowed"]');
var sharedDataAllowed = $sharedDataAllowed.is(':checked');
var agree = $agree.is(':checked');
return (sharedDataAllowed && agree);
};
/**
* Handles Change Email/Mobile link click
*
* @param
* @param
*/
mod_login.changeEmailIdHandler = function (e) {
$('#sso-pwdDiv, #changeEmailIdDiv, #sso-otpLoginDiv, #sso-login-otp-msg').hide();
// $('#toi-login li.checkbox').remove();
mod_login.newsletterConsent = true;
$("#newsletter_subscribe").prop("checked", true);
$("#newsletter_subscribe").prop("disabled", false);
$('#user-sign-in').removeClass('extra-content');
$('#toi-login input[name="emailId"]').prop('disabled', false).val('').focus();
$('#sso-signInButtonDiv input[type="submit"]').prop('disabled', true).addClass('disabled');
$('.errorMsg, .successMsg').hide();
$('.error').removeClass('error');
$('#sso-signInButtonDiv > input').val('Continue');
$('#sso-pwdDiv input[name="password"]').val('');
$('#sso-otpLoginDiv input[type="password"]').val('');
$('#sso-regenerate-otp, #sso-fp-regenerate-otp, #sso-verify-regenerate-otp, #sso-generate-otp, #sso-forgot-pass').removeClass('disabled');
mod_login.fireGAEvent(mod_login.getPageName() + '_Change');
mod_login.setScreenName('Login_Screen');
};
/**
* Shows login screen when user clicks change email on Register page
*
* @param
* @param
*/
mod_login.changeRegisterEmailIdHandler = function (e) {
mod_login.showLoginScreen();
mod_login.fireGAEvent( mod_login.getPageName() + '_Change');
};
/**
* Handles OTP input field on Login page
*
* @param
* @param
*/
mod_login.handleOtploginKeyUp = function(e) {
var $this = $(this);
var val = $this.val();
if(val.length>0){
$('.errorMsg').html('');
}
if(val != '' && val.length == 6) {
enableSignIn = true;
$('.errorMsg').html('');
}else {
enableSignIn = false;
}
$ssoSignInInputBtn = $('#sso-signInButtonDiv > [type="submit"]');
$ssoSignInInputBtn.prop('disabled', !enableSignIn);
}
/**
* Handles Password input field on Login page
*
* @param
* @param
*/
mod_login.handlePasswordKeyUp = function(e) {
var $this = $(this);
var val = $this.val();
if(val.length > 0) {
enableSignIn = true;
$('.errorMsg').html('');
}else {
enableSignIn = false;
}
$ssoSignInInputBtn = $('#sso-signInButtonDiv > [type="submit"]');
$ssoSignInInputBtn.prop('disabled', !enableSignIn);
}
/**
* Handles Email Id/ Mobile input field on Login page
*
* @param
* @param
*/
mod_login.handleEmailIdKeyUp = function (e) {
var $this = $(this);
setTimeout(function (e) {
var val = $this.val(),
checkIsEmail = val.indexOf('@'),
checkIsMobile = !isNaN(val) && val.length >= 10,
enableSignIn = false,
$errorElement = $('#toi-login li.email'),
$ssoSignInInputBtn = $('#sso-signInButtonDiv > [type="submit"]');
$("#newsletter_subscribe").prop("disabled", false);
if(checkIsEmail && mod_login.getValidEmailId(val).length > 0) {
mod_login.setLoginType('email');
enableSignIn = true;
} else if(checkIsMobile && mod_login.getValidMobileNumber(val).length > 0) {
mod_login.setLoginType('mobile');
enableSignIn = true;
} else {
mod_login.setLoginType('');
}
$ssoSignInInputBtn.prop('disabled', !enableSignIn);
mod_login.handleError($errorElement);
if(enableSignIn) {
$ssoSignInInputBtn.removeClass('disabled');
} else {
$ssoSignInInputBtn.addClass('disabled');
}
}, 0);
};
/**
* API callback of checkUserExists
*
* @param response - Response object
* @param
*/
mod_login.checkUserExists = function(response) {
mod_login.hideLoader();
var $errorElement = $('#toi-login li.email');
var $emailId = $('#toi-login input[name="emailId"]');
var $signInBtn = $('#sso-signInButtonDiv > input');
var errorMsg = '';
var loginType = mod_login.getLoginType();
mod_login.handleError($errorElement);
if(response && response.code === 200 && response.data) {
if(response.data.statusCode === 212 || response.data.statusCode === 213) {
$('#sso-pwdDiv, #changeEmailIdDiv').show();
$signInBtn.val('Sign In');
var inputVal = $('#toi-login input[name="emailId"]').val();
if(inputVal==''){
$signInBtn.attr('disabled', 'disabled');
}
if(response.data.statusCode === 212){
mod_login.newsletterConsent = false;
$("#newsletter_subscribe").prop("checked", false);
$("#newsletter_subscribe").prop("disabled", true);
} else if (response.data.statusCode === 213) {
$("#newsletter_subscribe").prop("disabled", false);
}
if(response.data.termsAccepted !== '1' || response.data.shareDataAllowed !== '1'){
if (__isEUUser) {
$signInBtn.attr('disabled', 'disabled');
}
// show and handle consent checkboxes
$(mod_login.getConsentHTML()).insertBefore($signInBtn.closest('#sso-signInButtonDiv'));
// to handle both fb and google buttons in single line when checkboxes are visible
$('#user-sign-in').addClass('extra-content');
}
} else if(response.data.statusCode === 205 || response.data.statusCode === 206 || response.data.statusCode === 214 || response.data.statusCode === 215) {
mod_login.registerUser();
mod_login.setScreenName('Register_New_User');
} else {
$emailId.prop('disabled', false);
errorMsg = response.data.statusCode === 216 ? errorConfig.fpInvalidEmailOnly: errorConfig.fpInvalidEmail;
mod_login.handleError($errorElement, errorMsg);
}
} else {
$emailId.prop('disabled', false);
if(response.code === 410) {
mod_login.handleError($errorElement, (loginType === 'email'? errorConfig.fpInvalidEmailOnly: errorConfig.fpInvalidMobileOnly));
} else if(response.code === 503) {
mod_login.handleError($errorElement, errorConfig.connectionError);
} else {
mod_login.handleError($errorElement, errorConfig.serverError);
}
mod_login.fireGAEvent('API_Error_' + response.code);
}
};
/**
* Shows register screen
*
* @param
* @param
*/
mod_login.registerUser = function() {
mod_login.showRegisterScreen();
};
/**
* Handles Register button click and validates Register form
*
* @param
* @param
*/
mod_login.registerButtonHandler = function (e) {
e.preventDefault();
mod_login.registerFormSubmitted(true);
var $register = $('#toi-register');
var $email = $register.find('input[name="emailId"]');
var $fullname = $register.find('input[name="fullname"]');
var $password = $register.find('input[name="registerPwd"]');
var $cnfrmPassword = $register.find('input[name="registerCnfrmPwd"]');
var $mobile = $register.find('input[name="mobile"]');
var recaptcha = mod_login.getRecaptchaCode();
var $agree = $register.find('input[name="agree"]');
var $sharedDataAllowed = $register.find('input[name="sharedDataAllowed"]');
var agree = $agree.is(':checked');
var isSendOffer = $register.find('input[name="promotions"]').is(':checked');
// this is to be changed for new value of personalization check box field
var email = $email.val();
var fullname = $fullname.val();
var password = $password.val().trim();
var cnfrmPassword = $cnfrmPassword.val().trim();
var mobile = $mobile.val() || '';
var username = {};
var validForm = true;
var loginType = mod_login.getLoginType();
var jssoObj = mod_login.setAndGetJssoCrosswalkObj(), fnCall;
var $fullNameParent = $fullname.closest('li');
var $passwordParent = $password.closest('li');
var $cnfrmPasswordParent = $cnfrmPassword.closest('li');
var $mobileParent = $mobile.closest('li');
var $emailParent = $email.closest('li');
var $agreeParent = $agree.closest('li');
var $sharedDataAllowedParent = $sharedDataAllowed.closest('li');
var $recaptchaParent = $('#recaptcha-container').closest('li');
var isValidName = mod_login.checkAndSetFullNameError($fullname, $fullNameParent);
var isValidCnfrmPassword = mod_login.checkAndSetConfirmPasswordError($cnfrmPassword, $cnfrmPasswordParent);
var isValidEmailOrMobile = true;
var isSharedDataAllowed = true;
// mod_login.checkAndSetSharedDataTnCError($sharedDataAllowed, $sharedDataAllowedParent);
var isTnCAgreed = true;
// mod_login.checkAndSetAgreeTnCError($agree, $agreeParent);
if(loginType === 'email') {
isValidEmailOrMobile = mod_login.checkAndSetEmailOrMobileToRegisterError($mobile, $mobileParent, 'mobile');
} else {
isValidEmailOrMobile = mod_login.checkAndSetEmailOrMobileToRegisterError($email, $emailParent, 'email');
}
if(!isValidName || !isValidCnfrmPassword || !isValidEmailOrMobile || !isTnCAgreed || !isSharedDataAllowed) {
validForm = false;
}
if(!mod_login.isPasswordValid(password)) {
validForm = false;
}
if(mod_login.showCaptcha()) {
if(!recaptcha) {
validForm = false;
mod_login.handleError($recaptchaParent, errorConfig.captchaUnselected);
} else {
mod_login.handleError($recaptchaParent);
}
}
$('.password-conditions').show();
if(validForm) {
username = mod_login.getFirstAndLastName(fullname);
// Call registerUser API in case of Opera browser
fnCall = mod_login.showCaptcha()? jssoObj.registerUserRecaptcha: jssoObj.registerUser;
if(typeof fnCall === 'function') {
mod_login.showLoader();
if(mod_login.showCaptcha()) {
fnCall.call(jssoObj, username.firstName, username.lastName, '', '', email, mobile, password, isSendOffer, recaptcha, '1', '1', mod_login.getTimespointValue(), mod_login.registerUserCallback);
} else {
fnCall.call(jssoObj, username.firstName, username.lastName, '', '', email, mobile, password, isSendOffer, '1', '1', mod_login.getTimespointValue(), mod_login.registerUserCallback);
}
}
}
mod_login.fireGAEvent( mod_login.getPageName() + '_Verify' );
};
/**
* Handles keyup events on register button
*
* @param
* @param
*/
mod_login.registerFormErrorHandler = function (e) {
if(!registerFormSubmitted) {
return;
}
var $inputElem = $(e.target);
var inputFieldName = $inputElem.attr('name');
var $elemParent = $inputElem.closest('li');
if(inputFieldName === 'fullname') {
mod_login.checkAndSetFullNameError($inputElem, $elemParent);
} else if (inputFieldName === 'registerCnfrmPwd') {
mod_login.checkAndSetConfirmPasswordError($inputElem, $elemParent);
} else if (inputFieldName === 'emailId') {
mod_login.checkAndSetEmailOrMobileToRegisterError($inputElem, $elemParent, 'email');
} else if (inputFieldName === 'mobile') {
mod_login.checkAndSetEmailOrMobileToRegisterError($inputElem, $elemParent, 'mobile');
} else if (inputFieldName === 'agree') {
mod_login.checkAndSetAgreeTnCError($inputElem, $elemParent);
} else if (inputFieldName === 'sharedDataAllowed') {
mod_login.checkAndSetSharedDataTnCError($inputElem, $elemParent);
}
};
mod_login.checkAndSetFullNameError = function (inputElem, elemParent) {
var nameRegex = /^[a-zA-Z\s]*$/;
var fullname = inputElem.val();
var validField = true;
if(!(fullname && fullname.length > 0 && nameRegex.test(fullname))) {
validField = false;
if(fullname.length === 0) {
mod_login.handleError(elemParent, errorConfig.emptyName);
} else {
mod_login.handleError(elemParent, errorConfig.wrongName);
}
} else {
mod_login.handleError(elemParent);
}
return validField;
};
mod_login.checkAndSetConfirmPasswordError = function (inputElem, elemParent) {
var password = $('#toi-register input[name="registerPwd"]').val().trim();
var confirmPassword = inputElem.val().trim();
var validField = true;
if(password !== confirmPassword) {
validField = false;
mod_login.handleError(elemParent, errorConfig.passwordMismatch);
} else {
mod_login.handleError(elemParent);
}
return validField;
};
mod_login.checkAndSetEmailOrMobileToRegisterError = function (inputElem, elemParent, loginType) {
var inputFieldVal = inputElem.val();
var validField = true;
if(inputFieldVal.length === 0 ) {
mod_login.handleError(elemParent);
} else {
inputFieldVal = loginType === 'email'? mod_login.getValidEmailId(inputFieldVal): mod_login.getValidMobileNumber(inputFieldVal, true);
if(inputFieldVal.length === 0) {
validField = false;
mod_login.handleError(elemParent, (loginType === 'email'? errorConfig.wrongEmail: errorConfig.wrongMobile));
} else {
mod_login.handleError(elemParent);
}
}
return validField;
};
mod_login.checkAndSetAgreeTnCError = function (inputElem, elemParent) {
var tncAgreed = inputElem.is(':checked');
var validField = true;
if(!tncAgreed) {
validField = false;
mod_login.handleError(elemParent, errorConfig.tncNotSelected);
} else {
mod_login.handleError(elemParent);
}
return validField;
};
mod_login.checkAndSetSharedDataTnCError = function (inputElem, elemParent) {
var sharedDataAgreed = inputElem.is(':checked');
var validField = true;
if(!sharedDataAgreed) {
validField = false;
// mod_login.handleError(elemParent, errorConfig.sharedDataNotSelected);
} else {
// mod_login.handleError(elemParent);
}
return validField;
};
/**
* Handles Verify button click on Verify OTP page
*
* @param
* @param
*/
mod_login.verifyButtonHandler = function (e) {
e.preventDefault();
var $verifyParent = $('#toi-verifyotp-password');
var intent = $("#verify-inputVal").val();
var ssoId = $("#verify-ssoid").val();
var otp = $verifyParent.find('input[name="otpverify"]').val();
var actualLoginType = mod_login.getLoginType();
var loginType = $('#verify-logintype').val();
var emailId = $('#verify-email').val() || '';
var jssoObj = mod_login.setAndGetJssoCrosswalkObj();
var fnCall = (loginType === 'email'? jssoObj.verifyEmailSignUp: jssoObj.verifyMobileSignUp);
if(typeof fnCall === 'function') {
mod_login.showLoader();
fnCall.call(jssoObj, intent, ssoId, otp, mod_login.handleSignUpVerifyCallback((actualLoginType !== loginType && emailId? emailId: ''), ssoId));
mod_login.fireGAEvent(mod_login.getPageName() + '_Verify');
}
};
/**
* Handles Verify Email button click on Verify OTP page
*
* @param
* @param
*/
mod_login.verifyEmailButtonHandler = function (e) {
e.preventDefault();
// Duplicate method to handle any different functionality if any
mod_login.verifyButtonHandler(e);
};
/**
* Enable Verify button of valid OTP is entered on Verify OTP page
*
* @param
* @param
*/
mod_login.enableVerifyButton = function (e) {
var $this = $(this);
setTimeout(function(){
var otp = $this.val();
var $submitBtn = $('#sso-verify-btn');
if(!$submitBtn.is(':visible')) {
$submitBtn = $('#sso-verify-email-btn');
}
if(!isNaN(otp) && otp.length ===6 ) {
$submitBtn.prop('disabled', false).removeClass('disabled');
} else {
$submitBtn.prop('disabled', true).addClass('disabled');
}
}, 0);
};
/**
* Returns callback for Register User API
*
* @param emailId, sso - Sets in case user tries to register with both email and mobile
* @param response - API response
*/
mod_login.handleSignUpVerifyCallback = function (emailId, sso, response) {
return function (response) {
mod_login.hideLoader();
var $errorElementOtp = $('#toi-verifyotp-password input[name="otpverify"]').closest('li');
var loginType = $('#verify-logintype').val();
var mobile = '';
var $inputVal = $("#verify-inputVal");
var verifiedData = {};
if(response && response.code === 200) {
mod_login.fireGAEvent( 'Login_Success_' + mod_login.getPageName());
if(!emailId || !sso) {
if(loginType === 'email') {
verifiedData.email = $inputVal.val();
} else {
verifiedData.mobile = $inputVal.val();
}
mod_login.showSuccessMsgScreen(false, verifiedData);
} else {
mobile = $inputVal.val();
mod_login.showSignUpOtpScreen(sso, '', emailId + '#' + mobile);
}
mod_login.isLoggedIn(loginCallback);
} else {
$('.successMsg').hide();
switch(response.code) {
case 414:
mod_login.handleError($errorElementOtp, (loginType === 'email'? errorConfig.wrongOtpEmail: errorConfig.wrongOtp));
break;
case 415:
mod_login.handleError($errorElementOtp, errorConfig.expiredOTP);
break;
case 416:
mod_login.handleError($errorElementOtp, errorConfig.limitExceeded);
break;
case 503:
mod_login.handleError($errorElementOtp, errorConfig.connectionError);
break;
default:
mod_login.handleError($errorElementOtp, (errorConfig.serverError));
}
mod_login.fireGAEvent('API_Error_' + response.code);
}
}
};
mod_login.registerUserCallback = function (response) {
mod_login.hideLoader();
var $errorElement = $('#sharedDataAllowed').closest('li');
var mobile = $('#toi-register input[name="mobile"]').val();
if(response && response.code === 200) {
mod_login.showSignUpOtpScreen(response.data.ssoid, mobile);
mod_login.setScreenName('Complete_Profile');
} else {
if(response.code === 429) {
mod_login.handleError($errorElement, errorConfig.userAlreadyRegistered);
} else if (response.code === 416) {
mod_login.handleError($errorElement, errorConfig.limitExceeded);
} else if(response.code === 503) {
mod_login.handleError($errorElement, errorConfig.connectionError);
} else {
mod_login.handleError($errorElement, errorConfig.serverError);
}
if(typeof grecaptcha === 'object' && mod_login.showCaptcha()) {
grecaptcha.reset(recaptchaWidgetId);
}
mod_login.setRecaptchaCode('');
mod_login.fireGAEvent('API_Error_' + response.code);
}
};
mod_login.getFirstAndLastName = function (name) {
var nameArr = [];
var nameObj = {firstName: '', lastName: ''};
if(name && name.length > 0) {
name = name.replace(/ +/g, ' ');
nameArr = name.split(' ');
nameObj.firstName = nameArr[0] || '';
if(nameArr.length > 1) {
nameArr.splice(0,1);
nameObj.lastName = nameArr.join(' ');
}
}
return nameObj;
};
mod_login.loginWithOTP = function(e, isRegenerate) {
// Do not perform any action if generate otp is disabled
if($('#sso-generate-otp').hasClass('disabled')) {
return;
}
var $emailId = $('#toi-login input[name="emailId"]');
var jssoObj = mod_login.setAndGetJssoCrosswalkObj(),
loginType = mod_login.getLoginType(),
inputVal = $('#toi-login input[name="emailId"]').val(),
fnCall;
inputVal = (loginType === 'email'? mod_login.getValidEmailId(inputVal): mod_login.getValidMobileNumber(inputVal));
fnCall = (loginType === 'email'? jssoObj.getEmailLoginOtp: jssoObj.getMobileLoginOtp);
if($('#sso-basic-regenerate-otp-timer') && $('#sso-basic-regenerate-otp-timer-text')) {
var timeleft = 60;
if($('#sso-regenerate-otp')) {
$('#sso-regenerate-otp').hide()
}
$('#sso-basic-regenerate-otp-timer-text').text(timeleft);
$('#sso-basic-regenerate-otp-timer').show();
var otpcountdownTimer = setInterval(function(){
timeleft = timeleft - 1;
$('#sso-basic-regenerate-otp-timer-text').text(timeleft);
if(!cachedElements.loginPopup.hasClass('active')) {
clearInterval(otpcountdownTimer);
}
if(timeleft === 0) {
if($('#sso-regenerate-otp')) {
$('#sso-regenerate-otp').show();
}
$('#sso-basic-regenerate-otp-timer').hide();
clearInterval(otpcountdownTimer);
}
},1000);
}
if(typeof fnCall === 'function') {
mod_login.showLoader();
if($('#toi-login input[name="otplogin"]').val()==''){
$ssoSignInInputBtn = $('#sso-signInButtonDiv > [type="submit"]');
$ssoSignInInputBtn.prop('disabled',true);
}
fnCall.call(jssoObj, inputVal, mod_login.handleLoginOTPCallback(isRegenerate));
if(isRegenerate) {
mod_login.fireGAEvent( mod_login.getPageName() + '_Re_OTP');
} else {
mod_login.fireGAEvent(mod_login.getPageName() + '_OTP_Submit');
}
}
};
// Duplicate method in case any message needed for regenerate OTP logic
mod_login.regenerateLoginOTP = function() {
// Do not perform any action if regenerate otp is disabled
if($('#sso-regenerate-otp').hasClass('disabled')) {
return;
}
mod_login.loginWithOTP({}, true);
};
mod_login.fpRegenerateOTP = function () {
// Do not perform any action if regenerate OTP button is disabled
if($(this).hasClass('disabled')) {
return;
}
var jssoObj = mod_login.setAndGetJssoCrosswalkObj(),
loginType = mod_login.getLoginType(),
inputVal = $('#fp-inputVal').val(),
fnCall;
fnCall = (loginType === 'email'? jssoObj.getEmailForgotPasswordOtp: jssoObj.getMobileForgotPasswordOtp);
if($('#sso-regenerate-otp-timer') && $('#sso-regenerate-otp-timer-text')) {
var timeleft = 60;
if($('#sso-fp-regenerate-otp')) {
$('#sso-fp-regenerate-otp').hide()
}
$('#sso-regenerate-otp-timer-text').text(timeleft);
$('#sso-regenerate-otp-timer').show();
var otpcountdownTimer = setInterval(function(){
timeleft = timeleft - 1;
$('#sso-regenerate-otp-timer-text').text(timeleft);
if(!cachedElements.loginPopup.hasClass('active')) {
clearInterval(otpcountdownTimer);
}
if(timeleft === 0) {
if($('#sso-fp-regenerate-otp')) {
$('#sso-fp-regenerate-otp').show();
}
$('#sso-regenerate-otp-timer').hide();
clearInterval(otpcountdownTimer);
}
},1000);
}
if(typeof fnCall === 'function') {
mod_login.showLoader();
fnCall.call(jssoObj, inputVal, mod_login.handleForgotPasswordRegenerateOTPCallback);
mod_login.fireGAEvent(mod_login.getPageName() + '_Re_OTP');
}
};
mod_login.handleForgotPasswordRegenerateOTPCallback = function (response) {
mod_login.hideLoader();
var $errorElement = $('input[name="otpfp"]').parent().parent();
mod_login.handleError($errorElement);
if(response && response.code === 200) {
$('#toi-forgot-password input[name="otpfp"]').val('');
$('.successMsg').text('OTP has been successfully sent.').show();
} else {
$('.successMsg').hide();
switch(response.code) {
case 416:
mod_login.handleError($errorElement, errorConfig.limitExceeded);
$('#sso-fp-regenerate-otp').addClass('disabled');
$('#forgot-password-sent').hide();
break;
case 503:
mod_login.handleError($errorElement, errorConfig.connectionError);
break;
default:
mod_login.handleError($errorElement, errorConfig.serverError);
}
mod_login.fireGAEvent('API_Error_' + response.code);
}
};
mod_login.verifyPageRegenerateOTP = function () {
if($('#sso-verify-regenerate-otp').hasClass('disabled')) {
return;
}
var jssoObj = mod_login.setAndGetJssoCrosswalkObj(),
loginType = $('#verify-logintype').val(),
inputVal = $('#verify-inputVal').val(),
ssoId = $('#verify-ssoid').val(),
fnCall;
fnCall = (loginType === 'email'? jssoObj.resendEmailSignUpOtp: jssoObj.resendMobileSignUpOtp);
if( $('#sso-verify-regenerate-otp-timer') && $('#sso-verify-regenerate-otp-timer-text')) {
var timeleft = 60;
if($('#sso-verify-regenerate-otp')) {
$('#sso-verify-regenerate-otp').hide()
}
$('#sso-verify-regenerate-otp-timer-text').text(timeleft);
$('#sso-verify-regenerate-otp-timer').show();
var otpcountdownTimer = setInterval(function(){
timeleft = timeleft - 1;
$('#sso-verify-regenerate-otp-timer-text').text(timeleft);
if(!cachedElements.loginPopup.hasClass('active')) {
clearInterval(otpcountdownTimer);
}
if(timeleft === 0) {
if($('#sso-verify-regenerate-otp')) {
$('#sso-verify-regenerate-otp').show();
}
$('#sso-verify-regenerate-otp-timer').hide();
clearInterval(otpcountdownTimer);
}
},1000);
}
if(typeof fnCall === 'function') {
mod_login.showLoader();
fnCall.call(jssoObj, inputVal, ssoId, mod_login.handleSignUpVerifyRegenerateOTPCallback);
mod_login.fireGAEvent(mod_login.getPageName() + '_Re_OTP');
}
};
mod_login.handleSignUpVerifyRegenerateOTPCallback = function (response) {
mod_login.hideLoader();
var $errorElement = $('#toi-verifyotp-password li.password:visible');
mod_login.handleError($errorElement);
if(response && response.code === 200) {
$('#toi-verifyotp-password input[name="otpverify"]').val('');
$('.successMsg').text('OTP has been successfully sent.').show();
} else {
$('.successMsg').hide();
switch(response.code) {
case 416:
mod_login.handleError($errorElement, errorConfig.limitExceeded);
$('#sso-verify-regenerate-otp').addClass('disabled');
break;
case 503:
mod_login.handleError($errorElement, errorConfig.connectionError);
break;
default:
mod_login.handleError($errorElement, errorConfig.serverError);
}
mod_login.fireGAEvent('API_Error_' + response.code);
}
};
mod_login.handleLoginOTPCallback = function(isRegenerate) {
return function (response) {
mod_login.hideLoader();
var $errorElement = $('#toi-login li.password:visible');
mod_login.handleError($errorElement);
if(response && response.code === 200) {
var loginType = mod_login.getLoginType();
var inputVal = $('#toi-login input[name="emailId"]').val();
inputVal = (loginType === 'email'? mod_login.getValidEmailId(inputVal): mod_login.getValidMobileNumber(inputVal));
$('#sso-pwdDiv').hide();
$('#sso-otpLoginDiv, #sso-login-otp-msg').show();
$('#sso-login-otp-msg > p').text('We have sent a 6 digit verification code ' + (loginType === 'email'? 'to ': 'on +91-') + inputVal);
if(isRegenerate) {
$('#toi-login input[name="otplogin"]').val('');
$('#sso-otpLoginDiv .successMsg').text('OTP has been successfully sent.').show();
}
} else {
$('#sso-otpLoginDiv .successMsg').hide();
switch(response.code) {
case 416:
mod_login.handleError($errorElement, errorConfig.limitExceeded);
// Disable Regenerate OTP button and remove text message specifying OTP has been sent
$('#sso-regenerate-otp, #sso-generate-otp, #sso-forgot-pass').addClass('disabled');
$('#sso-login-otp-msg > p').text('');
break;
case 503:
mod_login.handleError($errorElement, errorConfig.connectionError);
break;
default:
mod_login.handleError($errorElement, errorConfig.serverError);
}
mod_login.fireGAEvent('API_Error_' + response.code);
}
}
};
mod_login.fbLoginHandler = function (e) {
var callback = function () {
mod_login.closeBtnHandler();
};
mod_login.initiateFbLogin(callback);
};
mod_login.gplusLoginHandler = function () {
var callback = function () {
mod_login.closeBtnHandler();
};
mod_login.initiateGplusLogin(callback);
};
mod_login.handleLoginCallback = function (response) {
mod_login.hideLoader();
var isOtpDivVisible = $('#sso-otpLoginDiv').is(':visible');
var $errorElement = $('#toi-login li.password:visible');
var loginType = mod_login.getLoginType();
if(response && response.code === 200) {
mod_login.closeBtnHandler();
mod_login.isLoggedIn(loginCallback);
mod_login.fireGAEvent('Login_Success_' + mod_login.getPageName());
$ssoSignInInputBtn = $('#sso-signInButtonDiv > [type="submit"]');
$ssoSignInInputBtn.prop('disabled', false);
// window.location.reload(false);
} else {
$('.successMsg').hide();
switch(response.code) {
case 415:
mod_login.handleError($errorElement, (!isOtpDivVisible? errorConfig.wrongPassword: errorConfig.expiredOTP));
break;
case 416:
mod_login.handleError($errorElement, errorConfig.limitExceeded);
break;
case 503:
mod_login.handleError($errorElement, errorConfig.connectionError);
break;
default:
mod_login.handleError($errorElement, (!isOtpDivVisible? errorConfig.wrongPassword: (loginType === 'email'? errorConfig.wrongOtpEmail: errorConfig.wrongOtp )));
}
mod_login.fireGAEvent('API_Error_' + response.code);
}
};
mod_login.handleEmailIdClick = function (e) {
e.preventDefault();
var $password = $('#sso-pwdDiv input[name="password"]');
var $otp = $('#sso-otpLoginDiv input[type="password"]');
var $emailId = $('#toi-login input[name="emailId"]');
var password = '';
var $errorMsgElem = $('#toi-login li.password:visible .errorMsg');
var $loginCont = $('#toi-login');
var $agree = $loginCont.find('input[name="agree"]');
var $sharedDataAllowed = $loginCont.find('input[name="sharedDataAllowed"]');
var $agreeParent = $agree.closest('li');
var $sharedDataAllowedParent = $sharedDataAllowed.closest('li');
var sharedDataAllowed = mod_login.checkAndSetSharedDataTnCError($sharedDataAllowed, $sharedDataAllowedParent) ? '1' : '0';
var tnCAgreed = mod_login.checkAndSetAgreeTnCError($agree, $agreeParent) ? '1' : '0';
var jssoObj = mod_login.setAndGetJssoCrosswalkObj(),
loginType = mod_login.getLoginType(),
inputVal = $('#toi-login input[name="emailId"]').val(),
fnCall,
isGDPRSpecific = $('#toi-login input.js-contentCB').length > 0,
inputVal = (loginType === 'email'? mod_login.getValidEmailId(inputVal): mod_login.getValidMobileNumber(inputVal));
$emailId.prop('disabled', true);
if($password.is(':visible') || $otp.is(':visible')) {
// fnCall = (loginType === 'email'? jssoObj.verifyEmailLogin: jssoObj.verifyMobileLogin);
if (isGDPRSpecific && (sharedDataAllowed !== '1' || tnCAgreed !== '1')) {
return;
}
fnCall = (function(){
var fn;
// consent checkboxes are visible on form use gdpr specific api methods
if(isGDPRSpecific){
if(loginType === 'email'){
fn = jssoObj.verifyEmailLoginGdpr;
}
else{
fn = jssoObj.verifyMobileLoginGdpr;
}
}
// use non gdpr api methods
else if(loginType === 'email'){
fn = jssoObj.verifyEmailLogin;
}
else{
fn = jssoObj.verifyMobileLogin;
}
return fn;
})();
password = $password.is(':visible')? $password.val(): $otp.val();
mod_login.fireGAEvent(mod_login.getPageName() + ($password.is(':visible')? '_PW': '_OTP') + '_Entry');
if(password.length === 0) {
$errorMsgElem.html(errorConfig.emptyPassword).show();
return;
} else if(typeof fnCall === 'function') {
$('.errorMsg').html('').hide();
mod_login.showLoader();
$ssoSignInInputBtn = $('#sso-signInButtonDiv > [type="submit"]');
$ssoSignInInputBtn.prop('disabled', true);
if(isGDPRSpecific){
fnCall.call(jssoObj, inputVal, password, tnCAgreed, sharedDataAllowed, mod_login.getTimespointValue(), mod_login.handleLoginCallback);
}
else{
fnCall.call(jssoObj, inputVal, password, mod_login.handleLoginCallback);
}
}
} else {
if(typeof jssoObj.checkUserExists === 'function') {
mod_login.showLoader();
jssoObj.checkUserExists(inputVal, mod_login.checkUserExists);
mod_login.setPageName(loginType);
mod_login.fireGAEvent(mod_login.getPageName() + '_Continue');
} else {
$emailId.prop('disabled', false);
}
}
};
mod_login.getValidEmailId = function (email) {
var regEmail = /^([A-Za-z0-9_\-\.])+\@([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,6})$/;
var emailId = '';
if(regEmail.test(email)) {
emailId = email;
}
return emailId;
};
// withoutPrefix parameter is needed to check for valid number without +91 or 0 appended
mod_login.getValidMobileNumber = function (mobile, withoutPrefix) {
var regMobile = (withoutPrefix? /^[6789]\d{9}$/ : /^(\+91)?[0]?[6789]\d{9}$/);
var notAllowedNumbers = ['6666666666', '7777777777', '8888888888', '9999999999'];
var mobileNo = '';
var length = mobile.length;
if(regMobile.test(mobile)) {
mobileNo = mobile.substring(mobile.length - 10, mobile.length);
}
if(notAllowedNumbers.indexOf(mobileNo) !== -1) {
mobileNo = '';
}
return mobileNo;
};
mod_login.closeModalOnEscapeKeyPress = function (e) {
if(!cachedElements.loginPopup.hasClass('active')) {
return;
}
var keyCode = e.keyCode || e.which;
if(keyCode === 27) {
cachedElements.closeBtn.click();
}
};
mod_login.isPasswordValid = function (password){
return password && password.length >= 6 && password.length <= 14 && mod_login.hasNumber(password) && mod_login.hasSpecialCharacters(password) && mod_login.hasLowerCase(password);
};
mod_login.hasLowerCase = function (str) {
return (/[a-z]/.test(str));
};
mod_login.hasNumber = function (str) {
return (/[0-9]/.test(str));
};
mod_login.hasSpecialCharacters = function (str) {
return (/[!@#$%^&*()]/.test(str));
};
mod_login.passwordErrors = function (e) {
var $this = $(this);
setTimeout(function(){
var password= $this.val();
if(password.length < 6 || password.length > 14){
$("#charCnt").removeClass('success').addClass('error');
}else{
$("#charCnt").removeClass('error').addClass('success');
}
if(mod_login.hasLowerCase(password)){
$("#lwCnt").removeClass('error').addClass('success');
}else{
$("#lwCnt").removeClass('success').addClass('error');
}
if(mod_login.hasNumber(password)){
$("#numCnt").removeClass('error').addClass('success');
}else{
$("#numCnt").removeClass('success').addClass('error');
}
if(mod_login.hasSpecialCharacters(password)){
$("#spclCharCnt").removeClass('error').addClass('success');
}else{
$("#spclCharCnt").removeClass('success').addClass('error');
}
}, 0);
// return validPassword;
};
mod_login.showPassword = function (e) {
var $this = $(this);
$this.prev().attr('type', 'text');
$this.removeClass('view-password').addClass('hide-password');
};
mod_login.hidePassword = function (e) {
var $this = $(this);
$this.prev().attr('type', 'password');
$this.removeClass('hide-password').addClass('view-password');
};
mod_login.showPasswordCondition = function (e) {
e.stopPropagation();
$('.password-conditions').show();
};
mod_login.stopEventProp = function (e) {
e.stopPropagation();
};
mod_login.setLoginType = function (type) {
if (type=='email'){
mod_login.newsletterConsent = true;
$("#newsletter_subscribe").prop("checked", true);
$("#newsletter_subscribe").prop("disabled", false);
}else if(type=='mobile'){
mod_login.newsletterConsent = false;
$("#newsletter_subscribe").prop("checked", false);
$("#newsletter_subscribe").prop("disabled", true);
}
ssoLoginType = type;
}
mod_login.getLoginType = function () {
return ssoLoginType;
}
mod_login.setPageName = function(loginType) {
pageName = (loginType === 'email'? 'Email': 'MobNo');
}
mod_login.getPageName = function() {
return pageName;
}
mod_login.setScreenName = function (name) {
screenName = name;
};
mod_login.getScreenName = function (name) {
return screenName;
};
mod_login.setAndGetJssoCrosswalkObj = function () {
var jssoObj = {};
if(typeof jssoCrosswalkObj === 'object') {
jssoObj = jssoCrosswalkObj;
} else if (typeof JssoCrosswalk === 'function') {
jssoCrosswalkObj = new JssoCrosswalk('toi', 'web');
jssoObj = jssoCrosswalkObj;
}
return jssoObj;
}
mod_login.showLoader = function() {
cachedElements.formContainer.addClass('loader');
}
mod_login.hideLoader = function() {
cachedElements.formContainer.removeClass('loader');
}
mod_login.closeBtnHandler = function() {
window.loginViaRatestar = null;
cachedElements.loginPopup.removeClass('active');
mod_login.setScreenName('Login_Screen');
$('body').removeClass('disable-scroll');
$('#user-sign-in.toggle').removeClass("toi-user-login");
if(typeof grecaptcha === 'object' && $('#toi-register').is(':visible') && mod_login.showCaptcha()) {
grecaptcha.reset(recaptchaWidgetId);
}
};
mod_login.showConsentPopUp = function(){
var popUpHtml = '
'
+ '
'
+ '
Welcome Back to THE TIMES OF INDIA
'
+ '+'
+ '
'
+ '
'
+ '
One Last Step!
'
+ '
We tailor your experience and understand how you and other visitors use this website by using cookies and other technologies. This means we are able to keep this site free-of-charge to use.
'
+ '
Please provide consent for the following scenarios so that we can ensure an enjoyable experience for you on our websites and mobile apps.
'
+ '
'
+ '
'
+ mod_login.getConsentHTML()
+ '
'
+ '
'
+ ''
+ '
'
+ '
';
isUserCloseActionForConsentOverlay = true;
TimesApps.overlayModule.create({
id : 'userConsentPopUp',
isFullscreen : true,
html : popUpHtml,
classString: 'login-consent',
_onRenderCb: function(){
//bind events
//checkbx change
$('#vcw').off('change', 'input.js-contentCB').on('change', 'input.js-contentCB', mod_login.handleConsentChange);
//accept btn click
$('#consentAcceptButton').off('click').on('click', mod_login.consentPopUpAcceptBtnHandler);
$('#vcw .consentHeader .closeBtn').off('click').on('click', function() {
if(isUserCloseActionForConsentOverlay){
mod_login.logout();
TimesApps.overlayModule.close();
}
});
//handle overlay closed by user
require(["tiljs/event"], function(eventBus){
eventBus.subscribe("overlayClosed", function(overlay){
if(overlay.id === 'userConsentPopUp' && isUserCloseActionForConsentOverlay){
mod_login.logout();
}
});
});
}
})
};
mod_login.consentPopUpAcceptBtnHandler = function(){
var $overlay = $('#vcw');
var $agree = $overlay.find('input[name="agree"]');
var $sharedDataAllowed = $overlay.find('input[name="sharedDataAllowed"]');
var $agreeParent = $agree.closest('li');
var $sharedDataAllowedParent = $sharedDataAllowed.closest('li');
var sharedDataAllowed = mod_login.checkAndSetSharedDataTnCError($sharedDataAllowed, $sharedDataAllowedParent) ? '1' : '0';
var tnCAgreed = mod_login.checkAndSetAgreeTnCError($agree, $agreeParent) ? '1' : '0';
var formValid = true;
if(sharedDataAllowed !== '1' || tnCAgreed !== '1'){
formValid = false;
}
if(formValid){
mod_login.updateUserPermissions(true);
}
}
mod_login.updateUserPermissions = function(allowCallbackAfterLogin) {
var jssoObj = mod_login.setAndGetJssoCrosswalkObj();
if(typeof jssoObj.updateUserPermissions === 'function') {
jssoObj.updateUserPermissions('1', '1', mod_login.getTimespointValue(), function(response){
isUserCloseActionForConsentOverlay = false;
TimesApps.overlayModule.close();
if (allowCallbackAfterLogin && typeof callbackToCallAfterConsent === 'function') {
callbackToCallAfterConsent(userObj);
callbackToCallAfterConsent = null;
}
// jssoObj.getValidLoggedInUser();
});
}
}
mod_login.checkAndUpdateTimespointValue = function() {
var consentAgreedVal = cookie.get('gdpr');
if (consentAgreedVal && consentAgreedVal.substr(0, 4) === '1#1#') {
if ((consentAgreedVal[4] !== '0' && __isEUUser) || (consentAgreedVal[4] !== '1' && !__isEUUser)) {
mod_login.updateUserPermissions();
}
}
};
mod_login.isConsentGiven = function() {
var consentAgreed = cookie.get('gdpr');
return (consentAgreed === '1#1#1' || consentAgreed === '1#1#0');
};
mod_login.init = function (init_config) {
var initCallback = function() {
var jssoObj = mod_login.setAndGetJssoCrosswalkObj();
cachedElements.loginPopup.show();
mod_login.updateConfig(init_config);
if (config.renderer === true) {
mod_login.onStatusChange(function (_user) {
mod_login.renderPlugins(_user);
});
}
mod_login.isLoggedIn(function (user) {
var _cbq = window._cbq = (window._cbq || []);
if (user && typeof user === 'object') {
event.publish("user.autologgedin", user);
require(['primeuserhandler'], function(puser) {
var isPrime = puser.isPrimeActiveUser();
if (isPrime) {
_cbq.push(['_acct', 'prime']);
} else {
_cbq.push(['_acct', 'lgdin']);
}
TimesApps.loadChartBeatCalls();
var hashVal = window.location.hash.toLowerCase();
if ((hashVal === ('#' + config.primeFreeSuccessHash) || hashVal === ('#' + config.primePaidSuccessHash))) {
// slice off the remaining '#' in HTML5:
if (typeof window.history.replaceState == 'function') {
window.history.replaceState({}, '', window.location.href.substr(0, window.location.href.indexOf('#')));
}
// mod_login.setPrcForUser(puser.getPrimeCongratsPopup.bind(puser, true, true));
}
/*else if( !puser.isPrimeActiveUser() && puser.isPrimeActiveUser(user.getPrimeStatus()) ){
mod_login.setPrcForUser(puser.getPrimeCongratsPopup.bind(puser, true, true));
}*/
// if (isPrime && typeof TimesApps.SavingsAPI === 'object') {
// TimesApps.SavingsAPI.initializeApi();
// }
// if (typeof TimesApps.SavingsAPI === 'object') {
// TimesApps.SavingsAPI.initializeApi();
// }
});
} else {
_cbq.push(['_acct', 'anon']);
TimesApps.loadChartBeatCalls();
}
});
mod_login.onStatusChange(function (_user) {
if(__isEUUser && _user && !mod_login.isConsentGiven()){
mod_login.showConsentPopUp();
}
});
mod_login.initActions();
}
TimesApps.checkGdprAndCall(function(){
__isEUUser = false;
initCallback();
}, function(){
initCallback();
});
};
mod_login.getConfig = function(){
return config;
}
mod_login.getErrorConfig = function(){
return errorConfig;
}
mod_login.initActions = function () {
cachedElements.closeBtn
.on("click", function() {
mod_login.closeBtnHandler();
mod_login.fireGAEvent('Close');
});
$("[data-plugin='user-isloggedin']")
.on("click", "[data-plugin='user-logout']", function () {
mod_login.logout();
});
$("[data-plugin='user-notloggedin']")
.on("click", "[data-plugin='user-login']", function () {
// handled by mobile login
if(typeof toiprops !== 'undefined' && toiprops.primetemplate === true){
return;
}
$('body').addClass('disable-scroll');
cachedElements.loginPopup.addClass('active');
mod_login.showLoginScreen(mod_login.subscribeNewletters);
mod_login.setScreenName('Login_Screen');
mod_login.fireGAEvent('Load');
})
.on("click", "[data-plugin='user-register']", function () {
mod_login.register();
})
.on("click", "[data-plugin='user-login-facebook']", function () {
mod_login.loginWithFacebook();
})
.on("click", "[data-plugin='user-login-twitter']", function () {
mod_login.loginWithTwitter();
})
.on("click", "[data-plugin='user-login-google']", function () {
mod_login.loginWithGoogle();
});
$(document).on('keyup', mod_login.closeModalOnEscapeKeyPress);
cachedElements.formContainer
.off('keyup paste', '#toi-login input[name="emailId"]').on('keyup paste', '#toi-login input[name="emailId"]', mod_login.handleEmailIdKeyUp)
.off('keyup paste', '#toi-login input[name="password"]').on('keyup paste', '#toi-login input[name="password"]', mod_login.handlePasswordKeyUp)
.off('keyup paste', '#toi-login input[name="otplogin"]').on('keyup paste', '#toi-login input[name="otplogin"]', mod_login.handleOtploginKeyUp)
.off('click', '#toi-login[data-login-type="email"] #sso-signInButtonDiv [type="submit"]').on('click', '#toi-login[data-login-type="email"] #sso-signInButtonDiv input[type="submit"]', mod_login.handleEmailIdClick)
.off('submit', '#toi-login[data-login-type="email"] #toi-login form').on('submit', '#toi-login[data-login-type="email"] #toi-login form', mod_login.handleEmailIdClick)
.off('click', '#toi-login[data-login-type="email"] #changeEmailIdDiv').on('click', '#toi-login[data-login-type="email"] #changeEmailIdDiv', mod_login.changeEmailIdHandler)
.off('click', '#changeRegisterEmailId').on('click', '#changeRegisterEmailId', mod_login.changeRegisterEmailIdHandler)
.off('click', '#sso-forgot-pass').on('click', '#sso-forgot-pass', mod_login.forgotPasswordHandler)
.off('click', '#sso-fb-login').on('click', '#sso-fb-login', mod_login.fbLoginHandler)
.off('click', '#sso-gplus-login').on('click', '#sso-gplus-login', mod_login.gplusLoginHandler)
.off('click', '#sso-generate-otp').on('click', '#sso-generate-otp', mod_login.loginWithOTP)
.off('click', '#toi-login[data-login-type="email"] #sso-regenerate-otp').on('click', '#sso-regenerate-otp', mod_login.regenerateLoginOTP)
.off('click', '#sso-fp-regenerate-otp').on('click', '#sso-fp-regenerate-otp', mod_login.fpRegenerateOTP)
.off('click', '#sso-verify-regenerate-otp').on('click', '#sso-verify-regenerate-otp', mod_login.verifyPageRegenerateOTP)
.off('click', '#sso-registerBtn').on('click', '#sso-registerBtn', mod_login.registerButtonHandler)
.off('submit', '#toi-register form').on('submit', '#toi-register form', mod_login.registerButtonHandler)
.off('click', '#sso-verify-btn').on('click', '#sso-verify-btn', mod_login.verifyButtonHandler)
.off('click', '#sso-verify-email-btn').on('click', '#sso-verify-email-btn', mod_login.verifyEmailButtonHandler)
.off('submit', '#toi-verifyotp-password form').on('submit', '#toi-verifyotp-password form', mod_login.verifyButtonHandler)
.off('click', '#sso-fp-btn').on('click', '#sso-fp-btn', mod_login.forgotPasswordBtnHandler)
.off('submit', '#toi-forgot-password form').on('submit', '#toi-forgot-password form', mod_login.forgotPasswordBtnHandler)
.off('focus', 'input[name="registerPwd"]').on('focus', 'input[name="registerPwd"]', mod_login.showPasswordCondition)
.off('keyup paste', '#toi-register input[name="registerPwd"]').on('keyup paste', '#toi-register input[name="registerPwd"]', mod_login.passwordErrors)
.off('keyup paste', '#toi-register input[type="text"]').on('keyup paste', '#toi-register input[type="text"]', mod_login.registerFormErrorHandler)
.off('keyup paste', '#toi-register input[name!="registerPwd"][type="password"]').on('keyup paste', '#toi-register input[name!="registerPwd"][type="password"]', mod_login.registerFormErrorHandler)
.off('change', '#toi-register input[name="agree"]').on('change', '#toi-register input[name="agree"]', mod_login.registerFormErrorHandler)
// .off('focus blur', '[placeholder]:not(input[name="registerPwd"])').on('focus blur', '[placeholder]:not(input[name="registerPwd"])', mod_login.stopEventProp)
.off('focus blur', '[placeholder]').on('focus blur', '[placeholder]', mod_login.stopEventProp)
.off('keyup paste', '#toi-forgot-password input').on('keyup paste', '#toi-forgot-password input', mod_login.fpInputKeyupHandler)
.off('keyup paste', '#toi-verifyotp-password input[name="otpverify"]').on('keyup paste', '#toi-verifyotp-password input[name="otpverify"]', mod_login.enableVerifyButton)
.off('click', '.view-password').on('click', '.view-password', mod_login.showPassword)
.off('click', '.hide-password').on('click', '.hide-password', mod_login.hidePassword)
.off('change', '#toi-register input[name="sharedDataAllowed"]').on('change', '#toi-register input[name="sharedDataAllowed"]', mod_login.registerFormErrorHandler)
.off('change', 'input.js-contentCB').on('change', 'input.js-contentCB', mod_login.handleConsentChange)
.off('change', '#newsletter_subscribe').on('change', '#newsletter_subscribe', mod_login.handleNewsletterConsent)
};
cachedElements.loginPopup.off('click').on('click', function(e){
if(e.srcElement && e.srcElement.id === 'login-popup') {
cachedElements.closeBtn.click();
}
});
mod_login.updateConfig(mod_login_config);
return mod_login;
});
define( 'login',[ "tiljs/apps/times/usermanagement" ],
function ( login) {
return login;
} );
/* To integrate login please do the following:
* 1. Fork toiusermanagement_js and usermanagementcss and include it in your project
* 2. Add below JS files in your project. These files should be added globally
* a)
* b)
* 3. Update GA events category in the toiusermanagement_js as per your project needs
* 4. Update usermanagementcss file to change skin of Login modal
*/
define('tiljs/apps/times/mobilelogin',[
"../../util",
"module",
"../../page",
"../../ajax",
"../times/api",
"../../is",
"../../cookie",
"../../ui",
"../../logger",
"../../event",
"../../load",
"../../localstorage",
"../../user",
"../../analytics/mytimes",
"primeuserhandler",
"tiljs/apps/times/usermanagement"
],
function(util, module, page, ajax, api, is, cookie, ui, logger, event, load, localstorage, user, mytimes, puser, mod_login){
var mod_mobilelogin = {};
var config = {
resendTimeInSec: 60,
headingText:'Log in to your account',
completeprofile:'COMPLETE YOUR PROFILE',
bottomText:''
};
var config_default = {
headingText:'Log in to your account',
bottomText:'',
};
config.primemessages={headingText:'START YOUR FREE TRIAL',bottomText:'Enjoy exclusive articles & premium benefits from'}
config.adfreeprimemessages={headingText:'START AD-FREE TRIAL',bottomText:'Enjoy an ad-free experience & premium benefits from'}
config.verifymobile={headingText:'VERIFY MOBILE TO SUBSCRIBE',bottomText:''}
config.subscribe={headingText:'LOGIN TO SUBSCRIBE',bottomText:''}
var errorConfig = {
wrongOtp: 'Please Enter a valid OTP',
limitExceeded:'Maximum number of attempts to generate otp is exceeded. Please try again later.'
}
var cachedElements = {
loginPopup: $('#login-popup'),
formContainer: $('#user-sign-in'),
mobileLoginFormContainer: $('#mobile-login'),
closeBtn: $('#login-popup .close-btn')
}
var loginCallback = null;
var updateMobileCallback = null;
var resendTimeInterval;
var fireGAEvent = function(_action, _label) {
require(["pgtrack"], function(pgtrack) {
pgtrack.track('#' + _label + '~' + _action);
});
};
mod_mobilelogin.loginWithOTP = function(e, isRegenerate) {
// Do not perform any action if generate otp is disabled
// if($('#sso-generate-otp').hasClass('disabled')) {
// return;
// }
var $emailId = $('#toi-login input[name="emailId"]');
var $errorElem = $('#sso-otpLoginDiv');
var jssoObj = mod_login.setAndGetJssoCrosswalkObj(),
inputVal = $('#toi-login input[name="emailId"]').val();
inputVal = mod_login.getValidMobileNumber(inputVal);
// fnCall = (loginType === 'email'? jssoObj.getEmailLoginOtp: jssoObj.getMobileLoginOtp);
mod_login.showLoader();
if (!!config.updateMobileFlow) {
mod_mobilelogin.updateUserMobile(inputVal, mod_mobilelogin.updateUserMobileCallback(isRegenerate, $errorElem));
}
else if (mod_login.getScreenName() === 'Register_New_User') {
jssoObj.resendMobileSignUpOtp(inputVal, mod_login.ssoid, mod_mobilelogin.handleLoginOTPCallback(isRegenerate, $errorElem));
mod_mobilelogin.showstate('.verifymobilenewuser');
} else {
jssoObj.getMobileLoginOtp(inputVal, mod_mobilelogin.handleLoginOTPCallback(isRegenerate, $errorElem));
mod_mobilelogin.showstate('.verifymobile');
}
// fnCall.call(jssoObj, inputVal, mod_login.handleLoginOTPCallback(isRegenerate));
if(isRegenerate) {
if(mod_login.getGa()!=""){
mod_login.fireGAEventMetered('Login_screen_OTPScreen_OTPResend','MobNo_OTP_Entry' + '/'+mod_login.getGa());
}
else
{
mod_login.fireGAEvent( mod_login.getPageName() + '_Re_OTP');
}
} else {
mod_login.fireGAEvent(mod_login.getPageName() + '_OTP_Submit');
}
};
// Duplicate method in case any message needed for regenerate OTP logic
mod_mobilelogin.regenerateLoginOTP = function() {
// Do not perform any action if regenerate otp is disabled
if($('#sso-regenerate-otp').hasClass('disabled')) {
return;
}
mod_mobilelogin.loginWithOTP({}, true);
};
mod_mobilelogin.handleLoginOTPCallback = function(isRegenerate, $errorElement) {
return function (response) {
mod_login.hideLoader();
// var $errorElement = $('#toi-login li.password:visible');
mod_login.handleError($errorElement);
if(response && response.code === 200) {
$('#regenerate-otp-container').show();
mod_mobilelogin.startResendOtpInterval();
var loginType = mod_login.getLoginType();
var inputVal = $('#toi-login input[name="emailId"]').val();
inputVal = (loginType === 'email'? mod_login.getValidEmailId(inputVal): mod_login.getValidMobileNumber(inputVal));
$('#sso-pwdDiv').hide();
$('#sso-otpLoginDiv, #sso-login-otp-msg').show();
$('#sso-mobile-input, .sso-signin-form-data, #sso-regenerate-otp, #sso-otpLoginDiv .errorMsg').hide();
$('#sso-otpLoginDiv, #sso-send-otp-screen').show();
$('#changeEmailIdDiv').css('display', 'inline-block');
// $('#sso-login-otp-msg > p').text('We have sent a 6 digit verification code ' + (loginType === 'email'? 'to ': 'on +91-') + inputVal);
if(isRegenerate) {
$('#toi-login input[name="otplogin"]').val('');
$('#toi-login .otpCodeInput').val('');
// $('#sso-otpLoginDiv .successMsg').text('OTP has been successfully sent.').show();
}
} else {
$('#sso-otpLoginDiv .successMsg').hide();
switch(response.code) {
case 416:
mod_login.handleError($errorElement, errorConfig.limitExceeded);
// Disable Regenerate OTP button and remove text message specifying OTP has been sent
$('#sso-regenerate-otp, #sso-generate-otp, #sso-forgot-pass').addClass('disabled');
$('#sso-mobile-input > p #changeEmailIdDivSignUpOtp').show();
break;
case 503:
mod_login.handleError($errorElement, errorConfig.connectionError);
break;
default:
mod_login.handleError($errorElement, errorConfig.serverError);
}
mod_login.fireGAEvent('API_Error_' + response.code);
}
}
};
/**
* API callback of checkUserExists
*
* @param response - Response object
* @param
*/
mod_mobilelogin.checkUserExists = function(response) {
mod_login.hideLoader();
var $errorElement = $('#toi-login li.mobile');
var $emailId = $('#toi-login input[name="emailId"]');
var errorMsg = '', userName = '';
var loginType = mod_login.getLoginType();
var $signInBtn = $('#sso-signInButtonDiv');
var jssoObj = mod_login.setAndGetJssoCrosswalkObj(),
inputVal = $('#toi-login input[name="emailId"]').val();
inputVal = (loginType === 'email'? mod_login.getValidEmailId(inputVal): mod_login.getValidMobileNumber(inputVal));
mod_login.handleError($errorElement);
$('#sso-send-otp-screen span').text(inputVal);
if(response && response.code === 200 && response.data) {
if(response.data.statusCode === 212 || response.data.statusCode === 213) {
if(typeof jssoObj.getMobileLoginOtp === 'function') {
mod_login.showLoader();
mod_mobilelogin.showstate('.verifymobile');
$('.toi-user-login #sso-signInButtonDiv [type="submit"]').removeClass("arrow-btn").addClass("user-submit-btn").text("Submit")
jssoObj.getMobileLoginOtp(inputVal, mod_mobilelogin.handleLoginOTPCallback(false, $errorElement));
if(mod_login.getGa()!=""){
mod_login.fireGAEventMetered('Login_screen_OTPScreen_view','MobNo_OTP_Entry' + '/'+mod_login.getGa())
}
else
{
mod_login.fireGAEvent(mod_login.getPageName() + '_OTP_Submit');
}
}
if(response.data.termsAccepted !== '1' || response.data.shareDataAllowed !== '1'){
$signInBtn.find('input[type="submit"]').attr('disabled', 'disabled');
// show and handle consent checkboxes
$(mod_login.getConsentHTML()).insertBefore($signInBtn);
// to handle both fb and google buttons in single line when checkboxes are visible
$('#user-sign-in').addClass('extra-content');
}
} else if(response.data.statusCode === 205 || response.data.statusCode === 206 || response.data.statusCode === 214 || response.data.statusCode === 215) {
mod_login.setScreenName('Register_New_User');
mod_mobilelogin.showstate('.verifymobilenewuser');
$('#sso-register-form input[name="emailId"]').val(inputVal);
mod_mobilelogin.showRegisterView();
} else {
$emailId.prop('disabled', false);
errorMsg = response.data.statusCode === 216 ? errorConfig.fpInvalidEmailOnly: errorConfig.fpInvalidEmail;
mod_login.handleError($errorElement, errorMsg);
}
} else {
$emailId.prop('disabled', false);
if(response.code === 410) {
mod_login.handleError($errorElement, (loginType === 'email'? errorConfig.fpInvalidEmailOnly: errorConfig.fpInvalidMobileOnly));
} else if(response.code === 503) {
mod_login.handleError($errorElement, errorConfig.connectionError);
} else {
mod_login.handleError($errorElement, errorConfig.serverError);
}
mod_login.fireGAEvent('API_Error_' + response.code);
}
};
mod_mobilelogin.otpNotSucceedHandling = function (response) {
var $errorElement = $('#sso-otpLoginDiv');
$('.successMsg').hide();
switch(response.code) {
case 414:
mod_login.handleError($errorElement, errorConfig.wrongOtp);
break;
case 415:
mod_login.handleError($errorElement, errorConfig.expiredOTP);
break;
case 416:
mod_login.handleError($errorElement, errorConfig.limitExceeded);
break;
case 503:
mod_login.handleError($errorElement, errorConfig.connectionError);
break;
default:
mod_login.handleError($errorElement, errorConfig.wrongOtp );
}
mod_login.fireGAEvent('API_Error_' + response.code);
};
mod_mobilelogin.handleLoginCallback = function (response) {
mod_login.hideLoader();
if(response && response.code === 200) {
mod_login.closeBtnHandler();
mod_login.isLoggedIn(mod_login.getLoginCallback());
if(mod_login.getGa()!=""){
sessionStorage.setItem('meteredLoginSuccess', 1);
}
else
{
mod_login.fireGAEvent('Login_Success_' + mod_login.getPageName());
}
if (resendTimeInterval) {
clearInterval(resendTimeInterval);
}
} else {
mod_mobilelogin.otpNotSucceedHandling(response);
}
};
mod_mobilelogin.handleEmailIdClick = function (e) {
e.preventDefault();
var $otp = $('#sso-otpLoginDiv');
var $emailId = $('#toi-login input[name="emailId"]');
var password = '';
var $errorMsgElem = $('#toi-login li.password:visible .errorMsg');
var _checkIsOTP;
$emailId.prop('disabled', true);
var jssoObj = mod_login.setAndGetJssoCrosswalkObj(),
loginType = mod_login.getLoginType(),
inputVal = $('#toi-login input[name="emailId"]').val(),
fnCall, $form, checkboxLen = 0;
inputVal = mod_login.getValidMobileNumber(inputVal);
if($otp.is(':visible')) {
// fnCall = (mod_login.getScreenName() === 'Register_New_User'? jssoObj.verifyMobileSignUp: jssoObj.verifyMobileLogin);
$('input.otpCodeInput').each(function(index, value) {
password += $(value).val().toString();
});
_checkIsOTP = mod_mobilelogin.checkIsOTP(password);
// password = $otp.val();
if(mod_login.getGa()!=""){
mod_login.fireGAEventMetered('Login_screen_OTPScreen_Verify_OTP','MobNo_OTP_Entry/'+mod_login.getGa())
}
else
{
mod_login.fireGAEvent(mod_login.getPageName() + '_OTP_Entry');
}
if(!_checkIsOTP) {
$errorMsgElem.html(errorConfig.emptyPassword).show();
return;
} else {
if(config.updateMobileFlow){
mod_mobilelogin.verifyUserMobile(inputVal, password, mod_mobilelogin.verifyUserMobileCallback);
}
else{
$form = $('#sso-login-form');
var checkboxLen = $form.find('.js-contentCB').length;
if (checkboxLen > 0 && !mod_login.areMandatoryFieldsSelected($form)) {
return;
}
$('.errorMsg').html('').hide();
mod_login.showLoader();
if (mod_login.getScreenName() === 'Register_New_User') {
jssoObj.verifyMobileSignUp(inputVal, mod_login.ssoid, password, mod_mobilelogin.handleLoginCallback);
mod_mobilelogin.showstate('.ftanew');
} else {
mod_mobilelogin.showstate('.fta');
$form = $('#sso-login-form');
checkboxLen = $form.find('.js-contentCB').length;
if (checkboxLen > 0 && !mod_login.areMandatoryFieldsSelected($form)) {
return;
}
if(checkboxLen > 0){
jssoObj.verifyMobileLoginGdpr(inputVal, password, '1', '1', mod_login.getTimespointValue(), mod_mobilelogin.handleLoginCallback);
} else {
jssoObj.verifyMobileLogin(inputVal, password, mod_mobilelogin.handleLoginCallback);
}
}
// fnCall.call(jssoObj, inputVal, password, mod_login.handleLoginCallback);
}
}
} else {
if(!!config.updateMobileFlow){
var $errorElement = $('#sso-mobile-input');
mod_mobilelogin.updateUserMobile(inputVal, mod_mobilelogin.updateUserMobileCallback(false, $errorElement));
}
else if(typeof jssoObj.checkUserExists === 'function') {
mod_login.showLoader();
jssoObj.checkUserExists(inputVal, mod_mobilelogin.checkUserExists);
mod_login.setPageName(loginType);
if(mod_login.getGa()!=""){
mod_login.fireGAEventMetered('Login_screen_Mobile_Submit','Mobno_Continue/'+mod_login.getGa())
}
else
{
mod_login.fireGAEvent(mod_login.getPageName() + '_Continue');
}
} else {
$emailId.prop('disabled', false);
}
}
};
mod_mobilelogin.handleEmailIdKeyPress = function(e) {
var $this = $(this);
var keyCode = mod_mobilelogin.getKeyCode(e);
if (keyCode === 13) {
return true;
}
if((keyCode === 8) || !mod_mobilelogin.allowNumber(e)){
return false;
}
}
mod_mobilelogin.changeRegisterMobileHandler = function(e) {
e.stopPropagation();
$('#sso-login-form, #sso-signin-form').show();
$('#sso-register-form').hide();
mod_mobilelogin.changeEmailIdHandler(e);
};
mod_mobilelogin.changeRegisterMobileHandlerOtp = function(e) {
e.stopPropagation();
$('#sso-mobile-input > p #changeEmailIdDivSignUpOtp').hide();
mod_mobilelogin.changeEmailIdHandler(e);
};
/**
* Handles Change Email/Mobile link click
*
* @param
* @param
*/
mod_mobilelogin.changeEmailIdHandler = function (e) {
$('#sso-pwdDiv, #changeEmailIdDiv, #sso-otpLoginDiv, #sso-login-otp-msg, #sso-send-otp-screen, #regenerate-otp-container, #sso-regenerate-otp').hide();
$('#sso-mobile-input, .sso-signin-form-data').show();
$('#toi-login input[name="emailId"]').prop('disabled', false).val('');
$('#sso-signInButtonDiv [type="submit"]').prop('disabled', true).addClass('disabled');
$('.errorMsg, .successMsg').hide();
$('.error').removeClass('error');
// $('#sso-signInButtonDiv > input').val('Continue');
$('#sso-pwdDiv input[name="password"]').val('');
$('#sso-otpLoginDiv input[type="password"]').val('');
$('#sso-regenerate-otp, #sso-fp-regenerate-otp, #sso-verify-regenerate-otp, #sso-generate-otp, #sso-forgot-pass').removeClass('disabled');
mod_login.fireGAEvent(mod_login.getPageName() + '_Change');
mod_login.setScreenName('Login_Screen');
mod_mobilelogin.showstate('.startscreen');
$('#sso-signInButtonDiv [type="submit"]').removeClass("user-submit-btn").addClass("arrow-btn").text("")
clearInterval(resendTimeInterval);
mod_login.ssoid = '';
$('#toi-login .otpCodeInput').val('');
if($("#sso-signin-form").find(".checkbox").length > 0){
$("#sso-signin-form").find(".checkbox").remove()
}
};
mod_mobilelogin.allowNumber = function(event) {
var keyCode = mod_mobilelogin.getKeyCode(event);
if (event.target.value.length >= 10 ||
$.inArray(keyCode, [0, 32]) > -1 ||
(keyCode != 8 && isNaN(String.fromCharCode(keyCode)))) {
event.preventDefault(); //stop character from entering input
return false;
}
return true;
};
mod_mobilelogin.getKeyCode = function (event) {
var keyCode = event.keyCode || event.which;
if (keyCode == 0 || keyCode == 229) { //for android chrome keycode fix
var value = event.target.value;
keyCode = value.charCodeAt(value.length - 1);
}
return keyCode;
}
mod_mobilelogin.showConsentPopUp = function(){
var popUpHtml = '
'
+ '
'
+ '
Welcome Back to THE TIMES OF INDIA
'
+ '+'
+ '
'
+ '
'
+ '
One Last Step!
'
+ '
We tailor your experience and understand how you and other visitors use this website by using cookies and other technologies. This means we are able to keep this site free-of-charge to use.
'
+ '
Please provide consent for the following scenarios so that we can ensure an enjoyable experience for you on our websites and mobile apps.
*
* @memberOf module:ajax#
* @function get
*
* @example
*
* require(['ajax'],function(ajax){
* ajax.get("http://www.abc.com/data.json",{},function(data){
* console.log(data); //data returned by ajax request
* });
* });
* @param {String|Function} url A string containing the URL to which the request is sent.
* @param {Object|String} [data] A plain object or string that is sent to the server with the request.
* @param {Function} [callback] A callback function that is executed if the request succeeds.
* @param {String} [type] The type of data expected from the server. Default: Intelligent Guess (xml, json, script, or html).
* @returns {object}
*/
mod_ajax.get = function ( url, data, callback, type ) {
if( is.funct( url ) ) {
return url( data, callback );
} else {
return $.get( url, data, callback, type );
}
};
/**
* Send/Load data to/from the server using a HTTP POST request.
*
* See {@link http://api.jquery.com/jQuery.get/|jQuery.get}
*
* This is a shorthand Ajax function, which is equivalent to:
*
*