Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- var ChatSession = {user: {}, otherUser: {}, tips: {}, me: null};
- var globalMuteArr = [];
- var someheartedyou, sendTypingStatus;
- var preloadingMessages = false;
- var autoMessageFunction = false;
- var chatInfoMemory = {};
- var serverTimeOffset = 0;
- var ecAdded = false;
- if (isMobileApp()) {
- var bubbleTabR = cloudfrontBase + 'img/bubbleR.png';
- var bubbleTabL = cloudfrontBase + 'img/bubbleL.png';
- var bubbleTabN = cloudfrontBase + 'img/bubbleNoniL.png';
- } else {
- var bubbleTabR = cloudfrontBase + 'img/bubbleBorderR.png';
- var bubbleTabL = cloudfrontBase + 'img/bubbleBorderL.png';
- var bubbleTabN = cloudfrontBase + 'img/bubbleBorderNoniL.png';
- }
- function isMobileApp() {
- return (typeof isApp !== 'undefined' && isApp) ? true : false;
- }
- function randomHash() {
- var text = "";
- var possible = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
- for (var i = 0; i < 32; i++) {
- text += possible.charAt(Math.floor(Math.random() * possible.length));
- }
- return text;
- }
- function getQSval(name) {
- name = name.replace(/[\[]/, "\\[").replace(/[\]]/, "\\]");
- var regex = new RegExp("[\\?&]" + name + "=([^&#]*)"),
- results = regex.exec(location.search);
- return results == null ? "" : decodeURIComponent(results[1].replace(/\+/g, " "));
- }
- function roomDiscussion(action) {
- if (action == 'end') {
- $.post('/connect/roomDiscussion.php', {action: action, convID: ChatSession.convID}, function (resp) {
- if (resp && resp.error) {
- alert(resp.error);
- }
- }, 'json');
- } else {
- var dmessage = '<form id="discussionStartForm">' +
- '<div class="form-group">' +
- '<label>Discussion Topic</label>' +
- '<input name="Topic" type="text" class="form-control" maxlength="50" />' +
- '</div>' +
- '<div class="form-group">' +
- '<label>Co-Leader (optional)</label>' +
- '<input name="coLeader" type="text" class="form-control" maxlength="50" />' +
- '</div>' +
- '<div class="form-group">' +
- '<label>Discussion Length</label>' +
- '<select name="lengthSecs" class="form-control">' +
- '<option value="900">15 Minutes</option>' +
- '<option value="1800">30 Minutes</option>' +
- '<option value="2700">45 Minutes</option>' +
- '<option value="3600">60 Minutes</option>' +
- '</select>' +
- '</div>' +
- '</form>';
- bootbox.dialog({
- message: dmessage,
- title: 'Create Discussion',
- buttons: {
- success: {
- label: "Start Discussion",
- className: "btn-success",
- callback: function () {
- var pData = {
- action: action,
- convID: ChatSession.convID,
- coLeader: $('#discussionStartForm input[name="coLeader"]').val(),
- Topic: $('#discussionStartForm input[name="Topic"]').val(),
- lengthSecs: $('#discussionStartForm select[name="lengthSecs"]').val()
- };
- $.post('/connect/roomDiscussion.php', pData, function (resp) {
- if (resp && resp.error) {
- alert(resp.error);
- }
- }, 'json');
- }
- }
- }
- });
- }
- }
- window.botCommand = false;
- function newBotGui (ChatSession, tree) {
- var t = this;
- if (window.botGUIObj)
- window.botGUIObj.destroy();
- window.botGUIObj = this;
- this.noniMenuButton = $('<div class="noniMenu"><img class="noniIcon" src="'+cloudfrontBase+'img/noni-menu.svg"></div>');
- this.noniMenu = $('<div class="noniBoxWrapper"><div class="noniBox"><div class="mainContainer"><div class="contentWrap"><div class="innerArea"></div></div></div><img class="noniArrow" src="'+cloudfrontBase+'img/noni-menu-open.png"/></div></div>');
- this.menuArea = this.noniMenu.find('.innerArea');
- this.chatForm = $('#chatForm');
- this.comment = $('#Comment');
- this.updates = 0;
- this.itemCount = 0;
- window.showNoniMenu = false;
- this.destroy = function () {
- this.noniMenuButton.remove();
- this.noniMenu.remove();
- this.comment.off('keyup', this.processKey);
- window.botCommand = false;
- delete this;
- this.chatForm.css('display', 'block');
- this.chatForm.css('width', '100%');
- window.botGUIObj = false;
- }
- this.processKey = function () {
- var c = $("#Comment").val();
- if (!window.showNoniMenu && c.length && c[0] == '/') {
- t.toggleMenu();
- } else if (window.showNoniMenu) {
- t.updateMenu(c);
- }
- }
- this.attach = function () {
- this.chatForm.css('display', 'inline-block');
- this.chatForm.css('width', 'calc(100% - 60px)');
- this.noniMenuButton.insertBefore(this.chatForm);
- this.noniMenu.appendTo('.chatBox');
- this.noniMenu.css('display', 'none');
- this.comment.on('keyup', this.processKey);
- }
- this.closeMenu = function () {
- window.showNoniMenu = 1;
- this.toggleMenu();
- }
- this.toggleMenu = function () {
- if (window.showNoniMenu) {
- t.noniMenuButton.css('opacity', 1);
- t.noniMenu.css('display', 'none');
- window.showNoniMenu = 0;
- window.botCommand = false;
- } else {
- t.noniMenuButton.css('opacity', .3);
- t.noniMenu.css('display', 'block');
- window.showNoniMenu = 1;
- t.updates = 0;
- //t.comment.focus();
- t.updateMenu();
- }
- }
- this.render = function () {
- this.attach();
- this.noniMenuButton.on('click', t.toggleMenu);
- }
- t.updateMenu = function (filter) {
- this.menuArea.empty();
- this.itemCount = 0;
- if (typeof filter === 'undefined')
- filter = (this.updates == 0 ? '' : this.comment.val()).toLowerCase();
- if (filter.length && filter[0] == '/')
- filter = filter.substring(1);
- this.updates++;
- if (filter.length == 0)
- filter = false;
- var lastCommand = false;
- var pasteItem = function (item, child) {
- t.itemCount++;
- var menuItem = $('<div class="menuItem '+(child ? 'child' : '')+'">'+item.name+'</div>');
- lastCommand = item.trigger;
- menuItem.on('click', function () {
- resetState(item.trigger !== null ? item.trigger : '#'+item.code);
- sendMessage();
- });
- menuItem.appendTo(t.menuArea);
- }
- for (var key in tree) {
- (function (item) {
- if (typeof item.children === 'undefined') {
- if (!filter || item.trigger.toLowerCase().indexOf(filter) !== -1 || item.code.toLowerCase().indexOf(filter) !== -1)
- pasteItem(item);
- } else {
- var pasteIt = pasteItAbove = (!filter ? true : false);
- if (filter && item.name.toLowerCase().indexOf(filter) !== -1)
- pasteItAbove = true;
- for (var key2 in item.children) {
- if (item.children[key2].trigger.toLowerCase().indexOf(filter) !== -1 || item.children[key2].code.toLowerCase().indexOf(filter) !== -1) {
- pasteIt = true;
- break;
- }
- }
- if (pasteIt || pasteItAbove) {
- var menuItem = $('<div>'+item.name+'</div>');
- menuItem.appendTo(t.menuArea);
- for (var key2 in item.children)
- if (pasteItAbove || !filter || item.children[key2].trigger.toLowerCase().indexOf(filter) !== -1 || item.children[key2].code.toLowerCase().indexOf(filter) !== -1)
- pasteItem(item.children[key2], true);
- }
- }
- })(tree[key]);
- }
- window.botCommand = false;
- if (!t.itemCount)
- t.noniMenu.css('display', 'none');
- else {
- t.noniMenu.css('display', 'block');
- if (t.itemCount == 1)
- window.botCommand = lastCommand;
- }
- }
- this.render();
- }
- function botGUI (ChatSession, tree) {
- var t = this;
- this.level = 0;
- this.e = $('<div style="border-radius:8px;background-color:#fcfcfc;padding:8px;margin-top:4px"></div>');
- this.e2 = $('<div class="hidden-md-up" style="position:absolute;top: 64px;right: 1px;left: 1px;background-color: #fcfcfc;border-bottom: solid .0625rem #e3e4e5;padding-left:18px;padding-right:18px;"></div>');
- this.destroy = function () {
- this.e.remove();
- this.e2.remove();
- delete this;
- }
- this.attach = function () {
- $('#convListItem_'+ChatSession.convID).append(this.e);
- $('.chatBox').append(this.e2);
- }
- this.render = function () {
- this.attach();
- items = [], current = tree, d = $('<div></div>'), d2 = $('<div></div>');
- if (this.level != 0 && typeof tree[this.level] !== "undefined" && typeof tree[this.level].children !== "undefined") {
- current = tree[this.level].children;
- items.unshift({
- name: 'Back',
- goto: 0
- });
- }
- for (var key in current)
- items.push(current[key]);
- for (k = 0; k < items.length; k++) {
- (function (items, k) {
- var e = $('<span class="badge badge-pill '+(items[k].goto !== 0 ? 'badge-primary' : '')+'">'+items[k].name+'</span>');
- $(e).click(function (evt) {
- t.handleClick(items[k]);
- });
- d.append(e);
- })(items, k);
- (function (items, k) {
- var e = $('<span class="badge badge-pill badge-primary">'+items[k].name+'</span>');
- $(e).click(function (evt) {
- t.handleClick(items[k]);
- });
- d2.append(e);
- })(items, k);
- }
- this.e.empty().append(d);
- this.e2.empty().append(d2);
- }
- this.handleClick = function (item) {
- if (typeof item.goto !== "undefined") {
- this.level = item.goto;
- this.render();
- } else if (typeof item.children != "undefined") {
- this.level = item.id;
- this.render();
- } else {
- resetState(item.trigger !== null ? item.trigger : '#'+item.code);
- sendMessage();
- }
- };
- this.render();
- }
- function processTopic() {
- function loadTopicHolder(show) {
- if (show) {
- if (!$('.chatBox .chatroomTopic').length) {
- $('#MessageScrollDivResize').before('<div class="chatroomTopic" style="position:relative;"><div style="padding:5px 10px;background-color:#1e90fe;position:absolute;top:0;left:0;width:100%;"><span class="chatTopic" style="color:#fff;"></span></div></div>');
- $('#MessageScrollDivResize').css('padding-top', '31px');
- }
- } else {
- if ($('.chatBox .chatroomTopic').length) {
- $('.chatBox .chatroomTopic').remove();
- $('#MessageScrollDivResize').css('padding-top', '0');
- }
- }
- }
- $('.chatBox .chatroomTopic .discussButton').remove();
- if (ChatSession.roomType) {
- if (ChatSession.discussion && ChatSession.discussion.Topic && ChatSession.discussion.endTime) {
- var hideTime = (parseInt(ChatSession.discussion.endTime) * 1000) - Date.now();
- if (window.hideTopic) {
- clearTimeout(window.hideTopic);
- }
- if (hideTime > 0) {
- loadTopicHolder(true);
- $('.chatBox .chatroomTopic .chatTopic').html('Discussion: <strong>' + ChatSession.discussion.Topic + '</strong> ');
- window.hideTopic = setTimeout(function () {
- loadTopicHolder();
- }, hideTime);
- }
- if (ChatSession.user.discussionLeader) {
- loadTopicHolder(true);
- $('.chatBox .chatroomTopic > div').append('<button class="btn btn-white btn-sm discussButton" onclick="roomDiscussion(\'end\');">End</button>');
- }
- } else {
- if (ChatSession.user.discussionLeader) {
- loadTopicHolder(true);
- $('.chatBox .chatroomTopic .chatTopic').text('');
- $('.chatBox .chatroomTopic > div').append('<button class="btn btn-white btn-sm discussButton" onclick="roomDiscussion(\'start\');">Start Discussion</button>');
- } else {
- loadTopicHolder();
- }
- }
- } else {
- loadTopicHolder();
- }
- }
- var lastSelectedConvID;
- var links = [];
- function setConversation(new_convID, refresh, bm) {
- if (window.stateLocked)
- resetState();
- lastSelectedConvID = new_convID;
- if (refresh || new_convID != ChatSession.convID) {
- $('#offlineMessageDiv').html('').removeClass('hide');
- $('#listenersInChatDiv').html('');
- $('#listenersInChatroomModal .modal-body').html('');
- $('#conversationHead span').html('Loading...');
- $('#MessageDiv').html('');
- $('#msgs-loading').show();
- $('#conversationListModal').modal('hide');
- $('[data-actionid=rateListenerButton]').hide();
- sendTypingStatus = false;
- ChatSession.convID = null;
- ChatSession.lastMessage = -1;
- ChatSession.checkingMessNow = null;
- ChatSession.initialLoad = true;
- ChatSession.tips.shown = [];
- delete window.ratingModal;
- delete ChatSession.goodExperience;
- $('[data-actionid=rateListenerButton]').hide();
- $.post('/connect/getConversation.php', {c: new_convID, bm: bm, checkin: window.checkinID}, function (json) {
- processJSON(json);
- if (typeof (checkMessages) === 'function')
- checkMessages();
- if (json.ack == 'success' && json.conv) {
- window.chatInfoMemory[userInfo.userIDe + new_convID] = window.chatInfoMemory[userInfo.userIDe + new_convID] || {};
- window.chatInfoMemory[userInfo.userIDe + new_convID].details = json;
- window.chatInfoMemory[userInfo.userIDe + new_convID].timestamp = Math.round(+new Date() / 1000);
- chatInfoSortArr = [];
- $.each(window.chatInfoMemory, function (key, value) {
- chatInfoSortArr.push([key, value.timestamp, value])
- });
- chatInfoSortArr.sort(function (a, b) {
- return a[1] - b[1]
- });
- chatInfoSortArr = chatInfoSortArr.slice(-75);
- window.chatInfoMemory = {};
- $.each(chatInfoSortArr, function (key, value) {
- window.chatInfoMemory[value[0]] = value[2];
- });
- }
- }, 'json');
- var recentChat = JSON.parse(getLocal('recentChat')) || {};
- var currentTS = new Date().getTime();
- for (k in recentChat) {
- if(parseInt(recentChat[k])+(1000*60*60*24*3) < currentTS){
- delete recentChat[k];
- }
- }
- recentChat[new_convID] = currentTS;
- setLocal('recentChat', JSON.stringify(recentChat));
- }
- function processJSON(json) {
- if (json.ack == 'error') {
- if (json.error && json.error == 'Please verify you are human') {
- //setting convID before captcha
- ChatSession.convID = lastSelectedConvID;
- showCaptcha();
- } else if(json.error && json.error == 'Engagement Checkin') {
- $('#conversationHead').html('Therapy Signup');
- $('#MessageDiv').html('Provide payment details to reconnect with your therapist.');
- $('#msgs-loading').hide();
- if (typeof Stripe === 'undefined') {
- (function (e, t) {
- var n = t.createElement("script");
- n.type = "text/javascript";
- n.async = true;
- n.src = "https://js.stripe.com/v2/";
- var s = t.getElementsByTagName("script")[0];
- s.parentNode.insertBefore(n, s);
- })(window, document);
- window.stripeInit = setInterval(function () {
- if (typeof Stripe !== 'undefined') {
- console.log('Stripe Initialized');
- Stripe.setPublishableKey(StripePublishableKey);
- clearInterval(window.stripeInit);
- window.libraryState += '-stripe-';
- }
- }, 100);
- }
- var message = {funcProp: 'onlinetherapy_monthly_15000', promoCode: true};
- ChatSession.convID = json.conv.convID;
- handleBotCreditCard3(message);
- } else {
- $('#conversationHead').html('Error');
- $('#MessageDiv').html(json.error);
- $('#msgs-loading').hide();
- }
- } else if (json.ack == 'success' && json.conv && json.conv.convID && lastSelectedConvID === json.conv.convID) {
- var OLDnodeRoom = ChatSession.nodeRoom;
- ChatSession.me = json.me;
- ChatSession.user = json.user;
- ChatSession.user.currentMessages = 0;
- ChatSession.init_numConvMessages = ChatSession.numConvMessages = parseInt(json.conv.numMsg);
- ChatSession.convID = json.conv.convID;
- ChatSession.nodeRoom = json.conv.nodeRoom;
- ChatSession.chatroomRules = json.conv.chatroomRules;
- ChatSession.numMsgListener = json.conv.numMsgListener;
- ChatSession.reqType = json.conv.reqType;
- ChatSession.reqStatus = json.conv.reqStatus;
- ChatSession.roomType = json.conv.chatRoomType;
- ChatSession.otherUser = {
- userType: json.conv.otherType,
- screenName: json.conv.otherScreenName
- };
- if (json.conv.otherType == 'b') {
- window.botMessageCount = 0;
- if (json.conv.currentBot)
- window.currentBot = json.conv.currentBot;
- if (window.currentBot.replyToMode) {
- tracker.emit("autoBotMessageView", {
- bot: window.currentBot.bot,
- botVersion: 2,
- mode: window.currentBot.replyToMode,
- stage: window.currentBot.replyToStage
- });
- }
- if (json.conv.doEmptyPing) {
- window.botPing = setTimeout(function () {
- if (ChatSession.otherUser && ChatSession.otherUser.userType == 'b') {
- window.allowEmpty = true;
- $('#Comment').val('');
- sendMessage();
- }
- }, 1000);
- }
- }
- if (json.conv.otherType == 'b' && json.conv.botMenu && !window.suppressBotMenu) {
- window.botMenu = json.conv.botMenu;
- if (window.botInterface)
- window.botInterface.destroy();
- if (window.botGUIObj)
- window.botGUIObj.destroy();
- //window.botInterface = new botGUI(ChatSession, botMenu);
- window.botGUIObj = new newBotGui (ChatSession, botMenu);
- } else if (json.conv.otherType != 'b') {
- if (window.botInterface) {
- window.botInterface.destroy();
- window.botInterface = false;
- }
- if (window.botGUIObj) {
- window.botGUIObj.destroy();
- window.botGUIObj = false;
- }
- }
- if ('otherListType' in json.conv)
- ChatSession.otherUser.listType = json.conv.otherListType;
- ChatSession.ratingPopped = (json.conv.ratingPopped && json.conv.ratingPopped > 0);
- delete ChatSession.tips.copy;
- delete ChatSession.privateMessagesSent;
- delete ChatSession.groupMessagesSent;
- delete ChatSession.discussion;
- ChatSession.discussion = json.conv.discussion;
- function addTo() {
- // Delay execution until async scripts are downloaded
- if (typeof ListMessagesSocket.emit === 'undefined') {
- initTimer = setTimeout(addTo, 25);
- return;
- }
- if (OLDnodeRoom != ChatSession.nodeRoom) {
- ListMessagesSocket.emit('addToRooms', [ChatSession.nodeRoom]);
- if (OLDnodeRoom) {
- ListMessagesSocket.emit('leave', [OLDnodeRoom]);
- }
- }
- }
- addTo();
- if (!json.conv.chatRoomType) {
- sendTypingStatus = true;
- if (ChatSession.user.userType == 'l') {
- if ($.inArray(ChatSession.otherUser.userType, ['m', 'g']) !== -1 && json.conv.reqAge && json.conv.reqAge === 'adult' && typeof ChatSession.user.whiteLabelResourceId == "undefined" && typeof json.conv.whiteLabelResourceId == "undefined") {
- $('#therapy-referral').slideDown();
- } else {
- $('#therapy-referral').slideUp();
- }
- if (links.indexOf(json.conv.convID) == -1) {
- if (ChatSession.otherUser.userType == 'm')
- tracker.emit("Link_L_to_M", {convID: json.conv.convID});
- else if (ChatSession.otherUser.userType == 'l')
- tracker.emit("Link_L_to_L", {convID: json.conv.convID});
- links.push(json.conv.convID);
- }
- }
- if (json.conv.numMsg == 0) {
- listTips(0);
- }
- } else {
- $('#therapy-referral').slideUp();
- var nowUnix = Math.round(+new Date() / 1000);
- var newToRoomArr = $.cookie('newToRoom') ? JSON.parse($.cookie('newToRoom')) : {};
- if (!newToRoomArr[ChatSession.nodeRoom] || parseInt(newToRoomArr[ChatSession.nodeRoom]) > parseInt(nowUnix)) {
- ListMessagesSocket.emit('sendConvAction', {room: ChatSession.nodeRoom, action: 'enterRoom', screenName: ChatSession.user.screenName, userType: ChatSession.user.userType, userTypeID: ChatSession.user.userTypeID, ua: ChatSession.user.ua, me: ChatSession.me});
- newToRoomArr[ChatSession.nodeRoom] = parseInt(nowUnix) - (60 * 60 * 24);
- newToRoomArr = JSON.stringify(newToRoomArr);
- $.cookie("newToRoom", newToRoomArr, {path: '/', expires: 1});
- ChatSession.roomLoadedToday = true;
- listTips(0);
- } else {
- delete ChatSession.roomLoadedToday;
- }
- }
- //$('#conversationHead').html(json.conv.otherScreenName);
- var name = '';
- var countryBlock = '';
- if (json.conv.imgURL == null) {
- var img = '<div class="userImage" style="background-color:' + json.conv.otherUserColor + ';">' + json.conv.otherScreenName.substring(0, 2) + '</div>';
- } else {
- var img = '<div class="img-profile ' + json.conv.imageClass + '" style="background-image:url(\'' + json.conv.imgURL + '\');"></div>';
- }
- if (json.conv.otherCountry) {
- countryBlock = '<img class="countryBlock" src="' + cloudfrontBase + 'img/countryFlags/' + json.conv.otherCountry.toLowerCase() + '.png" data-toggle="tooltip" title="' + json.conv.otherCountryFull + '" alt"' + json.conv.otherCountryFull + '" />';
- }
- var screenName = '<span class="name">' + json.conv.otherScreenName + '</span>';
- if (json.conv.reqStatus === 'request') {
- img = '<div class="headerImageBlock">' + img + '</div>';
- } else if (json.conv.otherType == 'l') {
- img = '<a class="headerImageBlock" data-usercard="' + json.conv.otherScreenName + '" href="/@' + json.conv.otherScreenName + '">' + img + countryBlock + '</a>';
- } else if (json.conv.otherType == 'm') {
- img = '<a class="headerImageBlock" data-usercard="' + json.conv.otherScreenName + '" href="/@' + json.conv.otherScreenName + '">' + img + countryBlock + '</a>';
- } else if (json.conv.otherType == 'b') {
- img = '<div class="headerImageBlock">'+img+'</div>';
- } else if (json.conv.otherType == 'g') {
- img = '<div class="headerImageBlock">' + img + countryBlock + '</div>';
- } else {
- img = '';
- screenName = json.conv.otherScreenName;
- }
- $('#conversationHead').html(img + screenName);
- /*
- if (json.user.userType != 'l' && json.conv.numMsgUser == 0) {
- $('#conversationStarter').html('<h2>Welcome...</h2><p>You are now connected to ' + json.conv.otherScreenName + ' from ' + printCountry(json.conv.otherCountry) + '. Please introduce yourself to ' + json.conv.otherScreenName + '.</p>');
- } else */
- if (json.conv.otherType == 'b') {
- $('#conversationStarter').hide();
- $('#MessageScrollDiv .alert').hide();
- $('#MessageScrollDiv .alert.alert-noni').show();
- } else if (json.user.userType == 'l' && json.conv.otherType != 'l' && json.conv.numMsgListener == 0) {
- $('#conversationStarter').html('<h3>Get the Conversation Started...</h3><p>Please introduce yourself and start by welcoming your member to 7 Cups of Tea.</p>');
- $('#MessageScrollDiv .alert').show();
- $('#MessageScrollDiv .alert.alert-noni').hide();
- } else {
- $('#conversationStarter').html('');
- $('#MessageScrollDiv .alert').show();
- $('#MessageScrollDiv .alert.alert-noni').hide();
- }
- processTopic();
- if (json.conv.chatRoomType) {
- soundOn = false;
- $('#MessageScrollDiv > .alert').hide();
- $('#blockConnectionButton').hide();
- $('#clearConversationButton').hide();
- $('#endLiveChatButton').hide();
- $('#getHelpButton').hide();
- showUnmuteButton();
- $('[href="#prevConListGroup"]').click();
- if (json.user.userType != 'l') {
- groupChatOrientation();
- }
- $('.headerTable .topLink').attr('href', '/conversations.php?show=GROUPSUPPORT');
- } else if (json.conv.otherType == 'b') {
- $('#unMuteButton').remove();
- $('#MessageScrollDiv > .alert').hide();
- $('#blockConnectionButton').hide();
- $('#getHelpButton').hide();
- $('#endLiveChatButton').hide();
- soundOn = (parseInt(json.user.alertInConv) == 1) ? true : false;
- } else {
- $('#unMuteButton').remove();
- $('#MessageScrollDiv > .alert').show();
- $('#blockConnectionButton').show();
- $('#clearConversationButton').show();
- $('#getHelpButton').show();
- soundOn = (parseInt(json.user.alertInConv) == 1) ? true : false;
- if (json.user.userType == 'l' && json.conv.otherType == 'l') {
- $('#endLiveChatButton').hide();
- } else {
- $('#endLiveChatButton').show();
- }
- loadRatingModal();
- }
- ChatSession.scrollDelay = 0;
- if ((json.user.userType == 'g' && $.cookie("permaCreateAccount"))) {
- if (isMobileApp()) {
- $('#MessageScrollDiv').prepend('<div style="position:relative;height:45px;" class="createAccountMessage"><button data-modal-target="NewMemberAccount" class="btn btn-sucess btn-cta" style="z-index:500;margin:0;position:fixed;top:50px;left:0;width:100%">CREATE YOUR FREE ACCOUNT NOW</button></div>');
- } else {
- if (!$('#permCreateAcctButton').length) {
- $('#topAlertHolder').append('<button id="permCreateAcctButton" data-modal-target="NewMemberAccount" class="btn btn-cta btn-success btn-sm createAccountMessage" style="margin-bottom:1em">Create Your Free Account Now</button>');
- }
- }
- } else if ($.cookie("permaCreateAccount")) {
- $.removeCookie("permaCreateAccount", {path: '/'});
- }
- if (isMobileApp()) {
- if (json.conv.imgURL) {
- $('#otherUserImage').css('background-image', 'url(' + json.conv.imgURL + ')').show();
- } else {
- $('#otherUserImage').css('background-image', 'none').css('background-color', json.conv.otherUserColor).text(json.conv.otherScreenName.substring(0, 2)).show();
- }
- }
- $('.activeConv').removeClass('activeConv');
- $('[id="convListItem_' + json.conv.convID + '"]').removeClass('newMsg').addClass('activeConv');
- window.convID = json.conv.convID;
- $('#chatForm').show();
- $('#selectConvPrompt').hide();
- //Show Related Communities if Any
- if(json.conv.relatedCommunities && json.conv.relatedCommunities.length){
- $('[data-id="related-community-holder"]').html('<div class="card card-normal card-block subtle-box-shadow"><h6>Related Subcommunities</h6></div>');
- $.each(json.conv.relatedCommunities, function(idx, val){
- $('[data-id="related-community-holder"] > div.card').append('<a href="'+val.url+'" class="btn btn-primary btn-block text-left" >'+val.community_title+'</a>');
- });
- }else{
- $('[data-id="related-community-holder"]').empty();
- }
- // Hide the delete messages forever button for therapy conversations
- if (ChatSession.reqType === 'personal_therapy' || ChatSession.reqType === 'general_therapy') {
- $('#clearConversationButton').hide();
- }
- checkConv(ChatSession.convID);
- }
- }
- }
- window.activeButton = false;
- window.activeButtonHash = false;
- window.lastPlace = $('#Comment').attr("placeholder");
- window.botDatum = false;
- window.selectData = false;
- function enforceSelect () {
- if (!window.selectData)
- resetState();
- var commentPost = $('#Comment').val(), re = new RegExp('^'+commentPost.trim()+'$', "i");
- for (var i = 0; i < window.selectData.length; i++)
- if (re.test(window.selectData[i])) {
- $('#sendButton').fadeTo(0, 1);
- return;
- }
- $('#sendButton').fadeTo(0, .5);
- }
- function setupSelect (data) {
- var isfocused = $('#Comment').is(":focus");
- var previousValue = $('#Comment').val();
- resetState();
- window.selectData = data;
- if ($('#Comment').typeahead) {
- $('#Comment').typeahead(
- {
- hint:true,
- highlight:true,
- minLength: 1
- },
- {
- name: 'ttdata',
- limit: 100,
- source: taSubstringMatcher(data)
- }
- ).on('typeahead:select', sendMessage);
- }
- $('#Comment').on('keyup', enforceSelect);
- if (isfocused) {
- $('#Comment').focus();
- setTimeout(function() {
- $('#Comment').focus();
- },250);
- }
- $('#Comment').val(previousValue);
- enforceSelect();
- }
- function lockState (disableMenu) {
- window.botDatum = false;
- window.selectData = false;
- $('#Comment').unbind("keyup", resetChatBox);
- $('#Comment').unbind("keyup", enforceSelect);
- $('#Comment').off('typeahead:selected');
- window.stateLocked = true;
- window.lastPlace = $('#Comment').attr("placeholder") ? $('#Comment').attr("placeholder") : window.lastPlace;
- $('#Comment').blur().attr("disabled", true).attr("placeholder", "").val('');
- $('#sendButton').fadeTo(0, .5);
- if (disableMenu)
- $('.noniMenu').fadeTo(0, .5).off('click');
- }
- function resetState (comment) {
- window.selectData = false;
- window.botDatum = false;
- $('#Comment').unbind("keyup", resetChatBox);
- $('#Comment').unbind("keyup", enforceSelect);
- $('#Comment').off('typeahead:selected');
- if ($('#Comment').typeahead) {
- var isfocused = $('#Comment').is(":focus");
- $('#Comment').typeahead("destroy");
- if (isfocused) {
- setTimeout(function() {
- $('#Comment').focus();
- },250);
- $('#Comment').focus();
- }
- }
- window.stateLocked = false;
- $('#Comment').attr("disabled", false).attr("placeholder", window.lastPlace);
- if (typeof comment !== 'undefined')
- $('#Comment').val(comment);
- $('#sendButton').fadeTo(0, 1);
- if (window.activeButtonHash) {
- removeMessage(window.activeButtonHash);
- window.activeButtonHash = false;
- window.activeButton = false;
- }
- if (window.botGUIObj)
- window.botGUIObj.closeMenu();
- if (window.botPing)
- clearTimeout(window.botPing);
- }
- function handleBotCreditCard (message, row) {
- if ($.cookie('ab_smartSophiaTest1') == "oldPayment") {
- handleBotCreditCard2(message, row);
- return;
- }
- tracker.emit("OnlineTherapy", {step: 'loadpayment', reqType: "general_therapy"});
- if (window.activeButton > parseInt(message.msgID)) {
- // Remove any old function button in memory or otherwise
- removeMessage(message.msgHash);
- return;
- }
- console.log('[LOCK] Creating payment form', message.msgID);
- lockState();
- window.activeButton = parseInt(message.msgID);
- window.activeButtonHash = message.msgHash;
- $('#MessageDiv button[data-func]').each(function() {
- var parent = $(this).closest('div.convRow');
- var id = $(parent).attr('id');
- removeMessage(id.split('_')[1]);
- });
- $('#message_'+message.msgHash+' .youArea').empty(); render($('#message_'+message.msgHash+' .youArea'), 'Forms_Payment_CreditCard', {sub: {submitbutton: "Continue"}}, function (form) {
- var $payForm = form;
- if (!window.stateLocked) {
- console.log('State has been reset. Removing payment');
- removeMessage(message.msgHash);
- window.activeButtonHash = false;
- window.activeButton = false;
- return;
- } else
- console.log('[RENDER] Creating payment form', message.msgID);
- tracker.emit('OnlineTherapy', {step: 'loadcreditcard', uri: window.location.href, reqType: "general_therapy"});
- form.find('.card-js').CardJs();
- var submit = form.find("button");
- $payForm.on('submit', function (event) {
- tracker.emit('OnlineTherapy', {step: 'creditcardsubmit', uri: window.location.href, reqType: "general_therapy"});
- event.preventDefault();
- submit.attr("disabled", "disabled")
- form.find(".stripe-errors").hide();
- Stripe.card.createToken(form, function(status, response) {
- if (response.error) {
- form.find(".stripe-errors").text(response.error.message).show();
- submit.removeAttr("disabled");
- } else {
- $payForm.append('<input type="hidden" name="stripeToken" value="' + response['id'] + '" />');
- if (!$payForm.find('[name="convID"]').length)
- $payForm.append('<input type="hidden" name="convID" value="' + ChatSession.convID + '" />');
- $payForm.append('<input type="hidden" name="planID" value="' + message.funcProp + '" />');
- $.post("/ajax/processSubscription.php", $payForm.serialize(), function (resp) {
- if (resp.success) {
- tracker.emit("OnlineTherapy", {step: 'completepayment', reqType: "general_therapy"});
- resetState();
- window.allowEmpty = true;
- $('#Comment').val('');
- sendMessage();
- if (typeof ga !== 'undefined' && resp.sub) {
- try {
- ga('ec:setAction', 'purchase', {
- 'id': resp.sub.subID,
- 'revenue': sub.amt
- });
- // Record Adwords conversion
- window.google_conversion_id = 991416627;
- window.google_conversion_label = "KjZ_CMnek3EQs6Lf2AM";
- window.google_remarketing_only = false;
- window.google_conversion_format = "3";
- var opt = new Object();
- opt.onload_callback = function() {
- console.log('Transaction Recorded');
- }
- var conv_handler = window['google_trackConversion'];
- if (typeof(conv_handler) == 'function')
- conv_handler(opt);
- } catch (e) { }
- }
- $payForm.closest('.convRow').remove();
- } else {
- if (resp.err && resp.err.copy) {k
- for (e in resp.err.copy) {
- $payForm.prepend('<div class="alert alert-danger"><button type="button" class="close" data-dismiss="alert" aria-label="Close"><span aria-hidden="true">×</span></button>' + resp.err.copy[e] + '</div>');
- }
- tracker.emit("OnlineTherapy", {message: resp.err.copy, step: 'paymentfail', reqType: "general_therapy"});
- } else
- tracker.emit("OnlineTherapy", {step: 'paymentfail', reqType: "general_therapy"});
- }
- }, 'json');
- }
- });
- });
- });
- }
- function handleBotCreditCard4 (button) {
- try {
- var payload = JSON.parse($(button).data('payload'));
- } catch (e) {
- var payload = false;
- }
- if (!payload) {
- $('#MessageDiv button[data-func]').each(function() {
- var parent = $(this).closest('div.convRow');
- var id = $(parent).attr('id');
- removeMessage(id.split('_')[1]);
- });
- return;
- }
- handleBotCreditCard2(payload);
- }
- $('body').on('click', 'button[data-therapyaction="signupform"]', function () {
- tracker.emit("OnlineTherapy", {step: 'loadmoreinfo', reqType: ChatSession.reqType});
- if (autoMessageFunction) clearTimeout(autoMessageFunction);
- $.ajax({
- type: 'GET',
- url: '/inc/local.php',
- async: false,
- contentType: "application/json",
- dataType: 'jsonp',
- data: {return: 'local'},
- success: function (json) {
- //tracker.emit("debugUserinfo", {step: 'localLoaded'});
- if (typeof ga !== 'undefined') {
- ga('ec:addProduct', {
- 'id': 'onlinetherapy',
- 'name': 'Online Therapy',
- 'price': '150.00',
- 'category': 'therapy',
- 'brand': '7 Cups',
- 'position': 1,
- });
- }
- function padDigits(number, digits) {
- return Array(Math.max(digits - String(number).length + 1, 0)).join(0) + number;
- }
- var param = {};
- param.dob = {year: [], month: [], day: []};
- param.states = json.states;
- param.countries = json.countries;
- var curyear = new Date().getFullYear();
- for (var i = curyear - 5; i >= curyear - 110; i--) {
- param.dob.year.push(i);
- }
- for (var i = 1; i <= 31; i++) {
- param.dob.day.push(padDigits(i, 2));
- }
- var monthNames = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"];
- for (var i = 0; i < 12; i++) {
- param.dob.month.push({val: padDigits(i + 1, 2), disp: monthNames[i]});
- }
- param.convID = ChatSession.convID;
- if (!($.cookie("mid") || $.cookie("lid"))) {
- param.showLogin = true;
- } else {
- param.showLogin = false;
- }
- // param.showLogin = userInfo.userType === 'g';
- if (typeof window.eventDetails !== 'undefined' && window.eventDetails.screenName)
- param.screenName = window.eventDetails.screenName;
- else
- param.screenName = '';
- var form = 'SC_Forms_OnlineTherapy_PersonalInfo2';
- //tracker.emit("debugUserinfo", {step: 'localProcessed'});
- render(false, form, param, function (content) {
- //tracker.emit("debugUserinfo", {step: 'HB Rendered'});
- bootbox.dialog({
- title: 'Personal Information',
- size: 'large',
- message: content,
- onEscape: true,
- backdrop: true,
- closeButton: true
- }).off("shown.bs.modal").on("shown.bs.modal", function () {
- //tracker.emit("debugUserinfo", {step: 'HB Displayed'});
- var $mod = $(this);
- var $form = $mod.find('form');
- $form.find('[name="memberacct"]').on('change', function () {
- $form.find('div.tab-pane.active').removeClass('active');
- $form.find('div.tab-pane[data-tab="account-' + $form.find('[name="memberacct"]:checked').val() + '"]').addClass('active');
- });
- $form.find('select[name="addCountry"]').on('change', function() {
- if ($(this).val() == 'US')
- $form.find('select[name="addState"]').parent().show();
- else
- $form.find('select[name="addState"]').parent().hide();
- });
- $form.on('submit', function () {
- $form.find('.alert,.text-danger').remove();
- $form.find('.has-error').removeClass('has-error');
- $form.find('button[type="submit"]').attr("disabled", "disabled").attr("data-html", function () {
- return $(this).html()
- }).html('<i class="fa fa-spin fa-spinner"></i> Processing');
- $.post('/connect/therapist_ConsentTreatment.php', $form.serialize(), function (resp) {
- if (resp.success) {
- tracker.emit("OnlineTherapy", {step: 'completemoreinfo', reqType: ChatSession.reqType});
- if (typeof __adroll !== "undefined") {
- try {
- __adroll.record_user({"adroll_segments": "52091a73"});
- if (['US', 'GB', 'CA'].indexOf($form.find('select[name="addCountry"]').val()) !== -1)
- __adroll.record_user({"adroll_segments": "23ddcaa1"});
- } catch(err) {}
- }
- if (resp.refresh) {
- // Allow tracking to happen
- setTimeout(function () {
- window.location.href = '/member/connect/conversation.php?c=' + resp.refresh + '&ht=1';
- },25);
- } else {
- talkToNoni();
- $mod.modal('hide');
- }
- } else if (resp.err) {
- for (var key in resp.err) {
- if (key == 'copy') {
- for (var e = 0; e < resp.err.copy.length; e++) {
- $form.prepend('<div class="alert alert-danger">' + resp.err.copy[e] + '</div>');
- }
- } else {
- $form.find('[name="' + key + '"]').closest('.form-group').addClass('has-error');
- if (resp.err[key] != 'Required') {
- $form.find('[name="' + key + '"]').closest('.form-group').append('<div class="text-danger"><small>' + resp.err[key] + '</small></div>');
- }
- }
- }
- $form.find('button[type="submit"]').removeAttr("disabled").html(function () {
- return $(this).attr("data-html")
- });
- }
- }, 'json');
- return false;
- });
- });
- });
- }
- });
- });
- function personalDetails (message, row) {
- bootbox.hideAll();
- if (window.activeButton > parseInt(message.msgID)) {
- // Remove any old function button in memory or otherwise
- removeMessage(message.msgHash);
- return;
- }
- window.activeButton = parseInt(message.msgID);
- window.activeButtonHash = message.msgHash;
- lockState();
- tracker.emit("OnlineTherapy", {step: 'loadmoreinfo', reqType: ChatSession.reqType});
- if (autoMessageFunction) clearTimeout(autoMessageFunction);
- $.ajax({
- type: 'GET',
- url: '/inc/local.php',
- async: false,
- contentType: "application/json",
- dataType: 'jsonp',
- data: {return: 'local'},
- success: function (json) {
- //tracker.emit("debugUserinfo", {step: 'localLoaded'});
- if (typeof ga !== 'undefined') {
- ga('ec:addProduct', {
- 'id': 'onlinetherapy',
- 'name': 'Online Therapy',
- 'price': '150.00',
- 'category': 'therapy',
- 'brand': '7 Cups',
- 'position': 1,
- });
- }
- function padDigits(number, digits) {
- return Array(Math.max(digits - String(number).length + 1, 0)).join(0) + number;
- }
- var param = {};
- param.dob = {year: [], month: [], day: []};
- param.states = json.states;
- param.countries = json.countries;
- var curyear = new Date().getFullYear();
- for (var i = curyear - 5; i >= curyear - 110; i--) {
- param.dob.year.push(i);
- }
- for (var i = 1; i <= 31; i++) {
- param.dob.day.push(padDigits(i, 2));
- }
- var monthNames = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"];
- for (var i = 0; i < 12; i++) {
- param.dob.month.push({val: padDigits(i + 1, 2), disp: monthNames[i]});
- }
- param.convID = ChatSession.convID;
- if (!($.cookie("mid") || $.cookie("lid"))) {
- param.showLogin = true;
- } else {
- param.showLogin = false;
- }
- // param.showLogin = userInfo.userType === 'g';
- if (typeof window.eventDetails !== 'undefined' && window.eventDetails.screenName)
- param.screenName = window.eventDetails.screenName;
- else
- param.screenName = '';
- var form = 'SC_Forms_OnlineTherapy_PersonalInfo2';
- //tracker.emit("debugUserinfo", {step: 'localProcessed'});
- render(false, form, param, function (content) {
- //tracker.emit("debugUserinfo", {step: 'HB Rendered'});
- bootbox.dialog({
- title: 'Personal Information',
- size: 'large',
- message: content,
- onEscape: true,
- backdrop: true,
- closeButton: true
- }).off("shown.bs.modal").on("shown.bs.modal", function () {
- //tracker.emit("debugUserinfo", {step: 'HB Displayed'});
- var $mod = $(this);
- var $form = $mod.find('form');
- $form.find('[name="memberacct"]').on('change', function () {
- $form.find('div.tab-pane.active').removeClass('active');
- $form.find('div.tab-pane[data-tab="account-' + $form.find('[name="memberacct"]:checked').val() + '"]').addClass('active');
- });
- $form.find('select[name="addCountry"]').on('change', function() {
- if ($(this).val() == 'US')
- $form.find('select[name="addState"]').parent().show();
- else
- $form.find('select[name="addState"]').parent().hide();
- });
- $form.on('submit', function () {
- $form.find('.alert,.text-danger').remove();
- $form.find('.has-error').removeClass('has-error');
- $form.find('button[type="submit"]').attr("disabled", "disabled").attr("data-html", function () {
- return $(this).html()
- }).html('<i class="fa fa-spin fa-spinner"></i> Processing');
- $.post('/connect/therapist_ConsentTreatment.php', $form.serialize(), function (resp) {
- if (resp.success) {
- tracker.emit("OnlineTherapy", {step: 'completemoreinfo', reqType: ChatSession.reqType});
- fbq('track', 'CompleteRegistration');
- if (typeof __adroll !== "undefined") {
- try {
- __adroll.record_user({"adroll_segments": "52091a73"});
- if (['US', 'GB', 'CA'].indexOf($form.find('select[name="addCountry"]').val()) !== -1)
- __adroll.record_user({"adroll_segments": "23ddcaa1"});
- } catch(err) {}
- }
- if (resp.refresh) {
- // Allow tracking to happen
- setTimeout(function () {
- window.location.href = '/member/connect/conversation.php?c=' + resp.refresh + '&ht=1';
- },25);
- } else {
- bootbox.hideAll();
- resetState();
- window.allowEmpty = true;
- $('#Comment').val('');
- sendMessage();
- }
- } else if (resp.err.stateUnavailable) {
- $('.modal').on('hidden.bs.modal', function () {
- window.location = '/BrowseListeners/';
- });
- $('.modal-title').text('Therapy Unavailable');
- $form.parent().replaceWith('<div class="text-center">' + resp.err.stateUnavailable + '<br/><br/><a class="btn btn-primary" href="/BrowseListeners/" style="width:200px; margin-right:30px;">Browse Listeners</a><a class="btn btn-secondary" href="/" style="width:200px;">Home</a></div>');
- } else if (resp.err) {
- for (var key in resp.err) {
- if (key == 'copy') {
- for (var e = 0; e < resp.err.copy.length; e++) {
- $form.prepend('<div class="alert alert-danger">' + resp.err.copy[e] + '</div>');
- }
- } else {
- $form.find('[name="' + key + '"]').closest('.form-group').addClass('has-error');
- if (resp.err[key] != 'Required') {
- $form.find('[name="' + key + '"]').closest('.form-group').append('<div class="text-danger"><small>' + resp.err[key] + '</small></div>');
- }
- }
- }
- $form.find('button[type="submit"]').removeAttr("disabled").html(function () {
- return $(this).attr("data-html")
- });
- }
- }, 'json');
- return false;
- });
- });
- });
- }
- });
- }
- function handleBotCreditCard2 (message, row) {
- if ($.cookie('ab_smartSophiaTest2') == "oldForm") {
- } else {
- handleBotCreditCard3(message, row);
- return;
- }
- bootbox.hideAll();
- if (window.activeButton > parseInt(message.msgID)) {
- // Remove any old function button in memory or otherwise
- removeMessage(message.msgHash);
- return;
- }
- window.activeButton = parseInt(message.msgID);
- window.activeButtonHash = message.msgHash;
- lockState();
- var reqType="general_therapy";
- var planID = message.funcProp;
- tracker.emit("OnlineTherapy", {step: 'loadpayment', reqType: reqType});
- stopAutoPing ();
- if (autoMessageFunction) clearTimeout(autoMessageFunction);
- var subs = {};
- if (typeof __adroll !== "undefined") {
- try {
- __adroll.record_user({"adroll_segments": "13b73f15"})
- } catch(err) {}
- try {
- __adroll.record_user({product_id: "onlineTherapy", product_action: "AddToCart"})
- } catch (e) { }
- }
- subs['onlinetherapy_monthly_15000'] = {
- planID: 'onlinetherapy_monthly_15000',
- modaltitle: 'Get Started!',
- desc: '',
- topdesc: 'Just like texting with a close friend, you can now message your therapist every day, writing as many times as you want.',
- amt: '150.00',
- recur: 'Monthly',
- submitbutton: 'Start Therapy Now',
- disclaimer: 'Your subscription will begin when you click on the button above. To cancel, go to “settings” and click on “manage subscriptions” and cancel. By clicking the button above, you authorize us to continue your month to month 7 Cups subscription automatically at the rate of $150 USD/month.'
- };
- subs['onlinetherapy_monthly_15000_tr3'] = {
- planID: 'onlinetherapy_monthly_15000_tr3',
- modaltitle: 'Start Free Trial Now!',
- desc: '',
- topdesc: 'Just like texting with a close friend, you can now message your therapist every day, writing as many times as you want. And the first 3 days are free!',
- amt: '150.00',
- recur: 'Monthly',
- submitbutton: 'Start Therapy with 3 Day Trial',
- disclaimer: 'Your subscription, which starts with a 3 day (72 hour) free trial, will begin when you click on the button above. We will authorize your card, much like what happens when you check into a hotel room. Simply cancel anytime in the first 72 hours (3 days), and you will not be charged. To cancel, go to “settings” and click on “manage subscriptions” and cancel. By clicking the button above, you authorize us to continue your month to month 7 Cups subscription automatically at the rate of $150 USD/month.'
- };
- if(subs[planID]){
- var sub = subs[planID];
- }else{
- bootbox.alert('Error: Therapy plan not found.');
- return false;
- }
- var ccyears = [];
- var year = new Date().getFullYear();
- for (var i = 0; i < 15; i++) {
- ccyears.push(year + i);
- }
- if (typeof ga !== 'undefined') {
- ga('ec:setAction', 'checkout');
- }
- var form = 'SC_Forms_Payment_StripeSubscription2';
- var pt = 'Calmer days are ahead...';
- var ph = 'paymentHeader2.jpg';
- render(false, form, {paymentHeader: ph, paymentText: pt, ccyears: ccyears, sub: sub, ab_paymentpcode: ($.cookie('ab_paymentpcode')==true)}, function (content) {
- tracker.emit('OnlineTherapy', {step: 'loadcreditcard', uri: window.location.href, reqType: reqType});
- fbq('track', 'AddPaymentInfo');
- bootbox.dialog({
- className: "payment-details-modal",
- title: '<span style="font-size:1.5em" class="text-primary">'+sub.modaltitle+'</span>',
- message: content,
- onEscape: true,
- backdrop: true,
- closeButton: true
- }).off("shown.bs.modal").on("shown.bs.modal", function () {
- var $payModal = $(this);
- var $payForm = $(this).find(".stripe-payment-form");
- $payForm.find('[data-action="applypromo"]').on('click', function () {
- var btn = $(this);
- $payForm.find('.alert-danger').remove();
- btn.attr('data-html', function () {
- return $(this).html()
- }).attr('disabled', 'true').html('<i class="fa fa-spinner fa-spin"></i> Checking');
- $.post($payForm.attr('action'), {action: 'verifypromo', promo: $payForm.find('[name="promo"]').val(), planID: $payForm.find('[name="planID"]').val()}, function (resp) {
- if (resp.success) {
- if (resp.update) {
- for (var key in resp.update) {
- $payModal.find(key).replaceWith(resp.update[key]);
- }
- }
- } else {
- $payForm.prepend('<div class="alert alert-danger"><button type="button" class="close" data-dismiss="alert" aria-label="Close"><span aria-hidden="true">×</span></button>Invalid Promo Code</div>');
- btn.html(function () {
- return $(this).attr('data-html')
- }).removeAttr('disabled');
- }
- }, 'json');
- });
- $payForm.on('submit', function (event) {
- var submitCard = function () {
- $('.payment-details-modal').show();
- $('body').addClass('modal-open');
- //$payModal.modal('show');
- tracker.emit('OnlineTherapy', {step: 'creditcardsubmit', uri: window.location.href, reqType: reqType});
- $payForm.find('[name="stripeToken"], .alert').remove();
- $payForm.find('button[type="submit"]').attr("disabled", "disabled").attr("data-text", function () {
- return $(this).html();
- }).html('<i class="fa fa-spin fa-spinner"></i> Processing');
- var card = {
- number: $payForm.find("[data-stripe='number']").val(),
- cvc: $payForm.find("[data-stripe='cvc']").val(),
- exp_month: $payForm.find("[data-stripe='exp_month']").val(),
- exp_year: $payForm.find("[data-stripe='exp_year']").val()
- };
- Stripe.createToken(card, function(status, response) {
- if (response.error) {
- $payForm.find('button[type="submit"]').removeAttr("disabled").html(function () {
- return $(this).attr("data-text")
- });
- $payForm.prepend('<div class="alert alert-danger"><button type="button" class="close" data-dismiss="alert" aria-label="Close"><span aria-hidden="true">×</span></button>' + response.error.message + '</div>');
- tracker.emit("OnlineTherapy", {message: response.error.message, step: 'paymentStripefail', reqType: "general_therapy"});
- } else {
- $payForm.append('<input type="hidden" name="stripeToken" value="' + response['id'] + '" />');
- if (!$payForm.find('[name="convID"]').length) {
- $payForm.append('<input type="hidden" name="convID" value="' + ChatSession.convID + '" />');
- }
- $.post($payForm.attr('action'), $payForm.serialize(), function (resp) {
- if (resp.success) {
- tracker.emit("OnlineTherapy", {step: 'completepayment', reqType: reqType});
- resetState();
- window.allowEmpty = true;
- $('#Comment').val('');
- sendMessage();
- if (typeof __adroll !== "undefined")
- try {
- __adroll.record_user({"adroll_segments": "9cb7fee1"})
- __adroll.record_user({product_id: "onlineTherapy", product_action: "Purchased"})
- } catch (e) { }
- if (typeof ga !== 'undefined' && resp.sub) {
- try {
- ga('ec:setAction', 'purchase', {
- 'id': resp.sub.subID,
- 'revenue': sub.amt
- });
- // Record Adwords conversion
- window.google_conversion_id = 991416627;
- window.google_conversion_label = "KjZ_CMnek3EQs6Lf2AM";
- window.google_remarketing_only = false;
- window.google_conversion_format = "3";
- var opt = new Object();
- opt.onload_callback = function() {
- console.log('Transaction Recorded');
- }
- var conv_handler = window['google_trackConversion'];
- if (typeof(conv_handler) == 'function')
- conv_handler(opt);
- $('#MessageDiv button[data-func]').each(function() {
- var parent = $(this).closest('div.convRow');
- var id = $(parent).attr('id');
- removeMessage(id.split('_')[1]);
- });
- } catch (e) { }
- }
- $payModal.modal('hide');
- } else {
- if (resp.err && resp.err.copy) {k
- for (e in resp.err.copy) {
- $payForm.prepend('<div class="alert alert-danger"><button type="button" class="close" data-dismiss="alert" aria-label="Close"><span aria-hidden="true">×</span></button>' + resp.err.copy[e] + '</div>');
- }
- tracker.emit("OnlineTherapy", {message: resp.err.copy, step: 'paymentfail', reqType: "general_therapy"});
- } else
- tracker.emit("OnlineTherapy", {step: 'paymentfail', reqType: "general_therapy"});
- $payForm.find('button[type="submit"]').removeAttr("disabled").html(function () {
- return $(this).attr("data-text")
- });
- }
- }, 'json')
- }
- });
- }
- if (1 || window.confirmAuthorization){
- submitCard();
- } else {
- //$payModal.modal('hide');
- $('.payment-details-modal').hide();
- tracker.emit('OnlineTherapy', {step: 'creditcardconfirm', uri: window.location.href, reqType: reqType});
- bootbox.dialog({
- className: "payment-confirm-modal",
- message: "Please note: Your card will be authorized for the amount of the first payment and we release that authorization after we verify that the funds exist.",
- buttons: {
- confirm: {
- label: 'Connect me to my therapist',
- className: 'btn-success',
- callback: submitCard
- }
- },
- onEscape: function() {
- console.log('Dismissed');
- $('.payment-details-modal').show();
- $('body').addClass('modal-open');
- //$payModal.modal('show');
- }
- }).on('hidden.bs.modal', function () {
- $('.payment-details-modal').show();
- $('body').addClass('modal-open');
- });
- }
- return false;
- });
- });
- });
- }
- function handleBotCreditCard3 (message, row) {
- bootbox.hideAll();
- if (window.activeButton > parseInt(message.msgID)) {
- // Remove any old function button in memory or otherwise
- removeMessage(message.msgHash);
- return;
- }
- window.activeButton = parseInt(message.msgID);
- window.activeButtonHash = message.msgHash;
- lockState();
- var reqType="general_therapy";
- var planID = message.funcProp;
- tracker.emit("OnlineTherapy", {step: 'loadpayment', reqType: reqType});
- stopAutoPing ();
- if (autoMessageFunction) clearTimeout(autoMessageFunction);
- var subs = {};
- if (typeof __adroll !== "undefined") {
- try {
- __adroll.record_user({"adroll_segments": "13b73f15"})
- } catch(err) {}
- try {
- __adroll.record_user({product_id: "onlineTherapy", product_action: "AddToCart"})
- } catch (e) { }
- }
- subs['onlinetherapy_monthly_15000'] = {
- planID: 'onlinetherapy_monthly_15000',
- modaltitle: 'Get Started!',
- desc: '',
- topdesc: 'Just like texting with a close friend, you can now message your therapist every day, writing as many times as you want.',
- amt: '150.00',
- recur: 'Monthly',
- submitbutton: 'Start Therapy Now',
- disclaimer: 'Your subscription will begin when you click on the button above. To cancel, go to “settings” and click on “manage subscriptions” and cancel. By clicking the button above, you authorize us to continue your month to month 7 Cups subscription automatically at the rate of $150 USD/month.'
- };
- if (message.promoCode) {
- subs['onlinetherapy_monthly_15000'].promo = true;
- subs['onlinetherapy_monthly_15000'].submitbutton = 'Continue Therapy';
- }
- subs['onlinetherapy_monthly_15000_tr3'] = {
- planID: 'onlinetherapy_monthly_15000_tr3',
- modaltitle: 'Start Free Trial Now!',
- desc: '',
- topdesc: 'Just like texting with a close friend, you can now message your therapist every day, writing as many times as you want. And the first 3 days are free!',
- amt: '150.00',
- recur: 'Monthly',
- submitbutton: 'Start Therapy with 3 Day Trial',
- disclaimer: 'Your subscription, which starts with a 3 day (72 hour) free trial, will begin when you click on the button above. We will authorize your card, much like what happens when you check into a hotel room. Simply cancel anytime in the first 72 hours (3 days), and you will not be charged. To cancel, go to “settings” and click on “manage subscriptions” and cancel. By clicking the button above, you authorize us to continue your month to month 7 Cups subscription automatically at the rate of $150 USD/month.'
- };
- if(subs[planID]){
- var sub = subs[planID];
- }else{
- bootbox.alert('Error: Therapy plan not found.');
- return false;
- }
- var ccyears = [];
- var year = new Date().getFullYear();
- for (var i = 0; i < 15; i++) {
- ccyears.push(year + i);
- }
- if (typeof ga !== 'undefined') {
- ga('ec:setAction', 'checkout');
- }
- var form = 'SC_Forms_Payment_StripeSubscription3';
- var pt = 'Calmer days are ahead...';
- var ph = 'paymentHeader2.jpg';
- render(false, form, {paymentHeader: ph, paymentText: pt, ccyears: ccyears, sub: sub, ab_paymentpcode: ($.cookie('ab_paymentpcode')==true)}, function (content) {
- tracker.emit('OnlineTherapy', {step: 'loadcreditcard', uri: window.location.href, reqType: reqType});
- fbq('track', 'AddPaymentInfo');
- bootbox.dialog({
- className: "payment-details-modal",
- title: '<span style="font-size:1.5em" class="text-primary">'+sub.modaltitle+'</span>',
- message: content,
- onEscape: true,
- backdrop: true,
- closeButton: true
- }).off("shown.bs.modal").on("shown.bs.modal", function () {
- var $payModal = $(this);
- var $payForm = $(this).find(".stripe-payment-form");
- $payForm.find('.card-js').CardJs();
- $payForm.find('[data-action="applypromo"]').on('click', function () {
- var btn = $(this);
- $payForm.find('.alert-danger').remove();
- btn.attr('data-html', function () {
- return $(this).html()
- }).attr('disabled', 'true').html('<i class="fa fa-spinner fa-spin"></i> Checking');
- $.post($payForm.attr('action'), {action: 'verifypromo', promo: $payForm.find('[name="promo"]').val(), planID: $payForm.find('[name="planID"]').val()}, function (resp) {
- if (resp.success) {
- if (resp.update) {
- for (var key in resp.update) {
- $payModal.find(key).replaceWith(resp.update[key]);
- }
- }
- } else {
- $payForm.prepend('<div class="alert alert-danger"><button type="button" class="close" data-dismiss="alert" aria-label="Close"><span aria-hidden="true">×</span></button>Invalid Promo Code</div>');
- btn.html(function () {
- return $(this).attr('data-html')
- }).removeAttr('disabled');
- }
- }, 'json');
- });
- $payForm.on('submit', function (event) {
- var submitCard = function () {
- $('.payment-details-modal').show();
- $('body').addClass('modal-open');
- //$payModal.modal('show');
- tracker.emit('OnlineTherapy', {step: 'creditcardsubmit', uri: window.location.href, reqType: reqType});
- $payForm.find('[name="stripeToken"], .alert').remove();
- $payForm.find('button[type="submit"]').attr("disabled", "disabled").attr("data-text", function () {
- return $(this).html();
- }).html('<i class="fa fa-spin fa-spinner"></i> Processing');
- /*var card = {
- number: $payForm.find("[data-stripe='number']").val(),
- cvc: $payForm.find("[data-stripe='cvc']").val(),
- exp_month: $payForm.find("[data-stripe='exp_month']").val(),
- exp_year: $payForm.find("[data-stripe='exp_year']").val()
- };*/
- Stripe.createToken($payForm, function(status, response) {
- if (response.error) {
- $payForm.find('button[type="submit"]').removeAttr("disabled").html(function () {
- return $(this).attr("data-text")
- });
- $payForm.prepend('<div class="alert alert-danger"><button type="button" class="close" data-dismiss="alert" aria-label="Close"><span aria-hidden="true">×</span></button>' + response.error.message + '</div>');
- tracker.emit("OnlineTherapy", {message: response.error.message, step: 'paymentStripefail', reqType: "general_therapy"});
- } else {
- $payForm.append('<input type="hidden" name="stripeToken" value="' + response['id'] + '" />');
- if (!$payForm.find('[name="convID"]').length) {
- $payForm.append('<input type="hidden" name="convID" value="' + ChatSession.convID + '" />');
- }
- if (window.checkinID) {
- $payForm.append('<input type="hidden" name="checkinID" value="' + window.checkinID + '" />');
- }
- var form = $payForm.serialize();
- $.post($payForm.attr('action'), form, function (resp) {
- if (resp.success) {
- tracker.emit("OnlineTherapy", {step: 'completepayment', reqType: reqType});
- fbq('track', 'Purchase', {value: sub.amt, currency: 'USD'});
- resetState();
- window.allowEmpty = true;
- $('#Comment').val('');
- if (window.checkinID) {
- $('#MessageDiv').html('You have successfully renewed your subscription. Connecting you with your therapist now...');
- window.location = window.location;
- } else {
- sendMessage();
- }
- if (typeof __adroll !== "undefined")
- try {
- __adroll.record_user({"adroll_segments": "9cb7fee1"})
- __adroll.record_user({product_id: "onlineTherapy", product_action: "Purchased"})
- } catch (e) { }
- if (typeof ga !== 'undefined' && resp.sub) {
- try {
- ga('ec:setAction', 'purchase', {
- 'id': resp.sub.subID,
- 'revenue': sub.amt
- });
- // Record Adwords conversion
- window.google_conversion_id = 991416627;
- window.google_conversion_label = "KjZ_CMnek3EQs6Lf2AM";
- window.google_remarketing_only = false;
- window.google_conversion_format = "3";
- var opt = new Object();
- opt.onload_callback = function() {
- console.log('Transaction Recorded');
- }
- var conv_handler = window['google_trackConversion'];
- if (typeof(conv_handler) == 'function')
- conv_handler(opt);
- $('#MessageDiv button[data-func]').each(function() {
- var parent = $(this).closest('div.convRow');
- var id = $(parent).attr('id');
- removeMessage(id.split('_')[1]);
- });
- } catch (e) { }
- }
- $payModal.modal('hide');
- } else {
- if (resp.err && resp.err.copy) {
- for (e in resp.err.copy) {
- $payForm.prepend('<div class="alert alert-danger"><button type="button" class="close" data-dismiss="alert" aria-label="Close"><span aria-hidden="true">×</span></button>' + resp.err.copy[e] + '</div>');
- }
- tracker.emit("OnlineTherapy", {message: resp.err.copy, step: 'paymentfail', reqType: "general_therapy"});
- } else
- tracker.emit("OnlineTherapy", {step: 'paymentfail', reqType: "general_therapy"});
- $payForm.find('button[type="submit"]').removeAttr("disabled").html(function () {
- return $(this).attr("data-text")
- });
- }
- }, 'json')
- }
- });
- }
- if (1 || window.confirmAuthorization){
- submitCard();
- } else {
- //$payModal.modal('hide');
- $('.payment-details-modal').hide();
- tracker.emit('OnlineTherapy', {step: 'creditcardconfirm', uri: window.location.href, reqType: reqType});
- bootbox.dialog({
- className: "payment-confirm-modal",
- message: "Please note: Your card will be authorized for the amount of the first payment and we release that authorization after we verify that the funds exist.",
- buttons: {
- confirm: {
- label: 'Connect me to my therapist',
- className: 'btn-success',
- callback: submitCard
- }
- },
- onEscape: function() {
- console.log('Dismissed');
- $('.payment-details-modal').show();
- $('body').addClass('modal-open');
- //$payModal.modal('show');
- }
- }).on('hidden.bs.modal', function () {
- $('.payment-details-modal').show();
- $('body').addClass('modal-open');
- });
- }
- return false;
- });
- });
- });
- }
- function handleBotButton (message, row) {
- if (window.activeButton > parseInt(message.msgID)) {
- // Remove any old function button in memory or otherwise
- removeMessage(message.msgHash);
- return;
- }
- if (message.func == 'waitForChoice' && !(typeof message.doNotLock !== "undefined"))
- lockState();
- else
- resetState();
- window.activeButton = parseInt(message.msgID);
- window.activeButtonHash = message.msgHash;
- // For every functional button, remove it, or add onclick if in active button messae set
- $('#MessageDiv button[data-func]').each(function() {
- var parent = $(this).closest('div.convRow');
- var id = $(parent).attr('id');
- if (id == 'message_'+message['msgHash'])
- $(this).click(function () {
- var reply = $(this).html();
- removeMessage(id.split('_')[1]);
- console.log('resetting from button push');
- resetState(reply);
- sendMessage();
- });
- else
- removeMessage(id.split('_')[1]);
- });
- }
- function removeMessage(hash) {
- $('#message_' + hash).hide();
- if (ChatSession.convID && userInfo.userIDe) {
- var idx = userInfo.userIDe + ChatSession.convID;
- if (window.chatInfoMemory[idx] && window.chatInfoMemory[idx].messages) {
- for (mi = 0; mi < window.chatInfoMemory[idx].messages.length; mi++) {
- if (window.chatInfoMemory[idx].messages[mi].msgHash === hash) {
- delete window.chatInfoMemory[idx].messages.splice(mi, 1);
- }
- }
- }
- }
- }
- var botTimer = false;
- var botMessageCount = 0;
- var currentBot = {};
- var protectedBotMessages = [];
- var autoPing = false;
- var autoPingIdx = 0;
- var autoPingExec = false;
- var autoPingName = false;
- function startAutoPing (autoPingInstructions) {
- if (typeof autoPingInstructions !== 'undefined') {
- if (ChatSession.otherUser)
- autoPingName = ChatSession.otherUser.screenName;
- stopAutoPing();
- autoPingIdx = 0;
- var setAutoPinger = function (idx) {
- autoPing = setTimeout(function () {
- if (window.selectData) {
- setAutoPinger(0);
- return;
- }
- // abort autoping if conversation changed
- if (!ChatSession.otherUser || ChatSession.otherUser.screenName != autoPingName)
- return;
- autoPingExec = true;
- $('#Comment').val('/autoping '+autoPingInstructions[idx].stage);
- sendMessage();
- autoPingIdx = idx + 1;
- if (autoPingInstructions.length - 1 >= autoPingIdx) {
- console.log('Setting New Ping', autoPingIdx);
- setAutoPinger(autoPingIdx);
- }
- }, autoPingInstructions[idx].delay*1000);
- }
- setAutoPinger(0);
- }
- }
- function stopAutoPing () {
- console.log('Resetting auto ping');
- if (autoPing)
- clearTimeout(autoPing);
- }
- function sendToBot (instructions, autoPing) {
- var k = instructions.length, j;
- if (instructions.length) {
- window.protectedBotMessages = [];
- for (j = 0; j < k; j++)
- window.protectedBotMessages.push(instructions[j].msgHash);
- if (window.botTimer) {
- clearTimeout( window.botTimer );
- window.botTimer = false;
- }
- var current = instructions.shift();
- (function (current, instructions) {
- window.botTimer = setTimeout(function () {
- var appendMsg = function () {
- $('#offlineMessageDiv').html('');
- var s = parseInt((new Date()).getTime() - serverTimeOffset*1000);
- current.msgTime = moment(s).format("h:mm A");
- // Allow this message to load
- var idx = window.protectedBotMessages.indexOf(current.msgHash);
- window.protectedBotMessages.splice(idx, 1);
- loadMessage(current);
- scrollConversation();
- botMessageCount++;
- if (current.tracking) {
- window.currentBot = current.tracking;
- tracker.emit("botMessage", {
- bot: window.currentBot.bot,
- botVersion: 2,
- sender: 'bot',
- msgCount: botMessageCount,
- mode: window.currentBot.mode,
- stage: window.currentBot.stage
- });
- if (window.currentBot.mode == "introTherapy")
- switch (window.currentBot.stage) {
- case 'account1' : tracker.emit("OnlineTherapy", {step: 'loadmoreinfo',
- reqType: "general_therapy"}); break;
- case 'confirm' : tracker.emit("OnlineTherapy", {step: 'completemoreinfo',
- reqType: "general_therapy"}); break;
- case 'therapistLink' :
- case 'waitForOK' : tracker.emit("OnlineTherapy", {step: 'loadagreement',
- reqType: "general_therapy"}); break;
- default: break;
- }
- }
- if (instructions.length)
- (function (instructions) {
- sendToBot(instructions);
- })(instructions);
- else
- startAutoPing(autoPing);
- };
- if (current.typingTime) {
- if (window.noniButtonsOnly) {
- lockState();
- }
- $('#offlineMessageDiv').html('<div class="" style="margin-bottom:.5em;"><small><em>' + current.screenName
- + ' is typing...</em></small></div>');
- scrollConversation();
- window.botTimer = setTimeout(function () {
- appendMsg();
- }, current.typingTime*1000);
- } else
- appendMsg();
- }, current.delayTime*1000);
- })(current, instructions);
- }
- }
- var noniTimer, waitForSend, stopNoni, currentNoni = {screenName: 'Noni', imgURL: cloudfrontBase + 'img/noniCup.jpg'};
- function talkToNoni() {
- if (!stopNoni) {
- var noniFactor = .65;
- waitForSend = false;
- clearTimeout(noniTimer);
- if (!ChatSession.roomType && ChatSession.user.userType != 'l' && ChatSession.numMsgListener == 0 && (ChatSession.reqType == 'general' || ChatSession.reqType == 'general_therapy' || ChatSession.reqType == 'personal_therapy') && ChatSession.reqStatus == 'request') {
- var lastMsg = -1;
- $('[data-nonimsg]').each(function () {
- lastMsg = parseInt($(this).attr('data-nonimsg')) > parseInt(lastMsg) ? parseInt($(this).attr('data-nonimsg')) : lastMsg;
- });
- if (ChatSession.reqType == 'general' && lastMsg == -1) {
- $('#MessageDiv').append('<div class="alert" style="color:#999;font-size:0.9em"><i class="fa fa-info-circle"></i> You are currently on a waiting list for a listener. Noni is a bot who will chat with you until your listener arrives. Anything you say here will be viewable to the listener you connect to.</div>');
- scrollConversation();
- }
- $.post('/connect/talkToNoni.php', {convID: ChatSession.convID, lastNoniMsg: lastMsg}, function (json) {
- console.log('##standard noni delay', 6000 * noniFactor);
- if (json && json.message) {
- if (lastMsg == -1) {
- tracker.emit("noniMessage", {msg: lastMsg + 1});
- }
- currentNoni.screenName = json.message.screenName;
- currentNoni.imgURL = json.message.imgURL;
- currentNoni.imageClass = json.message.imageClass;
- $('#offlineMessageDiv').html('<div class="" style="margin-bottom:.5em;"><small><em>' + json.message.screenName + ' is typing...</em></small></div>');
- scrollConversation();
- console.log('####noni typing', 6000 * noniFactor);
- setTimeout(function () {
- $('#offlineMessageDiv').html('');
- var s = parseInt((new Date()).getTime() - serverTimeOffset*1000);
- json.message.msgTime = moment(s).format("h:mm A");
- loadMessage(json.message);
- scrollConversation();
- tracker.emit("botMessage", {bot: currentNoni.screenName, msg: lastMsg+1, msgid: json.tag ? json.tag : null});
- if (json.delay && json.delay > 0) {
- console.log('######noni delaying to talk', json.delay * 1000 * noniFactor);
- noniTimer = setTimeout(talkToNoni, json.delay * 1000 * noniFactor);
- } else {
- waitForSend = true;
- }
- }, 6000 * noniFactor);
- } else if (json.delay && json.delay < 0) {
- waitForSend = true;
- }
- }, 'json');
- }
- }
- }
- function hideAlert(alertID) {
- $('#' + alertID).hide();
- setLocal("hide" + alertID, true);
- }
- function setLocal(key, value) {
- if (typeof (Storage) !== "undefined") {
- try {
- var res = localStorage.setItem(key, value);
- } catch (e) {
- console.log('Local storage reported available but not writable.');
- }
- }
- }
- function getLocal(key) {
- if (typeof (Storage) !== "undefined") {
- try {
- return localStorage.getItem(key);
- } catch (e) {
- console.log('Local storage reported available but not readable.');
- }
- return null;
- }
- }
- function surveyPop(token) {
- var viewportwidth = screen.width;
- var viewportheight = screen.height;
- var popWidth = Math.floor(viewportwidth * 0.75);
- var popHeight = Math.floor(viewportheight * 0.75);
- var popLeft = viewportwidth - popWidth;
- var notePop = window.open('/survey/201502.php?t=' + token,
- "Survey",
- "width=" + popWidth + ",height=" + popHeight + ",left=" + popLeft + ",top=0,location=0,toolbar=0,directories=0,status=0,menubar=0,scrollbars=1,resizable=1");
- ga('send', 'event', {
- 'eventCategory': 'Survey',
- 'eventAction': 'AgreeToTake'
- });
- }
- function endLiveChat(receive) {//Call this function to request an end of chat or when receiving an end of chat
- tracker.emit("EndLiveChat");
- if (!ChatSession.roomType && ChatSession.allowEndPop && (ChatSession.user.userType != 'l' || ChatSession.otherUser.userType != 'l')) {//Only allow in 1-on-1 with member/guest
- ChatSession.allowEndPop = false;
- if (typeof (receive) === 'undefined' || !receive) {
- ListMessagesSocket.emit('sendConvAction', {room: ChatSession.nodeRoom, action: 'endLiveChat', me: ChatSession.me});
- }
- if (ChatSession.user.userType == 'l') {
- $('<div class="modal"><div class="modal-dialog"><div class="modal-content"><div class="modal-body"><div class="text-center ">' +
- '<h2>This live chat session has ended.</h2>' +
- '<h4>Thank you so much for all your good work on 7 Cups of Tea!</h4>' +
- '<button type="button" class="btn btn-simple btn-primary" data-dismiss="modal" aria-label="Close">Close</button>' +
- '</div></div></div></div></div>').modal().on('hidden.bs.modal', function () {
- $(this).data('bs.modal', null);
- wrapUp();
- });
- } else if (ChatSession.ratingPopped && window.ratingModal) {
- window.ratingModal.modal('show').on('hidden.bs.modal', function () {
- wrapUp();
- });
- } else {
- bootbox.alert('<h2 class="text-center">Live Chat Session Complete<small><br />We hope you had a great conversation & are feeling better.</small></h2>', function () {
- wrapUp();
- });
- }
- }
- function wrapUp() {
- if (isMobileApp()) {
- requestRedirect = true;
- window.location.href = '/conversations.php';
- } else {
- if (ChatSession.nodeRoom) {
- ListMessagesSocket.emit('leave', [ChatSession.nodeRoom]);
- }
- ChatSession.nodeRoom = null;
- ChatSession.convID = null;
- $('#chatForm').hide();
- $('#MessageDiv').html('');
- $('#selectConvPrompt').show();
- if (ChatSession.goodExperience) {
- $('<div class="modal"><div class="modal-dialog"><div class="modal-content"><div class="modal-body"><div class="text-center ">' +
- '<h1>Awesome!</h1>' +
- '<h3>We are glad to hear that you had a positive experience with your Listener.</h3>' +
- '<h3>Learn more about yourself by reviewing your Personalized Growth Path.</h3>' +
- '<div class="text-center">' +
- '<div><a href="https://www.7cups.com/member/" class="btn btn-success">Visit My Growth Path</a></div>' +
- '<div style="margin-top:1em"><a href="/member/" class="btn btn-link">no thanks</a></div>' +
- '</div>' +
- '</div></div></div></div></div>').modal();
- } else if (ChatSession.goodExperience === false) {
- $('<div class="modal"><div class="modal-dialog"><div class="modal-content"><div class="modal-body"><div class="text-center ">' +
- '<h2>We’re sorry that this conversation wasn’t very helpful.</h2>' +
- '<h3>Many people try several listeners before finding one that clicks.</h3>' +
- '<div class="text-center">' +
- '<div><button type="button" class="btn btn-success" onclick="$(this).parents(\'div.modal\').modal(\'hide\');connectNowLoad(\'#connectNowAgree\');">Connect to a New Listener</button></div>' +
- '<div style="margin-top:1em"><a href="/BrowseListeners/" class="btn btn-simple btn-primary">Browse Listeners by Issue & Language</a></div>' +
- '<div style="margin-top:1em"><button type="button" onclick="$(this).parents(\'div.modal\').modal(\'hide\');connectNowLoad(\'#connectNowNotReady\');" class="btn btn-link">I’m not ready to reconnect</button></div>' +
- '</div>' +
- '</div></div></div></div></div>').modal();
- }
- }
- }
- }
- function muteUser(userTypeID) {
- $('#multiModal').modal('hide');
- var muteArr = $.cookie('muteArr') ? $.cookie('muteArr') : '[]';
- muteArr = JSON.parse(muteArr);
- if ($.inArray(userTypeID, muteArr) === -1) {
- muteArr.push(userTypeID);
- muteArr = JSON.stringify(muteArr);
- $.cookie("muteArr", muteArr, {path: '/'});
- }
- $('.convRow[data-usertypeid="' + userTypeID + '"]').remove();
- showUnmuteButton();
- }
- function globalMuteUsers(userTypeID) {
- if ($.inArray(userTypeID, globalMuteArr) === -1) {
- globalMuteArr.push(userTypeID);
- }
- if (ChatSession.user.userTypeID != userTypeID) {
- $('.convRow[data-usertypeid="' + userTypeID + '"]').remove();
- }
- }
- function heartMsg(msgHash) {
- $('#message_' + msgHash + ' .heartCommentButton').removeClass('compassionHeartFade').addClass('compassionHeart').attr('onclick', '');
- ListMessagesSocket.emit('sendConvAction', {room: ChatSession.nodeRoom, action: 'heartMsg', msgHash: msgHash, me: ChatSession.me});
- $.post('/connect/heartMessage.php', {convID: ChatSession.convID, msgHash: msgHash}, function (json) {
- if (json.error) {
- //alert(json.error);
- } else {
- tracker.emit('chatHeart', {
- convID: ChatSession.convID,
- chatroomName: ChatSession.otherUser.screenName || null,
- roomType: ChatSession.roomType || null
- });
- }
- }, 'json');
- }
- function sendTyping(val) {
- if (val) {
- ChatSession.sendingTyping = true;
- ListMessagesSocket.emit('sendConvAction', {room: ChatSession.nodeRoom, action: 'typingStatus', isTyping: true, screenName: ChatSession.user.screenName, userType: ChatSession.user.userType, userTypeID: ChatSession.user.userTypeID, ua: ChatSession.user.ua, me: ChatSession.me});
- } else {
- ChatSession.sendingTyping = false;
- ListMessagesSocket.emit('sendConvAction', {room: ChatSession.nodeRoom, action: 'typingStatus', isTyping: false, me: ChatSession.me});
- }
- }
- function blockLink() {
- if(ChatSession.convID && ChatSession.otherUser){
- ChatSession.otherUser.is = {};
- ChatSession.otherUser.is.userType = {};
- ChatSession.otherUser.is.userType[ChatSession.otherUser.userType] = true;
- render(false, 'Chat_BlockConnection', ChatSession, function ($html) {
- bootbox.dialog({
- title: ChatSession.otherUser.is.userType.l ? 'Block/Report Listener' : 'Block/Report User',
- message: $html
- });
- $html.find('select[name=blockCategoryInput]').on('change',function(){
- $html.find('textarea[name=blockReasonInput]').toggle($(this).val() != 'none');
- });
- });
- }
- }
- function clearConversation() {
- if (confirm('We only save the last 10 messages for your privacy and to make it easier to follow the conversation. Are you sure you want to clear all messages in this conversation?')) {
- $('#msgs-loading').show();
- scrollConversation();
- delete window.chatInfoMemory[userInfo.userIDe + ChatSession.convID].messages;
- $.post('/connect/clearConversation.php', {c: ChatSession.convID}, function (json) {
- if (json.ack == 'success') {
- $('#MessageDiv').html('');
- } else if (json.ack == 'error') {
- alert(json.error);
- }
- }, 'json').always(function () {
- $('#msgs-loading').hide();
- });
- $('#actionsModal').modal('hide');
- }
- }
- function chatRoomRules() {
- if (ChatSession.chatroomRules) {
- var title = (ChatSession.roomType == 'l') ? 'Listener Chat Rules' : 'Group Chat Rules';
- var message = '<ol>';
- for (var i = 0; i < ChatSession.chatroomRules.length; i++) {
- message += '<li>' + ChatSession.chatroomRules[i][0] + '</li>';
- }
- message += '</ol>';
- bootbox.dialog({
- message: message,
- title: title
- });
- }
- }
- function resetChatBox () { if (window.botDatum) $(this).val(window.botDatum) }
- function loadMessage(message, skip) {
- var exisingCheck = $("#message_" + message.msgHash);
- if (message.msgHash && exisingCheck.length === 0 && typeof message.msgBody !== 'undefined' && message.msgBody.length > 0 && ChatSession.convID == message.convID && window.protectedBotMessages.indexOf(message.msgHash) == -1) {
- // My messages have no timestamp
- if (!message.msgTS) {
- var t = (new Date()).getTime()/1000 - serverTimeOffset;
- console.log('Setting msgTS', t, 'With Offset:', serverTimeOffset);
- message.msgTS = t;
- }
- message.isMod = (message.badges && message.badges.indexOf('Mod') !== -1);
- // Stringify and then reparse message objec to break theobject pointer
- message = JSON.stringify(message);
- message = JSON.parse(message);
- // Do not resave messages that already exist in the chat history
- if (!ChatSession.roomType && !skip) {
- var chatMsgs = [];
- var idx = userInfo.userIDe + message.convID;
- window.chatInfoMemory[idx] = window.chatInfoMemory[idx] || {};
- window.chatInfoMemory[idx].messages = window.chatInfoMemory[idx].messages || [];
- window.chatInfoMemory[idx].messages.push(message);
- window.chatInfoMemory[idx].messages = window.chatInfoMemory[idx].messages.slice(-40);
- }
- message.msgBody = ['n','b'].indexOf(message.userType) == -1 ? encodeMsg(message.msgBody) : swapEmoticons(message.msgBody);
- if (ChatSession.roomType ||
- !(
- (ChatSession.otherUser.listType == "therapist" || ChatSession.user.listType == "therapist")
- )) {
- message.msgBody = censorMsgAssist(message.msgBody) ? null : message.msgBody;
- message.msgBody = (censorMsgPhrases(message.msgBody) || (ChatSession.user.userType == 'l' && ChatSession.otherUser.userType &&
- ChatSession.otherUser.userType == 'l' && censorMsgLLpm(message.msgBody))) ? null : message.msgBody;
- }
- message.msgBody = ChatSession.roomType ? censorMsgWords(message.msgBody) : message.msgBody;
- if (message.msgBody) {
- message.screenName = !message.screenName ? '' : message.screenName;
- message.msgHash = strip_tags(message.msgHash);
- message.imgURL = message.imgURL === null ? null : strip_tags(message.imgURL);
- message.imageClass = message.imageClass || '';
- message.userColor = strip_tags(message.userColor);
- message.msgTime = strip_tags(message.msgTime);
- message.convSide = message.convSide || ((ChatSession.user.userTypeID == message.userTypeID) ? 'mine' : 'other');
- if (ChatSession.otherUser && ChatSession.otherUser.userType == 'b') {
- // Update chat bar
- if (!skip) {
- var simple = strip_tags(message.msgBody);
- var newHTML = message.msgTime + ' ' + (simple.length > 50 ? simple.substr(0,47) + '...': simple);
- $('#convListItem_'+message.convID+' .userInfo small').html(newHTML);
- $('#botInformation').html(newHTML);
- }
- console.log('[APPEND]', message.msgID, window.activeButton, window.stateLocked);
- if (window.stateLocked && window.activeButton < parseInt(message.msgID))
- resetState();
- }
- ChatSession.allowEndPop = true;
- var muteArr = $.cookie('muteArr') ? $.cookie('muteArr') : '[]';
- muteArr = JSON.parse(muteArr);
- muteArr = $.merge(muteArr, globalMuteArr);
- if (!ChatSession.roomType || $.inArray(message['userTypeID'], muteArr) === -1 || ChatSession.user.userTypeID == message['userTypeID']) {
- var newRow = '<div class="convRow side-' + message['convSide'] + (message['userType'] == 'n' ? ' nonimsg' : '') + '" id="message_' + message['msgHash'] + '" data-msgid="' + message['msgID'] + '" data-msgts="'+ message['msgTS'] +'" data-usertypeid="' + message['userTypeID'] + '">';
- var screenName = '';
- if (message['userType'] == 'l') {
- screenName = '<a href="/@' + message['screenName'] + '" data-usercard="' + message['screenName'] + '"><span class="userScreenName">' + message['screenName'] + '</span></a>';
- } else if (message['userType'] == 'm') {
- screenName = '<a href="/@' + message['screenName'] + '/" data-usercard="' + message['screenName'] + '"><span class="userScreenName">' + message['screenName'] + '</span></a>';
- } else if (message['userType'] == 'n') {
- screenName += '<span class="userScreenName">' + message['screenName'] + '</span>';
- } else {
- screenName += '<span class="userScreenName">' + message['screenName'] + '</span>';
- }
- var img = '<div class="img-profile ' + message['imageClass'] + '" style="background-image:url(' + message['imgURL'] + ')"></div>';
- if (message['userType'] == 'l' || message['userType'] == 'm') {
- img = '<a href="/@' + message['screenName'] + '">' + img + '</a>';
- }
- var testTime = message['msgTime'].split(' ');
- if (testTime.length > 2 || skip) {
- testTime = true;
- } else {
- testTime = false;
- }
- var heart = '';
- if (message['convSide'] == 'other' && message['userType'] != 'n' && message['userType'] != 'b') {
- heart = ' <span style="cursor:pointer" class="heartCommentButton compassionHeartFade" onclick="heartMsg(\'' + message['msgHash'] + '\');"><i class="fa fa-heart"></i><span class="pointHolder"></span></span>';
- } else if (message['convSide'] == 'mine') {
- heart = ' <span class="heartCommentButton compassionHeart" style="display:none"><i class="fa fa-heart"></i><span class="pointHolder"></span></span>';
- }
- var modLink = ChatSession.user.isMod && message['userType'] != 'n' && message['userType'] != 'b' && !message.isMod ? '<i class="fa fa-times-circle pull-right modLink" onclick="modRemove(\'' + message['msgHash'] + '\');" data-toggle="tooltip" data-trigger="hover" title="Remove message as a moderator."></i>' : '';
- var refer = '';
- var mute = '';
- var warn = '';
- if (ChatSession.roomType && message['convSide'] == 'other' && message['userType'] != 'n' && message['userType'] != 'b' && !message.isMod) {
- if (ChatSession.user.isMod) {
- warn = '<span class="warn" onclick="modWarnPop(\'' + message['userTypeID'] + '\',\'' + message['screenName'] + '\');" data-toggle="tooltip" data-trigger="hover" title="Warn this user as a Moderator"><i class="fa fa-exclamation-triangle"></i> Mod</span>';
- }
- if (message['userType'] != 'l') {
- refer = '<span class="refer" onclick="referUserPopup(\'' + message['userTypeID'] + '\',\'' + message['screenName'] + '\');" data-toggle="tooltip" data-trigger="hover" title="Anonymously refer ' + message['screenName'] + ' to suicide hotline and chat resources."><i class="fa fa-reply"></i> Refer</span>';
- }
- mute = '<span class="mute" onclick="muteUserPopup(\'' + message['userTypeID'] + '\',\'' + message['screenName'] + '\');" data-toggle="tooltip" data-trigger="hover" title="Hide messages from ' + message['screenName'] + '."><i class="fa fa-hand-paper-o"></i> Mute/Report</span>';
- }
- var badges = '';
- var uType = '';
- if (message['userType'] == 'm') {
- uType = ' (M) ';
- } else if (message['userType'] == 'l') {
- if (message.listType && message.listType == 'therapist') {
- uType = ' (T) ';
- } else {
- uType = ' (L) ';
- }
- }
- if (ChatSession.roomType) {
- badges += ' <span class="badgeHolder">';
- if (message.badges) {
- badges += message.badges;
- }
- badges += '</span>';
- }
- var icons = '<span class="chatIconHolder">';
- if (message.shareIcons && message.shareIcons.sustainability) {
- icons += message.shareIcons.sustainability.display;
- }
- icons += '</span>';
- var fadeIn = false;
- if (message['convSide'] == 'mine') {
- var detailString = false;
- if (message['userType'] == 'g')
- detailString = screenName;
- if (!ChatSession.roomType || testTime)
- detailString = (detailString ? detailString + ' ' : '') + '<span class="msgTime">' + message['msgTime'] + '</span>';
- else
- detailString = (detailString ? detailString + ' ' : '') + '<span class="msgTime" style="display:none" data-msgTime="' + (new Date()).getTime() + '">' + message['msgTime'] + '</span>';
- if (ChatSession.user.crisisMessage) {
- message['msgBody'] = ChatSession.user.crisisMessage;
- ChatSession.user.crisisMessage = null;
- }
- newRow +=
- '<div class="meArea clearfix">' + heart +
- ' <div class="meWrap">' + message['msgBody'].replace(/\n/g, '<br/>') + '</div>' +
- (detailString ? ' <div class="details">' + detailString + '</div>' : '') +
- '</div>';
- } else {
- if (message['userType'] == 'b' && message['msgBody'].indexOf("<button") != -1) {
- newRow += '<div class="youArea clearfix buttonArea" style="text-align:center;">'+
- message['msgBody']+
- '</div>';
- fadeIn = true;
- } else {
- var imageWrap = (message['userType'] == 'b' && message['msgBody'].indexOf("<img ") === 0 && message.msgBody.match(/\<img/g).length == 1);
- newRow += '<div class="youArea clearfix">' + '<div class="youImg">' + img + '</div>' +
- ' <div class="youWrap' + (imageWrap ? ' imageWrap' : '') + '">' +
- modLink + message['msgBody'].replace(/\n/g, '<br/>') + '</div>' + heart +
- ' <div class="details">' +
- (ChatSession.roomType || message['userType'] == 'n' || message['userType'] == 'b' ? screenName + ' ' : '') +
- (ChatSession.roomType && uType != '' ? uType : '') +
- (ChatSession.roomType && message.zodiac && message.zodiac.html ? message.zodiac.html : '') +
- (!ChatSession.roomType || testTime ? ' ' + message['msgTime'] + ' ' : '<span style="display:none" data-msgTime="' + (new Date()).getTime() + '">' + message['msgTime'] + '</span> ') +
- badges + warn + refer + mute + icons + '</div>' +
- '</div>';
- }
- }
- newRow += '</div>';
- // When mass loading see where it goes
- newRow = $(newRow);
- // Lets look for functional buttons in the chat logs
- if (message['userType'] == 'b' && !message['func']) {
- //console.log('CHECKING', newRow.find('button'));
- var func = newRow.find('button').data('func');
- if (func)
- message.func = func;
- else {
- var func = newRow.find('i').data('func');
- if (func)
- message.func = func;
- }
- }
- if (fadeIn)
- newRow.find('.buttonArea').hide();
- // Whenever user inputs, lets remove wait buttons (theyll reappear if needed)
- if (!skip && message['userType'] != 'b' && window.activeButtonHash) {
- removeMessage(window.activeButtonHash);
- window.activeButtonHash = false;
- window.activeButton = false;
- }
- var e = findLater(message['msgTS']);
- if (e)
- newRow.insertBefore(e);
- else
- $('#MessageDiv').append(newRow);
- if (fadeIn)
- newRow.find('.buttonArea').fadeIn(400, 'swing');
- var noSound = false;
- // Run these each time for bot messages
- if (message['userType'] == 'b' && message['func']) {
- console.log('Switching2', message['func']);
- switch (message['func']) {
- case 'waitForChoice' :
- case 'waitForButton' :
- noSound = true;
- handleBotButton(message, newRow);
- break;
- case 'creditcard' :
- noSound = true;
- handleBotCreditCard2(message, newRow);
- break;
- case 'popModal' : $("#"+message['funcProp']).modal(); break;
- case 'personalDetails' :
- noSound = true;
- personalDetails(message, newRow);
- break;
- case 'datePicker' :
- window.stateLocked = true;
- $('#Comment').datepicker("destroy");
- $('#Comment').val("");
- $('#Comment').datepicker({startDate: new Date(), orientation:"top", immediateUpdates: true}).on("changeDate", function (d) { window.botDatum = d.date.toString().split(' ').slice(0,4).join(' '); $('#Comment').val(window.botDatum); });
- $('#Comment').focus();
- $('#Comment').on('keyup', resetChatBox);
- window.stateLocked = true;
- window.activeButton = parseInt(message.msgID);
- window.stateLocked = true;
- break;
- default: break;
- }
- }
- if (typeof (soundManager) != 'undefined' && !ChatSession.initialLoad && message['convSide'] == 'other') {
- if (soundOn && !noSound) {
- soundManager.play('newMessage');
- }
- $.titleAlert("*** NEW Message ***", {
- requireBlur: true,
- stopOnFocus: true,
- duration: 30000,
- interval: 500
- });
- }
- if (!skip && typeof message.fill !== "undefined")
- $('#Comment').val(message.fill);
- var messageE = $('#message_'+message['msgHash']);
- if (message.funcEmbed) {
- var lastRow = messageE;
- var button = lastRow.find('button')
- button.data('payload', JSON.stringify(message));
- }
- if (skip && messageE.find('button').data('norerender'))
- messageE.remove();
- else if (!skip && message['func']) {
- console.log('Switching', message['func']);
- switch (message['func']) {
- case 'clearButtons' :
- $('#MessageDiv button[data-func]').each(function() {
- var parent = $(this).closest('div.convRow');
- var id = $(parent).attr('id');
- removeMessage(id.split('_')[1]);
- });
- break;
- case 'launchConnect' : startConnection(); break;
- case 'emptyPing' :
- window.botPing = setTimeout(function () {
- if (ChatSession.otherUser && ChatSession.otherUser.userType == 'b') {
- window.allowEmpty = true;
- $('#Comment').val('');
- sendMessage();
- }
- }, message['funcArg'] * 1000);
- break;
- case 'updateCSRF' : $('#chatForm input[name="csrf"]').val(message['funcProp']); break;
- case 'checkRequests' : checkRequest(); break;
- case 'popModal' : $("#"+message['funcProp']).modal(); break;
- case 'setupSelect' : setupSelect(message['funcProp']); break;
- case 'showElement' : console.log('SHOWING', message['funcProp']); $(message['funcProp']).show().removeClass('hidden'); break;
- case 'hideElement' : console.log('HIDING', message['funcProp']); $(message['funcProp']).hide(); break;
- case 'memberLogin' : loginModal({
- params: {
- t: 'm',
- intent: 'botLogin',
- bot: ChatSession.convID
- },
- location: (message['funcProp'] ? message['funcProp'] : '/member/connect/conversation.php?c='+ChatSession.convID)
- });
- break;
- case 'gotoURL' : setTimeout(function () { window.location = message['funcArg'] }, 500); break;
- case 'gotoListenerSignup' : setTimeout(function () { window.location = '/listener/become-a-volunteer-listener.php'}, 500); break;
- case 'gotoGrowthPath' : setTimeout(function () { window.location = '/member/'}, 500); break;
- case 'gotoCommunities' : setTimeout(function () { window.location = '/home/'}, 500); break;
- case 'gotoChatrooms' : setTimeout(function () { window.location = '/connect/groupChatrooms.php'}, 500); break;
- case 'gotoListener' : setTimeout(function () { window.location = '/connect/'}, 500); break;
- case 'wellnessTestModal' : wellnessTestModal(); break;
- case 'gotoTherapy' : window.loadTherapyWaiting(); break;
- case 'trackTherapyLead' :
- console.log('Logging FB Lead');
- fbq('track', 'Lead');
- break;
- case 'simClick' :
- // Get Newly appened record:
- var lastRow = $('#message_'+message['msgHash']);
- console.log('Clicking ', '#message_'+message['msgHash'], lastRow);
- autoMessageFunction = setTimeout(function () {
- lastRow.find('button').click();
- console.log('Doing Click', lastRow.find('button'));
- }, message['funcDelay']);
- break;
- case 'autoClick' :
- // Get Newly appened record:
- var lastRow = $('#message_'+message['msgHash']);
- var button = lastRow.find('button')
- console.log('Clicking ', '#message_'+message['msgHash'], button);
- autoMessageFunction = setTimeout(function () {
- button.click();
- console.log('Doing Click', lastRow.find('button'));
- }, message['funcDelay']);
- break;
- case 'disableChat' :
- lockState(true);
- break;
- }
- }
- if (!ChatSession.roomType) {
- if (ChatSession.lastMessage != -1 && ChatSession.relaySide == 'other' && message['convSide'] == 'mine') {
- ga('send', 'event', {'eventCategory': 'Conversation', 'eventAction': 'OneRelay'});
- //tracker.emit("OneRelay");
- }
- ChatSession.relaySide = message['convSide'];
- }
- if (ChatSession.lastMessage != -1 && message['userType'] != 'n' && message['userType'] != 'b') {
- ChatSession.numConvMessages++;
- listTips(ChatSession.numConvMessages);
- if (isMobileApp()) {
- if (typeof (shareContacts) === 'function') {
- shareContacts('Help Your Friends', ' Look around you. Many of your friends may need someone to talk to. Choose friends who you would like to help...', 'No Thanks', 'Yes', 0);
- }
- if (userType == 'l' && typeof (allowPush) === 'function') {
- allowPush('Allow Push Notifications', 'Would you like to be notified when your users respond?', 'No Thanks', 'Notify Me', false);
- }
- }
- }
- if (!ChatSession.initialLoad && ChatSession.roomType)
- chatroomParticipants([message], false);
- }
- if (!ChatSession.initialLoad && ChatSession.roomType)
- chatroomParticipants([message], false);
- }
- }
- return message.msgBody;
- }
- var lastMessageTS = 0;
- function findLater(msgTS) {
- msgTS = parseInt(msgTS);
- if (msgTS >= lastMessageTS) {
- lastMessageTS = msgTS;
- return false;
- }
- var rows = $('#MessageDiv .convRow'), l = rows.length;
- var minIndex = 0, maxIndex = l-1, currentIndex=0, cmpTime = 0;
- if (l > 1) {
- // Binary Search
- while (minIndex <= maxIndex) {
- currentIndex = (minIndex + maxIndex) / 2 | 0;
- cmpTime = parseInt(rows[currentIndex].getAttribute('data-msgts'));
- if (cmpTime < msgTS)
- minIndex = currentIndex+1;
- else if (cmpTime > msgTS)
- maxIndex = currentIndex-1;
- else {
- currentIndex++;
- break;
- }
- }
- if (currentIndex < l-1 && msgTS > cmpTime)
- currentIndex++;
- if (currentIndex < l)
- return rows[currentIndex];
- }
- lastMessageTS = msgTS;
- return false;
- }
- window.botPing = false;
- window.allowEmpty = false;
- function sendMessage(massage='Default') {
- var commentPost = $('#Comment').val();
- if(massage!='Default'){
- commentPost = massage;
- }
- if(commentPost==lastMsgSent){
- return;
- }
- lastMsgSent = commentPost;
- var csrf = $('#chatForm input[name="csrf"]').length ? $('#chatForm input[name="csrf"]').val() : null;
- ChatSession.scrollDelay = 0;
- if (sendTypingStatus) {
- sendTyping(0);
- }
- if (ChatSession.otherUser && ChatSession.otherUser.userType == 'b') {
- if (window.selectData) {
- var hint = $('.tt-hint').val();
- if (hint && typeof hint === "string" && hint.length > 0) {
- commentPost = hint;
- $('#Comment').val(commentPost);
- } else {
- var found = false, re = new RegExp('^'+commentPost.trim()+'$', "i");
- for (var i = 0; i < window.selectData.length; i++)
- if (re.test(window.selectData[i])) {
- found = true;
- break;
- }
- if (!found) return;
- }
- }
- // Update chat bar
- if (window.selectData || window.stateLocked)
- resetState();
- else if (window.botGUIObj)
- window.botGUIObj.closeMenu();
- }
- if (commentPost != '' || window.allowEmpty) {
- window.allowEmpty = false;
- if (ChatSession.user.sendDisabled) {
- switch (ChatSession.user.sendDisabled) {
- case 'memberacct':
- bootbox.confirm({
- message: '<h3 class="text-center">In order to participate in this Chat, a Member Account is required. Would you like to create one now?</h3>',
- buttons: {
- confirm: {
- label: 'Yes, Please',
- className: 'btn-success'
- },
- cancel: {
- label: 'no thanks',
- className: 'btn-link text-muted'
- }
- },
- callback: function (result) {
- if(result){
- MemberAccountModal();
- }
- }
- });
- return false;
- break;
- }
- }
- var sendThisMessage = true;
- if (censorMsgAssist(commentPost) && ChatSession.user.listType != 'therapist' && ChatSession.otherUser.listType != "therapist") {
- if (!(ChatSession.otherUser.userType == 'b')) {
- $('#MessageDiv').append('<div class="alert alert-info pull-left">Something in your message suggests that you might best be helped by another service. If you are in a potentially dangerous situation, please call 911 or the Suicide Prevention Helpline at 1-800-273-8255. If I made a mistake, please rephrase your message to continue our conversation.</div>');
- scrollConversation();
- sendThisMessage = false;
- } else {
- //if censor assist message detected and talking to bot, send the code for crisis mode. store the actual message for later use/display
- ChatSession.user.crisisMessage = commentPost;
- commentPost = "/crisisAssist";
- }
- ga('send', 'event', {
- 'eventCategory': 'Conversation',
- 'eventAction': 'CensoredMsgAssist',
- 'eventLabel': ChatSession.user.userType
- });
- } else if (censorMsgPhrases(commentPost) || (ChatSession.user.userType == 'l' && ChatSession.otherUser.userType && ChatSession.otherUser.userType == 'l' && censorMsgLLpm(commentPost))) {
- ChatSession.otherUser.userType = ChatSession.roomType ? ChatSession.roomType : ChatSession.otherUser.userType;
- if (ChatSession.user.listType != 'therapist' && ChatSession.otherUser.listType != "therapist") {
- $('#MessageDiv').append('<div class="alert alert-info pull-left">Something in your message appears to violate our terms of service (such as sharing personal contact information or social media accounts, or containing inappropriate content). 7 Cups depends upon you keeping your identity secure and private to protect everyone involved. Please also take care to show kindness and respect in every interaction here on 7 Cups.</div>');
- scrollConversation();
- ga('send', 'event', {
- 'eventCategory': 'Conversation',
- 'eventAction': 'CensoredMsg',
- 'eventLabel': ChatSession.user.userType
- });
- sendThisMessage = false
- }
- if (ChatSession.user.userType != 'g' && !(ChatSession.user.userType == 'l' && ChatSession.otherUser.userType == 'l') && ChatSession.otherUser.userType != 'b') {
- $.post('/connect/reportCensoredMsg.php', {msgBody: '[' + ChatSession.user.userType + '->' + ChatSession.otherUser.userType + '] ' + commentPost });
- }
- }
- if (sendThisMessage) {
- if (ChatSession.roomType) {
- switch (ChatSession.roomType) {
- case 'l':
- var roomDesc = 'Listener Chatroom';
- break;
- case 'lm':
- var roomDesc = 'Member Chatroom';
- break;
- case 'lmg':
- var roomDesc = 'Guest Chatroom';
- break;
- default:
- var roomDesc = 'Unknown Chatroom';
- }
- } else {
- var roomDesc = 'Private Message';
- }
- $('#Comment').val('');
- if ($(window).width() <= 767) {
- //$('#Comment').blur();
- }
- var msgHash = randomHash();
- var s = parseInt((new Date()).getTime() - serverTimeOffset*1000);
- var sendmessage = {msgID: null,
- msgHash: msgHash,
- msgBody: commentPost,
- msgTime: moment(s).format("h:mm A"),
- userTypeID: ChatSession.user.userTypeID,
- screenName: ChatSession.user.screenName,
- userType: ChatSession.user.userType,
- listType: ChatSession.user.listType,
- imgURL: ChatSession.user.imgURL,
- imageClass: ChatSession.user.imageClass,
- convSide: "mine",
- userColor: ChatSession.user.userColor,
- convID: ChatSession.convID,
- ua: ChatSession.user.ua,
- badges: ChatSession.user.badges,
- badgesE: ChatSession.user.badgesE,
- shareIcons: ChatSession.user.shareIcons
- };
- if ($.inArray(ChatSession.user.userTypeID, globalMuteArr) === -1) {
- ChatSession.user.currentMessages++;
- if (ChatSession.user.currentMessages >= 3 && ChatSession.convID != "Sophia")
- $('.returnGP').fadeIn(3000);
- else
- $('.returnGP').hide();
- if (!ChatSession.roomType) {
- var prefix = '';
- if (ChatSession.user.userType == 'l')
- prefix = 'listener';
- if (!('privateMessagesSent' in ChatSession)) {
- if (ChatSession.user.userType == 'l' && ChatSession.otherUser.userType == 'l')
- ChatSession.privateMessagesSent = Math.floor(parseInt(ChatSession.numMsgListener) / 2);
- else if (ChatSession.user.userType == 'l')
- ChatSession.privateMessagesSent = parseInt(ChatSession.numMsgListener);
- else
- ChatSession.privateMessagesSent = parseInt(ChatSession.numConvMessages) - parseInt(ChatSession.numMsgListener);
- }
- if (ChatSession.user.messagesSent) {
- ChatSession.user.messagesSent++;
- }
- if (!('privateMessagesSent' in ChatSession)) {
- ChatSession.privateMessagesSent = 0;
- }
- ChatSession.privateMessagesSent++;
- if (ChatSession.otherUser && ChatSession.otherUser.userType == 'b') {
- botMessageCount++;
- var data = {
- bot: window.currentBot.bot,
- botVersion: 2,
- sender: 'user',
- msgCount: botMessageCount,
- mode: window.currentBot.mode,
- stage: window.currentBot.stage
- };
- if (window.currentBot.replyToMode)
- data.replyToMode = window.currentBot.replyToMode;
- if (window.currentBot.replyToStage)
- data.replyToStage = window.currentBot.replyToStage;
- tracker.emit("botMessage", data);
- } else
- tracker.emit("privateMessage", {msgCount: ChatSession.privateMessagesSent});
- } else {
- if (!('groupMessagesSent' in ChatSession)) {
- ChatSession.groupMessagesSent = 0;
- }
- ChatSession.groupMessagesSent++;
- tracker.emit("groupMessage", {msgCount: ChatSession.groupMessagesSent, room: ChatSession.otherUser.screenName});
- }
- }
- if (autoPingExec) {
- autoPingExec = false;
- } else {
- loadMessage(sendmessage);
- scrollConversation();
- stopAutoPing();
- }
- if ($.inArray(ChatSession.user.userTypeID, globalMuteArr) === -1 || !ChatSession.roomType || ChatSession.roomType == 'l') {
- if (ChatSession.nodeRoom && !(ChatSession.otherUser.userType && ChatSession.otherUser.userType == 'b')) {
- sendmessage.convSide = "other";
- ListMessagesSocket.emit('sendConvAction', {room: ChatSession.nodeRoom, action: 'newMessage', message: sendmessage, me: ChatSession.me});
- }
- if (commentPost.trim().toLowerCase() == 'stop') {
- //console.log('Stop Noni');
- stopNoni = true;
- ga('send', 'event', {'eventCategory': 'Conversation', 'eventAction': 'StopNoni'});
- } else if (waitForSend && !stopNoni) {
- waitForSend = false;
- var delayToTyping = 750;
- var delayToOutput = 1250;
- var noniFactor = .65;
- //if (parseInt($.cookie('ab_fastSophia6')) == 1)
- // noniFactor = .6;
- setTimeout(function () {
- $('#offlineMessageDiv').html('<div class="" style="margin-bottom:.5em"><small><em>' + currentNoni.screenName + ' is typing...</em></small></div>');
- scrollConversation();
- var replyopt = ['Got it', 'I see', 'Thank you', 'Alright', 'OK'];
- replyopt = replyopt[Math.floor(Math.random() * replyopt.length)];
- setTimeout(function () {
- $('#offlineMessageDiv').html('');
- var s = parseInt((new Date()).getTime() - serverTimeOffset*1000);
- loadMessage({msgID: null,
- msgHash: randomHash(),
- msgBody: replyopt,
- msgTime: moment(s).format("h:mm A"),
- userTypeID: '0GKvccLHkpyGnA!!',
- screenName: currentNoni.screenName,
- userType: 'n',
- imgURL: currentNoni.imgURL,
- imgClass: currentNoni.imageClass,
- convSide: "other",
- convID: sendmessage.convID});
- scrollConversation();
- noniTimer = setTimeout(talkToNoni, 4000*noniFactor);
- }, delayToOutput);
- }, delayToTyping);
- }
- $.post('/connect/sendMessage.php', {
- comment: commentPost,
- csrf: csrf,
- msgHash: msgHash,
- convID: ChatSession.convID
- }, function (json) {
- if (json.ack && json.ack == 'success') {
- if (json.convID == ChatSession.convID) {
- if (false && json.otherScreenName && parseInt(json.otherOnline) != 2 && $.inArray(ChatSession.reqType, ['general', 'personal']) !== -1) {
- if ($.inArray(userInfo.userType, ['g', 'm']) !== -1 && (!userInfo.age || userInfo.age >= 18)) {
- $('#offlineMessageDiv').html('<div class="text-center " style="margin-bottom:.5em"><small>It seems ' + json.otherScreenName + ' is not currently available. Sorry! Would you like expert support from one of our therapists? You can start a 3 day free trial here: <a href="/online-therapy/">7cups.com/online-therapy</a></small></div>');
- } else {
- $('#offlineMessageDiv').html('<div class="text-center " style="margin-bottom:.5em"><small>' + json.otherScreenName + ' may not be immediately available. There could be some delay in response.</small></div>');
- }
- } else {
- $('#offlineMessageDiv').html('');
- }
- scrollConversation();
- switch (json.action) {
- case 'sendToBot' :
- sendToBot(json.bot, json.autoPing);
- break;
- case 'createAccount':
- MemberAccountModal();
- $.cookie("permaCreateAccount", 1, {expires: 90, path: '/'});
- if (isMobileApp()) {
- $('#MessageScrollDiv').prepend('<div style="position:relative;height:45px;" class="createAccountMessage"><button data-modal-target="NewMemberAccount" class="btn btn-green btn-block btn-md" style="z-index:500;margin:0;position:fixed;top:50px;left:0;width:100%">CREATE YOUR FREE ACCOUNT NOW</button></div>');
- } else {
- if (!$('#permCreateAcctButton').length) {
- $('#topAlertHolder').append('<button id="permCreateAcctButton" data-modal-target="NewMemberAccount" class="btn btn-cta btn-success btn-sm" style="margin-bottom:1em">Create Your Free Account Now</button>');
- }
- }
- break;
- case 'requestRating':
- if(window.ratingModal){
- $('[data-actionid=rateListenerButton]').show();
- $('[data-actionid=rateListenerButton] i').addClass('star-blink');
- ChatSession.ratingPopped = true;
- }
- break;
- case 'requestRatingShow':
- if(window.ratingModal){
- $('[data-actionid=rateListenerButton]').show();
- $('[data-actionid=rateListenerButton] i').addClass('star-blink');
- window.ratingModal.modal('show');
- ChatSession.ratingPopped = true;
- }
- break;
- case 'selfCareModal':
- bootbox.alert('<h1 class="text-center">Care for Yourself First</h1><h5 class="text-center">We all want to care for others, but we can only adequately care for other people if we are in good shape ourselves. If we are not in good shape, then we run the risk of hurting ourselves, others, and burning out. Take good care of ourselves means eating, exercising, and sleeping well. We care for you and want you to rest and take care of yourself. You matter and are important to us!</h5>');
- break;
- }
- }
- } else if (json.error) {
- if (json.error == 'Message not sent. (Code 300)') {
- var errdisp = 'Invalid login or deactivated account.';
- } else if (json.error.indexOf("(Code 304)") > -1) {
- var errdisp = 'This user is unavailable to chat with you, please select another.';
- } else {
- var errdisp = json.error;
- }
- $('#MessageDiv').append('<div class="alert alert-danger pull-left">' + errdisp + '</div>');
- scrollConversation();
- }
- }, 'json').always(function () {
- $('#msgs-loading').hide();
- });
- //ga('send', 'event', {'eventCategory': 'Conversation', 'eventAction': 'MessageSent', 'eventLabel': roomDesc});
- //Fix via HTTP API
- //mixpanel.people.increment("MessageSent");
- }
- }
- }
- }
- function muteUserPopup(userTypeID, screenName) {
- var modalhtml = '<div class="text-center">';
- modalhtml += '<h2>Has <strong>' + screenName + '</strong> acted inappropriately or in violation of our Terms of Service?</h2>';
- modalhtml += '<div style="display:none" id="chatroomReportReason"><textarea class="form-control" rows="3" placeholder="Please describe your reason for reporting ' + screenName + '."></textarea><div class="text-center"><button style="margin-top:2em" onclick="reportUser(\'' + userTypeID + '\');" type="button" class="btn btn-danger">Submit Report</button></div></div>';
- modalhtml += '<div class="row" id="chatroomReportOptions" style="margin-top: 2em;">';
- modalhtml += '<div class="col-sm-6 col-sm-push-6" style="margin-bottom:1em"><div class="text-center"><button onclick="muteUser(\'' + userTypeID + '\');" type="button" class="btn btn-warning">No, Just <strong>MUTE</strong> Them for Me</button></div></div>';
- if (ChatSession.user.userType != 'g') {
- modalhtml += '<div class="col-sm-6 col-sm-pull-6 text-center" style="margin-bottom:1em"><button onclick="$(\'#chatroomReportOptions\').hide();$(\'#chatroomReportReason\').show();" type="button" class="btn btn-danger">';
- modalhtml += ChatSession.user.isMod && false ? 'Moderator Mute for All!' : 'Yes, <strong>FILE REPORT!</strong>';
- modalhtml += '</button></div>';
- }
- modalhtml += '</div>';
- modalhtml += '<div style="margin-top:1em"><span data-dismiss="modal" style="cursor:pointer;color:#999;">Cancel</span></div></div>';
- $('#multiModal .modal-body').html(modalhtml);
- $('#multiModal').modal({backdrop: true, keyboard: true});
- }
- function referUserPopup(userTypeID, screenName) {
- var modalhtml = '<div class="text-center"><h2 style="margin:1em 0 .5em 0;">Refer ' + screenName + '</h2>';
- modalhtml += '<h3>Is ' + screenName + ' talking about suicide or seems to be in crisis? If so, please refer them to the suicide hotline and other crisis resources.</h3>';
- modalhtml += '<div class="row">';
- modalhtml += '<div class="col-sm-6 text-center" style="margin-bottom:1em"><button data-dismiss="modal" type="button" class="btn btn-default">Cancel</button></div>';
- modalhtml += '<div class="col-sm-6 text-center" style="margin-bottom:1em"><button onclick="referUser(\'' + userTypeID + '\');" type="button" class="btn btn-primary">Send Anonymous Referral</button></div>';
- modalhtml += '</div></div>';
- $('#multiModal .modal-body').html(modalhtml);
- $('#multiModal').modal({backdrop: true, keyboard: true});
- }
- function referUser(userTypeID) {
- if (ChatSession.nodeRoom) {
- ListMessagesSocket.emit('sendConvAction', {room: ChatSession.nodeRoom, action: 'referalResources', userTypeID: userTypeID, me: ChatSession.me});
- }
- $('#multiModal').modal('hide');
- }
- function reportUser(userTypeID) {
- if ($('#chatroomReportReason > textarea').val() != undefined && $('#chatroomReportReason > textarea').val() != '') {
- $.post('/connect/reportChatroomUser.php', {userTypeID: userTypeID, reason: $('#chatroomReportReason > textarea').val(), convID: ChatSession.convID});
- muteUser(userTypeID);
- $('#multiModal').modal('hide');
- } else {
- $('#chatroomReportReason').addClass('has-error');
- }
- }
- function listTips(msgNum) {
- if (typeof ChatSession.otherUser !== "undefined" && ChatSession.otherUser.userType && ChatSession.otherUser.userType == 'b')
- return false;
- function showTip(msgNum) {
- msgNum = ChatSession.roomType ? ChatSession.numConvMessages - ChatSession.init_numConvMessages : msgNum;
- ChatSession.tips.shown = ChatSession.tips.shown || [];
- if (ChatSession.tips.copy && ChatSession.tips.copy[msgNum] && $.inArray(msgNum, ChatSession.tips.shown) === -1) {
- ChatSession.tips.shown.push(msgNum);
- $('#MessageDiv').append('<div class="alert" style="color:#999;font-size:0.9em"><i class="fa fa-info-circle"></i> ' + ChatSession.tips.copy[msgNum] + '</div>');
- scrollConversation();
- }
- }
- if (ChatSession.tips.copy) {
- showTip(msgNum);
- } else {
- $.post('/connect/chatTips.php', {convID: ChatSession.convID}, function (json) {
- if (json) {
- ChatSession.tips.copy = json.tips;
- showTip(msgNum);
- }
- }, 'json');
- }
- }
- function showCaptcha() {
- if (!window.bootboxCaptcha) {
- var tvar = {origin: window.location.pathname};
- if (ChatSession.convID) {
- tvar.origin += '?c=' + ChatSession.convID;
- } else if (getQSval('c')) {
- tvar.origin += '?c=' + getQSval('c');
- }
- render(false, 'Forms_Captcha_ChatCaptcha', tvar, function (content) {
- window.bootboxCaptcha = bootbox.dialog({
- message: content,
- closeButton: false,
- onEsacape: false,
- size: 'small'
- }).on('shown.bs.modal', function () {
- $(this).find('.captchaParent').load('/objects/captcha/renderCaptcha.php?captcha-w=225&captcha-h=60');
- $(this).find('[name="vscu"]').focus();
- }).on('hidden.bs.modal', function () {
- delete window.bootboxCaptcha;
- });
- });
- }
- }
- function bindSocket() {
- console.log('PRE-BINDING JS FUNCTIONS');
- // Delay execution until async scripts are downloaded
- if (typeof window.ListMessagesSocket.on === 'undefined') {
- initTimer = setTimeout(bindSocket, 25);
- return;
- }
- window.ListMessagesSocket.bindTime = (new Date()).getTime();
- console.log('BINDING JS FUNCTIONS', window.ListMessagesSocket.bindTime);
- ListMessagesSocket.on('reconnect_failed', function () {
- alert('Error: Unable to connect to Chat Server');
- });
- ListMessagesSocket.on('reconnect', function () {
- if (ChatSession.nodeRoom) {
- ListMessagesSocket.emit('addToRooms', [ChatSession.nodeRoom]);
- }
- });
- ListMessagesSocket.on('notification', function (notification) {
- if (ChatSession.convID && ChatSession.nodeRoom == notification.roomID) {
- if (notification.msg && notification.msg.indexOf("globalMute_") === 0) {
- var muteUserTypeID = notification.msg.replace('globalMute_', '');
- globalMuteUsers(muteUserTypeID);
- } else if (notification.msg) {
- switch (notification.msg) {
- case 'startTopic':
- ChatSession.discussion = {Topic: notification.Topic, endTime: notification.endTime};
- processTopic();
- break;
- case 'endTopic':
- delete ChatSession.discussion;
- processTopic();
- break;
- }
- }
- } else {
- try {
- var json = JSON.parse(notification.msg);
- if (json.alert) {
- bootbox.alert(json.alert);
- }
- }
- catch (e) {
- }
- }
- });
- ListMessagesSocket.on('recConvAction', function (data) {
- console.log(data);
- if (ChatSession.nodeRoom == data.room) {
- switch (data.action) {
- case 'authexp':
- if (ChatSession && ChatSession.convID) {
- setConversation(ChatSession.convID, true);
- }
- break;
- case 'endLiveChat':
- endLiveChat(true);
- break;
- case 'modRemove':
- removeMessage(data.msgHash);
- break;
- case 'typingStatus':
- if (!ChatSession.roomType && data.screenName && data.screenName != ChatSession.user.screenName) {
- var msg = data.isTyping ? '<em>' + data.screenName + ' is typing...</em>' : '';
- $('#offlineMessageDiv').html('<div class="" style="margin-bottom:1em;"><small>' + msg + '</small></div>');
- scrollConversation();
- }
- break;
- case 'newMessage':
- if (data.message.convID == ChatSession.convID && data.message.userType != 'n') {
- if (data.message.msgTS)
- var s = data.message.msgTS*1000;
- else
- var s = parseInt((new Date()).getTime() - serverTimeOffset*1000);
- data.message.msgTime = moment(s).format("h:mm A");
- console.log(data.message.msgBody);
- var censoredMsg = loadMessage(data.message);
- // console.log(data.message.msgBody.split(" "));
- if(censoredMsg != data.message.msgBody){
- console.log("Gaali Bak delas");
- }
- var censorArr = censoredMsg.split(" ");
- var uncensorArr = data.message.msgBody.split(" ");
- var lenth = uncensorArr.length;
- var isGaali = false;
- var newMsg = "";
- for (var i=0;i<lenth;i++){
- if((censorArr[i]!=uncensorArr[i]) && censorArr[i]=="***"){
- isGaali = true;
- var newWord = "";
- for(var j=0;j<uncensorArr[i].length;j++){
- newWord+=uncensorArr[i][j];
- newWord+="_";
- }
- newMsg = newMsg + newWord + " ";
- }
- else{
- newMsg = newMsg + uncensorArr[i] + " ";
- }
- }
- if(isGaali){
- console.log("Gaali = " + newMsg);
- }
- scrollConversation();
- }
- break;
- case 'enterRoom':
- if (data.screenName && data.screenName != ChatSession.user.screenName) {
- $('#MessageDiv').append('<div class="enterRoom"><i class="fa fa-user"></i> ' + data.screenName + ' has entered this room.</div>');
- scrollConversation();
- }
- break;
- case 'heartMsg':
- var curPoints = $('#message_' + data.msgHash + ' .pointHolder').text() != '' ? parseInt($('#message_' + data.msgHash + ' .pointHolder').text()) : 0;
- var newPoints = curPoints + 1;
- if (newPoints <= 20) {
- $('#message_' + data.msgHash + ' .pointHolder').text(' +' + newPoints);
- $('#message_' + data.msgHash + ' .heartCommentButton').removeClass('compassionHeartFade').addClass('compassionHeart').show();
- if (!someheartedyou && ChatSession.user.userType == 'g' && $('#message_' + data.msgHash).attr('data-usertypeid') == ChatSession.user.userTypeID) {
- $('#multiModal .modal-body').html('<div class="text-center"><h2 style="font-weight:normal" class="font-serif">Congratulations! You just earned a Compassion Heart!</h2><p>You said something kind and someone hearted your message. Sign up to be a member so you don’t lose your compassion points. As a member, you can also give hearts, earn growth points, and unlock badges.</p><button class="btn btn-block btn-success" data-modal-target="NewMemberAccount">Become a Member</button><br /><span data-dismiss="modal" style="cursor:pointer;color:#999;">No Thanks</span></div>');
- $('#multiModal').modal({backdrop: true, keyboard: true});
- someheartedyou = true;
- }
- }
- break;
- case 'referalResources':
- if (data.userTypeID == ChatSession.user.userTypeID && !$.cookie('resourcesSent')) {
- $('#multiModal .modal-body').html('<div class="text-center"><h2 style="font-weight:normal" class="font-serif">Helpful resources if you are in crisis</h2><p>Someone believes you could benefit from accessing these resources. Please do not use 7 Cups of Tea if you are suicidal. We need you to get the best help you can by using these resources.</p><dl class=""><dt>Suicide Prevention Lifeline</dt><dd>1-800-273-TALK(8255) or 1-800-SUICIDE(7842433)</h5></dd><dt>Suicide Prevention Online Chat</dt><dd><a href="http://www.suicidepreventionlifeline.org/GetHelp/LifelineChat.aspx">suicidepreventionlifeline.org/GetHelp/</a></dd><dt>Sexual Assault Hotline</dt><dd>(574)-254-7473</dd><dt>US Veterans Crisis Hotline</dt><dd>1-800-273-TALK(8255)</dd><dt>Center to Prevent Youth Violence</dt><dd>1-866-773-2587</dd><dt>National Runaway Switchboard</dt><dd>1-800-RUNAWAY</dd><dt>The Trevor Project for LGBT teens</dt><dd>1-800-488-7386</dd><dt>Teen Line</dt><dd><a href="http://teenlineonline.org" target="_blank">teenlineonline.org</a></dd><dt>Safe Haven for self-injurers</dt><dd><a href="http://gabrielle.self-injury.net" target="_blank">gabrielle.self-injury.net</a></dd><dt>Al-Anon / Alateen</dt><dd><a href="http://www.al-anon.alateen.org" target="_blank">www.al-anon.alateen.org</a></dd></dl><br /><span data-dismiss="modal" class="btn btn-primary">Close</span></div>');
- $('#multiModal').modal({backdrop: true, keyboard: true});
- $.cookie("resourcesSent", true, {path: '/'});
- }
- break;
- }
- }
- });
- }
- bindSocket();
- function chatroomParticipants(inChatroom, newlist) {
- window.chatroomParticipantList = !newlist && window.chatroomParticipantList ? window.chatroomParticipantList : [];
- NewParticipantLoop:
- for (var i = 0; i < inChatroom.length; i++) {
- var u = inChatroom[i];
- if(u.screenName && u.userTypeID){
- if(u.userType && $.inArray(u.userType, ['l', 'm']) !== -1){u.profileURL = '/@'+u.screenName;}
- for(var pi =0; pi < window.chatroomParticipantList.length; pi++){
- if(window.chatroomParticipantList[pi].userTypeID === u.userTypeID){
- window.chatroomParticipantList[pi] = u;
- continue NewParticipantLoop;
- }
- }
- window.chatroomParticipantList.push(u);
- }
- }
- window.chatroomParticipantList.sort(function(a, b){
- if (a.screenName.toLowerCase() === b.screenName.toLowerCase()) return 0;
- return a.screenName.toLowerCase() > b.screenName.toLowerCase() ? 1 : -1;
- });
- render(false, 'Chat_CurrentParticipants', {
- participants: window.chatroomParticipantList
- }, function (content) {
- $('#listenersInChatroomModal .modal-body').html(content);
- });
- $('#listenersInChatDiv').html('<div class="text-center "><small><a href="#" onclick="chatRoomRules();" style="color:#5cc8df;font-weight:bold;">Please read the Chatroom Rules</a> | <a href="#" data-toggle="modal" data-target="#listenersInChatroomModal" style="color:##1e90fe;font-weight:bold;">' + window.chatroomParticipantList.length + ' Currently Participating</a></small></div>');
- }
- var checkConvTimeout;
- var debugger1 = '';
- function checkConv(setConvID) {
- clearTimeout(checkConv);
- var setConvReqID = typeof (setConvID) !== 'undefined' ? setConvID : ChatSession.convID;
- if (!requestRedirect && (ChatSession.lastMessage != ChatSession.checkingMessNow)) {
- ChatSession.checkingMessNow = ChatSession.lastMessage;
- if (ChatSession.checkingMessNow == -1) {
- if (window.chatInfoMemory[userInfo.userIDe + setConvID] && window.chatInfoMemory[userInfo.userIDe + setConvID].messages) {
- preloadingMessages = true;
- debugger1 = userInfo.userIDe + setConvID;
- $.each(window.chatInfoMemory[userInfo.userIDe + setConvID].messages, function (key, value) {
- loadMessage(value, true);
- });
- scrollConversation();
- preloadingMessages = false;
- }
- }
- $.post("/connect/checkConvMessages.php", {convID: setConvReqID, lastMessage: ChatSession.checkingMessNow}, function (json) {
- serverTimeOffset = (new Date()).getTime()/1000-json['serverTime'];
- console.log('Setting server time offset:', serverTimeOffset);
- loadConversation(json);
- if (!ChatSession.roomType)
- checkMessages();
- if (ChatSession.otherUser && ChatSession.otherUser.userType == 'b') {
- $('#MessageScrollDiv .alert').hide();
- $('#MessageScrollDiv .alert.alert-noni').show();
- if (typeof json.bot !== 'undefined')
- sendToBot(json.bot, json.autoPing);
- if (typeof json.suppressToast !== 'undefined')
- window.suppressToast = true;
- } else
- $('#MessageScrollDiv .alert.alert-noni').hide();
- }, 'json').always(function () {
- //checkConvTimeout = setTimeout(checkConv, 60000 * 3);
- });
- }
- var loadAttempts = 0;
- function loadConversation(json) {
- if (typeof (setConvID) !== 'undefined' && setConvID != ChatSession.convID) {
- if (loadAttempts <= 100) {
- setTimeout(function () {
- loadConversation(json)
- }, 200);
- loadAttempts++;
- }
- } else {
- if (json.ack && json.ack == 'success') {
- if (ChatSession.convID == json.convID) {
- ChatSession.user.userTypeID = json.user.userTypeID;
- //var newMessages = false;
- // Make sure other message loading isn't also happening
- loadAllMessages = function () {
- if (!preloadingMessages) {
- console.log('Loading Ajax Messages');
- var idx = userInfo.userIDe + ChatSession.convID;
- window.chatInfoMemory[idx] = window.chatInfoMemory[idx] || {};
- window.chatInfoMemory[idx].messages = window.chatInfoMemory[idx].messages || [];
- var chatMsgs = window.chatInfoMemory[idx].messages;
- var histMap = {};
- for (var k = 0; k < chatMsgs.length; k++)
- histMap[chatMsgs[k].msgHash] = k;
- var updated = false;
- var newQueue = [];
- for (var i = 0; i < json.messages.length; i++) {
- if (histMap[json.messages[i].msgHash] && (chatMsgs[histMap[json.messages[i].msgHash]].msgID === null || chatMsgs[histMap[json.messages[i].msgHash]].msgTime != json.messages[i].msgTime)) {
- updated = true;
- chatMsgs[histMap[json.messages[i].msgHash]].msgID = json.messages[i].msgID;
- chatMsgs[histMap[json.messages[i].msgHash]].msgTime = json.messages[i].msgTime;
- var msg = $("#message_" + json.messages[i].msgHash);
- if (msg[0]) {
- msg[0].setAttribute('data-msgid', json.messages[i].msgID);
- msg.find('.msgTime').html(json.messages[i].msgTime);
- }
- } else if (!histMap[json.messages[i].msgHash]) {
- newQueue.push(json.messages[i]);
- updated = true;
- chatMsgs.push(json.messages[i]);
- }
- }
- for (var t = 0; t < newQueue.length; t++)
- loadMessage(newQueue[t], true);
- chatMsgs.sort(function (x, y) {
- if (x.msgID < y.msgID) {
- return -1;
- }
- if (x.msgID > y.msgID) {
- return 1;
- }
- return 0;
- });
- if (updated) {
- chatMsgs = chatMsgs.slice(-40);
- window.chatInfoMemory[idx].messages = chatMsgs;
- console.log('Resaving history', idx, window.chatInfoMemory[idx]);
- }
- } else {
- console.log('Waiting to preload messages');
- setTimeout(loadAllMessages, 100);
- }
- };
- loadAllMessages();
- ChatSession.lastMessage = json.lastMessage;
- if (ChatSession.initialLoad) {
- talkToNoni();
- if ((ChatSession.reqType && ChatSession.reqType === 'general_therapy' || ChatSession.reqType === 'personal_therapy') || (ChatSession.convID == "Sophia")) {// && ChatSession.reqStatus && ChatSession.reqStatus === 'request'){
- $('#bottomStatus').slideUp(function () {
- if (typeof resizeChat == 'function') {
- resizeChat();
- }
- });
- $('body').addClass('in-therapy');
- $('#non-therapy-ad').hide();
- window.holdToast = true;
- if (ChatSession.reqStatus === 'request' || ChatSession.convID == "Sophia")
- render(false, 'Ads_Therapyreviews', {}, function (content) {
- var e = $('#therapy-reviews-holder');
- e.empty().hide().html(content);
- e.find('.therapyReviews').carousel();
- e.fadeIn();
- });
- else
- render(false, 'Ads_Therapysupport', {}, function (content) {
- var e = $('#therapy-reviews-holder');
- e.empty().hide().html(content);
- e.fadeIn();
- });
- if (typeof Stripe === 'undefined') {
- (function (e, t) {
- var n = t.createElement("script");
- n.type = "text/javascript";
- n.async = true;
- n.src = "https://js.stripe.com/v2/";
- var s = t.getElementsByTagName("script")[0];
- s.parentNode.insertBefore(n, s);
- })(window, document);
- window.stripeInit = setInterval(function () {
- if (typeof Stripe !== 'undefined') {
- console.log('Stripe Initialized');
- Stripe.setPublishableKey(StripePublishableKey);
- clearInterval(window.stripeInit);
- window.libraryState += '-stripe-';
- }
- }, 100);
- }
- if (!ecAdded && typeof ga !== 'undefined') {
- ecAdded = true;
- ga('require', 'ec');
- ga('ec:addImpression', {
- 'id': 'onlinetherapy',
- 'name': 'Online Therapy',
- 'category': 'therapy',
- 'brand': '7 Cups',
- 'position': 1,
- });
- ga('ec:setAction', 'detail');
- (function (e, t) {
- var n = t.createElement("script");
- n.type = "text/javascript";
- n.async = true;
- n.src = "https://www.googleadservices.com/pagead/conversion_async.js";
- var s = t.getElementsByTagName("script")[0];
- s.parentNode.insertBefore(n, s);
- })(window, document);
- }
- if (typeof __adroll !== "undefined") {
- try {
- __adroll.record_user({"adroll_segments": "acc662f5"})
- } catch(err) {}
- }
- } else {
- $('body').removeClass('in-therapy');
- window.holdToast = false;
- $('#therapy-reviews-holder').hide();
- $('#non-therapy-ad').fadeIn();
- }
- }
- if (json.inChatroom) {
- chatroomParticipants(json.inChatroom, true);
- if (json.overFlow) {
- if ($('#overflowAlert').length) {
- var roomBtns = '';
- for (var i = 0; i < json.overFlow.length; i++) {
- if (ChatSession.user.userType = 'l') {
- var url = '/listener/connect/conversation.php?c=' + json.overFlow[i]['convID'];
- } else {
- var url = '/member/connect/conversation.php?c=' + json.overFlow[i]['convID'];
- }
- roomBtns += '<a href="' + url + '" class="btn btn-default btn-sm">' + json.overFlow[i]['chatroomName'] + ' ' + json.overFlow[i]['reqTime'] + '</a> ';
- }
- roomBtns = '<div id="overflowAlert" class="alert alert-info" style="padding:1em"><strong>Is it getting cramped in here?</strong> This group chat is now beyond capacity. If you are up for helping us all out, then please move over to one of these rooms: ' + roomBtns + '</div>';
- $('#offlineMessageDiv').append(roomBtns);
- scrollConversation();
- }
- } else {
- $('#overflowAlert').hide();
- }
- }
- scrollConversation();
- ChatSession.initialLoad = false;
- }
- } else if (json.error) {
- if (json.error == 'Please verify you are human') {
- showCaptcha();
- } else if (console && console.log) {
- $('#MessageDiv').append('<div class="alert alert-danger pull-left">' + json.error + '</div>');
- }
- }
- $('#msgs-loading').hide();
- }
- }
- }
- function groupChatOrientation() {
- /*
- if ($.cookie('newuser_groupsupport') && !isMobileApp()) {
- $.removeCookie('newuser_groupsupport', {path: '/'});
- $('#popoverTarget').popover({
- container: 'body',
- content: '<h3 class="text-center font-serif">Welcome to<br />Group Support</h3><h4 class="text-center" style="font-weight:normal">Please share your thoughts with this supportive group. You can start by simply saying “Hello” <img src="'+cloudfrontBase+'img/emoticons/smile.png" /></h4>',
- trigger: 'hover',
- placement: 'top',
- html: 'true'
- }).popover('show');
- $("body").append($("<div>").css({
- position: "fixed"
- , width: "100%"
- , height: "100%"
- , "background-color": "#000"
- , opacity: 0.6
- , "z-index": 1001
- , top: 0
- , left: 0
- }).attr("id", "page-cover")).click(function () {
- $('#page-cover').remove();
- $('.popover').popover('hide');
- $('#chatForm').popover('destroy');
- });
- }*/
- }
- loadRatingModalFails = 0;
- function loadRatingModal() {
- //have to wait until handlebars is loaded in
- if(typeof(render) != 'function'){
- if(loadRatingModalFails >= 8){
- throw Error('Error opening modal. Handlebars not loading.')
- } else {
- setTimeout(loadRatingModal, 1000);
- loadRatingModalFails++;
- return;
- }
- }
- render(false, 'Forms_Connect_RateListener', {
- convID: ChatSession.convID,
- screenName: ChatSession.otherUser.screenName
- }, function (content) {
- $('div.modal-rating').remove();
- window.ratingModal = bootbox.dialog({
- message: content,
- show: false,
- className: 'modal-rating'
- });
- window.ratingModal.init(function () {
- if (ChatSession.ratingPopped) {
- $('[data-actionid=rateListenerButton]').show();
- }
- });
- window.ratingModal.on('shown.bs.modal', function(){
- tracker.emit("RatingModalShown");
- });
- if (getQSval('rp') && !window.didRP) {
- window.didRP=1;
- function checkPageReady() {
- if (window.pageReady)
- window.ratingModal.modal('show');
- else
- setTimeout(checkPageReady, 100);
- }
- setTimeout(checkPageReady, 500);
- }
- });
- // $.post('/connect/listenerRating.php', {a: 'req', convID: ChatSession.convID}, function (json) {
- // if (true) {
- // render(false, 'Forms_Connect_RateListener', {
- // convID: ChatSession.convID,
- // screenName: ChatSession.otherUser.screenName
- // }, function (content) {
- // $('div.modal-rating').remove();
- // window.ratingModal = bootbox.dialog({
- // message: content,
- // show: false,
- // className: 'modal-rating'
- // });
- // window.ratingModal.init(function () {
- // if (ChatSession.ratingPopped) {
- // $('[data-actionid=rateListenerButton]').show();
- // }
- // });
- // if (getQSval('rp') && !window.didRP) {
- // window.didRP=1;
- // function checkPageReady() {
- // if (window.pageReady)
- // window.ratingModal.modal('show');
- // else
- // setTimeout(checkPageReady, 100);
- // }
- // setTimeout(checkPageReady, 500);
- // }
- // });
- // }
- // }, 'json');
- }
- $(function () {
- $('body').on('shown.bs.modal', 'div.modal-rating', function () {
- var $modal = $(this).closest('div.modal-rating');
- });
- $('body').on('submit', 'div.modal-rating form[data-id="feedbackForm"]', function () {
- var $modal = $(this).closest('div.modal-rating');
- ga('send', 'event', {eventCategory: 'Conversation', eventAction: 'Review', eventLabel: 'Written'});
- var $form = $(this);
- var starValue = ChatSession.otherUser['rating'];
- var feedbackInput = $form.find('textarea[name="feedbackInput"]').val();
- $form.find('.alert').remove();
- if (!(starValue > 0 && starValue <= 5 && feedbackInput.length > 14)) {
- var warningText = '<div class="alert alert-danger">';
- var starPass = true;
- var feedbackPass = true;
- if(!(starValue > 0 && starValue <= 5)){
- starPass = false;
- }
- if(feedbackInput.length <= 14){
- feedbackPass = false;
- }
- if (!starPass && !feedbackPass) {
- warningText = warningText + 'Please provide a star rating and ensure the review is at least 15 characters.';
- } else if(!starPass) {
- warningText = warningText + 'Please provide a star rating.';
- } else if(!feedbackPass) {
- warningText = warningText + 'Please provide a review with at least 15 characters.';
- } else {
- warningText = warningText + 'Unknown error';
- }
- warningText = warningText + '</div>';
- $form.append(warningText);
- return false;
- }
- $form.find('button[type=submit]').attr('data-html', function () {
- return $(this).html()
- }).html('Processing <i class="fa fa-spin fa-spinner"></i>').attr('disabled', 'true');
- $.post('/connect/listenerRating.php', {
- a: 'rating',
- convID: $form.find('input[name="convID"]').val() || ChatSession.convID,
- overallRating: starValue,
- feedbackInput: feedbackInput
- }, function (json) {
- if (json.ack && json.ack == 'success') {
- $modal.on('hidden.bs.modal', function () {
- if (starValue <= 3) {
- bootbox.alert('<div class="text-center m-t-md"><h1 class="text-primary">We are sorry your experience was not great.</h1><h2>Click <a href="https://www.7cups.com/BrowseListeners/?find=&sort=&ageGroup=&listType=&country=&category=&gender=&language=&verifiedlistener=on">here</a> to connect with a verified listener.</h2></div>');
- } else {
- bootbox.alert('<div class="text-center m-t-md"><h1 class="text-primary">Thanks for your feedback!</h1><h2>We are glad you are getting the help you are looking for!</h2></div>');
- }
- }).modal('hide');
- $form.find('textarea[name="feedbackInput"]').val('');
- //hide rate button after submitting a review (should be unavailable for 48hrs)
- $('[data-actionid=rateListenerButton]').hide();
- } else {
- json.error = json.error || 'Feedback text not received';
- $form.append('<div class="alert alert-danger">' + json.error + '</div>');
- }
- }, 'json').always(function () {
- $form.find('button[type=submit]').html(function () {
- return $(this).attr('data-html')
- }).removeAttr('disabled');
- });
- $('[data-actionid=rateListenerButton] i').removeClass('star-blink');
- return false;
- });
- //Submit Ratings
- $('body').on('mouseenter mouseleave click', 'div.modal-rating [data-rating] > i', function (e) {
- var $modal = $(this).closest('div.modal-rating');
- var clickedStar = $(this);
- // var ratingIDint = parseInt(clickedStar.closest('[data-rating]').attr('data-rating'));
- switch (e.type) {
- case 'mouseenter':
- lightStars($modal, parseInt($(this).attr('data-value')));
- ratingDescription($modal, parseInt($(this).attr('data-value')));
- break;
- case 'mouseleave':
- lightStars($modal);
- ratingDescription($modal);
- break;
- case 'click':
- var newRating = parseInt(clickedStar.attr('data-value'));
- ChatSession.otherUser['rating'] = newRating;
- lightStars($modal);
- ratingDescription($modal, newRating);
- // $.post('/connect/listenerRating.php', {
- // a: 'set',
- // convID: clickedStar.closest('form').find('input[name="convID"]').val(),
- // r: ratingIDint,
- // v: newRating
- // });
- $('[data-actionid=rateListenerButton] i').removeClass('star-blink');
- // var overallRating = 0;
- // var numSet = 0;
- // for (var i = 1; i <= 4; i++) {
- // if (parseInt(ChatSession.otherUser['ratingR' + i]) > 0) {
- // overallRating = overallRating + parseInt(ChatSession.otherUser['ratingR' + i]);
- // numSet++;
- // }
- // }
- // if (numSet) {
- // overallRating = overallRating / numSet;
- // ChatSession.goodExperience = overallRating >= 4;
- // if (numSet >= 4) {
- // tracker.emit("ListenerRating", {rating: overallRating});
- // if (ChatSession.goodExperience) {
- // $modal.on('hidden.bs.modal', function () {
- // bootbox.confirm({
- // message: '<h2 class="text-center">Would you consider supporting 7 Cups?</h2>',
- // buttons: {
- // cancel: {
- // label: "no thanks",
- // className: "btn-link"
- // },
- // confirm: {
- // label: "Yes",
- // className: "btn-success"
- // }
- // },
- // callback: function (result) {
- // if (result)
- // window.location.href = '/backus/back7cups.php';
- // }
- // });
- // });
- // }
- // }
- // }
- break;
- }
- });
- function lightStars($modal, hoveredOverInt) {
- hoveredOverInt = (hoveredOverInt != null) ? hoveredOverInt : parseInt(eval('ChatSession.otherUser.rating'));
- $modal.find('[data-rating="1"] > i').removeClass('fa-star').removeClass('text-warning').addClass('fa-star-o');
- $modal.find('[data-rating="1"] > i:lt(' + hoveredOverInt + ')').removeClass('fa-star-o').addClass('fa-star').addClass('text-warning');
- }
- function ratingDescription($modal, ratingValue) {
- text = '';
- ratingValue = (ratingValue != null) ? ratingValue : parseInt(eval('ChatSession.otherUser.rating'));
- switch (ratingValue) {
- case 1:
- text = 'This was not a helpful chat.';
- break;
- case 2:
- text = 'Could have gone better.';
- break;
- case 3:
- text = 'It went okay.';
- break;
- case 4:
- text = 'I liked it, helpful chat.';
- break;
- case 5:
- text = 'Loved it! Awesome chat!';
- break;
- default:
- break;
- }
- $modal.find('[name="ratingText"]').text(text);
- }
- });
- function scrollConversation() {
- ChatSession.scrollDelay = ChatSession.scrollDelay || 0;
- var unix = Math.round(+new Date() / 1000);
- if (unix >= ChatSession.scrollDelay) {
- $("#MessageScrollDiv").animate({scrollTop: $("#MessageScrollDiv").prop("scrollHeight")}, 300);
- }
- }
- function showUnmuteButton() {
- if (!$('#unMuteButton').length && $.cookie('muteArr')) {
- if (isMobileApp()) {
- $('#unMuteButton').show();
- } else {
- $('#actionButtons').append(
- '<img src="/img/chat-unmute.png" onclick="$.removeCookie(\'muteArr\',{path:\'/\'});$(\'.convRow\').show();scrollConversation();$(this).remove();" style="margin-left:.5em" id="unMuteButton" class="pull-right" data-toggle="tooltip" title="Unmute Everyone You Have Muted"/>');
- }
- }
- }
- function attachTestResults(data) {
- var jsonObj = JSON.parse(data);
- var resultsDiv = document.createElement("div");
- resultsDiv.id = "resultsDiv";
- resultsDiv.classList.add("resultsMain");
- resultsDiv.innerHTML = "Loading Results...";
- var bbModal = bootbox.dialog({
- title: 'Results',
- message: resultsDiv
- });
- $('#resultsDiv').setWellnessEngineTestInterface(jsonObj.testID, jsonObj.sessionID);
- }
- function wellnessTestModal() {
- if (typeof (gpTest) !== 'undefined') {
- wtRender();
- } else {
- $.getScript('/exercises/js/test.js', function () {
- wtRender();
- });
- }
- function wtRender() {
- $.get('/connect/holdRequest.php', {holdReq: 1});
- render(false, 'SC_WellnessEngine_Test', null, function (content) {
- var bb = bootbox.dialog({
- message: '<div class="text-center" id="TestHolder"><i class="fa fa-spin fa-spinner"></i> Loading Wellness Test</div>',
- size: 'large',
- onEscape: function () {
- $.get('/connect/holdRequest.php', {holdReq: 0});
- }
- });
- bb.on('shown.bs.modal', function () {
- gpTest($('#TestHolder'), {"finishButton": "Return to Noni", "finishCallback": bootbox.hideAll});
- $('body').addClass('modal-open');
- //this page is using bootstrap 3 and we need this styling from bootstrap 4...
- var css = document.createElement("style");
- css.type = "text/css";
- css.innerHTML = ".progress-bar { height: 1rem; color: #fff; background-color: #0275d8; height: 2rem;}";
- css.innerHTML += ".progress { background-color: #eceeef; border-radius: .75rem; overflow: hidden; line-height: 1rem;}";
- css.innerHTML += ".mt-2 { margin-top: 0.5rem;}";
- document.body.appendChild(css);
- });
- });
- }
- }
- function crisisNumberClick() {
- tracker.emit("CrisisNumber", {action: 'click'});
- }
- //crisis resources and helplines
- function popCrisisResources(useModal, location) {
- //render a modal containing the handlebars template if required
- if (useModal) {
- render(false, "WellnessEngine_CrisisResources", null, function($html) {
- bootbox.dialog({
- title: 'Crisis Resources',
- message: $html
- });
- });
- }
- //emit amplitude event specifying the location/source of the event
- tracker.emit("CrisisResources", {action: 'click', location: location});
- }
- //listener advice information
- function popListenerAdvice(useModal, location) {
- //render a modal containing the handlebars template if required
- if (useModal) {
- render(false, "Training_Advice", null, function($html) {
- bootbox.dialog({
- title: 'Advice and Crisis Resources',
- message: $html
- });
- });
- }
- //emit amplitude event specifying the location/source of the event
- tracker.emit("AdviceAndCrisis", {action: 'click', location: location});
- }
- function confirmEmail() {
- render(false, "Forms_Account_VerifyEmail", {
- userInfo: userInfo
- }, function($html){
- bootbox.dialog({
- title: 'Verify Your Email Address',
- message: $html
- }).on('shown.bs.modal', function () {
- console.log('Showing email confirm modal');
- }).on('hidden.bs.modal', function () {
- console.log('Hiding email confirm modal');
- resetState();
- window.allowEmpty = true;
- $('#Comment').val('');
- sendMessage();
- });
- });
- }
- $(function () {
- $('body').on('click','[data-actionid=rateListenerButton]', function(){
- if(window.ratingModal){
- window.ratingModal.modal('show');
- }
- });
- setInterval(function () {
- var now = (new Date()).getTime() - (60000 * 5);
- $('[data-msgTime]').each(function () {
- var time = parseInt(this.getAttribute('data-msgTime'));
- if (time <= now) {
- this.removeAttribute('data-msgTime');
- this.removeAttribute('style');
- }
- });
- }, 15000);
- if (getQSval('c')) {
- setConversation(getQSval('c'));
- } else if (window.therapyConvID) {
- if (window.therapyConvID !== 'reload')
- setConversation(window.therapyConvID, false, window.forceBotMode);
- else {
- tracker.emit('ctaTherapy', {uri: window.location.href, location: 'direct'});
- setTimeout(function () { window.location = '/connect/?r=therapy';}, 25);
- }
- }
- $('#MessageScrollDiv').on('scroll', function (e) {
- if (!$(this).is(':animated')) {
- if ($(this).scrollTop() + $(this).innerHeight() >= $(this)[0].scrollHeight) {
- ChatSession.scrollDelay = 0;
- } else {
- var unix = Math.round(+new Date() / 1000);
- ChatSession.scrollDelay = unix + 30;
- }
- }
- });
- $(window).on('beforeunload', function (e) {
- requestRedirect = true;
- });
- $('#Comment').on('keyup', function () {
- if (sendTypingStatus) {
- if ($('#Comment').val().length === 0) {//Empty message send not typing
- sendTyping(0);
- } else if ($('#Comment').val().length > 1 && !ChatSession.sendingTyping) {//Send on first character
- sendTyping(1);
- }
- }
- if (isMobileApp()) {
- if ($('#Comment').val().length === 0) {
- $('#sendButton').css({'color': '#999999'});
- } else if ($('#Comment').val().length > 1) {
- $('#sendButton').css({'color': '#163e4a'});
- }
- }
- });
- $('#Comment').on('keydown', function (e) {
- var key = e.which || e.keyCode || 0;
- if (key == 13) {
- if (!e.shiftKey) {
- e.preventDefault();
- if (window.showNoniMenu && window.botCommand)
- resetState(window.botCommand);
- sendMessage();
- }
- }
- });
- $('#sendButton').on('click', function (e) {
- e.preventDefault();
- if (window.stateLocked)
- return;
- sendMessage();
- });
- $('#banButtonOnModal').on('click', function (e) {
- if ($('#blockReasonInput').val() == '') {
- alert('Please describe the reason for banning this user.');
- e.preventDefault();
- }
- });
- if (getLocal("hideSafetyAlert")) {
- $('#SafetyAlert').hide();
- }
- if (getLocal("hideReferralAlert")) {
- $('#ReferralAlert').hide();
- }
- $('#MessageScrollDiv').on('click', 'button[data-selectcat]', function () {
- var catID = $(this).attr('data-selectcat');
- var convID = $(this).attr('data-convid');
- var catName = $(this).text();
- if (typeof __adroll !== "undefined" && [37,22,16,23].indexOf(parseInt(catID)) !== -1) {
- try {
- __adroll.record_user({"adroll_segments": "0ab24dd2"})
- } catch(err) {}
- }
- $('button[data-selectcat]').closest('div.row').replaceWith('<h5 class="text-primary">' + catName + ' Selected</h5>');
- if (parseInt(catID) > 0 || catID == '') {
- waitForSend = false;
- if (currentNoni.screenName.indexOf('Noni') !== -1) {
- $('#offlineMessageDiv').html('<div class="" style="margin-bottom:.5em"><small><em>Noni is typing...</em></small></div>');
- scrollConversation();
- setTimeout(function () {
- $('#offlineMessageDiv').html('');
- var s = parseInt((new Date()).getTime() - serverTimeOffset*1000);
- loadMessage({msgID: null,
- msgHash: randomHash(),
- msgBody: 'While you wait, I will create a create a personalized path for you to better address ' + catName + '. It starts with a free emotional wellness test that will help you better understand ' + catName + '.',
- msgTime: moment(s).format("h:mm A"),
- userTypeID: '0GKvccLHkpyGnA!!',
- screenName: 'Noni',
- userType: 'n',
- imgURL: cloudfrontBase + 'img/noniCup.jpg',
- imageClass: 'img-profile-l',
- convSide: "other",
- convID: convID});
- scrollConversation();
- $('#offlineMessageDiv').html('<div class="" style="margin-bottom:.5em"><small><em>Noni is typing...</em></small></div>');
- setTimeout(function () {
- $('#offlineMessageDiv').html('');
- var s = parseInt((new Date()).getTime() - serverTimeOffset*1000);
- loadMessage({msgID: null,
- msgHash: randomHash(),
- msgBody: 'Don’t worry, you won’t lose your place in line. We’ll connect you with your listener as soon as they are available.<br /><button class="btn btn-sm btn-success" onclick="wellnessTestModal();">Start Now</button>',
- msgTime: moment(s).format("h:mm A"),
- userTypeID: '0GKvccLHkpyGnA!!',
- screenName: 'Noni',
- userType: 'n',
- imgURL: cloudfrontBase + 'img/noniCup.jpg',
- imageClass: 'img-profile-l',
- convSide: "other",
- convID: convID});
- scrollConversation();
- noniTimer = setTimeout(talkToNoni, 30000);
- }, 2000);
- }, 2000);
- } else {
- talkToNoni();
- }
- if (parseInt(catID) > 0) {
- $.post('/connect/addCategory.php', {convID: convID, catID: catID}, function (resp) {
- if (resp.loadad) {
- setTimeout(function () {
- if (!$('.ModuleHolder-Back7CupsAd > .Module-Back7CupsAd').length) {
- $('.ModuleHolder-Back7CupsAd').hide().html(resp.loadad).slideDown(1500);
- }
- }, 5000);
- }
- }, 'json');
- }
- }
- });
- $('body').on('click', 'button[data-therapyaction="payment"]', function () {
- tracker.emit("OnlineTherapy", {step: 'loadpayment', reqType: ChatSession.reqType});
- if (autoMessageFunction) clearTimeout(autoMessageFunction);
- var planID = $(this).attr('data-planID') ? $(this).attr('data-planID') : NULL;
- var subs = {};
- if (typeof __adroll !== "undefined") {
- try {
- __adroll.record_user({"adroll_segments": "13b73f15"})
- } catch(err) {}
- try {
- __adroll.record_user({product_id: "onlineTherapy", product_action: "AddToCart"})
- } catch (e) { }
- }
- subs['onlinetherapy_monthly_15000'] = {
- planID: 'onlinetherapy_monthly_15000',
- modaltitle: 'Get Started!',
- desc: '',
- topdesc: 'Just like texting with a close friend, you can now message your therapist every day, writing as many times as you want.',
- amt: '150.00',
- recur: 'Monthly',
- submitbutton: 'Start Therapy Now',
- disclaimer: 'Your subscription will begin when you click on the button above. To cancel, go to “settings” and click on “manage subscriptions” and cancel. By clicking the button above, you authorize us to continue your month to month 7 Cups subscription automatically at the rate of $150 USD/month.'
- };
- subs['onlinetherapy_monthly_15000_tr3'] = {
- planID: 'onlinetherapy_monthly_15000_tr3',
- modaltitle: 'Start Free Trial Now!',
- desc: '',
- topdesc: 'Just like texting with a close friend, you can now message your therapist every day, writing as many times as you want. And the first 3 days are free!',
- amt: '150.00',
- recur: 'Monthly',
- submitbutton: 'Start Therapy with 3 Day Trial',
- disclaimer: 'Your subscription, which starts with a 3 day (72 hour) free trial, will begin when you click on the button above. We will authorize your card, much like what happens when you check into a hotel room. Simply cancel anytime in the first 72 hours (3 days), and you will not be charged. To cancel, go to “settings” and click on “manage subscriptions” and cancel. By clicking the button above, you authorize us to continue your month to month 7 Cups subscription automatically at the rate of $150 USD/month.'
- };
- if(subs[planID]){
- var sub = subs[planID];
- }else{
- bootbox.alert('Error: Therapy plan not found.');
- return false;
- }
- var ccyears = [];
- var year = new Date().getFullYear();
- for (var i = 0; i < 15; i++) {
- ccyears.push(year + i);
- }
- if (typeof ga !== 'undefined') {
- ga('ec:setAction', 'checkout');
- }
- var form = 'SC_Forms_Payment_StripeSubscription2';
- var pt = 'Calmer days are ahead...';
- var ph = 'paymentHeader2.jpg';
- /*var ab = parseInt($.cookie('ab_fancyPaymentCopy'));
- if (ab == 1)
- pt = 'Let us help you find your peace...';
- else if (ab == 2)
- pt = 'Let the healing begin...';*/
- render(false, form, {paymentHeader: ph, paymentText: pt, ccyears: ccyears, sub: sub, ab_paymentpcode: ($.cookie('ab_paymentpcode')==true)}, function (content) {
- tracker.emit('OnlineTherapy', {step: 'loadcreditcard', uri: window.location.href, reqType: ChatSession.reqType});
- bootbox.dialog({
- className: "payment-details-modal",
- title: '<span style="font-size:1.5em" class="text-primary">'+sub.modaltitle+'</span>',
- message: content,
- onEscape: true,
- backdrop: true,
- closeButton: true
- }).off("shown.bs.modal").on("shown.bs.modal", function () {
- var $payModal = $(this);
- var $payForm = $(this).find(".stripe-payment-form");
- $payForm.find('[data-action="applypromo"]').on('click', function () {
- var btn = $(this);
- $payForm.find('.alert-danger').remove();
- btn.attr('data-html', function () {
- return $(this).html()
- }).attr('disabled', 'true').html('<i class="fa fa-spinner fa-spin"></i> Checking');
- $.post($payForm.attr('action'), {action: 'verifypromo', promo: $payForm.find('[name="promo"]').val(), planID: $payForm.find('[name="planID"]').val()}, function (resp) {
- if (resp.success) {
- if (resp.update) {
- for (var key in resp.update) {
- $payModal.find(key).replaceWith(resp.update[key]);
- }
- }
- } else {
- $payForm.prepend('<div class="alert alert-danger"><button type="button" class="close" data-dismiss="alert" aria-label="Close"><span aria-hidden="true">×</span></button>Invalid Promo Code</div>');
- btn.html(function () {
- return $(this).attr('data-html')
- }).removeAttr('disabled');
- }
- }, 'json');
- });
- $payForm.on('submit', function (event) {
- var submitCard = function () {
- $('.payment-details-modal').show();
- $('body').addClass('modal-open');
- //$payModal.modal('show');
- tracker.emit('OnlineTherapy', {step: 'creditcardsubmit', uri: window.location.href, reqType: ChatSession.reqType});
- $payForm.find('[name="stripeToken"], .alert').remove();
- $payForm.find('button[type="submit"]').attr("disabled", "disabled").attr("data-text", function () {
- return $(this).html();
- }).html('<i class="fa fa-spin fa-spinner"></i> Processing');
- var card = {
- number: $payForm.find("[data-stripe='number']").val(),
- cvc: $payForm.find("[data-stripe='cvc']").val(),
- exp_month: $payForm.find("[data-stripe='exp_month']").val(),
- exp_year: $payForm.find("[data-stripe='exp_year']").val()
- };
- Stripe.createToken(card, function(status, response) {
- if (response.error) {
- $payForm.find('button[type="submit"]').removeAttr("disabled").html(function () {
- return $(this).attr("data-text")
- });
- $payForm.prepend('<div class="alert alert-danger"><button type="button" class="close" data-dismiss="alert" aria-label="Close"><span aria-hidden="true">×</span></button>' + response.error.message + '</div>');
- } else {
- $payForm.append('<input type="hidden" name="stripeToken" value="' + response['id'] + '" />');
- if (!$payForm.find('[name="convID"]').length) {
- $payForm.append('<input type="hidden" name="convID" value="' + ChatSession.convID + '" />');
- }
- $.post($payForm.attr('action'), $payForm.serialize(), function (resp) {
- if (resp.success) {
- tracker.emit("OnlineTherapy", {step: 'completepayment', reqType: ChatSession.reqType});
- talkToNoni();
- if (typeof __adroll !== "undefined")
- try {
- __adroll.record_user({"adroll_segments": "9cb7fee1"})
- __adroll.record_user({product_id: "onlineTherapy", product_action: "Purchased"})
- } catch (e) { }
- if (typeof ga !== 'undefined' && resp.sub) {
- try {
- ga('ec:setAction', 'purchase', {
- 'id': resp.sub.subID,
- 'revenue': sub.amt
- });
- // Record Adwords conversion
- window.google_conversion_id = 991416627;
- window.google_conversion_label = "KjZ_CMnek3EQs6Lf2AM";
- window.google_remarketing_only = false;
- window.google_conversion_format = "3";
- var opt = new Object();
- opt.onload_callback = function() {
- console.log('Transaction Recorded');
- }
- var conv_handler = window['google_trackConversion'];
- if (typeof(conv_handler) == 'function')
- conv_handler(opt);
- } catch (e) { }
- }
- $payModal.modal('hide');
- } else {
- tracker.emit("OnlineTherapy", {step: 'paymentfail', reqType: ChatSession.reqType});
- if (resp.err && resp.err.copy) {
- for (e in resp.err.copy) {
- $payForm.prepend('<div class="alert alert-danger"><button type="button" class="close" data-dismiss="alert" aria-label="Close"><span aria-hidden="true">×</span></button>' + resp.err.copy[e] + '</div>');
- }
- }
- $payForm.find('button[type="submit"]').removeAttr("disabled").html(function () {
- return $(this).attr("data-text")
- });
- }
- }, 'json')
- }
- });
- }
- if (1 || window.confirmAuthorization){
- submitCard();
- } else {
- //$payModal.modal('hide');
- $('.payment-details-modal').hide();
- tracker.emit('OnlineTherapy', {step: 'creditcardconfirm', uri: window.location.href, reqType: ChatSession.reqType});
- bootbox.dialog({
- className: "payment-confirm-modal",
- message: "Please note: Your card will be authorized for the amount of the first payment and we release that authorization after we verify that the funds exist.",
- buttons: {
- confirm: {
- label: 'Connect me to my therapist',
- className: 'btn-success',
- callback: submitCard
- }
- },
- onEscape: function() {
- console.log('Dismissed');
- $('.payment-details-modal').show();
- $('body').addClass('modal-open');
- //$payModal.modal('show');
- }
- }).on('hidden.bs.modal', function () {
- $('.payment-details-modal').show();
- $('body').addClass('modal-open');
- });
- }
- return false;
- });
- });
- });
- });
- $('body').on('click', 'a[data-therapyaction="informedconsentstatic"]', function () {
- //tracker.emit("OnlineTherapy", {step: 'loadagreement', reqType: ChatSession.reqType});
- var param = JSON.parse($(this).attr('data-tparams'));
- render(false, 'SC_Forms_Connect_TherapistInformedConsentStatic', param, function (content) {
- bootbox.dialog({
- title: 'Online Therapy Agreement',
- message: content,
- onEscape: true,
- backdrop: true,
- closeButton: true,
- size: 'large'
- });
- });
- });
- $('body').on('click', 'button[data-therapyaction="informedconsent"]', function () {
- tracker.emit("OnlineTherapy", {step: 'loadagreement', reqType: ChatSession.reqType});
- if (autoMessageFunction) clearTimeout(autoMessageFunction);
- var param = JSON.parse($(this).attr('data-tparams'));
- render(false, 'SC_Forms_Connect_TherapistInformedConsent', param, function (content) {
- bootbox.dialog({
- title: 'Online Therapy Agreement',
- message: content,
- onEscape: true,
- backdrop: true,
- closeButton: true,
- size: 'large'
- }).off("shown.bs.modal").on("shown.bs.modal", function () {
- var $thisModal = $(this);
- $thisModal.find('[data-agree="true"]').on('click', function () {
- var $thisBtn = $(this);
- $thisModal.find('.modal-body .alert-danger').remove();
- $thisBtn.attr('data-html', function () {
- return $(this).html()
- }).attr("disabled", "disabled").html('<i class="fa fa-spin fa-spinner"></i> Processing');
- $.post('/connect/therapist_SignConsent.php', {convID: ChatSession.convID}, function (resp) {
- if (resp.err) {
- $thisModal.find('.modal-body').prepend('<div class="alert alert-danger">' + resp.err + '</div>')
- $thisBtn.removeAttr("disabled").html(function () {
- return $(this).attr('data-html')
- });
- } else {
- tracker.emit("OnlineTherapy", {step: 'completeagreement'});
- stopNoni = true;
- var s = parseInt((new Date()).getTime() - serverTimeOffset*1000);
- loadMessage({msgID: null,
- msgHash: randomHash(),
- msgBody: 'Thank you. You are now connected to your therapist. Start by saying "hello" or describing what brings you here in more detail.<br><br>Your therapist may not be available immediately, but will be in touch shortly. Thanks for being here!',
- msgTime: moment(s).format("h:mm A"),
- userTypeID: '0GKvccLHkpyGnA!!',
- screenName: currentNoni.screenName,
- userType: 'n',
- imgURL: currentNoni.imgURL,
- imageClass: currentNoni.imageClass,
- convSide: "other",
- convID: resp.convID});
- scrollConversation();
- $thisModal.modal('hide');
- /*
- setTimeout(function(){
- var s = parseInt((new Date()).getTime() - serverTimeOffset*1000);
- loadMessage({msgID: null,
- msgHash: randomHash(),
- msgBody: 'Your therapist may not be available immediately, but will be in touch shortly. While you are waiting, try taking this <button class="btn btn-sm btn-white" onclick="wellnessTestModal(\'sophia\');">free emotional wellness test</button> to learn more about yourself. You can share the results with your therapist.',
- msgTime: moment(s).format("h:mm A"),
- userTypeID: '0GKvccLHkpyGnA!!',
- screenName: currentNoni.screenName,
- userType: 'n',
- imgURL: currentNoni.imgURL,
- imageClass: currentNoni.imageClass,
- convSide: "other",
- convID: resp.convID});
- scrollConversation();
- }, 3000);*/
- }
- }, 'json');
- });
- });
- });
- });
- $('body').on('click', '#therapy-referral button', function () {
- $('#Comment').val('Have you considered seeing a therapist for your issue? I think it might be helpful for you. I\'m happy to keep chatting with you, but I would recommend that you also check out our 7 Cups therapists here: 7cups.com/online-therapy');
- bootbox.alert('<h3 class="text-center">We have inserted a referral into your message box. Just send it or edit it into your own words.</h3>');
- });
- });
- if (!isMobileApp()) {
- var soundOn = true;
- function setupConvSound() {
- // Delay execution until async scripts are downloaded
- if (typeof soundManager === 'undefined') {
- console.log('delayed');
- initTimer = setTimeout(setupConvSound, 25);
- return;
- }
- soundManager.setup({
- url: '/js/soundManager/swf/',
- flashVersion: 9, // optional: shiny features (default = 8)
- // optional: ignore Flash where possible, use 100% HTML5 mode
- // preferFlash: false,
- onready: function () {
- // Ready to use; soundManager.createSound() etc. can now be called.
- soundManager.createSound({
- id: 'newMessage',
- url: cloudfrontBase+'img/newMessage.mp3'
- });
- }
- });
- }
- setupConvSound();
- var chatExpanded = false;
- function expandChat() {
- chatExpanded = true;
- $('.chatRow').addClass('expanded');
- $('.right-hand-content').addClass('col-lg-9').removeClass('col-lg-7').addClass('col-lg-push-3').removeClass('col-lg-push-4');
- $('.left-hand-content').removeClass('col-lg-pull-6').addClass('col-lg-pull-9');
- $('.expandButton').hide();
- $('.shrinkButton').show();
- resizeChat();
- }
- function shrinkChat() {
- $('.chatRow').removeClass('expanded');
- $('.right-hand-content').removeClass('col-lg-9').addClass('col-lg-7').removeClass('col-lg-push-3').addClass('col-lg-push-4');
- $('.left-hand-content').addClass('col-lg-pull-6').removeClass('col-lg-pull-9');
- $('.expandButton').show();
- $('.shrinkButton').hide();
- chatExpanded = false;
- resizeChat();
- }
- function resizeChat() {
- if ($(window).width() <= 767) {
- setTimeout(function () {
- window.scrollTo(document.body.scrollLeft, document.body.scrollTop);
- }, 0);
- //var bottomBar = 0;
- //if ($('.bottomStatus').is(":visible"))
- //bottomBar = $('.bottomStatus').height();
- var chatHeight = $(window).height() - (chatExpanded ? 20 : 70);
- chatHeight -= (chatExpanded ? 8 : $('#bottomStatus').outerHeight());
- var banner = $('.upperChatBanner');
- if (banner.length)
- chatHeight -= banner.outerHeight();
- if (chatExpanded) {
- $('.chatBox').height($(window).height());
- $('.conversationBox').css('max-height', '');
- if (banner.length)
- banner.hide();
- } else {
- $('.chatBox').height(chatHeight);
- $('.conversationBox').css('max-height', chatHeight + 'px');
- if (banner.length)
- banner.show();
- }
- $('.chatBox .card-block').height($('.chatBox').outerHeight() - $('.chatInput').outerHeight() - $('#conversationHead').outerHeight());
- } else {
- setTimeout(function () {
- window.scrollTo(document.body.scrollLeft, document.body.scrollTop);
- }, 0);
- //var bottomBar = 0;
- //if ($('.bottomStatus').is(":visible"))
- //bottomBar = $('.bottomStatus').height();
- var chatHeight = $(window).height() - (chatExpanded ? 20 : 120);
- chatHeight -= (chatExpanded ? 8 : $('#bottomStatus').outerHeight());
- var banner = $('.upperChatBanner');
- if (banner.length)
- chatHeight -= banner.outerHeight();
- if (chatExpanded) {
- $('.chatBox').height($(window).height() -20);
- $('.conversationBox').css('max-height', '');
- if (banner.length)
- banner.hide();
- } else {
- $('.chatBox').height(chatHeight);
- $('.conversationBox').css('max-height', chatHeight + 'px');
- if (banner.length)
- banner.show();
- }
- $('.chatBox .card-block').height($('.chatBox').outerHeight() - $('.chatInput').outerHeight() - $('#conversationHead').outerHeight());
- }
- }
- $(function () {
- window.pageReady = true;
- if (!getQSval('c')) {
- $('#selectConvPrompt').show();
- }
- resizeChat();
- $('#bottomStatus').resize(function () {
- resizeChat();
- });
- $(window).resize(function () {
- resizeChat();
- });
- $('#chatForm').submit(function (e) {
- e.preventDefault();
- sendMessage();
- });
- //$(".resizableDiv").resizable({handles: 's', minHeight: 150});
- $('#getHelpButton').on('click', function () {
- tracker.emit("ClickChatHelpButton");
- if (ChatSession.user.age < 18) {
- setConversation('k2VowHPgmMxSy5k!');
- } else {
- setConversation('k2dmeXmbkuJO42uXh1iY');
- }
- });
- });
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement