/*!
 * jQuery Cookie Plugin v1.4.1
 * https://github.com/carhartl/jquery-cookie
 *
 * Copyright 2013 Klaus Hartl
 * Released under the MIT license
 */
(function (factory) {
	if (typeof define === 'function' && define.amd) {
		// AMD
		define(['jquery'], factory);
	} else if (typeof exports === 'object') {
		// CommonJS
		factory(require('jquery'));
	} else {
		// Browser globals
		factory(jQuery);
	}
}(function ($) {

	var pluses = /\+/g;

	function encode(s) {
		return config.raw ? s : encodeURIComponent(s);
	}

	function decode(s) {
		return config.raw ? s : decodeURIComponent(s);
	}

	function stringifyCookieValue(value) {
		return encode(config.json ? JSON.stringify(value) : String(value));
	}

	function parseCookieValue(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 {
			// Replace server-side written pluses with spaces.
			// If we can't decode the cookie, ignore it, it's unusable.
			// If we can't parse the cookie, ignore it, it's unusable.
			s = decodeURIComponent(s.replace(pluses, ' '));
			return config.json ? JSON.parse(s) : s;
		} catch(e) {}
	}

	function read(s, converter) {
		var value = config.raw ? s : parseCookieValue(s);
		return $.isFunction(converter) ? converter(value) : value;
	}

	var config = $.cookie = function (key, value, options) {

		// Write

		if (value !== undefined && !$.isFunction(value)) {
			options = $.extend({}, config.defaults, options);

			if (typeof options.expires === 'number') {
				var days = options.expires, t = options.expires = new Date();
				t.setTime(+t + days * 864e+5);
			}

			return (document.cookie = [
				encode(key), '=', stringifyCookieValue(value),
				options.expires ? '; expires=' + options.expires.toUTCString() : '', // use expires attribute, max-age is not supported by IE
				options.path    ? '; path=' + options.path : '',
				options.domain  ? '; domain=' + options.domain : '',
				options.secure  ? '; secure' : ''
			].join(''));
		}

		// Read

		var result = key ? undefined : {};

		// To prevent the for loop in the first place assign an empty array
		// in case there are no cookies at all. Also prevents odd result when
		// calling $.cookie().
		var cookies = document.cookie ? document.cookie.split('; ') : [];

		for (var i = 0, l = cookies.length; i < l; i++) {
			var parts = cookies[i].split('=');
			var name = decode(parts.shift());
			var cookie = parts.join('=');

			if (key && key === name) {
				// If second argument (value) is a function it's a converter...
				result = read(cookie, value);
				break;
			}

			// Prevent storing a cookie that we couldn't decode.
			if (!key && (cookie = read(cookie)) !== undefined) {
				result[name] = cookie;
			}
		}

		return result;
	};

	config.defaults = {};

	$.removeCookie = function (key, options) {
		if ($.cookie(key) === undefined) {
			return false;
		}

		// Must not alter options, thus extending a fresh object...
		$.cookie(key, '', $.extend({}, options, { expires: -1 }));
		return !$.cookie(key);
	};

}));
;
var _isLogin = null;
var BaseUrl = null;
var _isFree_paid = null;

var TotalImages = 0;
var TotalImagesDone = 0;
var StoryMapDeskTop = [];
var g_AnalyticsId;
function SetUrl(url) {

    BaseUrl = url;
}
//function webEngageEvent(action, obtype) {
//    try {
//        var PageId = $.cookie("PageId");
//        var pageName = $("#page" + PageId).attr('pg_title');
//        if (pageName == undefined) {
//            pageName = "pageName";
//        }
//        var Edname = $("#span_Edition").text();
//        var viewData = {};
//        viewData['domain'] = "ELM";
//        viewData['screenName'] = "Story Detail";
//        switch (action) {
//            case "read":
//                viewData["section"] = pageName;
//                viewData["subSection"] = "story";
//                if (obtype == "4") {
//                    viewData["subSection"] = "image";
//                }
//                viewData["timeToRead"] = new Date();;
//                viewData["publishedDate"] = "";
//                viewData["publishedTime"] = "";
//                viewData["author"] = "";
//                viewData["storyType"] = "story";
//                viewData["articleDesk"] = "Epaper"
//                webengage.track("ArticleRead", viewData);
//                break;
//            case "login":
//                webengage.track("Sign Up Pop Up Viewed", viewData);
//                break;
//            case "subscribe":
//                viewData['Button Name'] = "Subscribe Now"
//                webengage.track("Sign Up Pop Up Viewed", viewData);
//                break;

