/* Minification failed. Returning unminified contents.
(623,35-36): run-time error JS1195: Expected expression: >
 */
(function ($) {
	$.fn.emoji = function (params) {
		var defaults = {
			button: '&#x1F642;',
			place: 'before',
			emojis: ['&#x1F642;', '&#x1F641;', '&#x1f600;', '&#x1f601;', '&#x1f602;', '&#x1f603;', '&#x1f604;', '&#x1f605;', '&#x1f606;', '&#x1f607;', '&#x1f608;', '&#x1f609;', '&#x1f60a;', '&#x1f60b;', '&#x1f60c;', '&#x1f60d;', '&#x1f60e;', '&#x1f60f;', '&#x1f610;', '&#x1f611;', '&#x1f612;', '&#x1f613;', '&#x1f614;', '&#x1f615;', '&#x1f616;', '&#x1f617;', '&#x1f618;', '&#x1f619;', '&#x1f61a;', '&#x1f61b;', '&#x1f61c;', '&#x1f61d;', '&#x1f61e;', '&#x1f61f;', '&#x1f620;', '&#x1f621;', '&#x1f622;', '&#x1f623;', '&#x1f624;', '&#x1f625;', '&#x1f626;', '&#x1f627;', '&#x1f628;', '&#x1f629;', '&#x1f62a;', '&#x1f62b;', '&#x1f62c;', '&#x1f62d;', '&#x1f62e;', '&#x1f62f;', '&#x1f630;', '&#x1f631;', '&#x1f632;', '&#x1f633;', '&#x1f634;', '&#x1f635;', '&#x1f636;', '&#x1f637;', '&#x1f638;', '&#x1f639;', '&#x1f63a;', '&#x1f63b;', '&#x1f63c;', '&#x1f63d;', '&#x1f63e;', '&#x1f63f;', '&#x1f640;', '&#x1f643;', '&#x1f4a9;', '&#x1f644;', '&#x2620;', '&#x1F44C;','&#x1F44D;', '&#x1F44E;', '&#x1F648;', '&#x1F649;', '&#x1F64A;'],
			fontSize: '20px',
			listCSS: {position: 'absolute', border: '1px solid gray', 'background-color': '#fff', display: 'none'},
			rowSize: 10,
		};
		var settings = {};
		if (!params) {
			settings = defaults;
		} else {
			for (var n in defaults) {
				settings[n] = params[n] ? params[n] : defaults[n];
			}
		}

		this.each(function (n, input) {
			var $input = $(input);

			function showEmoji() {
				$list.show();
				$input.focus();
				setTimeout(function () {
				    $(document).on('click', closeEmoji);
				    $button.off('click', showEmoji);
				}, 1);
			}

			function closeEmoji() {
			    $list.hide();
			    $button.on('click', showEmoji);
				$(document).off('click', closeEmoji);
			}

			function clickEmoji(ev) {
				if (input.selectionStart || input.selectionStart == '0') {
					var startPos = input.selectionStart;
					var endPos = input.selectionEnd;
					input.value = input.value.substring(0, startPos)
						+ ev.currentTarget.innerHTML
						+ input.value.substring(endPos, input.value.length);
				} else {
					input.value += ev.currentTarget.innerHTML;
				}

				closeEmoji();
				$input.focus();
				input.selectionStart = startPos + 2;
				input.selectionEnd = endPos + 2;
			}

			var $button = $("<span>").html(settings.button).css({cursor: 'pointer', 'font-size': settings.fontSize}).on('click', showEmoji);
			var $list = $('<div>').css(defaults.listCSS).css(settings.listCSS);
			for (var n in settings.emojis) {
				if (n > 0 && n % settings.rowSize == 0) {
					$("<br>").appendTo($list);
				}
				$("<span>").html(settings.emojis[n]).css({cursor: 'pointer', 'font-size': settings.fontSize}).on('click', clickEmoji).appendTo($list);
			}

			if (settings.place === 'before') {
				$button.insertBefore(this);
			} else {
				$button.insertAfter(this);
			}
			$list.insertAfter($input);
		});
		return this;
	};
}
)(jQuery);
;
+function (window, jQuery, moment) {
    'use strict';

    var ContractFX = window.ContractFX = window.ContractFX || {};
    ContractFX.Controls = ContractFX.Controls || {};
    var ERFx = ContractFX.Controls.ERFx = ContractFX.Controls.ERFx || {};

    ERFx.ChatNotification = function (containerId, domainUrl, userId) {

        this.containerId = containerId;
        this.container = jQuery('#' + containerId);
        this.userId = userId;
        var self = this;

        this.chatHb =  jQuery.connection.chatHub;
        this.commentHb = jQuery.connection.commentHub;
        this.takeNotificationCount = 10;  // <-- change for change notifications counts
        this.firstTime = true;
        this.autoLoadMessages = true;
        this.count = 0;


        this.clientTZOffset = new Date().getTimezoneOffset();
        this.clientTZHour = this.clientTZOffset / 60;
        this.months = ["Jan", "Feb", "Mar","Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"];

        jQuery(function () {
            self.InitLoadingCount();
            self.InitLoadingMessages();

            // Create a function that the hub can call to broadcast messages.
            self.chatHb.client.broadcastNotification = function (notification) {
                self.addMessageObj(notification, false);
            };

            self.commentHb.client.broadcastNotification = function (notification) {
                self.addMessageObj(notification, false);
            };

            // Create a function that the hub can call js method.
            self.chatHb.client.decreaseCounter = function (id) {
                var row = self.container.find('.notification-row[data-notification-id=' + id + ']');
                row.remove();
                self.ChangeNotificationCount("Decrease");
            };

            // Create a function that the hub can call js method.
            self.commentHb.client.decreaseCounter = function (id) {
                var row = self.container.find('.notification-row[data-notification-id=' + id + ']');
                row.remove();
                self.ChangeNotificationCount("Decrease");
            };

            // Create a function that the hub can call js method.
            self.chatHb.client.increaseCounter = function () {
                self.ChangeNotificationCount("Increase");
            };

            // Create a function that the hub can call js method.
            self.commentHb.client.increaseCounter = function () {
                self.ChangeNotificationCount("Increase");
            };

            // Create a function that the hub can call js method.
            self.chatHb.client.resetCounter = function () {
                self.ChangeNotificationCount("reset");
                self.autoLoadMessages = true;
            };
        })

        // Start the connection.
        var connectionStart = jQuery.connection.hub.start({ transport: ['serverSentEvents', 'foreverFrame', 'longPolling'] });

        // Click on notification btn
        let btn = $('.js-notifications-btn');
        btn.click(function () {
            var notification = $('.js-notification-container');
            if (notification.css('display') == 'none') {
                btn.addClass('notifications-btn-active');
                btn.prop('title', 'Hide notifications');
                notification.show();
                if(self.firstTime){
                    setTimeout(function () {
                        self.ScrollBottom();
                    }, 1);
                    self.firstTime = false;
                }
            }
            else {
                btn.removeClass('notifications-btn-active');
                btn.prop('title', 'Show notifications');
                notification.hide();
            }
        });

        //Hide notifications after click on page
        $(document).mouseup(function (e){
            if (!self.container.is(e.target) && self.container.has(e.target).length === 0 && !btn.is(e.target) && btn.has(e.target).length === 0) {
                self.container.hide();
                btn.removeClass('notifications-btn-active');
                btn.prop('title', 'Show notifications');
            }
        });
      
        //Close all notifications
        let closeAll = $('.btnCloseAllNotification');
        closeAll.click(function () {
            var row = self.container.find('*[data-notification-id]');
            self.autoLoadMessages = false;
            // Call the close method on the hub.
            self.chatHb.server.closeAllNotifications(self.userId); 
            $('.js-messages-count').hide();
            row.remove(); 
            self.ShowNoMessagesLabel();
        });

        // Add notifiation
        this.addMessageObj = function (message, isToTop) {

            var messageContainer = self.container.find('.js--notification-container');
            var messageRow = self.container.find('.js--notification-row-base').clone();
            messageRow.removeClass("js--notification-row-base");
            messageRow.attr('data-notification-id', message.ID);
            
            try {
                let datetimeUTC = new Date(Date.parse(message.CreationDateJsFormat)).toUTCString();
                // Local users time
                messageRow.find('.notification-message-sent-date > span').text(this.getUsersLocalTime(new Date(new Date(datetimeUTC).getTime() - self.clientTZOffset * 60000)));
            } catch (ex) {
                messageRow.find('.notification-message-sent-date > span').text(message.CreationDateStr + " (GMT)");
            }

            if(message.ChannelLogo != null){
                messageRow.find('.js-channel-logo').attr('src', message.ChannelLogo);
                messageRow.find('.js-channel-logo').attr('title', message.ChannelName);
            }
            messageRow.find('.notification-video-title-url > span').html(message.VideoName);
            messageRow.find('.autor-message').text(message.Author);
            messageRow.find('.notification-message-text > span').html(message.MessageText);
            messageRow.find('.js-video-thumbanail-img').attr('src', message.ImgPath);
            
            //Close btn Click
            let closeQuestionToBtn = messageRow.find('.close-notification-btn');
            closeQuestionToBtn.attr('close-btn-notification-id', message.ID);
            closeQuestionToBtn.click(function (ev) {

                let clickedObj = jQuery(this);
                let clickedMessageId = [];
                clickedMessageId[0] = clickedObj.attr('close-btn-notification-id');
                    
                self.chatHb.server.closeNotification(clickedMessageId, self.userId);
            });

            //Click on video thumbanail
            let videoClick = messageRow.find('.js-video-section-click');
            videoClick.click(function (ev) {
                var url = document.location.origin+'/view/' + message.VideoUrl;
                location.href = url;
            });

            //Click on message text
            let chatClick = messageRow.find('.js-chat-section-click');
            chatClick.attr('notification-id', message.ID);
            chatClick.click(function (ev) {
                var url = document.location.origin+'/view/' + message.VideoUrl;

                let clickedObj = jQuery(this);
                let clickedMessageId = [];
                clickedMessageId[0] = clickedObj.attr('notification-id');
                    
                self.chatHb.server.closeNotification(clickedMessageId, self.userId); 
               
                var currentURL = window.location.href.split('?')[0];
                var notificationType = 'm';

                if (url != currentURL) {
                    if(message.FK_OnlineChatMessageReplyTo > 0){
                        location.href = url + '?'+notificationType+'=' + message.FK_OnlineChatMessageReplyTo +'/'+ message.ID;
                    }
                    else
                        location.href = url + '?'+notificationType+'=' + message.ID;
                }
                else {
                    //scroll to message in chat
                    if($('#divComments').hasClass('hidden-tab')){
                        let selectedMesage = messageRow.find('.notification-row');
                        selectedMesage.attr('data-notification-id', message.ID);

                        if(message.FK_OnlineChatMessageReplyTo > 0)
                            self.ScrollToMessage(message.ID, message.VideoUrl, message.FK_OnlineChatMessageReplyTo);
                        else
                            self.ScrollToMessage(message.ID, message.VideoUrl);

                        $(".js-notification-container").hide();
                        btn.removeClass('notifications-btn-active');
                        btn.prop('title', 'Show notifications');
                    }
                    else{
                        if(message.FK_OnlineChatMessageReplyTo > 0){
                            location.href = url + '?'+notificationType+'=' + message.FK_OnlineChatMessageReplyTo +'/'+ message.ID;
                        }
                        else
                            location.href = url + '?'+notificationType+'=' + message.ID;
                    }
                }
            });

            //reply message
            if (message.FK_OnlineChatMessageReplyTo > 0 && message.MessageRepliedTo != null) {
                messageRow.find('.notification-message-replied-to-username > span').text(message.MessageRepliedTo.Author);
                messageRow.find('.notification-message-replied-to-message').html(message.MessageRepliedTo.MessageText);
                let repliedToMessageSection = messageRow.find('.notification-message-replied-to-section');

                repliedToMessageSection.attr('data-reply-id', message.FK_OnlineChatMessageReplyTo);

                repliedToMessageSection.show();
                repliedToMessageSection.click(function (ev) {
                    let repliedOriginalMessageContainer = self.container.find('.notification-message[data-notification-id=' + message.FK_OnlineChatMessageReplyTo + ']');
                    if (repliedOriginalMessageContainer != null && repliedOriginalMessageContainer.length > 0) {
                        self.ScrollToMessage(message.FK_OnlineChatMessageReplyTo);
                    }
                });
            }

            if (self.isNoMessagesLabelVisible())
                self.HideNoMessagesLabel();

            messageRow.show();

            if (isToTop)
                messageContainer.prepend(messageRow);
            else
                messageContainer.append(messageRow);
          
            //display question icon if message is question
            if (message.IsQuestion) {
                messageRow.find('.js--notification-note').html('sent new question at');
                messageRow.find('.notification-question-icon').removeClass("hide-button");
            }

            if(message.ChatId.split('_')[0] == "comment"){
                messageRow.find('.js--notification-note').html('sent new comment at');
            }
        }

        //Get count of all messages and update notification counters
        this.GetCount = function () {
            $.ajax({
                url: '/Services/EventsService.asmx/GetCount',
                type: "POST",
                data: JSON.stringify(), 
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                async: true,
                success: function (data) {
                    if (data != null) {
                        if (data.d > 0) {
                            self.count = data.d;
                            self.ChangeNotificationCount('SetCount');
                        }
                    } 
                },
                error: function (xhr, status, error) {
                    console.error('GetCount Service not Responding');
                }
            });
        }

        //Get next messages pull
        this.GetNextMessages = function (fromMessageId, isScrollBottomAfterLoad) {
            if (fromMessageId == null)
                fromMessageId = 0;

            if (!self.isLoadingMessages) {
                self.isLoadingMessages = true;

                $.ajax({
                    url: '/Services/EventsService.asmx/GetNotifications',
                    type: "POST",
                    data: JSON.stringify({ fromMessageId: fromMessageId, size: self.takeNotificationCount }), 
                    contentType: "application/json; charset=utf-8",
                    dataType: "json",
                    async: true,
                    success: function (data) {
                        if (data != null) {
                            if (typeof data.d != 'undefined' && data.d != null &&
                                typeof data.d.length != 'undefined' && data.d.length != null
                                && data.d.length > 0) {
                                self.PushMessagesToChat(data.d, true, isScrollBottomAfterLoad);
                                self.hideLoadMessagesIndicator();
                            } else {
                                self.hideLoadMessagesIndicator();
                                self.isTheEnd = true;
                            }
                        } else {
                            self.hideLoadMessagesIndicator();
                            self.isTheEnd = true;
                        }

                        self.isFirstLoad = false;
                        self.isLoadingMessages = false;

                        if (self.isRepliedMessageClicked && self.RepliedToMessageID > 0) {
                            self.LoadMessagesToMessage(self.RepliedToMessageID, true);
                        }
                    },
                    error: function (xhr, status, error) {
                        console.error('GetNotifications Service not Responding');
                    }
                });
            }
        }

        //Load replies messages
        //this.LoadMessagesToMessage = function (toMessageId, isScrollToLastMessage) {
        //    self.isRepliedMessageClicked = true;
        //    self.RepliedToMessageID = toMessageId;

        //    if (!self.isLoadingMessages) {
        //        self.showLoadMessagesIndicator();
        //        self.isLoadingMessages = true;

        //        let _AllMessages = self.container.find('.chat-message:not(.js--chat-message-base)');
        //        let lastMessage = _AllMessages.first();

        //        let fromMessageId = lastMessage.attr('data-notification-id');

        //        $.ajax({
        //            type: "POST",
        //            url: domainUrl + "/Services/EventsService.asmx/GetOnlineChatMessagesToMessage",
        //            contentType: "application/json; charset=utf-8",
        //            async: true,
        //            data: JSON.stringify({ 'fromMessageId': fromMessageId, 'messageId': toMessageId }),
        //            dataType: "json",
        //            success: function (data) {
        //                if (data != null) {
        //                    if (typeof data.d != 'undefined' && data.d != null &&
        //                        typeof data.d.length != 'undefined' && data.d.length != null
        //                        && data.d.length > 0) {
        //                        self.PushMessagesToChat(data.d, true, false);
        //                        self.hideLoadMessagesIndicator();
        //                        if (isScrollToLastMessage) {
        //                            self.ScrollToMessage(toMessageId);
        //                        }
        //                    } else {
        //                        self.hideLoadMessagesIndicator();
        //                        self.isTheEnd = true;
        //                    }
        //                } else {
        //                    self.hideLoadMessagesIndicator();
        //                    self.isTheEnd = true;
        //                }
        //                self.isFirstLoad = false;
        //                self.isLoadingMessages = false;

        //                self.isRepliedMessageClicked = false;
        //                self.RepliedToMessageID = 0;
        //            },
        //            error: function (xhr, status, error) {
        //                self.isLoadingMessages = false;
        //                self.hideLoadMessagesIndicator();
        //                self.isRepliedMessageClicked = false;
        //                self.RepliedToMessageID = 0;
        //                console.error('GetOnlineChatMessagesToMessage Service not Responding');
        //            }
        //        });
        //    }
        //}

        //Add messages to chat
        this.PushMessagesToChat = function (messages, isToTop, isScrollBottomAfterLoad) {
            if (messages != null) {
                for (var i = 0; i < messages.length; i++) {
                    var message = messages[i];
                    if (message != null) {
                        self.addMessageObj(message, isToTop);
                    }
                }
                if (isScrollBottomAfterLoad) {
                    setTimeout(function () {
                        self.ScrollBottom();
                    }, 1);
                }
            }
        }

        //Change notification counter, set, increase, decrease and reset counter
        this.ChangeNotificationCount = function (paremetr) {
            let counter = $('.js-messages-count');
            switch (paremetr){
                case "SetCount":
                    if(self.count<=99 && self.count > 0){
                        counter.text(self.count);
                        counter.show();
                    }
                    if(self.count > 99){
                        counter.text('99+');
                        counter.show();
                    }
                    break;

                case "Increase":
                    self.count++;
                    if(counter.css('display') == 'none')
                        counter.show();
                    if(self.count <= 99)
                        counter.text(self.count);                    
                    if(self.count > 99 && counter.text != '99+')
                        counter.text('99+');
                    break;

                case "Decrease":
                    self.count--;
                    if(self.count <= 0){
                        counter.hide();
                        self.ShowNoMessagesLabel();
                        break;
                    }
                    if(self.count <= 99){
                        counter.text(self.count);
                    }
                    break;

                case "reset":
                    self.count = 0;
                    counter.text(0);
                    counter.hide();
                    self.ShowNoMessagesLabel();
                    break;
            }
        };

        this.InitLoadingCount = function () {
            self.GetCount();
        };

        this.InitLoadingMessages = function () {
            self.GetNextMessages(0, true);
        }

        let notificationContainer = self.container.find('.js--notification-container');
        jQuery(notificationContainer).scroll(function () {
            var scrolledEl = this;

            if ($(this).scrollTop() <= 100 && self.autoLoadMessages) {
                self.loadNewMessages();
            }
        });

        this.loadNewMessages = function(){
            if (!self.isTheEnd && !self.isFirstLoad && !self.isLoadingMessages) {
                self.showLoadMessagesIndicator();
                var notification = self.container.find('.js--notification-container');
                var messages = notification.find('.notification-row:not(.js--notification-row-base)');
                var lastMessage = messages.first();
                var lastMessageId = lastMessage.attr('data-notification-id');
                self.GetNextMessages(lastMessageId, false);
            }
        }

        this.showLoadMessagesIndicator = function () {
            self.container.find('.js--loading-message-indicator').show();
        }

        this.hideLoadMessagesIndicator = function () {
            self.container.find('.js--loading-message-indicator').hide();
        }

        this.ShowNoMessagesLabel = function () {
            self.container.find('.js--chat-no-notification').show();
            closeAll.hide();
        }

        this.HideNoMessagesLabel = function () {
            self.container.find('.js--chat-no-notification').hide();
            closeAll.show();
        }

        this.isNoMessagesLabelVisible = function () {
            var label = self.container.find('.js--chat-no-notification');
            if (label.css('display') != 'none')
                return true;
            return false;
        }

        this.ScrollToChatSection = function () {
            $([document.documentElement, document.body]).animate({
                scrollTop: $(".js--txt-chat-message").offset().top
            }, 500);

            let messageContainer = self.container.find('.js--txt-chat-message');
            messageContainer.focus();
        }

        this.ScrollToMessage = function (messageId, videUrl, replyId) {
            let chatContainer = $('.js--chat-message-container');
            var messageContainer =  $('.chat-message[data-message-id=' + messageId + ']');
            var originalMessage = $('.chat-message[data-message-id=' + replyId + ']');
            if(originalMessage != null && originalMessage != 'undefined'){
                originalMessage.find('.js-replies').show();
                originalMessage.find('.js-reply-container').show();
            }

            if (messageContainer.length > 0) {
                chatContainer.animate({
                    scrollTop: parseInt(messageContainer.offset().top - chatContainer.offset().top + chatContainer.scrollTop())
                },
                500,
                null,
                function () {
                    messageContainer.removeClass('chat-message-highlight-out').addClass('chat-message-highlight-in');
                    setTimeout(function () {
                        messageContainer.removeClass('chat-message-highlight-in').addClass('chat-message-highlight-out');
                    }, 1000);
                });
            }
        else{
            if(videUrl != null){
                var url = document.location.origin+'/view/' + videUrl;

                if(replyId > 0)
                    location.href = url + '?m=' + replyId +'/'+ messageId;
                else
                    location.href = url + '?m=' + messageId;

            }    
        }
    }

        this.ScrollBottom = function () {
            let chatContainer = self.container.find('.js--notification-container');
            chatContainer.scrollTop(chatContainer[0].scrollHeight);
        }
        
        this.timeZoneAbbreviated = function() {
            //let { 1: tz } 
            let tz = new Date().toString().match(/\((.+)\)/);

            // In Chrome browser, new Date().toString() is
            // "Thu Aug 06 2020 16:21:38 GMT+0530 (India Standard Time)"

            // In Safari browser, new Date().toString() is
            // "Thu Aug 06 2020 16:24:03 GMT+0530 (IST)"

            if (tz.includes(" ")) {
                return tz
                  .split(" ")
                  .map(([first]) => first)
                  .join("");
            } else {
                return tz;
            }
        };

        this.getUsersLocalTime = function(dateInUsersTimeZone) {
            var res = "";
            var dateNow = new Date();
            var clientTZHourStr = " "+self.clientTZHour;
            if(self.clientTZHour < 0) {
                clientTZHourStr = " +" + Math.abs(self.clientTZHour);
            }
            else if(self.clientTZHour == 0) {
                clientTZHourStr = "";
            }
            else{
                clientTZHourStr = " -" + self.clientTZHour;
            }
            if(dateNow.getDate() == dateInUsersTimeZone.getDate()) {
                res = this.custTime(dateInUsersTimeZone.getHours(), dateInUsersTimeZone.getMinutes(), dateInUsersTimeZone.getSeconds()) + " (GMT" + clientTZHourStr + ")";
            } else if(dateNow.getFullYear() == dateInUsersTimeZone.getFullYear()) {
                res = dateInUsersTimeZone.getDate() + " " + this.months[dateInUsersTimeZone.getMonth()] + " " +
                this.custTime(dateInUsersTimeZone.getHours(), dateInUsersTimeZone.getMinutes(), dateInUsersTimeZone.getSeconds()) + " (GMT" + clientTZHourStr + ")";
            } else {
                res = dateInUsersTimeZone.getDate() + " " + this.months[dateInUsersTimeZone.getMonth()] + " " + dateInUsersTimeZone.getFullYear() + ", " + 
                this.custTime(dateInUsersTimeZone.getHours(), dateInUsersTimeZone.getMinutes(), dateInUsersTimeZone.getSeconds()) + " (GMT" + clientTZHourStr + ")";
            }

            return res;
        }
        
        this.custTime = function (h, m, s){
            return ("0" + h).slice(-2) + ":" + ("0" + m).slice(-2) + ":" + ("0" + s).slice(-2); 
        }


    }
}(window, jQuery, moment);
;