//        }
//    } catch (error) { }
//}
function getResult(url, param) {
    var result;
  
    $.ajax({
        url: url,
        type: "Get",
        async: false,
        dataType: "json",
        data: param,
        contentType: "application/json; charset=utf-8",
        success: function (data, textStatus) {
              result = data;                 

        },
        error: function (e) {            
            result = "Error";
        }
    });
    //$("#loader").hide();
    return result;
   
}

function alertMesage(Message) {
    $.notify({
        //  title: '<strong>Heads up!</strong>',
        message: Message
    }, {
        type: 'success',
        animate: {
                   enter: 'animated bounceIn',
                   exit: 'animated bounceOut'
               },
        delay: 2000,
        offset: {
            x: 0,
            y: 0
        }
    });
}
function alert_Mesage_Selector(_Selector, _Display_Position, _Msg_Type, _Message, _delay_in_milliseconds) {

    $(_Selector).notify(_Message, _Msg_Type,

        {
            position: _Display_Position,
            autoHideDelay: _delay_in_milliseconds,
            clickToHide: true,
            autoHide: true,
            gap: 2,
            arrowShow: true,
            arrowSize: 5,
            //style: 'happyblue',
            // default class (string or [string])
            //className: 'notifyjs-happyblue-base',
            // show animation
            showAnimation: 'slideDown',
            // show animation duration
            showDuration: 400,
            //  hide animation
            hideAnimation: 'slideUp'
            //  hide animation duration
            // hideDuration: 200

        }
    );

}

function setcookies_long(name, value) {

    var date = new Date();
    var minutes = 60 * 24 * 365;
    date.setTime(date.getTime() + (minutes * 60 * 1000));
    $.cookie(name, value, { expires: date });
}
var IsIos = function () {
    var _IsIos = false;
    var platform = navigator.platform;
    if (platform.match(/(iPod|iPhone|iPad)/)) {
        _IsIos = true;
    }
    return _IsIos;
}();
function isEmail(email) {
    var regex = /^(([^<>()\[\]\\.,;:\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 regex.test(email);
}


function Checklogin() {

    var url = BaseUrl + "Home/checklogin";
    var param = {}
    var result = getResult(url, param);
    if (result != "Error") {
        if (result.status) {
            var _user = result.UserName;
            var _email = result.Email;
            if (_user.length > 10) {
                $('#user_name,.user-name').text(_user.substring(0, 10) + "...");

            } else {
                $('#user_name,.user-name').text(_user);
            }
            $('.user-email').text(_email);
            $('.avatar').text(_email.slice(0, 1));
            $('#user_name_mob').text(_user.toUpperCase());

        } else {
            $('#user_name,.user-name').text('');
        }
        return result.status;
    } else {
        $('#user_name,.user-name').text('');
        return false;
    }

}
function MobChecklogin(result) {

    if (result != "Error") {
        if (result.status) {
            var _user = result.UserName;
            if (_user.length > 10) {
                $('#user_name').text(_user.substring(0, 10) + "...");
            } else {
                $('#user_name').text(_user);
            }
            $('#user_name_mob').text(_user.toUpperCase());

        } else {
            $('#user_name').text('');
        }
        return result.status;
    } else {
        $('#user_name').text('');
        return false;
    }

}

function getResultasync(url, param) {
    var result;

    $.ajax({
        url: url,
        type: "Get",
        async: true,
        dataType: "json",
        data: param,
        contentType: "application/json; charset=utf-8",
        success: function (data, textStatus) {
            result = data;

        },
        error: function (e) {
            result = "Error";
        }
    });
    return result;
}

function getResultnew(url, param) {
    var result;

    $.ajax({
        url: url,
        type: "Get",
        async: false,
        dataType: "json",
        data: param,
        contentType: "application/json; charset=utf-8",
        success: function (data, textStatus) {
            result = data;

        },
        error: function (e) {
           
            result = "Error";
        }

    });
    if (result.length == 0)
    {
        $("#idsocial_share_box a").css("display", "none");  
    }
    else {
        $("#idsocial_share_box a").css("display", "block");
    }
   
    $("#loader").hide();
    return result;

}

function getResultPost(url, param) {
    var result;

    $.ajax({
        url: url,
        type: "POST",
        async: false,
        dataType: "json",
        data: param,
        contentType: "application/json; charset=utf-8",
        success: function (data, textStatus) {
            result = data;

        },
        error: function (e) {
           
            result = "Error";

        }

    });

    return result;
}

function Count_DSVF(Cdown, Csha, Cvi, Cfav, Id, IsImg) {
    var url = BaseUrl + "Home/Count_DSVF";
    var param = { Cdownload: Cdown, Cshare: Csha, Cview: Cvi, Cfavourite: Cfav, stid: Id, IsImage: IsImg };
    var result = getResultasync(url, param);

}

function goDefaultView() {
   // $.removeCookie("MainEditionId");  // commneted by sarvesh
    $.removeCookie("PageId");
    $.removeCookie("changeddate");
    $.removeCookie("EditionId");
    $.removeCookie("MainEdName");
    var url = window.location.href.toLowerCase();
    if ((url.indexOf('index') > -1)) {
        window.location.href = BaseUrl + "Home/Index";
    }
    else if ((url.indexOf('articleview') > -1)) {
        window.location.href = BaseUrl + "Home/ArticleView";
    }
    else if ((url.indexOf('FullPage') > -1)) {
        window.location.href = BaseUrl + "Home/FullPage";
    } else {
        window.location.href = BaseUrl + "Home/ArticleView";
    }
  
}
var audio = document.getElementById("myAudio");
function playAudio() {
    try {
        audio.play();
    } catch (error) { }

}

function pauseAudio() {
    audio.pause();
}
function preloadImagesMobile(array) {
    if (!preloadImages.list) {
        preloadImages.list = [];
    }
    var list = preloadImages.list;
    for (var i = 0; i < array.length; i++) {
        var img = new Image();
        $(img).attr("class", "preload");
        img.onload = function () {
            var index = list.indexOf(this);
            if (index !== -1) {
                // remove image from the array once it's loaded
                // for memory consumption reasons
                list.splice(index, 1);
                TotalImagesDone = TotalImagesDone + 1;


            }
        }
        list.push(img);
        img.src = array[i];

    }
}

function stop() {
    try {
        player.setAttribute('src', '');
        player.load();
        playButton.style.display = "block";
        pauseButton.style.display = "none";
    }
    catch (error) { }
   
};
function stopAudio() {
    try{
        player.pause();
        playButton.style.display = "block";
        pauseButton.style.display = "none";
    } catch (error) { }
}
function comScore() {
    try
    {
        var sLash = "/"; var qPara = "?"; var responseUrl = "customResponse.json";
        self.COMSCORE && COMSCORE.beacon({ c1: "2", c2: "6035286" });
        var randomNumber = Math.floor((Math.random() * 9999999) + 1);
        var xhttp = new XMLHttpRequest(); var apiURL = BaseUrl + "Js" + sLash + responseUrl + qPara + "q=" + randomNumber;
        xhttp.open("GET", apiURL, true);
        xhttp.send();
        xhttp.onreadystatechange = function () { if (xhttp.readyState == 4 && xhttp.status == 200) { } }
    }catch(error){}
}
function AddtoGA(Edname, eddate, Pgname, evName, obtype,action,gaType) {
    try {
        //gtag('config', g_AnalyticsId, {
        //    'page_title': evName,
        //    'page_path': '/' + Edname + '/' + eddate + '/Page/' + Pgname,

        //});
        
            var PagePath = 'Epaper/' + Edname + '/' + eddate + '/Page/' + Pgname;
            ga('send', 'pageview', PagePath);
            comScore();
            window.dapCollector("trackPageView", Pgname);
       
    }
    catch (error)
    { }
}

function AddtoGAArt(Edname, eddate, Pgname, aricleName, evName, obtype) {
    try {
        //gtag('config', g_AnalyticsId, {
        //    'page_title': evName,
        //    'page_path': '/' + Edname + '/' + eddate + '/' + Pgname + '/Article/' + aricleName,

        //});

        if (obtype != undefined && obtype != null && obtype == "2") {

           var PagePath ='Epaper/'+ Edname + '/' + eddate + '/' + Pgname + '/Article/' + aricleName;
           ga('send', 'pageview', PagePath);
            comScore();
            window.dapCollector("trackPageView", Pgname);
        }
        
    }
    catch (error)
    { }
}
;
/* 
* Project: Bootstrap Notify = v3.1.3
* Description: Turns standard Bootstrap alerts into "Growl-like" notifications.
* Author: Mouse0270 aka Robert McIntosh
* License: MIT License
* Website: https://github.com/mouse0270/bootstrap-growl
*/
(function (factory) {
	if (typeof define === 'function' && define.amd) {
		// AMD. Register as an anonymous module.
		define(['jquery'], factory);
	} else if (typeof exports === 'object') {
		// Node/CommonJS
		factory(require('jquery'));
	} else {
		// Browser globals
		factory(jQuery);
	}
}(function ($) {
	// Create the defaults once
	var defaults = {
			element: 'body',
			position: null,
			type: "info",
			allow_dismiss: true,
			newest_on_top: false,
			showProgressbar: false,
			placement: {
				from: "top",
				align: "right"
			},
			offset: 20,
			spacing: 10,
			z_index: 1031,
			delay: 5000,
			timer: 1000,
			url_target: '_blank',
			mouse_over: null,
			animate: {
				enter: 'animated fadeInDown',
				exit: 'animated fadeOutUp'
			},
			onShow: null,
			onShown: null,
			onClose: null,
			onClosed: null,
			icon_type: 'class',
			template: '<div data-notify="container" class="col-xs-11 col-sm-4 alert alert-{0}" role="alert"><button type="button" aria-hidden="true" class="close" data-notify="dismiss">&times;</button><span data-notify="icon"></span> <span data-notify="title">{1}</span> <span data-notify="message">{2}</span><div class="progress" data-notify="progressbar"><div class="progress-bar progress-bar-{0}" role="progressbar" aria-valuenow="0" aria-valuemin="0" aria-valuemax="100" style="width: 0%;"></div></div><a href="{3}" target="{4}" data-notify="url"></a></div>'
		};

	String.format = function() {
		var str = arguments[0];
		for (var i = 1; i < arguments.length; i++) {
			str = str.replace(RegExp("\\{" + (i - 1) + "\\}", "gm"), arguments[i]);
		}
		return str;
	};

	function Notify ( element, content, options ) {
		// Setup Content of Notify
		var content = {
			content: {
				message: typeof content == 'object' ? content.message : content,
				title: content.title ? content.title : '',
				icon: content.icon ? content.icon : '',
				url: content.url ? content.url : '#',
				target: content.target ? content.target : '-'
			}
		};

		options = $.extend(true, {}, content, options);
		this.settings = $.extend(true, {}, defaults, options);
		this._defaults = defaults;
		if (this.settings.content.target == "-") {
			this.settings.content.target = this.settings.url_target;
		}
		this.animations = {
			start: 'webkitAnimationStart oanimationstart MSAnimationStart animationstart',
			end: 'webkitAnimationEnd oanimationend MSAnimationEnd animationend'
		}

		if (typeof this.settings.offset == 'number') {
		    this.settings.offset = {
		    	x: this.settings.offset,
		    	y: this.settings.offset
		    };
		}

		this.init();
	};

	$.extend(Notify.prototype, {
		init: function () {
			var self = this;

			this.buildNotify();
			if (this.settings.content.icon) {
				this.setIcon();
			}
			if (this.settings.content.url != "#") {
				this.styleURL();
			}
			this.placement();
			this.bind();

			this.notify = {
				$ele: this.$ele,
				update: function(command, update) {
					var commands = {};
					if (typeof command == "string") {					
						commands[command] = update;
					}else{
						commands = command;
					}
					for (var command in commands) {
						switch (command) {
							case "type":
								this.$ele.removeClass('alert-' + self.settings.type);
								this.$ele.find('[data-notify="progressbar"] > .progress-bar').removeClass('progress-bar-' + self.settings.type);
								self.settings.type = commands[command];
								this.$ele.addClass('alert-' + commands[command]).find('[data-notify="progressbar"] > .progress-bar').addClass('progress-bar-' + commands[command]);
								break;
							case "icon":
								var $icon = this.$ele.find('[data-notify="icon"]');
								if (self.settings.icon_type.toLowerCase() == 'class') {
									$icon.removeClass(self.settings.content.icon).addClass(commands[command]);
								}else{
									if (!$icon.is('img')) {
										$icon.find('img');
									}
									$icon.attr('src', commands[command]);
								}
								break;
							case "progress":
								var newDelay = self.settings.delay - (self.settings.delay * (commands[command] / 100));
								this.$ele.data('notify-delay', newDelay);
								this.$ele.find('[data-notify="progressbar"] > div').attr('aria-valuenow', commands[command]).css('width', commands[command] + '%');
								break;
							case "url":
								this.$ele.find('[data-notify="url"]').attr('href', commands[command]);
								break;
							case "target":
								this.$ele.find('[data-notify="url"]').attr('target', commands[command]);
								break;
							default:
								this.$ele.find('[data-notify="' + command +'"]').html(commands[command]);
						};
					}
					var posX = this.$ele.outerHeight() + parseInt(self.settings.spacing) + parseInt(self.settings.offset.y);
					self.reposition(posX);
				},
				close: function() {
					self.close();
				}
			};
		},
		buildNotify: function () {
			var content = this.settings.content;
			this.$ele = $(String.format(this.settings.template, this.settings.type, content.title, content.message, content.url, content.target));
			this.$ele.attr('data-notify-position', this.settings.placement.from + '-' + this.settings.placement.align);		
			if (!this.settings.allow_dismiss) {
				this.$ele.find('[data-notify="dismiss"]').css('display', 'none');
			}
			if ((this.settings.delay <= 0 && !this.settings.showProgressbar) || !this.settings.showProgressbar) {
				this.$ele.find('[data-notify="progressbar"]').remove();
			}
		},
		setIcon: function() {
			if (this.settings.icon_type.toLowerCase() == 'class') {
				this.$ele.find('[data-notify="icon"]').addClass(this.settings.content.icon);
			}else{
				if (this.$ele.find('[data-notify="icon"]').is('img')) {
					this.$ele.find('[data-notify="icon"]').attr('src', this.settings.content.icon);
				}else{
					this.$ele.find('[data-notify="icon"]').append('<img src="'+this.settings.content.icon+'" alt="Notify Icon" />');
				}	
			}
		},
		styleURL: function() {
			this.$ele.find('[data-notify="url"]').css({
				backgroundImage: 'url(data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7)',
				height: '100%',
				left: '0px',
				position: 'absolute',
				top: '0px',
				width: '100%',
				zIndex: this.settings.z_index + 1
			});
			this.$ele.find('[data-notify="dismiss"]').css({
				position: 'absolute',
				right: '10px',
				top: '5px',
				zIndex: this.settings.z_index + 2
			});
		},
		placement: function() {
			var self = this,
				offsetAmt = this.settings.offset.y,
				css = {
					display: 'inline-block',
					margin: '0px auto',
					position: this.settings.position ?  this.settings.position : (this.settings.element === 'body' ? 'fixed' : 'absolute'),
					transition: 'all .5s ease-in-out',
					zIndex: this.settings.z_index
				},
				hasAnimation = false,
				settings = this.settings;

			$('[data-notify-position="' + this.settings.placement.from + '-' + this.settings.placement.align + '"]:not([data-closing="true"])').each(function() {
				return offsetAmt = Math.max(offsetAmt, parseInt($(this).css(settings.placement.from)) +  parseInt($(this).outerHeight()) +  parseInt(settings.spacing));
			});
			if (this.settings.newest_on_top == true) {
				offsetAmt = this.settings.offset.y;
			}
			css[this.settings.placement.from] = offsetAmt+'px';

			switch (this.settings.placement.align) {
				case "left":
				case "right":
					css[this.settings.placement.align] = this.settings.offset.x+'px';
					break;
				case "center":
					css.left = 0;
					css.right = 0;
					break;
			}
			this.$ele.css(css).addClass(this.settings.animate.enter);
			$.each(Array('webkit', 'moz', 'o', 'ms', ''), function(index, prefix) {
				self.$ele[0].style[prefix+'AnimationIterationCount'] = 1;
			});

			$(this.settings.element).append(this.$ele);

			if (this.settings.newest_on_top == true) {
				offsetAmt = (parseInt(offsetAmt)+parseInt(this.settings.spacing)) + this.$ele.outerHeight();
				this.reposition(offsetAmt);
			}
			
			if ($.isFunction(self.settings.onShow)) {
				self.settings.onShow.call(this.$ele);
			}

			this.$ele.one(this.animations.start, function(event) {
				hasAnimation = true;
			}).one(this.animations.end, function(event) {
				if ($.isFunction(self.settings.onShown)) {
					self.settings.onShown.call(this);
				}
			});

			setTimeout(function() {
				if (!hasAnimation) {
					if ($.isFunction(self.settings.onShown)) {
						self.settings.onShown.call(this);
					}
				}
			}, 600);
		},
		bind: function() {
			var self = this;

			this.$ele.find('[data-notify="dismiss"]').on('click', function() {		
				self.close();
			})

			this.$ele.mouseover(function(e) {
				$(this).data('data-hover', "true");
			}).mouseout(function(e) {
				$(this).data('data-hover', "false");
			});
			this.$ele.data('data-hover', "false");

			if (this.settings.delay > 0) {
				self.$ele.data('notify-delay', self.settings.delay);
				var timer = setInterval(function() {
					var delay = parseInt(self.$ele.data('notify-delay')) - self.settings.timer;
					if ((self.$ele.data('data-hover') === 'false' && self.settings.mouse_over == "pause") || self.settings.mouse_over != "pause") {
						var percent = ((self.settings.delay - delay) / self.settings.delay) * 100;
						self.$ele.data('notify-delay', delay);
						self.$ele.find('[data-notify="progressbar"] > div').attr('aria-valuenow', percent).css('width', percent + '%');
					}
					if (delay <= -(self.settings.timer)) {
						clearInterval(timer);
						self.close();
					}
				}, self.settings.timer);
			}
		},
		close: function() {
			var self = this,
				$successors = null,
				posX = parseInt(this.$ele.css(this.settings.placement.from)),
				hasAnimation = false;

			this.$ele.data('closing', 'true').addClass(this.settings.animate.exit);
			self.reposition(posX);			
			
			if ($.isFunction(self.settings.onClose)) {
				self.settings.onClose.call(this.$ele);
			}

			this.$ele.one(this.animations.start, function(event) {
				hasAnimation = true;
			}).one(this.animations.end, function(event) {
				$(this).remove();
				if ($.isFunction(self.settings.onClosed)) {
					self.settings.onClosed.call(this);
				}
			});

			setTimeout(function() {
				if (!hasAnimation) {
					self.$ele.remove();
					if (self.settings.onClosed) {
						self.settings.onClosed(self.$ele);
					}
				}
			}, 600);
		},
		reposition: function(posX) {
			var self = this,
				notifies = '[data-notify-position="' + this.settings.placement.from + '-' + this.settings.placement.align + '"]:not([data-closing="true"])',
				$elements = this.$ele.nextAll(notifies);
			if (this.settings.newest_on_top == true) {
				$elements = this.$ele.prevAll(notifies);
			}
			$elements.each(function() {
				$(this).css(self.settings.placement.from, posX);
				posX = (parseInt(posX)+parseInt(self.settings.spacing)) + $(this).outerHeight();
			});
		}
	});

	$.notify = function ( content, options ) {
		var plugin = new Notify( this, content, options );
		return plugin.notify;
	};
	$.notifyDefaults = function( options ) {
		defaults = $.extend(true, {}, defaults, options);
		return defaults;
	};
	$.notifyClose = function( command ) {
		if (typeof command === "undefined" || command == "all") {
			$('[data-notify]').find('[data-notify="dismiss"]').trigger('click');
		}else{
			$('[data-notify-position="'+command+'"]').find('[data-notify="dismiss"]').trigger('click');
		}
	};

}));;

//jQuery for page scrolling feature - requires jQuery Easing plugin
$(function() {
    $(document).on('click', 'a.page-scroll', function(event) {
        var $anchor = $(this);

        $('html, body').stop().animate({
            scrollTop: $($anchor.attr('href')).offset().top
        }, 1500, 'easeInOutExpo');

        $(".navigation_mobile").removeClass('show');
        $(".site-overlay").hide();

        event.preventDefault();
    });
});

// back to top button hide show

$(window).scroll(function () {

    if ($(this).scrollTop() > 50) {
        $('#back-to-top').fadeIn();
    } else {
        $('#back-to-top').fadeOut();
    }
});
// scroll body to 0px on click
$('#back-to-top').click(function () {
    $('body,html').animate({
        scrollTop: 0
    }, 800);
    return false;
});
;

var objuser = {};
var BaseUrl;
var GUserId = 0;
var Gemail
var windowWidth = $(window).width();
function SetUrl(url) {

    BaseUrl = url;
}


function Login_UserActionLog(Action, Id, View, Status, Remark,email) {

    var url = BaseUrl + "Home/UserActionLog";

    if (Action == "Forgot password")
        var param = { useraction: Action, id: Id, view: View, status: Status, remark: Remark, Email: email, ActionCode: "13" };
    else
        var param = { useraction: Action, id: Id, view: View, status: Status, remark: Remark, Email: email};

    var result = getResultasync(url, param);

}

function forgotPasswords(emailId) {  
   // var EmailId = $("#Email1").val();

    // Code added by sarvesh for clevertap  
    /* Start of code */  
    CleverTap_ForgotPassword(emailId);    
    /* End of code */

    if (emailId == '') {
        $('#divforgotpass').text('Please enter email id !!');
        $('#divforgotpass').show();
        $("#Email1").focus();
        $('.field-info.error.fmail').slideDown(100).css('display', 'block');
        $("#Femail").addClass("error-field");
        return false;
    }
    var reg = /^([A-Za-z0-9_\-\.])+\@([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/;
    //var expr = /^([\w-\.]+)@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([\w-]+\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$/;
    
    if (reg.test(emailId)) {
        $('#divforgotpass').removeClass("alert alert-danger");
        $('#divforgotpass').addClass("alert alert-success");
        $('#divforgotpass').show();        
        $('#divforgotpass').text("Please wait...");       

        setTimeout(function () {
            var url = BaseUrl + "Login/ForgotPassword";
            var param = "{'EmailId' :'" + emailId + "'}";
            var result = getResultPost(url, param);
            if (result.status) {
                Login_UserActionLog("Forgot password", "", "", "Success", "Forgot password done successfully", emailId);
                $('#divforgotpass').hide();
                $("#forgotpassModal").dialog('close');
                $("#forgotPassmodal").modal('hide');
                if (windowWidth > 767) {
                    $.notify({
                        message: result.message
                    }, {
                            type: 'success',
                            delay: 5000,
                            offset: {
                                x: 400,
                                y: 25
                            }
                        });
                }
                else {
                    $.notify({
                        message: result.message
                    }, {
                            type: 'success',
                            delay: 5000,
                            offset: {
                                x: 0,
                                y: 50
                            }
                        });
                }
               
            }
            else {
                $('#divforgotpass').removeClass("alert alert-success");
                $('#divforgotpass').addClass("alert alert-danger");
                $('#divforgotpass').text(result.message);
                $('#divforgotpass').show();
                Login_UserActionLog("Forgot password", "", "", "Failed", "Forgot password Failed", emailId);
               // $("#forgotPassmodal").modal('hide');
            }
        }, 2000); 
    }
    else {
        $('#divforgotpass').removeClass("alert alert-success");
        $('#divforgotpass').addClass("alert alert-danger");
        $('#divforgotpass').text("Please enter a valid email address!!");
        $("#Email1").focus();
        $('#divforgotpass').show();
        $('.field-info.error.fmail').slideDown(100).css('display', 'block');
        $("#Femail").addClass("error-field");
        return false;
    }
}

function createGoogleUser(objus)
{
    $('#Message_mobileno').show();
    $('#Message_mobileno').html("Registering you, please wait...");
    $('#divsocialLoginmsg').html("<strong> Registering you, please wait...</strong>");
    $('#divRegistermsg').html("<strong> Registering you, please wait...</strong>");

    var parameter = { 'obj': objus };

    $.ajax({
                url: BaseUrl + "Login/createGoogleUser",
                type: "POST",
                dataType: "json",
                data: JSON.stringify(parameter),
                contentType: "application/json; charset=utf-8",
                success: function (data, textStatus) {
                    if (data.status) {                       
                        GotoWelcomePage(objus.email);
                            
                    }
                    else {
                        alert("Some Technical Error");
                    }

                },
                error: function (e) {
                    alert("Some technical error in google user login !! EmailId:  " + objus.email)
                }
            });
    $('#Message_mobileno').hide();
}


//function checkMobileNoExist()
//{

//    $('#Message_mobileno').show();
//    $('#Message_mobileno').html("Login you, please wait...");

//    $.ajax({
//        url: BaseUrl + "Login/checkMobileNoExist",
//        type: "POST",
//        dataType: "json",
//        data: JSON.stringify(parameter),
//        contentType: "application/json; charset=utf-8",
//        success: function (data, textStatus) {
//            if (data.status) {
//                LoginWithMobileNo(objus.email);
//                $('#Message_mobileno').hide();
//            }
//            else {
//                $('#Message_mobileno').text(data.message);
//            }
//        },
//        error: function (e) {
//            alert("Some technical error in google user login !! EmailId:  " + objus.email)
//        }
//    });   
//}

function CheckUserRegister(username, emailid, password) {

    var newuser = {};
    newuser.username = username;
    newuser.email = emailid;
    newuser.password = password;
    var parameter = { 'obj': newuser };

    $('#divsocialLoginmsg').show();
    $('#divsocialLoginmsg').text("Please wait...");
    $('#divRegistermsg').show();
    $('#divRegistermsg').text("Please wait...");

    var url = BaseUrl + "Login/checkuserexist";
    var param = JSON.stringify(parameter);
    var result = getResultPost(url, param);
    if (result.status)
    {
        if (result.IsBlocked)
        {
            $('#divsocialLoginmsg').text("Your account is temporarily suspended.");
            $('#divRegistermsg').text("Your account is temporarily suspended.");
        }
        else {
            $('#divsocialLoginmsg').hide();
            $('#divRegistermsg').hide();
            if (result.HaveMobNo == 2)
            {
                GUserId = result.UserId;
                Gemail = emailid;
               // $("#Normal_login_contactno").attr('userid',result.UserId)
                $("#Normal_login_contactno").dialog('open');
            }
            else {
                GotoHomePage(emailid);
            }                                  
        }       
    }
    else
    {
        objuser = newuser;
        $("#Social_login_contactno").dialog("open");
    }
}

function GotoHomePage(emailId) {
    var url = BaseUrl + "Login/GotoHomePage";  

    var htmlForm = "<form id='myform' method='POST' action='"+url+"'>" +
                "<input type='hidden' name='EmailId' value=" + emailId + " />" +
                //"<input type='hidden' name='isfirstvisit' value=" + isfirstvisit + " />" +
                "</form>";
            $(htmlForm).appendTo("body").submit();
};
function LoginWithMobileNo() {
    var url = BaseUrl + "Login/GotoHomePageByNormal";

    var htmlForm = "<form id='myform' method='POST' action='" + url + "'>" +
                //"<input type='hidden' name='EmailId' value=" + emailId + " />" +
               // "<input type='hidden' name='mobile' value=" + mobileno + " />" +
                "</form>";
    $(htmlForm).appendTo("body").submit();
};

function LoginWithPrompt() {
    var url = BaseUrl + "Login/GotoHomePageByNormal";
    var htmlForm = "<form id='myform' method='POST' action='" + url + "'>" +
               // "<input type='hidden' name='EmailId' value=" + emailId + " />" +
               // "<input type='hidden' name='mobile' value=" + mobileno + " />" +
                "</form>";
    $(htmlForm).appendTo("body").submit();
};

function GotoWelcomePage(emailId)
{
    var url = BaseUrl + "Login/GotoWelcomePage";

    var htmlForm = "<form id='myform' method='POST' action='" + url + "'>" +
                   "<input type='hidden' name='EmailId' value=" + emailId + " />" +                  
                   "</form>";
    $(htmlForm).appendTo("body").submit();
}

function EpaperLogin_Piano(emailId, firstName, uid, subid) {//, source
    var url = BaseUrl + "Login/EpaperLogin_Piano";
    var htmlForm = "<form id='myform' method='POST' action='" + url + "'>" +
        "<input type='hidden' name='Email' value=" + emailId + " />" +
        "<input type='hidden' name='Username' value=" + firstName + " />" +
        "<input type='hidden' name='Piano_userid' value=" + uid + " />" +
        "<input type='hidden' name='Piano_subid' value=" + subid + " />" +
        //"<input type='hidden' name='Piano_source' value=" + source + " />" +
        "</form>";
    $(htmlForm).appendTo("body").submit();
}

function SocialLogMobile(mobile)
{
    if (mobile == "")
    {
        $("#Message_mobileno").html("Mobile number can not be blank");
        return false;
    }
    else
    {
        $("#MobileSubmit").hide();
        objuser.MobileNumber = mobile;
        createGoogleUser(objuser);
        $("#Social_login_contactno").dialog("close");
    }
  
}

function InitializeQuiz() {
    var parameter = {};
    var url = BaseUrl + "Login/GetQuizDetail";
    var param = JSON.stringify(parameter);
    //var result = getResult(url, param);    
    $.ajax({
        url: url,
        type: "Get",
        async: true,
        dataType: "json",
        data: param,
        contentType: "application/json; charset=utf-8",
        success: function (data, textStatus) {
            result = data;
            if (result != null || result != '' || result != undefined) {
                jsonResult = JSON.parse(result);
                if (jsonResult.pk != null && jsonResult.title != null) {
                    var quizTitle = jsonResult.title.toLocaleLowerCase().replace(" ", "-");
                    var quizId = jsonResult.pk;
                    var quizUrl = 'https://www.quiz.me/' + quizTitle + '_' + quizId+'/';
                    $('#quiz>iframe')[0].src = quizUrl;
                }
            }
        },
        error: function (e) {
            result = "Error";
        }
    });
}

function redirecttoquiz() {
    // window.open( BaseUrl + "/home/Quiz", '_blank');
    window.location.href = BaseUrl + "/home/Quiz";
};
