Advertisement
Guest User

Untitled

a guest
Apr 8th, 2019
136
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 204.52 KB | None | 0 0
  1.  
  2. var ChatSession = {user: {}, otherUser: {}, tips: {}, me: null};
  3. var globalMuteArr = [];
  4. var someheartedyou, sendTypingStatus;
  5. var preloadingMessages = false;
  6. var autoMessageFunction = false;
  7. var chatInfoMemory = {};
  8. var serverTimeOffset = 0;
  9. var ecAdded = false;
  10.  
  11. if (isMobileApp()) {
  12. var bubbleTabR = cloudfrontBase + 'img/bubbleR.png';
  13. var bubbleTabL = cloudfrontBase + 'img/bubbleL.png';
  14. var bubbleTabN = cloudfrontBase + 'img/bubbleNoniL.png';
  15. } else {
  16. var bubbleTabR = cloudfrontBase + 'img/bubbleBorderR.png';
  17. var bubbleTabL = cloudfrontBase + 'img/bubbleBorderL.png';
  18. var bubbleTabN = cloudfrontBase + 'img/bubbleBorderNoniL.png';
  19. }
  20.  
  21. function isMobileApp() {
  22. return (typeof isApp !== 'undefined' && isApp) ? true : false;
  23. }
  24.  
  25. function randomHash() {
  26. var text = "";
  27. var possible = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
  28.  
  29. for (var i = 0; i < 32; i++) {
  30. text += possible.charAt(Math.floor(Math.random() * possible.length));
  31. }
  32. return text;
  33. }
  34.  
  35. function getQSval(name) {
  36. name = name.replace(/[\[]/, "\\[").replace(/[\]]/, "\\]");
  37. var regex = new RegExp("[\\?&]" + name + "=([^&#]*)"),
  38. results = regex.exec(location.search);
  39. return results == null ? "" : decodeURIComponent(results[1].replace(/\+/g, " "));
  40. }
  41.  
  42. function roomDiscussion(action) {
  43. if (action == 'end') {
  44. $.post('/connect/roomDiscussion.php', {action: action, convID: ChatSession.convID}, function (resp) {
  45. if (resp && resp.error) {
  46. alert(resp.error);
  47. }
  48. }, 'json');
  49. } else {
  50. var dmessage = '<form id="discussionStartForm">' +
  51. '<div class="form-group">' +
  52. '<label>Discussion Topic</label>' +
  53. '<input name="Topic" type="text" class="form-control" maxlength="50" />' +
  54. '</div>' +
  55. '<div class="form-group">' +
  56. '<label>Co-Leader (optional)</label>' +
  57. '<input name="coLeader" type="text" class="form-control" maxlength="50" />' +
  58. '</div>' +
  59. '<div class="form-group">' +
  60. '<label>Discussion Length</label>' +
  61. '<select name="lengthSecs" class="form-control">' +
  62. '<option value="900">15 Minutes</option>' +
  63. '<option value="1800">30 Minutes</option>' +
  64. '<option value="2700">45 Minutes</option>' +
  65. '<option value="3600">60 Minutes</option>' +
  66. '</select>' +
  67. '</div>' +
  68. '</form>';
  69.  
  70. bootbox.dialog({
  71. message: dmessage,
  72. title: 'Create Discussion',
  73. buttons: {
  74. success: {
  75. label: "Start Discussion",
  76. className: "btn-success",
  77. callback: function () {
  78. var pData = {
  79. action: action,
  80. convID: ChatSession.convID,
  81. coLeader: $('#discussionStartForm input[name="coLeader"]').val(),
  82. Topic: $('#discussionStartForm input[name="Topic"]').val(),
  83. lengthSecs: $('#discussionStartForm select[name="lengthSecs"]').val()
  84. };
  85.  
  86. $.post('/connect/roomDiscussion.php', pData, function (resp) {
  87. if (resp && resp.error) {
  88. alert(resp.error);
  89. }
  90. }, 'json');
  91. }
  92. }
  93. }
  94. });
  95. }
  96. }
  97.  
  98. window.botCommand = false;
  99.  
  100. function newBotGui (ChatSession, tree) {
  101.  
  102. var t = this;
  103. if (window.botGUIObj)
  104. window.botGUIObj.destroy();
  105.  
  106. window.botGUIObj = this;
  107. this.noniMenuButton = $('<div class="noniMenu"><img class="noniIcon" src="'+cloudfrontBase+'img/noni-menu.svg"></div>');
  108. 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>');
  109. this.menuArea = this.noniMenu.find('.innerArea');
  110. this.chatForm = $('#chatForm');
  111. this.comment = $('#Comment');
  112. this.updates = 0;
  113. this.itemCount = 0;
  114.  
  115. window.showNoniMenu = false;
  116.  
  117. this.destroy = function () {
  118. this.noniMenuButton.remove();
  119. this.noniMenu.remove();
  120. this.comment.off('keyup', this.processKey);
  121. window.botCommand = false;
  122. delete this;
  123.  
  124. this.chatForm.css('display', 'block');
  125. this.chatForm.css('width', '100%');
  126. window.botGUIObj = false;
  127. }
  128.  
  129. this.processKey = function () {
  130. var c = $("#Comment").val();
  131. if (!window.showNoniMenu && c.length && c[0] == '/') {
  132. t.toggleMenu();
  133. } else if (window.showNoniMenu) {
  134. t.updateMenu(c);
  135. }
  136. }
  137.  
  138. this.attach = function () {
  139. this.chatForm.css('display', 'inline-block');
  140. this.chatForm.css('width', 'calc(100% - 60px)');
  141.  
  142. this.noniMenuButton.insertBefore(this.chatForm);
  143. this.noniMenu.appendTo('.chatBox');
  144. this.noniMenu.css('display', 'none');
  145.  
  146. this.comment.on('keyup', this.processKey);
  147.  
  148. }
  149.  
  150. this.closeMenu = function () {
  151. window.showNoniMenu = 1;
  152. this.toggleMenu();
  153. }
  154.  
  155. this.toggleMenu = function () {
  156. if (window.showNoniMenu) {
  157. t.noniMenuButton.css('opacity', 1);
  158. t.noniMenu.css('display', 'none');
  159. window.showNoniMenu = 0;
  160. window.botCommand = false;
  161. } else {
  162. t.noniMenuButton.css('opacity', .3);
  163. t.noniMenu.css('display', 'block');
  164. window.showNoniMenu = 1;
  165. t.updates = 0;
  166. //t.comment.focus();
  167. t.updateMenu();
  168. }
  169. }
  170.  
  171. this.render = function () {
  172.  
  173. this.attach();
  174.  
  175. this.noniMenuButton.on('click', t.toggleMenu);
  176. }
  177.  
  178. t.updateMenu = function (filter) {
  179. this.menuArea.empty();
  180. this.itemCount = 0;
  181.  
  182. if (typeof filter === 'undefined')
  183. filter = (this.updates == 0 ? '' : this.comment.val()).toLowerCase();
  184.  
  185. if (filter.length && filter[0] == '/')
  186. filter = filter.substring(1);
  187.  
  188. this.updates++;
  189.  
  190. if (filter.length == 0)
  191. filter = false;
  192.  
  193. var lastCommand = false;
  194.  
  195. var pasteItem = function (item, child) {
  196. t.itemCount++;
  197. var menuItem = $('<div class="menuItem '+(child ? 'child' : '')+'">'+item.name+'</div>');
  198. lastCommand = item.trigger;
  199. menuItem.on('click', function () {
  200. resetState(item.trigger !== null ? item.trigger : '#'+item.code);
  201. sendMessage();
  202. });
  203. menuItem.appendTo(t.menuArea);
  204. }
  205.  
  206. for (var key in tree) {
  207. (function (item) {
  208. if (typeof item.children === 'undefined') {
  209. if (!filter || item.trigger.toLowerCase().indexOf(filter) !== -1 || item.code.toLowerCase().indexOf(filter) !== -1)
  210. pasteItem(item);
  211. } else {
  212. var pasteIt = pasteItAbove = (!filter ? true : false);
  213. if (filter && item.name.toLowerCase().indexOf(filter) !== -1)
  214. pasteItAbove = true;
  215.  
  216. for (var key2 in item.children) {
  217. if (item.children[key2].trigger.toLowerCase().indexOf(filter) !== -1 || item.children[key2].code.toLowerCase().indexOf(filter) !== -1) {
  218. pasteIt = true;
  219. break;
  220. }
  221. }
  222.  
  223. if (pasteIt || pasteItAbove) {
  224. var menuItem = $('<div>'+item.name+'</div>');
  225. menuItem.appendTo(t.menuArea);
  226. for (var key2 in item.children)
  227. if (pasteItAbove || !filter || item.children[key2].trigger.toLowerCase().indexOf(filter) !== -1 || item.children[key2].code.toLowerCase().indexOf(filter) !== -1)
  228. pasteItem(item.children[key2], true);
  229. }
  230. }
  231. })(tree[key]);
  232. }
  233.  
  234. window.botCommand = false;
  235. if (!t.itemCount)
  236. t.noniMenu.css('display', 'none');
  237. else {
  238. t.noniMenu.css('display', 'block');
  239.  
  240. if (t.itemCount == 1)
  241. window.botCommand = lastCommand;
  242. }
  243.  
  244. }
  245.  
  246. this.render();
  247.  
  248. }
  249.  
  250.  
  251.  
  252. function botGUI (ChatSession, tree) {
  253.  
  254. var t = this;
  255. this.level = 0;
  256. this.e = $('<div style="border-radius:8px;background-color:#fcfcfc;padding:8px;margin-top:4px"></div>');
  257. 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>');
  258.  
  259. this.destroy = function () {
  260. this.e.remove();
  261. this.e2.remove();
  262. delete this;
  263. }
  264.  
  265. this.attach = function () {
  266. $('#convListItem_'+ChatSession.convID).append(this.e);
  267. $('.chatBox').append(this.e2);
  268. }
  269.  
  270. this.render = function () {
  271. this.attach();
  272.  
  273. items = [], current = tree, d = $('<div></div>'), d2 = $('<div></div>');
  274. if (this.level != 0 && typeof tree[this.level] !== "undefined" && typeof tree[this.level].children !== "undefined") {
  275. current = tree[this.level].children;
  276. items.unshift({
  277. name: 'Back',
  278. goto: 0
  279. });
  280. }
  281.  
  282. for (var key in current)
  283. items.push(current[key]);
  284.  
  285. for (k = 0; k < items.length; k++) {
  286. (function (items, k) {
  287. var e = $('<span class="badge badge-pill '+(items[k].goto !== 0 ? 'badge-primary' : '')+'">'+items[k].name+'</span>');
  288. $(e).click(function (evt) {
  289. t.handleClick(items[k]);
  290. });
  291. d.append(e);
  292. })(items, k);
  293. (function (items, k) {
  294. var e = $('<span class="badge badge-pill badge-primary">'+items[k].name+'</span>');
  295. $(e).click(function (evt) {
  296. t.handleClick(items[k]);
  297. });
  298. d2.append(e);
  299. })(items, k);
  300. }
  301.  
  302. this.e.empty().append(d);
  303. this.e2.empty().append(d2);
  304. }
  305.  
  306. this.handleClick = function (item) {
  307. if (typeof item.goto !== "undefined") {
  308. this.level = item.goto;
  309. this.render();
  310. } else if (typeof item.children != "undefined") {
  311. this.level = item.id;
  312. this.render();
  313. } else {
  314. resetState(item.trigger !== null ? item.trigger : '#'+item.code);
  315. sendMessage();
  316. }
  317. };
  318.  
  319. this.render();
  320. }
  321.  
  322. function processTopic() {
  323.  
  324. function loadTopicHolder(show) {
  325. if (show) {
  326. if (!$('.chatBox .chatroomTopic').length) {
  327. $('#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>');
  328. $('#MessageScrollDivResize').css('padding-top', '31px');
  329. }
  330. } else {
  331. if ($('.chatBox .chatroomTopic').length) {
  332. $('.chatBox .chatroomTopic').remove();
  333. $('#MessageScrollDivResize').css('padding-top', '0');
  334. }
  335. }
  336. }
  337.  
  338. $('.chatBox .chatroomTopic .discussButton').remove();
  339. if (ChatSession.roomType) {
  340. if (ChatSession.discussion && ChatSession.discussion.Topic && ChatSession.discussion.endTime) {
  341. var hideTime = (parseInt(ChatSession.discussion.endTime) * 1000) - Date.now();
  342. if (window.hideTopic) {
  343. clearTimeout(window.hideTopic);
  344. }
  345.  
  346. if (hideTime > 0) {
  347. loadTopicHolder(true);
  348. $('.chatBox .chatroomTopic .chatTopic').html('Discussion: <strong>' + ChatSession.discussion.Topic + '</strong> ');
  349. window.hideTopic = setTimeout(function () {
  350. loadTopicHolder();
  351. }, hideTime);
  352. }
  353.  
  354. if (ChatSession.user.discussionLeader) {
  355. loadTopicHolder(true);
  356. $('.chatBox .chatroomTopic > div').append('<button class="btn btn-white btn-sm discussButton" onclick="roomDiscussion(\'end\');">End</button>');
  357. }
  358.  
  359. } else {
  360. if (ChatSession.user.discussionLeader) {
  361. loadTopicHolder(true);
  362. $('.chatBox .chatroomTopic .chatTopic').text('');
  363. $('.chatBox .chatroomTopic > div').append('<button class="btn btn-white btn-sm discussButton" onclick="roomDiscussion(\'start\');">Start Discussion</button>');
  364. } else {
  365. loadTopicHolder();
  366. }
  367. }
  368. } else {
  369. loadTopicHolder();
  370. }
  371. }
  372.  
  373. var lastSelectedConvID;
  374. var links = [];
  375. function setConversation(new_convID, refresh, bm) {
  376.  
  377. if (window.stateLocked)
  378. resetState();
  379.  
  380. lastSelectedConvID = new_convID;
  381. if (refresh || new_convID != ChatSession.convID) {
  382. $('#offlineMessageDiv').html('').removeClass('hide');
  383. $('#listenersInChatDiv').html('');
  384. $('#listenersInChatroomModal .modal-body').html('');
  385. $('#conversationHead span').html('Loading...');
  386. $('#MessageDiv').html('');
  387. $('#msgs-loading').show();
  388. $('#conversationListModal').modal('hide');
  389. $('[data-actionid=rateListenerButton]').hide();
  390.  
  391. sendTypingStatus = false;
  392. ChatSession.convID = null;
  393. ChatSession.lastMessage = -1;
  394. ChatSession.checkingMessNow = null;
  395. ChatSession.initialLoad = true;
  396. ChatSession.tips.shown = [];
  397.  
  398. delete window.ratingModal;
  399. delete ChatSession.goodExperience;
  400. $('[data-actionid=rateListenerButton]').hide();
  401.  
  402. $.post('/connect/getConversation.php', {c: new_convID, bm: bm, checkin: window.checkinID}, function (json) {
  403. processJSON(json);
  404. if (typeof (checkMessages) === 'function')
  405. checkMessages();
  406.  
  407. if (json.ack == 'success' && json.conv) {
  408. window.chatInfoMemory[userInfo.userIDe + new_convID] = window.chatInfoMemory[userInfo.userIDe + new_convID] || {};
  409. window.chatInfoMemory[userInfo.userIDe + new_convID].details = json;
  410. window.chatInfoMemory[userInfo.userIDe + new_convID].timestamp = Math.round(+new Date() / 1000);
  411.  
  412. chatInfoSortArr = [];
  413. $.each(window.chatInfoMemory, function (key, value) {
  414. chatInfoSortArr.push([key, value.timestamp, value])
  415. });
  416. chatInfoSortArr.sort(function (a, b) {
  417. return a[1] - b[1]
  418. });
  419. chatInfoSortArr = chatInfoSortArr.slice(-75);
  420.  
  421. window.chatInfoMemory = {};
  422. $.each(chatInfoSortArr, function (key, value) {
  423. window.chatInfoMemory[value[0]] = value[2];
  424. });
  425. }
  426. }, 'json');
  427.  
  428. var recentChat = JSON.parse(getLocal('recentChat')) || {};
  429. var currentTS = new Date().getTime();
  430. for (k in recentChat) {
  431. if(parseInt(recentChat[k])+(1000*60*60*24*3) < currentTS){
  432. delete recentChat[k];
  433. }
  434. }
  435. recentChat[new_convID] = currentTS;
  436. setLocal('recentChat', JSON.stringify(recentChat));
  437. }
  438.  
  439. function processJSON(json) {
  440. if (json.ack == 'error') {
  441. if (json.error && json.error == 'Please verify you are human') {
  442. //setting convID before captcha
  443. ChatSession.convID = lastSelectedConvID;
  444. showCaptcha();
  445. } else if(json.error && json.error == 'Engagement Checkin') {
  446. $('#conversationHead').html('Therapy Signup');
  447. $('#MessageDiv').html('Provide payment details to reconnect with your therapist.');
  448. $('#msgs-loading').hide();
  449.  
  450. if (typeof Stripe === 'undefined') {
  451. (function (e, t) {
  452. var n = t.createElement("script");
  453. n.type = "text/javascript";
  454. n.async = true;
  455. n.src = "https://js.stripe.com/v2/";
  456. var s = t.getElementsByTagName("script")[0];
  457. s.parentNode.insertBefore(n, s);
  458. })(window, document);
  459.  
  460. window.stripeInit = setInterval(function () {
  461. if (typeof Stripe !== 'undefined') {
  462. console.log('Stripe Initialized');
  463. Stripe.setPublishableKey(StripePublishableKey);
  464. clearInterval(window.stripeInit);
  465. window.libraryState += '-stripe-';
  466. }
  467. }, 100);
  468. }
  469.  
  470. var message = {funcProp: 'onlinetherapy_monthly_15000', promoCode: true};
  471. ChatSession.convID = json.conv.convID;
  472. handleBotCreditCard3(message);
  473. } else {
  474. $('#conversationHead').html('Error');
  475. $('#MessageDiv').html(json.error);
  476. $('#msgs-loading').hide();
  477. }
  478. } else if (json.ack == 'success' && json.conv && json.conv.convID && lastSelectedConvID === json.conv.convID) {
  479.  
  480. var OLDnodeRoom = ChatSession.nodeRoom;
  481. ChatSession.me = json.me;
  482. ChatSession.user = json.user;
  483. ChatSession.user.currentMessages = 0;
  484. ChatSession.init_numConvMessages = ChatSession.numConvMessages = parseInt(json.conv.numMsg);
  485. ChatSession.convID = json.conv.convID;
  486. ChatSession.nodeRoom = json.conv.nodeRoom;
  487. ChatSession.chatroomRules = json.conv.chatroomRules;
  488. ChatSession.numMsgListener = json.conv.numMsgListener;
  489. ChatSession.reqType = json.conv.reqType;
  490. ChatSession.reqStatus = json.conv.reqStatus;
  491. ChatSession.roomType = json.conv.chatRoomType;
  492. ChatSession.otherUser = {
  493. userType: json.conv.otherType,
  494. screenName: json.conv.otherScreenName
  495. };
  496.  
  497. if (json.conv.otherType == 'b') {
  498.  
  499. window.botMessageCount = 0;
  500. if (json.conv.currentBot)
  501. window.currentBot = json.conv.currentBot;
  502.  
  503. if (window.currentBot.replyToMode) {
  504.  
  505. tracker.emit("autoBotMessageView", {
  506. bot: window.currentBot.bot,
  507. botVersion: 2,
  508. mode: window.currentBot.replyToMode,
  509. stage: window.currentBot.replyToStage
  510. });
  511. }
  512.  
  513. if (json.conv.doEmptyPing) {
  514. window.botPing = setTimeout(function () {
  515. if (ChatSession.otherUser && ChatSession.otherUser.userType == 'b') {
  516. window.allowEmpty = true;
  517. $('#Comment').val('');
  518. sendMessage();
  519. }
  520. }, 1000);
  521. }
  522.  
  523. }
  524.  
  525. if (json.conv.otherType == 'b' && json.conv.botMenu && !window.suppressBotMenu) {
  526. window.botMenu = json.conv.botMenu;
  527. if (window.botInterface)
  528. window.botInterface.destroy();
  529.  
  530. if (window.botGUIObj)
  531. window.botGUIObj.destroy();
  532.  
  533. //window.botInterface = new botGUI(ChatSession, botMenu);
  534. window.botGUIObj = new newBotGui (ChatSession, botMenu);
  535.  
  536. } else if (json.conv.otherType != 'b') {
  537. if (window.botInterface) {
  538. window.botInterface.destroy();
  539. window.botInterface = false;
  540. }
  541. if (window.botGUIObj) {
  542. window.botGUIObj.destroy();
  543. window.botGUIObj = false;
  544. }
  545. }
  546.  
  547. if ('otherListType' in json.conv)
  548. ChatSession.otherUser.listType = json.conv.otherListType;
  549.  
  550. ChatSession.ratingPopped = (json.conv.ratingPopped && json.conv.ratingPopped > 0);
  551. delete ChatSession.tips.copy;
  552. delete ChatSession.privateMessagesSent;
  553. delete ChatSession.groupMessagesSent;
  554. delete ChatSession.discussion;
  555.  
  556. ChatSession.discussion = json.conv.discussion;
  557.  
  558. function addTo() {
  559.  
  560. // Delay execution until async scripts are downloaded
  561. if (typeof ListMessagesSocket.emit === 'undefined') {
  562. initTimer = setTimeout(addTo, 25);
  563. return;
  564. }
  565.  
  566.  
  567. if (OLDnodeRoom != ChatSession.nodeRoom) {
  568. ListMessagesSocket.emit('addToRooms', [ChatSession.nodeRoom]);
  569. if (OLDnodeRoom) {
  570. ListMessagesSocket.emit('leave', [OLDnodeRoom]);
  571. }
  572. }
  573. }
  574.  
  575. addTo();
  576.  
  577. if (!json.conv.chatRoomType) {
  578. sendTypingStatus = true;
  579.  
  580. if (ChatSession.user.userType == 'l') {
  581. 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") {
  582. $('#therapy-referral').slideDown();
  583. } else {
  584. $('#therapy-referral').slideUp();
  585. }
  586.  
  587. if (links.indexOf(json.conv.convID) == -1) {
  588. if (ChatSession.otherUser.userType == 'm')
  589. tracker.emit("Link_L_to_M", {convID: json.conv.convID});
  590. else if (ChatSession.otherUser.userType == 'l')
  591. tracker.emit("Link_L_to_L", {convID: json.conv.convID});
  592.  
  593. links.push(json.conv.convID);
  594. }
  595. }
  596.  
  597. if (json.conv.numMsg == 0) {
  598. listTips(0);
  599. }
  600. } else {
  601. $('#therapy-referral').slideUp();
  602. var nowUnix = Math.round(+new Date() / 1000);
  603. var newToRoomArr = $.cookie('newToRoom') ? JSON.parse($.cookie('newToRoom')) : {};
  604. if (!newToRoomArr[ChatSession.nodeRoom] || parseInt(newToRoomArr[ChatSession.nodeRoom]) > parseInt(nowUnix)) {
  605. 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});
  606. newToRoomArr[ChatSession.nodeRoom] = parseInt(nowUnix) - (60 * 60 * 24);
  607. newToRoomArr = JSON.stringify(newToRoomArr);
  608. $.cookie("newToRoom", newToRoomArr, {path: '/', expires: 1});
  609. ChatSession.roomLoadedToday = true;
  610. listTips(0);
  611. } else {
  612. delete ChatSession.roomLoadedToday;
  613. }
  614. }
  615. //$('#conversationHead').html(json.conv.otherScreenName);
  616. var name = '';
  617. var countryBlock = '';
  618.  
  619.  
  620.  
  621. if (json.conv.imgURL == null) {
  622. var img = '<div class="userImage" style="background-color:' + json.conv.otherUserColor + ';">' + json.conv.otherScreenName.substring(0, 2) + '</div>';
  623. } else {
  624. var img = '<div class="img-profile ' + json.conv.imageClass + '" style="background-image:url(\'' + json.conv.imgURL + '\');"></div>';
  625. }
  626.  
  627. if (json.conv.otherCountry) {
  628. countryBlock = '<img class="countryBlock" src="' + cloudfrontBase + 'img/countryFlags/' + json.conv.otherCountry.toLowerCase() + '.png" data-toggle="tooltip" title="' + json.conv.otherCountryFull + '" alt"' + json.conv.otherCountryFull + '" />';
  629. }
  630.  
  631. var screenName = '<span class="name">' + json.conv.otherScreenName + '</span>';
  632.  
  633. if (json.conv.reqStatus === 'request') {
  634. img = '<div class="headerImageBlock">' + img + '</div>';
  635. } else if (json.conv.otherType == 'l') {
  636. img = '<a class="headerImageBlock" data-usercard="' + json.conv.otherScreenName + '" href="/@' + json.conv.otherScreenName + '">' + img + countryBlock + '</a>';
  637. } else if (json.conv.otherType == 'm') {
  638. img = '<a class="headerImageBlock" data-usercard="' + json.conv.otherScreenName + '" href="/@' + json.conv.otherScreenName + '">' + img + countryBlock + '</a>';
  639. } else if (json.conv.otherType == 'b') {
  640. img = '<div class="headerImageBlock">'+img+'</div>';
  641. } else if (json.conv.otherType == 'g') {
  642. img = '<div class="headerImageBlock">' + img + countryBlock + '</div>';
  643. } else {
  644. img = '';
  645. screenName = json.conv.otherScreenName;
  646. }
  647.  
  648. $('#conversationHead').html(img + screenName);
  649.  
  650.  
  651. /*
  652. if (json.user.userType != 'l' && json.conv.numMsgUser == 0) {
  653. $('#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>');
  654. } else */
  655. if (json.conv.otherType == 'b') {
  656. $('#conversationStarter').hide();
  657. $('#MessageScrollDiv .alert').hide();
  658. $('#MessageScrollDiv .alert.alert-noni').show();
  659. } else if (json.user.userType == 'l' && json.conv.otherType != 'l' && json.conv.numMsgListener == 0) {
  660. $('#conversationStarter').html('<h3>Get the Conversation Started...</h3><p>Please introduce yourself and start by welcoming your member to 7 Cups of Tea.</p>');
  661. $('#MessageScrollDiv .alert').show();
  662. $('#MessageScrollDiv .alert.alert-noni').hide();
  663. } else {
  664. $('#conversationStarter').html('');
  665. $('#MessageScrollDiv .alert').show();
  666. $('#MessageScrollDiv .alert.alert-noni').hide();
  667. }
  668.  
  669. processTopic();
  670.  
  671. if (json.conv.chatRoomType) {
  672. soundOn = false;
  673. $('#MessageScrollDiv > .alert').hide();
  674. $('#blockConnectionButton').hide();
  675. $('#clearConversationButton').hide();
  676. $('#endLiveChatButton').hide();
  677. $('#getHelpButton').hide();
  678. showUnmuteButton();
  679. $('[href="#prevConListGroup"]').click();
  680. if (json.user.userType != 'l') {
  681. groupChatOrientation();
  682. }
  683. $('.headerTable .topLink').attr('href', '/conversations.php?show=GROUPSUPPORT');
  684.  
  685. } else if (json.conv.otherType == 'b') {
  686.  
  687. $('#unMuteButton').remove();
  688. $('#MessageScrollDiv > .alert').hide();
  689. $('#blockConnectionButton').hide();
  690. $('#getHelpButton').hide();
  691. $('#endLiveChatButton').hide();
  692.  
  693. soundOn = (parseInt(json.user.alertInConv) == 1) ? true : false;
  694.  
  695. } else {
  696. $('#unMuteButton').remove();
  697. $('#MessageScrollDiv > .alert').show();
  698. $('#blockConnectionButton').show();
  699. $('#clearConversationButton').show();
  700. $('#getHelpButton').show();
  701. soundOn = (parseInt(json.user.alertInConv) == 1) ? true : false;
  702.  
  703. if (json.user.userType == 'l' && json.conv.otherType == 'l') {
  704. $('#endLiveChatButton').hide();
  705. } else {
  706. $('#endLiveChatButton').show();
  707. }
  708. loadRatingModal();
  709. }
  710.  
  711. ChatSession.scrollDelay = 0;
  712.  
  713.  
  714.  
  715. if ((json.user.userType == 'g' && $.cookie("permaCreateAccount"))) {
  716. if (isMobileApp()) {
  717. $('#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>');
  718. } else {
  719. if (!$('#permCreateAcctButton').length) {
  720. $('#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>');
  721. }
  722. }
  723. } else if ($.cookie("permaCreateAccount")) {
  724. $.removeCookie("permaCreateAccount", {path: '/'});
  725. }
  726.  
  727. if (isMobileApp()) {
  728. if (json.conv.imgURL) {
  729. $('#otherUserImage').css('background-image', 'url(' + json.conv.imgURL + ')').show();
  730. } else {
  731. $('#otherUserImage').css('background-image', 'none').css('background-color', json.conv.otherUserColor).text(json.conv.otherScreenName.substring(0, 2)).show();
  732. }
  733. }
  734.  
  735. $('.activeConv').removeClass('activeConv');
  736. $('[id="convListItem_' + json.conv.convID + '"]').removeClass('newMsg').addClass('activeConv');
  737. window.convID = json.conv.convID;
  738. $('#chatForm').show();
  739. $('#selectConvPrompt').hide();
  740.  
  741. //Show Related Communities if Any
  742. if(json.conv.relatedCommunities && json.conv.relatedCommunities.length){
  743. $('[data-id="related-community-holder"]').html('<div class="card card-normal card-block subtle-box-shadow"><h6>Related Subcommunities</h6></div>');
  744. $.each(json.conv.relatedCommunities, function(idx, val){
  745. $('[data-id="related-community-holder"] > div.card').append('<a href="'+val.url+'" class="btn btn-primary btn-block text-left" >'+val.community_title+'</a>');
  746. });
  747. }else{
  748. $('[data-id="related-community-holder"]').empty();
  749. }
  750.  
  751. // Hide the delete messages forever button for therapy conversations
  752. if (ChatSession.reqType === 'personal_therapy' || ChatSession.reqType === 'general_therapy') {
  753. $('#clearConversationButton').hide();
  754. }
  755.  
  756. checkConv(ChatSession.convID);
  757. }
  758. }
  759. }
  760.  
  761. window.activeButton = false;
  762. window.activeButtonHash = false;
  763. window.lastPlace = $('#Comment').attr("placeholder");
  764. window.botDatum = false;
  765. window.selectData = false;
  766.  
  767. function enforceSelect () {
  768.  
  769. if (!window.selectData)
  770. resetState();
  771.  
  772. var commentPost = $('#Comment').val(), re = new RegExp('^'+commentPost.trim()+'$', "i");
  773. for (var i = 0; i < window.selectData.length; i++)
  774. if (re.test(window.selectData[i])) {
  775. $('#sendButton').fadeTo(0, 1);
  776. return;
  777. }
  778.  
  779. $('#sendButton').fadeTo(0, .5);
  780.  
  781. }
  782.  
  783. function setupSelect (data) {
  784. var isfocused = $('#Comment').is(":focus");
  785. var previousValue = $('#Comment').val();
  786. resetState();
  787. window.selectData = data;
  788.  
  789. if ($('#Comment').typeahead) {
  790. $('#Comment').typeahead(
  791. {
  792. hint:true,
  793. highlight:true,
  794. minLength: 1
  795. },
  796. {
  797. name: 'ttdata',
  798. limit: 100,
  799. source: taSubstringMatcher(data)
  800. }
  801. ).on('typeahead:select', sendMessage);
  802. }
  803.  
  804. $('#Comment').on('keyup', enforceSelect);
  805. if (isfocused) {
  806. $('#Comment').focus();
  807. setTimeout(function() {
  808. $('#Comment').focus();
  809. },250);
  810. }
  811. $('#Comment').val(previousValue);
  812.  
  813. enforceSelect();
  814. }
  815.  
  816. function lockState (disableMenu) {
  817. window.botDatum = false;
  818. window.selectData = false;
  819. $('#Comment').unbind("keyup", resetChatBox);
  820. $('#Comment').unbind("keyup", enforceSelect);
  821. $('#Comment').off('typeahead:selected');
  822.  
  823.  
  824. window.stateLocked = true;
  825. window.lastPlace = $('#Comment').attr("placeholder") ? $('#Comment').attr("placeholder") : window.lastPlace;
  826. $('#Comment').blur().attr("disabled", true).attr("placeholder", "").val('');
  827. $('#sendButton').fadeTo(0, .5);
  828.  
  829. if (disableMenu)
  830. $('.noniMenu').fadeTo(0, .5).off('click');
  831. }
  832.  
  833. function resetState (comment) {
  834.  
  835. window.selectData = false;
  836. window.botDatum = false;
  837. $('#Comment').unbind("keyup", resetChatBox);
  838. $('#Comment').unbind("keyup", enforceSelect);
  839. $('#Comment').off('typeahead:selected');
  840. if ($('#Comment').typeahead) {
  841. var isfocused = $('#Comment').is(":focus");
  842. $('#Comment').typeahead("destroy");
  843.  
  844. if (isfocused) {
  845. setTimeout(function() {
  846. $('#Comment').focus();
  847. },250);
  848. $('#Comment').focus();
  849. }
  850.  
  851. }
  852.  
  853. window.stateLocked = false;
  854. $('#Comment').attr("disabled", false).attr("placeholder", window.lastPlace);
  855. if (typeof comment !== 'undefined')
  856. $('#Comment').val(comment);
  857.  
  858. $('#sendButton').fadeTo(0, 1);
  859. if (window.activeButtonHash) {
  860. removeMessage(window.activeButtonHash);
  861. window.activeButtonHash = false;
  862. window.activeButton = false;
  863. }
  864.  
  865. if (window.botGUIObj)
  866. window.botGUIObj.closeMenu();
  867.  
  868. if (window.botPing)
  869. clearTimeout(window.botPing);
  870. }
  871.  
  872. function handleBotCreditCard (message, row) {
  873.  
  874. if ($.cookie('ab_smartSophiaTest1') == "oldPayment") {
  875. handleBotCreditCard2(message, row);
  876. return;
  877. }
  878.  
  879. tracker.emit("OnlineTherapy", {step: 'loadpayment', reqType: "general_therapy"});
  880.  
  881. if (window.activeButton > parseInt(message.msgID)) {
  882. // Remove any old function button in memory or otherwise
  883. removeMessage(message.msgHash);
  884. return;
  885. }
  886. console.log('[LOCK] Creating payment form', message.msgID);
  887.  
  888. lockState();
  889.  
  890. window.activeButton = parseInt(message.msgID);
  891. window.activeButtonHash = message.msgHash;
  892.  
  893. $('#MessageDiv button[data-func]').each(function() {
  894. var parent = $(this).closest('div.convRow');
  895. var id = $(parent).attr('id');
  896.  
  897. removeMessage(id.split('_')[1]);
  898. });
  899.  
  900. $('#message_'+message.msgHash+' .youArea').empty(); render($('#message_'+message.msgHash+' .youArea'), 'Forms_Payment_CreditCard', {sub: {submitbutton: "Continue"}}, function (form) {
  901.  
  902. var $payForm = form;
  903.  
  904. if (!window.stateLocked) {
  905. console.log('State has been reset. Removing payment');
  906. removeMessage(message.msgHash);
  907. window.activeButtonHash = false;
  908. window.activeButton = false;
  909. return;
  910. } else
  911. console.log('[RENDER] Creating payment form', message.msgID);
  912.  
  913. tracker.emit('OnlineTherapy', {step: 'loadcreditcard', uri: window.location.href, reqType: "general_therapy"});
  914.  
  915. form.find('.card-js').CardJs();
  916. var submit = form.find("button");
  917.  
  918. $payForm.on('submit', function (event) {
  919. tracker.emit('OnlineTherapy', {step: 'creditcardsubmit', uri: window.location.href, reqType: "general_therapy"});
  920. event.preventDefault();
  921. submit.attr("disabled", "disabled")
  922. form.find(".stripe-errors").hide();
  923. Stripe.card.createToken(form, function(status, response) {
  924. if (response.error) {
  925. form.find(".stripe-errors").text(response.error.message).show();
  926. submit.removeAttr("disabled");
  927. } else {
  928.  
  929. $payForm.append('<input type="hidden" name="stripeToken" value="' + response['id'] + '" />');
  930. if (!$payForm.find('[name="convID"]').length)
  931. $payForm.append('<input type="hidden" name="convID" value="' + ChatSession.convID + '" />');
  932. $payForm.append('<input type="hidden" name="planID" value="' + message.funcProp + '" />');
  933.  
  934. $.post("/ajax/processSubscription.php", $payForm.serialize(), function (resp) {
  935. if (resp.success) {
  936. tracker.emit("OnlineTherapy", {step: 'completepayment', reqType: "general_therapy"});
  937. resetState();
  938. window.allowEmpty = true;
  939. $('#Comment').val('');
  940. sendMessage();
  941.  
  942. if (typeof ga !== 'undefined' && resp.sub) {
  943. try {
  944.  
  945. ga('ec:setAction', 'purchase', {
  946. 'id': resp.sub.subID,
  947. 'revenue': sub.amt
  948. });
  949.  
  950. // Record Adwords conversion
  951. window.google_conversion_id = 991416627;
  952. window.google_conversion_label = "KjZ_CMnek3EQs6Lf2AM";
  953. window.google_remarketing_only = false;
  954. window.google_conversion_format = "3";
  955. var opt = new Object();
  956. opt.onload_callback = function() {
  957. console.log('Transaction Recorded');
  958. }
  959. var conv_handler = window['google_trackConversion'];
  960. if (typeof(conv_handler) == 'function')
  961. conv_handler(opt);
  962.  
  963. } catch (e) { }
  964. }
  965.  
  966.  
  967. $payForm.closest('.convRow').remove();
  968. } else {
  969.  
  970. if (resp.err && resp.err.copy) {k
  971. for (e in resp.err.copy) {
  972. $payForm.prepend('<div class="alert alert-danger"><button type="button" class="close" data-dismiss="alert" aria-label="Close"><span aria-hidden="true">&times;</span></button>' + resp.err.copy[e] + '</div>');
  973. }
  974. tracker.emit("OnlineTherapy", {message: resp.err.copy, step: 'paymentfail', reqType: "general_therapy"});
  975. } else
  976. tracker.emit("OnlineTherapy", {step: 'paymentfail', reqType: "general_therapy"});
  977.  
  978.  
  979.  
  980.  
  981. }
  982. }, 'json');
  983.  
  984.  
  985. }
  986. });
  987.  
  988. });
  989. });
  990.  
  991. }
  992.  
  993. function handleBotCreditCard4 (button) {
  994.  
  995. try {
  996. var payload = JSON.parse($(button).data('payload'));
  997. } catch (e) {
  998. var payload = false;
  999. }
  1000.  
  1001.  
  1002. if (!payload) {
  1003. $('#MessageDiv button[data-func]').each(function() {
  1004. var parent = $(this).closest('div.convRow');
  1005. var id = $(parent).attr('id');
  1006.  
  1007. removeMessage(id.split('_')[1]);
  1008. });
  1009.  
  1010. return;
  1011. }
  1012.  
  1013.  
  1014. handleBotCreditCard2(payload);
  1015. }
  1016.  
  1017.  
  1018. $('body').on('click', 'button[data-therapyaction="signupform"]', function () {
  1019. tracker.emit("OnlineTherapy", {step: 'loadmoreinfo', reqType: ChatSession.reqType});
  1020. if (autoMessageFunction) clearTimeout(autoMessageFunction);
  1021. $.ajax({
  1022. type: 'GET',
  1023. url: '/inc/local.php',
  1024. async: false,
  1025. contentType: "application/json",
  1026. dataType: 'jsonp',
  1027. data: {return: 'local'},
  1028. success: function (json) {
  1029. //tracker.emit("debugUserinfo", {step: 'localLoaded'});
  1030.  
  1031. if (typeof ga !== 'undefined') {
  1032. ga('ec:addProduct', {
  1033. 'id': 'onlinetherapy',
  1034. 'name': 'Online Therapy',
  1035. 'price': '150.00',
  1036. 'category': 'therapy',
  1037. 'brand': '7 Cups',
  1038. 'position': 1,
  1039. });
  1040. }
  1041.  
  1042. function padDigits(number, digits) {
  1043. return Array(Math.max(digits - String(number).length + 1, 0)).join(0) + number;
  1044. }
  1045.  
  1046. var param = {};
  1047. param.dob = {year: [], month: [], day: []};
  1048. param.states = json.states;
  1049. param.countries = json.countries;
  1050.  
  1051. var curyear = new Date().getFullYear();
  1052. for (var i = curyear - 5; i >= curyear - 110; i--) {
  1053. param.dob.year.push(i);
  1054. }
  1055.  
  1056. for (var i = 1; i <= 31; i++) {
  1057. param.dob.day.push(padDigits(i, 2));
  1058. }
  1059.  
  1060. var monthNames = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"];
  1061. for (var i = 0; i < 12; i++) {
  1062. param.dob.month.push({val: padDigits(i + 1, 2), disp: monthNames[i]});
  1063. }
  1064.  
  1065. param.convID = ChatSession.convID;
  1066. if (!($.cookie("mid") || $.cookie("lid"))) {
  1067. param.showLogin = true;
  1068. } else {
  1069. param.showLogin = false;
  1070. }
  1071. // param.showLogin = userInfo.userType === 'g';
  1072. if (typeof window.eventDetails !== 'undefined' && window.eventDetails.screenName)
  1073. param.screenName = window.eventDetails.screenName;
  1074. else
  1075. param.screenName = '';
  1076.  
  1077. var form = 'SC_Forms_OnlineTherapy_PersonalInfo2';
  1078.  
  1079. //tracker.emit("debugUserinfo", {step: 'localProcessed'});
  1080.  
  1081. render(false, form, param, function (content) {
  1082. //tracker.emit("debugUserinfo", {step: 'HB Rendered'});
  1083.  
  1084. bootbox.dialog({
  1085. title: 'Personal Information',
  1086. size: 'large',
  1087. message: content,
  1088. onEscape: true,
  1089. backdrop: true,
  1090. closeButton: true
  1091. }).off("shown.bs.modal").on("shown.bs.modal", function () {
  1092. //tracker.emit("debugUserinfo", {step: 'HB Displayed'});
  1093.  
  1094. var $mod = $(this);
  1095. var $form = $mod.find('form');
  1096.  
  1097. $form.find('[name="memberacct"]').on('change', function () {
  1098. $form.find('div.tab-pane.active').removeClass('active');
  1099. $form.find('div.tab-pane[data-tab="account-' + $form.find('[name="memberacct"]:checked').val() + '"]').addClass('active');
  1100. });
  1101.  
  1102.  
  1103. $form.find('select[name="addCountry"]').on('change', function() {
  1104. if ($(this).val() == 'US')
  1105. $form.find('select[name="addState"]').parent().show();
  1106. else
  1107. $form.find('select[name="addState"]').parent().hide();
  1108.  
  1109. });
  1110.  
  1111.  
  1112. $form.on('submit', function () {
  1113.  
  1114. $form.find('.alert,.text-danger').remove();
  1115. $form.find('.has-error').removeClass('has-error');
  1116. $form.find('button[type="submit"]').attr("disabled", "disabled").attr("data-html", function () {
  1117. return $(this).html()
  1118. }).html('<i class="fa fa-spin fa-spinner"></i> Processing');
  1119.  
  1120. $.post('/connect/therapist_ConsentTreatment.php', $form.serialize(), function (resp) {
  1121. if (resp.success) {
  1122. tracker.emit("OnlineTherapy", {step: 'completemoreinfo', reqType: ChatSession.reqType});
  1123. if (typeof __adroll !== "undefined") {
  1124. try {
  1125. __adroll.record_user({"adroll_segments": "52091a73"});
  1126. if (['US', 'GB', 'CA'].indexOf($form.find('select[name="addCountry"]').val()) !== -1)
  1127. __adroll.record_user({"adroll_segments": "23ddcaa1"});
  1128. } catch(err) {}
  1129. }
  1130.  
  1131. if (resp.refresh) {
  1132. // Allow tracking to happen
  1133. setTimeout(function () {
  1134. window.location.href = '/member/connect/conversation.php?c=' + resp.refresh + '&ht=1';
  1135. },25);
  1136. } else {
  1137. talkToNoni();
  1138. $mod.modal('hide');
  1139. }
  1140. } else if (resp.err) {
  1141. for (var key in resp.err) {
  1142. if (key == 'copy') {
  1143. for (var e = 0; e < resp.err.copy.length; e++) {
  1144. $form.prepend('<div class="alert alert-danger">' + resp.err.copy[e] + '</div>');
  1145. }
  1146. } else {
  1147. $form.find('[name="' + key + '"]').closest('.form-group').addClass('has-error');
  1148. if (resp.err[key] != 'Required') {
  1149. $form.find('[name="' + key + '"]').closest('.form-group').append('<div class="text-danger"><small>' + resp.err[key] + '</small></div>');
  1150. }
  1151. }
  1152. }
  1153. $form.find('button[type="submit"]').removeAttr("disabled").html(function () {
  1154. return $(this).attr("data-html")
  1155. });
  1156. }
  1157. }, 'json');
  1158. return false;
  1159. });
  1160. });
  1161. });
  1162. }
  1163. });
  1164. });
  1165.  
  1166.  
  1167.  
  1168.  
  1169. function personalDetails (message, row) {
  1170.  
  1171. bootbox.hideAll();
  1172.  
  1173. if (window.activeButton > parseInt(message.msgID)) {
  1174. // Remove any old function button in memory or otherwise
  1175. removeMessage(message.msgHash);
  1176. return;
  1177. }
  1178.  
  1179. window.activeButton = parseInt(message.msgID);
  1180. window.activeButtonHash = message.msgHash;
  1181.  
  1182.  
  1183. lockState();
  1184.  
  1185. tracker.emit("OnlineTherapy", {step: 'loadmoreinfo', reqType: ChatSession.reqType});
  1186. if (autoMessageFunction) clearTimeout(autoMessageFunction);
  1187. $.ajax({
  1188. type: 'GET',
  1189. url: '/inc/local.php',
  1190. async: false,
  1191. contentType: "application/json",
  1192. dataType: 'jsonp',
  1193. data: {return: 'local'},
  1194. success: function (json) {
  1195. //tracker.emit("debugUserinfo", {step: 'localLoaded'});
  1196.  
  1197. if (typeof ga !== 'undefined') {
  1198. ga('ec:addProduct', {
  1199. 'id': 'onlinetherapy',
  1200. 'name': 'Online Therapy',
  1201. 'price': '150.00',
  1202. 'category': 'therapy',
  1203. 'brand': '7 Cups',
  1204. 'position': 1,
  1205. });
  1206. }
  1207.  
  1208. function padDigits(number, digits) {
  1209. return Array(Math.max(digits - String(number).length + 1, 0)).join(0) + number;
  1210. }
  1211.  
  1212. var param = {};
  1213. param.dob = {year: [], month: [], day: []};
  1214. param.states = json.states;
  1215. param.countries = json.countries;
  1216.  
  1217. var curyear = new Date().getFullYear();
  1218. for (var i = curyear - 5; i >= curyear - 110; i--) {
  1219. param.dob.year.push(i);
  1220. }
  1221.  
  1222. for (var i = 1; i <= 31; i++) {
  1223. param.dob.day.push(padDigits(i, 2));
  1224. }
  1225.  
  1226. var monthNames = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"];
  1227. for (var i = 0; i < 12; i++) {
  1228. param.dob.month.push({val: padDigits(i + 1, 2), disp: monthNames[i]});
  1229. }
  1230.  
  1231. param.convID = ChatSession.convID;
  1232. if (!($.cookie("mid") || $.cookie("lid"))) {
  1233. param.showLogin = true;
  1234. } else {
  1235. param.showLogin = false;
  1236. }
  1237.  
  1238. // param.showLogin = userInfo.userType === 'g';
  1239. if (typeof window.eventDetails !== 'undefined' && window.eventDetails.screenName)
  1240. param.screenName = window.eventDetails.screenName;
  1241. else
  1242. param.screenName = '';
  1243.  
  1244. var form = 'SC_Forms_OnlineTherapy_PersonalInfo2';
  1245.  
  1246. //tracker.emit("debugUserinfo", {step: 'localProcessed'});
  1247.  
  1248. render(false, form, param, function (content) {
  1249. //tracker.emit("debugUserinfo", {step: 'HB Rendered'});
  1250.  
  1251. bootbox.dialog({
  1252. title: 'Personal Information',
  1253. size: 'large',
  1254. message: content,
  1255. onEscape: true,
  1256. backdrop: true,
  1257. closeButton: true
  1258. }).off("shown.bs.modal").on("shown.bs.modal", function () {
  1259. //tracker.emit("debugUserinfo", {step: 'HB Displayed'});
  1260.  
  1261. var $mod = $(this);
  1262. var $form = $mod.find('form');
  1263.  
  1264. $form.find('[name="memberacct"]').on('change', function () {
  1265. $form.find('div.tab-pane.active').removeClass('active');
  1266. $form.find('div.tab-pane[data-tab="account-' + $form.find('[name="memberacct"]:checked').val() + '"]').addClass('active');
  1267. });
  1268.  
  1269.  
  1270. $form.find('select[name="addCountry"]').on('change', function() {
  1271. if ($(this).val() == 'US')
  1272. $form.find('select[name="addState"]').parent().show();
  1273. else
  1274. $form.find('select[name="addState"]').parent().hide();
  1275.  
  1276. });
  1277.  
  1278.  
  1279. $form.on('submit', function () {
  1280.  
  1281. $form.find('.alert,.text-danger').remove();
  1282. $form.find('.has-error').removeClass('has-error');
  1283. $form.find('button[type="submit"]').attr("disabled", "disabled").attr("data-html", function () {
  1284. return $(this).html()
  1285. }).html('<i class="fa fa-spin fa-spinner"></i> Processing');
  1286.  
  1287. $.post('/connect/therapist_ConsentTreatment.php', $form.serialize(), function (resp) {
  1288. if (resp.success) {
  1289. tracker.emit("OnlineTherapy", {step: 'completemoreinfo', reqType: ChatSession.reqType});
  1290. fbq('track', 'CompleteRegistration');
  1291.  
  1292. if (typeof __adroll !== "undefined") {
  1293. try {
  1294. __adroll.record_user({"adroll_segments": "52091a73"});
  1295. if (['US', 'GB', 'CA'].indexOf($form.find('select[name="addCountry"]').val()) !== -1)
  1296. __adroll.record_user({"adroll_segments": "23ddcaa1"});
  1297. } catch(err) {}
  1298. }
  1299.  
  1300. if (resp.refresh) {
  1301. // Allow tracking to happen
  1302. setTimeout(function () {
  1303. window.location.href = '/member/connect/conversation.php?c=' + resp.refresh + '&ht=1';
  1304. },25);
  1305. } else {
  1306. bootbox.hideAll();
  1307. resetState();
  1308. window.allowEmpty = true;
  1309. $('#Comment').val('');
  1310. sendMessage();
  1311. }
  1312. } else if (resp.err.stateUnavailable) {
  1313. $('.modal').on('hidden.bs.modal', function () {
  1314. window.location = '/BrowseListeners/';
  1315. });
  1316. $('.modal-title').text('Therapy Unavailable');
  1317. $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>');
  1318. } else if (resp.err) {
  1319. for (var key in resp.err) {
  1320. if (key == 'copy') {
  1321. for (var e = 0; e < resp.err.copy.length; e++) {
  1322. $form.prepend('<div class="alert alert-danger">' + resp.err.copy[e] + '</div>');
  1323. }
  1324. } else {
  1325. $form.find('[name="' + key + '"]').closest('.form-group').addClass('has-error');
  1326. if (resp.err[key] != 'Required') {
  1327. $form.find('[name="' + key + '"]').closest('.form-group').append('<div class="text-danger"><small>' + resp.err[key] + '</small></div>');
  1328. }
  1329. }
  1330. }
  1331. $form.find('button[type="submit"]').removeAttr("disabled").html(function () {
  1332. return $(this).attr("data-html")
  1333. });
  1334. }
  1335. }, 'json');
  1336. return false;
  1337. });
  1338. });
  1339. });
  1340. }
  1341. });
  1342. }
  1343.  
  1344.  
  1345.  
  1346. function handleBotCreditCard2 (message, row) {
  1347.  
  1348.  
  1349. if ($.cookie('ab_smartSophiaTest2') == "oldForm") {
  1350. } else {
  1351. handleBotCreditCard3(message, row);
  1352. return;
  1353. }
  1354.  
  1355.  
  1356. bootbox.hideAll();
  1357.  
  1358. if (window.activeButton > parseInt(message.msgID)) {
  1359. // Remove any old function button in memory or otherwise
  1360. removeMessage(message.msgHash);
  1361. return;
  1362. }
  1363.  
  1364. window.activeButton = parseInt(message.msgID);
  1365. window.activeButtonHash = message.msgHash;
  1366. lockState();
  1367.  
  1368. var reqType="general_therapy";
  1369. var planID = message.funcProp;
  1370. tracker.emit("OnlineTherapy", {step: 'loadpayment', reqType: reqType});
  1371. stopAutoPing ();
  1372. if (autoMessageFunction) clearTimeout(autoMessageFunction);
  1373. var subs = {};
  1374.  
  1375.  
  1376. if (typeof __adroll !== "undefined") {
  1377. try {
  1378. __adroll.record_user({"adroll_segments": "13b73f15"})
  1379. } catch(err) {}
  1380.  
  1381.  
  1382. try {
  1383. __adroll.record_user({product_id: "onlineTherapy", product_action: "AddToCart"})
  1384. } catch (e) { }
  1385. }
  1386.  
  1387.  
  1388. subs['onlinetherapy_monthly_15000'] = {
  1389. planID: 'onlinetherapy_monthly_15000',
  1390. modaltitle: 'Get Started!',
  1391. desc: '',
  1392. topdesc: 'Just like texting with a close friend, you can now message your therapist every day, writing as many times as you want.',
  1393. amt: '150.00',
  1394. recur: 'Monthly',
  1395. submitbutton: 'Start Therapy Now',
  1396. disclaimer: 'Your subscription will begin when you click on the button above. To cancel, go to &ldquo;settings&rdquo; and click on &ldquo;manage subscriptions&rdquo; 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.'
  1397. };
  1398.  
  1399. subs['onlinetherapy_monthly_15000_tr3'] = {
  1400. planID: 'onlinetherapy_monthly_15000_tr3',
  1401. modaltitle: 'Start Free Trial Now!',
  1402. desc: '',
  1403. 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!',
  1404. amt: '150.00',
  1405. recur: 'Monthly',
  1406. submitbutton: 'Start Therapy with 3 Day Trial',
  1407. 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 &ldquo;settings&rdquo; and click on &ldquo;manage subscriptions&rdquo; 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.'
  1408. };
  1409.  
  1410. if(subs[planID]){
  1411. var sub = subs[planID];
  1412. }else{
  1413. bootbox.alert('Error: Therapy plan not found.');
  1414. return false;
  1415. }
  1416.  
  1417. var ccyears = [];
  1418. var year = new Date().getFullYear();
  1419. for (var i = 0; i < 15; i++) {
  1420. ccyears.push(year + i);
  1421. }
  1422.  
  1423. if (typeof ga !== 'undefined') {
  1424. ga('ec:setAction', 'checkout');
  1425. }
  1426.  
  1427. var form = 'SC_Forms_Payment_StripeSubscription2';
  1428. var pt = 'Calmer days are ahead...';
  1429. var ph = 'paymentHeader2.jpg';
  1430.  
  1431. render(false, form, {paymentHeader: ph, paymentText: pt, ccyears: ccyears, sub: sub, ab_paymentpcode: ($.cookie('ab_paymentpcode')==true)}, function (content) {
  1432. tracker.emit('OnlineTherapy', {step: 'loadcreditcard', uri: window.location.href, reqType: reqType});
  1433. fbq('track', 'AddPaymentInfo');
  1434.  
  1435. bootbox.dialog({
  1436. className: "payment-details-modal",
  1437. title: '<span style="font-size:1.5em" class="text-primary">'+sub.modaltitle+'</span>',
  1438. message: content,
  1439. onEscape: true,
  1440. backdrop: true,
  1441. closeButton: true
  1442. }).off("shown.bs.modal").on("shown.bs.modal", function () {
  1443. var $payModal = $(this);
  1444. var $payForm = $(this).find(".stripe-payment-form");
  1445.  
  1446. $payForm.find('[data-action="applypromo"]').on('click', function () {
  1447. var btn = $(this);
  1448. $payForm.find('.alert-danger').remove();
  1449. btn.attr('data-html', function () {
  1450. return $(this).html()
  1451. }).attr('disabled', 'true').html('<i class="fa fa-spinner fa-spin"></i> Checking');
  1452. $.post($payForm.attr('action'), {action: 'verifypromo', promo: $payForm.find('[name="promo"]').val(), planID: $payForm.find('[name="planID"]').val()}, function (resp) {
  1453. if (resp.success) {
  1454. if (resp.update) {
  1455. for (var key in resp.update) {
  1456. $payModal.find(key).replaceWith(resp.update[key]);
  1457. }
  1458. }
  1459. } else {
  1460. $payForm.prepend('<div class="alert alert-danger"><button type="button" class="close" data-dismiss="alert" aria-label="Close"><span aria-hidden="true">&times;</span></button>Invalid Promo Code</div>');
  1461. btn.html(function () {
  1462. return $(this).attr('data-html')
  1463. }).removeAttr('disabled');
  1464. }
  1465. }, 'json');
  1466. });
  1467.  
  1468. $payForm.on('submit', function (event) {
  1469.  
  1470. var submitCard = function () {
  1471. $('.payment-details-modal').show();
  1472. $('body').addClass('modal-open');
  1473. //$payModal.modal('show');
  1474. tracker.emit('OnlineTherapy', {step: 'creditcardsubmit', uri: window.location.href, reqType: reqType});
  1475. $payForm.find('[name="stripeToken"], .alert').remove();
  1476. $payForm.find('button[type="submit"]').attr("disabled", "disabled").attr("data-text", function () {
  1477. return $(this).html();
  1478. }).html('<i class="fa fa-spin fa-spinner"></i> Processing');
  1479. var card = {
  1480. number: $payForm.find("[data-stripe='number']").val(),
  1481. cvc: $payForm.find("[data-stripe='cvc']").val(),
  1482. exp_month: $payForm.find("[data-stripe='exp_month']").val(),
  1483. exp_year: $payForm.find("[data-stripe='exp_year']").val()
  1484. };
  1485. Stripe.createToken(card, function(status, response) {
  1486. if (response.error) {
  1487. $payForm.find('button[type="submit"]').removeAttr("disabled").html(function () {
  1488. return $(this).attr("data-text")
  1489. });
  1490. $payForm.prepend('<div class="alert alert-danger"><button type="button" class="close" data-dismiss="alert" aria-label="Close"><span aria-hidden="true">&times;</span></button>' + response.error.message + '</div>');
  1491. tracker.emit("OnlineTherapy", {message: response.error.message, step: 'paymentStripefail', reqType: "general_therapy"});
  1492.  
  1493. } else {
  1494. $payForm.append('<input type="hidden" name="stripeToken" value="' + response['id'] + '" />');
  1495. if (!$payForm.find('[name="convID"]').length) {
  1496. $payForm.append('<input type="hidden" name="convID" value="' + ChatSession.convID + '" />');
  1497. }
  1498.  
  1499. $.post($payForm.attr('action'), $payForm.serialize(), function (resp) {
  1500. if (resp.success) {
  1501. tracker.emit("OnlineTherapy", {step: 'completepayment', reqType: reqType});
  1502. resetState();
  1503. window.allowEmpty = true;
  1504. $('#Comment').val('');
  1505. sendMessage();
  1506.  
  1507.  
  1508. if (typeof __adroll !== "undefined")
  1509. try {
  1510. __adroll.record_user({"adroll_segments": "9cb7fee1"})
  1511. __adroll.record_user({product_id: "onlineTherapy", product_action: "Purchased"})
  1512. } catch (e) { }
  1513.  
  1514. if (typeof ga !== 'undefined' && resp.sub) {
  1515. try {
  1516.  
  1517. ga('ec:setAction', 'purchase', {
  1518. 'id': resp.sub.subID,
  1519. 'revenue': sub.amt
  1520. });
  1521.  
  1522. // Record Adwords conversion
  1523. window.google_conversion_id = 991416627;
  1524. window.google_conversion_label = "KjZ_CMnek3EQs6Lf2AM";
  1525. window.google_remarketing_only = false;
  1526. window.google_conversion_format = "3";
  1527. var opt = new Object();
  1528. opt.onload_callback = function() {
  1529. console.log('Transaction Recorded');
  1530. }
  1531. var conv_handler = window['google_trackConversion'];
  1532. if (typeof(conv_handler) == 'function')
  1533. conv_handler(opt);
  1534.  
  1535.  
  1536. $('#MessageDiv button[data-func]').each(function() {
  1537. var parent = $(this).closest('div.convRow');
  1538. var id = $(parent).attr('id');
  1539.  
  1540. removeMessage(id.split('_')[1]);
  1541. });
  1542.  
  1543.  
  1544. } catch (e) { }
  1545. }
  1546. $payModal.modal('hide');
  1547. } else {
  1548. if (resp.err && resp.err.copy) {k
  1549. for (e in resp.err.copy) {
  1550. $payForm.prepend('<div class="alert alert-danger"><button type="button" class="close" data-dismiss="alert" aria-label="Close"><span aria-hidden="true">&times;</span></button>' + resp.err.copy[e] + '</div>');
  1551. }
  1552. tracker.emit("OnlineTherapy", {message: resp.err.copy, step: 'paymentfail', reqType: "general_therapy"});
  1553. } else
  1554. tracker.emit("OnlineTherapy", {step: 'paymentfail', reqType: "general_therapy"});
  1555.  
  1556. $payForm.find('button[type="submit"]').removeAttr("disabled").html(function () {
  1557. return $(this).attr("data-text")
  1558. });
  1559. }
  1560. }, 'json')
  1561. }
  1562. });
  1563. }
  1564.  
  1565. if (1 || window.confirmAuthorization){
  1566. submitCard();
  1567. } else {
  1568. //$payModal.modal('hide');
  1569. $('.payment-details-modal').hide();
  1570. tracker.emit('OnlineTherapy', {step: 'creditcardconfirm', uri: window.location.href, reqType: reqType});
  1571. bootbox.dialog({
  1572. className: "payment-confirm-modal",
  1573. 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.",
  1574. buttons: {
  1575. confirm: {
  1576. label: 'Connect me to my therapist',
  1577. className: 'btn-success',
  1578. callback: submitCard
  1579. }
  1580. },
  1581. onEscape: function() {
  1582. console.log('Dismissed');
  1583. $('.payment-details-modal').show();
  1584. $('body').addClass('modal-open');
  1585. //$payModal.modal('show');
  1586. }
  1587. }).on('hidden.bs.modal', function () {
  1588. $('.payment-details-modal').show();
  1589. $('body').addClass('modal-open');
  1590. });
  1591. }
  1592. return false;
  1593. });
  1594. });
  1595. });
  1596. }
  1597.  
  1598.  
  1599.  
  1600. function handleBotCreditCard3 (message, row) {
  1601.  
  1602. bootbox.hideAll();
  1603.  
  1604. if (window.activeButton > parseInt(message.msgID)) {
  1605. // Remove any old function button in memory or otherwise
  1606. removeMessage(message.msgHash);
  1607. return;
  1608. }
  1609.  
  1610. window.activeButton = parseInt(message.msgID);
  1611. window.activeButtonHash = message.msgHash;
  1612.  
  1613.  
  1614. lockState();
  1615.  
  1616. var reqType="general_therapy";
  1617. var planID = message.funcProp;
  1618. tracker.emit("OnlineTherapy", {step: 'loadpayment', reqType: reqType});
  1619. stopAutoPing ();
  1620. if (autoMessageFunction) clearTimeout(autoMessageFunction);
  1621. var subs = {};
  1622.  
  1623.  
  1624. if (typeof __adroll !== "undefined") {
  1625. try {
  1626. __adroll.record_user({"adroll_segments": "13b73f15"})
  1627. } catch(err) {}
  1628.  
  1629.  
  1630. try {
  1631. __adroll.record_user({product_id: "onlineTherapy", product_action: "AddToCart"})
  1632. } catch (e) { }
  1633. }
  1634.  
  1635.  
  1636. subs['onlinetherapy_monthly_15000'] = {
  1637. planID: 'onlinetherapy_monthly_15000',
  1638. modaltitle: 'Get Started!',
  1639. desc: '',
  1640. topdesc: 'Just like texting with a close friend, you can now message your therapist every day, writing as many times as you want.',
  1641. amt: '150.00',
  1642. recur: 'Monthly',
  1643. submitbutton: 'Start Therapy Now',
  1644. disclaimer: 'Your subscription will begin when you click on the button above. To cancel, go to &ldquo;settings&rdquo; and click on &ldquo;manage subscriptions&rdquo; 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.'
  1645. };
  1646.  
  1647. if (message.promoCode) {
  1648. subs['onlinetherapy_monthly_15000'].promo = true;
  1649. subs['onlinetherapy_monthly_15000'].submitbutton = 'Continue Therapy';
  1650. }
  1651.  
  1652. subs['onlinetherapy_monthly_15000_tr3'] = {
  1653. planID: 'onlinetherapy_monthly_15000_tr3',
  1654. modaltitle: 'Start Free Trial Now!',
  1655. desc: '',
  1656. 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!',
  1657. amt: '150.00',
  1658. recur: 'Monthly',
  1659. submitbutton: 'Start Therapy with 3 Day Trial',
  1660. 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 &ldquo;settings&rdquo; and click on &ldquo;manage subscriptions&rdquo; 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.'
  1661. };
  1662.  
  1663. if(subs[planID]){
  1664. var sub = subs[planID];
  1665. }else{
  1666. bootbox.alert('Error: Therapy plan not found.');
  1667. return false;
  1668. }
  1669.  
  1670. var ccyears = [];
  1671. var year = new Date().getFullYear();
  1672. for (var i = 0; i < 15; i++) {
  1673. ccyears.push(year + i);
  1674. }
  1675.  
  1676. if (typeof ga !== 'undefined') {
  1677. ga('ec:setAction', 'checkout');
  1678. }
  1679.  
  1680. var form = 'SC_Forms_Payment_StripeSubscription3';
  1681.  
  1682. var pt = 'Calmer days are ahead...';
  1683. var ph = 'paymentHeader2.jpg';
  1684.  
  1685. render(false, form, {paymentHeader: ph, paymentText: pt, ccyears: ccyears, sub: sub, ab_paymentpcode: ($.cookie('ab_paymentpcode')==true)}, function (content) {
  1686. tracker.emit('OnlineTherapy', {step: 'loadcreditcard', uri: window.location.href, reqType: reqType});
  1687. fbq('track', 'AddPaymentInfo');
  1688.  
  1689. bootbox.dialog({
  1690. className: "payment-details-modal",
  1691. title: '<span style="font-size:1.5em" class="text-primary">'+sub.modaltitle+'</span>',
  1692. message: content,
  1693. onEscape: true,
  1694. backdrop: true,
  1695. closeButton: true
  1696. }).off("shown.bs.modal").on("shown.bs.modal", function () {
  1697. var $payModal = $(this);
  1698. var $payForm = $(this).find(".stripe-payment-form");
  1699.  
  1700. $payForm.find('.card-js').CardJs();
  1701.  
  1702. $payForm.find('[data-action="applypromo"]').on('click', function () {
  1703. var btn = $(this);
  1704. $payForm.find('.alert-danger').remove();
  1705. btn.attr('data-html', function () {
  1706. return $(this).html()
  1707. }).attr('disabled', 'true').html('<i class="fa fa-spinner fa-spin"></i> Checking');
  1708. $.post($payForm.attr('action'), {action: 'verifypromo', promo: $payForm.find('[name="promo"]').val(), planID: $payForm.find('[name="planID"]').val()}, function (resp) {
  1709. if (resp.success) {
  1710. if (resp.update) {
  1711. for (var key in resp.update) {
  1712. $payModal.find(key).replaceWith(resp.update[key]);
  1713. }
  1714. }
  1715. } else {
  1716. $payForm.prepend('<div class="alert alert-danger"><button type="button" class="close" data-dismiss="alert" aria-label="Close"><span aria-hidden="true">&times;</span></button>Invalid Promo Code</div>');
  1717. btn.html(function () {
  1718. return $(this).attr('data-html')
  1719. }).removeAttr('disabled');
  1720. }
  1721. }, 'json');
  1722. });
  1723.  
  1724. $payForm.on('submit', function (event) {
  1725.  
  1726. var submitCard = function () {
  1727. $('.payment-details-modal').show();
  1728. $('body').addClass('modal-open');
  1729. //$payModal.modal('show');
  1730. tracker.emit('OnlineTherapy', {step: 'creditcardsubmit', uri: window.location.href, reqType: reqType});
  1731. $payForm.find('[name="stripeToken"], .alert').remove();
  1732. $payForm.find('button[type="submit"]').attr("disabled", "disabled").attr("data-text", function () {
  1733. return $(this).html();
  1734. }).html('<i class="fa fa-spin fa-spinner"></i> Processing');
  1735. /*var card = {
  1736. number: $payForm.find("[data-stripe='number']").val(),
  1737. cvc: $payForm.find("[data-stripe='cvc']").val(),
  1738. exp_month: $payForm.find("[data-stripe='exp_month']").val(),
  1739. exp_year: $payForm.find("[data-stripe='exp_year']").val()
  1740. };*/
  1741.  
  1742.  
  1743. Stripe.createToken($payForm, function(status, response) {
  1744. if (response.error) {
  1745. $payForm.find('button[type="submit"]').removeAttr("disabled").html(function () {
  1746. return $(this).attr("data-text")
  1747. });
  1748. $payForm.prepend('<div class="alert alert-danger"><button type="button" class="close" data-dismiss="alert" aria-label="Close"><span aria-hidden="true">&times;</span></button>' + response.error.message + '</div>');
  1749. tracker.emit("OnlineTherapy", {message: response.error.message, step: 'paymentStripefail', reqType: "general_therapy"});
  1750. } else {
  1751. $payForm.append('<input type="hidden" name="stripeToken" value="' + response['id'] + '" />');
  1752. if (!$payForm.find('[name="convID"]').length) {
  1753. $payForm.append('<input type="hidden" name="convID" value="' + ChatSession.convID + '" />');
  1754. }
  1755. if (window.checkinID) {
  1756. $payForm.append('<input type="hidden" name="checkinID" value="' + window.checkinID + '" />');
  1757. }
  1758.  
  1759. var form = $payForm.serialize();
  1760.  
  1761. $.post($payForm.attr('action'), form, function (resp) {
  1762. if (resp.success) {
  1763. tracker.emit("OnlineTherapy", {step: 'completepayment', reqType: reqType});
  1764. fbq('track', 'Purchase', {value: sub.amt, currency: 'USD'});
  1765.  
  1766. resetState();
  1767. window.allowEmpty = true;
  1768. $('#Comment').val('');
  1769. if (window.checkinID) {
  1770. $('#MessageDiv').html('You have successfully renewed your subscription. Connecting you with your therapist now...');
  1771. window.location = window.location;
  1772. } else {
  1773. sendMessage();
  1774. }
  1775.  
  1776.  
  1777.  
  1778. if (typeof __adroll !== "undefined")
  1779. try {
  1780. __adroll.record_user({"adroll_segments": "9cb7fee1"})
  1781. __adroll.record_user({product_id: "onlineTherapy", product_action: "Purchased"})
  1782. } catch (e) { }
  1783.  
  1784. if (typeof ga !== 'undefined' && resp.sub) {
  1785. try {
  1786.  
  1787. ga('ec:setAction', 'purchase', {
  1788. 'id': resp.sub.subID,
  1789. 'revenue': sub.amt
  1790. });
  1791.  
  1792. // Record Adwords conversion
  1793. window.google_conversion_id = 991416627;
  1794. window.google_conversion_label = "KjZ_CMnek3EQs6Lf2AM";
  1795. window.google_remarketing_only = false;
  1796. window.google_conversion_format = "3";
  1797. var opt = new Object();
  1798. opt.onload_callback = function() {
  1799. console.log('Transaction Recorded');
  1800. }
  1801. var conv_handler = window['google_trackConversion'];
  1802. if (typeof(conv_handler) == 'function')
  1803. conv_handler(opt);
  1804.  
  1805. $('#MessageDiv button[data-func]').each(function() {
  1806. var parent = $(this).closest('div.convRow');
  1807. var id = $(parent).attr('id');
  1808.  
  1809. removeMessage(id.split('_')[1]);
  1810. });
  1811.  
  1812.  
  1813. } catch (e) { }
  1814. }
  1815. $payModal.modal('hide');
  1816. } else {
  1817. if (resp.err && resp.err.copy) {
  1818. for (e in resp.err.copy) {
  1819. $payForm.prepend('<div class="alert alert-danger"><button type="button" class="close" data-dismiss="alert" aria-label="Close"><span aria-hidden="true">&times;</span></button>' + resp.err.copy[e] + '</div>');
  1820. }
  1821. tracker.emit("OnlineTherapy", {message: resp.err.copy, step: 'paymentfail', reqType: "general_therapy"});
  1822. } else
  1823. tracker.emit("OnlineTherapy", {step: 'paymentfail', reqType: "general_therapy"});
  1824.  
  1825. $payForm.find('button[type="submit"]').removeAttr("disabled").html(function () {
  1826. return $(this).attr("data-text")
  1827. });
  1828. }
  1829. }, 'json')
  1830. }
  1831. });
  1832. }
  1833.  
  1834. if (1 || window.confirmAuthorization){
  1835. submitCard();
  1836. } else {
  1837. //$payModal.modal('hide');
  1838. $('.payment-details-modal').hide();
  1839. tracker.emit('OnlineTherapy', {step: 'creditcardconfirm', uri: window.location.href, reqType: reqType});
  1840. bootbox.dialog({
  1841. className: "payment-confirm-modal",
  1842. 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.",
  1843. buttons: {
  1844. confirm: {
  1845. label: 'Connect me to my therapist',
  1846. className: 'btn-success',
  1847. callback: submitCard
  1848. }
  1849. },
  1850. onEscape: function() {
  1851. console.log('Dismissed');
  1852. $('.payment-details-modal').show();
  1853. $('body').addClass('modal-open');
  1854. //$payModal.modal('show');
  1855. }
  1856. }).on('hidden.bs.modal', function () {
  1857. $('.payment-details-modal').show();
  1858. $('body').addClass('modal-open');
  1859. });
  1860. }
  1861. return false;
  1862. });
  1863. });
  1864. });
  1865. }
  1866.  
  1867.  
  1868.  
  1869. function handleBotButton (message, row) {
  1870.  
  1871. if (window.activeButton > parseInt(message.msgID)) {
  1872. // Remove any old function button in memory or otherwise
  1873. removeMessage(message.msgHash);
  1874. return;
  1875. }
  1876.  
  1877. if (message.func == 'waitForChoice' && !(typeof message.doNotLock !== "undefined"))
  1878. lockState();
  1879. else
  1880. resetState();
  1881.  
  1882. window.activeButton = parseInt(message.msgID);
  1883. window.activeButtonHash = message.msgHash;
  1884.  
  1885.  
  1886. // For every functional button, remove it, or add onclick if in active button messae set
  1887. $('#MessageDiv button[data-func]').each(function() {
  1888.  
  1889. var parent = $(this).closest('div.convRow');
  1890. var id = $(parent).attr('id');
  1891. if (id == 'message_'+message['msgHash'])
  1892. $(this).click(function () {
  1893. var reply = $(this).html();
  1894. removeMessage(id.split('_')[1]);
  1895.  
  1896. console.log('resetting from button push');
  1897. resetState(reply);
  1898.  
  1899. sendMessage();
  1900.  
  1901. });
  1902. else
  1903. removeMessage(id.split('_')[1]);
  1904. });
  1905. }
  1906.  
  1907. function removeMessage(hash) {
  1908. $('#message_' + hash).hide();
  1909. if (ChatSession.convID && userInfo.userIDe) {
  1910. var idx = userInfo.userIDe + ChatSession.convID;
  1911. if (window.chatInfoMemory[idx] && window.chatInfoMemory[idx].messages) {
  1912. for (mi = 0; mi < window.chatInfoMemory[idx].messages.length; mi++) {
  1913. if (window.chatInfoMemory[idx].messages[mi].msgHash === hash) {
  1914. delete window.chatInfoMemory[idx].messages.splice(mi, 1);
  1915. }
  1916. }
  1917. }
  1918. }
  1919. }
  1920.  
  1921. var botTimer = false;
  1922. var botMessageCount = 0;
  1923. var currentBot = {};
  1924. var protectedBotMessages = [];
  1925. var autoPing = false;
  1926. var autoPingIdx = 0;
  1927. var autoPingExec = false;
  1928. var autoPingName = false;
  1929.  
  1930. function startAutoPing (autoPingInstructions) {
  1931. if (typeof autoPingInstructions !== 'undefined') {
  1932.  
  1933. if (ChatSession.otherUser)
  1934. autoPingName = ChatSession.otherUser.screenName;
  1935.  
  1936. stopAutoPing();
  1937.  
  1938. autoPingIdx = 0;
  1939.  
  1940. var setAutoPinger = function (idx) {
  1941. autoPing = setTimeout(function () {
  1942.  
  1943. if (window.selectData) {
  1944. setAutoPinger(0);
  1945. return;
  1946. }
  1947.  
  1948. // abort autoping if conversation changed
  1949. if (!ChatSession.otherUser || ChatSession.otherUser.screenName != autoPingName)
  1950. return;
  1951.  
  1952. autoPingExec = true;
  1953. $('#Comment').val('/autoping '+autoPingInstructions[idx].stage);
  1954. sendMessage();
  1955.  
  1956. autoPingIdx = idx + 1;
  1957.  
  1958. if (autoPingInstructions.length - 1 >= autoPingIdx) {
  1959. console.log('Setting New Ping', autoPingIdx);
  1960. setAutoPinger(autoPingIdx);
  1961. }
  1962. }, autoPingInstructions[idx].delay*1000);
  1963. }
  1964.  
  1965. setAutoPinger(0);
  1966. }
  1967. }
  1968.  
  1969. function stopAutoPing () {
  1970. console.log('Resetting auto ping');
  1971.  
  1972. if (autoPing)
  1973. clearTimeout(autoPing);
  1974. }
  1975.  
  1976. function sendToBot (instructions, autoPing) {
  1977.  
  1978. var k = instructions.length, j;
  1979.  
  1980. if (instructions.length) {
  1981.  
  1982. window.protectedBotMessages = [];
  1983. for (j = 0; j < k; j++)
  1984. window.protectedBotMessages.push(instructions[j].msgHash);
  1985.  
  1986. if (window.botTimer) {
  1987. clearTimeout( window.botTimer );
  1988. window.botTimer = false;
  1989. }
  1990.  
  1991. var current = instructions.shift();
  1992. (function (current, instructions) {
  1993. window.botTimer = setTimeout(function () {
  1994.  
  1995. var appendMsg = function () {
  1996. $('#offlineMessageDiv').html('');
  1997. var s = parseInt((new Date()).getTime() - serverTimeOffset*1000);
  1998. current.msgTime = moment(s).format("h:mm A");
  1999.  
  2000. // Allow this message to load
  2001. var idx = window.protectedBotMessages.indexOf(current.msgHash);
  2002. window.protectedBotMessages.splice(idx, 1);
  2003.  
  2004. loadMessage(current);
  2005. scrollConversation();
  2006.  
  2007. botMessageCount++;
  2008. if (current.tracking) {
  2009. window.currentBot = current.tracking;
  2010. tracker.emit("botMessage", {
  2011. bot: window.currentBot.bot,
  2012. botVersion: 2,
  2013. sender: 'bot',
  2014. msgCount: botMessageCount,
  2015. mode: window.currentBot.mode,
  2016. stage: window.currentBot.stage
  2017. });
  2018. if (window.currentBot.mode == "introTherapy")
  2019. switch (window.currentBot.stage) {
  2020. case 'account1' : tracker.emit("OnlineTherapy", {step: 'loadmoreinfo',
  2021. reqType: "general_therapy"}); break;
  2022. case 'confirm' : tracker.emit("OnlineTherapy", {step: 'completemoreinfo',
  2023. reqType: "general_therapy"}); break;
  2024. case 'therapistLink' :
  2025. case 'waitForOK' : tracker.emit("OnlineTherapy", {step: 'loadagreement',
  2026. reqType: "general_therapy"}); break;
  2027. default: break;
  2028. }
  2029. }
  2030.  
  2031. if (instructions.length)
  2032. (function (instructions) {
  2033. sendToBot(instructions);
  2034. })(instructions);
  2035. else
  2036. startAutoPing(autoPing);
  2037. };
  2038.  
  2039. if (current.typingTime) {
  2040. if (window.noniButtonsOnly) {
  2041. lockState();
  2042. }
  2043. $('#offlineMessageDiv').html('<div class="" style="margin-bottom:.5em;"><small><em>' + current.screenName
  2044. + ' is typing...</em></small></div>');
  2045. scrollConversation();
  2046. window.botTimer = setTimeout(function () {
  2047. appendMsg();
  2048. }, current.typingTime*1000);
  2049. } else
  2050. appendMsg();
  2051.  
  2052. }, current.delayTime*1000);
  2053. })(current, instructions);
  2054.  
  2055. }
  2056.  
  2057. }
  2058.  
  2059. var noniTimer, waitForSend, stopNoni, currentNoni = {screenName: 'Noni', imgURL: cloudfrontBase + 'img/noniCup.jpg'};
  2060. function talkToNoni() {
  2061. if (!stopNoni) {
  2062.  
  2063. var noniFactor = .65;
  2064.  
  2065.  
  2066. waitForSend = false;
  2067. clearTimeout(noniTimer);
  2068. if (!ChatSession.roomType && ChatSession.user.userType != 'l' && ChatSession.numMsgListener == 0 && (ChatSession.reqType == 'general' || ChatSession.reqType == 'general_therapy' || ChatSession.reqType == 'personal_therapy') && ChatSession.reqStatus == 'request') {
  2069. var lastMsg = -1;
  2070.  
  2071. $('[data-nonimsg]').each(function () {
  2072. lastMsg = parseInt($(this).attr('data-nonimsg')) > parseInt(lastMsg) ? parseInt($(this).attr('data-nonimsg')) : lastMsg;
  2073. });
  2074.  
  2075. if (ChatSession.reqType == 'general' && lastMsg == -1) {
  2076. $('#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>');
  2077. scrollConversation();
  2078. }
  2079.  
  2080. $.post('/connect/talkToNoni.php', {convID: ChatSession.convID, lastNoniMsg: lastMsg}, function (json) {
  2081. console.log('##standard noni delay', 6000 * noniFactor);
  2082.  
  2083. if (json && json.message) {
  2084. if (lastMsg == -1) {
  2085. tracker.emit("noniMessage", {msg: lastMsg + 1});
  2086. }
  2087.  
  2088. currentNoni.screenName = json.message.screenName;
  2089. currentNoni.imgURL = json.message.imgURL;
  2090. currentNoni.imageClass = json.message.imageClass;
  2091. $('#offlineMessageDiv').html('<div class="" style="margin-bottom:.5em;"><small><em>' + json.message.screenName + ' is typing...</em></small></div>');
  2092. scrollConversation();
  2093. console.log('####noni typing', 6000 * noniFactor);
  2094. setTimeout(function () {
  2095. $('#offlineMessageDiv').html('');
  2096. var s = parseInt((new Date()).getTime() - serverTimeOffset*1000);
  2097. json.message.msgTime = moment(s).format("h:mm A");
  2098. loadMessage(json.message);
  2099. scrollConversation();
  2100.  
  2101. tracker.emit("botMessage", {bot: currentNoni.screenName, msg: lastMsg+1, msgid: json.tag ? json.tag : null});
  2102.  
  2103. if (json.delay && json.delay > 0) {
  2104. console.log('######noni delaying to talk', json.delay * 1000 * noniFactor);
  2105. noniTimer = setTimeout(talkToNoni, json.delay * 1000 * noniFactor);
  2106. } else {
  2107. waitForSend = true;
  2108. }
  2109. }, 6000 * noniFactor);
  2110. } else if (json.delay && json.delay < 0) {
  2111. waitForSend = true;
  2112. }
  2113. }, 'json');
  2114. }
  2115. }
  2116. }
  2117.  
  2118. function hideAlert(alertID) {
  2119. $('#' + alertID).hide();
  2120. setLocal("hide" + alertID, true);
  2121. }
  2122.  
  2123. function setLocal(key, value) {
  2124. if (typeof (Storage) !== "undefined") {
  2125. try {
  2126. var res = localStorage.setItem(key, value);
  2127.  
  2128. } catch (e) {
  2129. console.log('Local storage reported available but not writable.');
  2130. }
  2131. }
  2132. }
  2133.  
  2134. function getLocal(key) {
  2135. if (typeof (Storage) !== "undefined") {
  2136. try {
  2137. return localStorage.getItem(key);
  2138. } catch (e) {
  2139. console.log('Local storage reported available but not readable.');
  2140. }
  2141. return null;
  2142. }
  2143. }
  2144.  
  2145. function surveyPop(token) {
  2146. var viewportwidth = screen.width;
  2147. var viewportheight = screen.height;
  2148. var popWidth = Math.floor(viewportwidth * 0.75);
  2149. var popHeight = Math.floor(viewportheight * 0.75);
  2150. var popLeft = viewportwidth - popWidth;
  2151. var notePop = window.open('/survey/201502.php?t=' + token,
  2152. "Survey",
  2153. "width=" + popWidth + ",height=" + popHeight + ",left=" + popLeft + ",top=0,location=0,toolbar=0,directories=0,status=0,menubar=0,scrollbars=1,resizable=1");
  2154. ga('send', 'event', {
  2155. 'eventCategory': 'Survey',
  2156. 'eventAction': 'AgreeToTake'
  2157. });
  2158. }
  2159.  
  2160. function endLiveChat(receive) {//Call this function to request an end of chat or when receiving an end of chat
  2161. tracker.emit("EndLiveChat");
  2162. if (!ChatSession.roomType && ChatSession.allowEndPop && (ChatSession.user.userType != 'l' || ChatSession.otherUser.userType != 'l')) {//Only allow in 1-on-1 with member/guest
  2163. ChatSession.allowEndPop = false;
  2164. if (typeof (receive) === 'undefined' || !receive) {
  2165. ListMessagesSocket.emit('sendConvAction', {room: ChatSession.nodeRoom, action: 'endLiveChat', me: ChatSession.me});
  2166. }
  2167.  
  2168. if (ChatSession.user.userType == 'l') {
  2169. $('<div class="modal"><div class="modal-dialog"><div class="modal-content"><div class="modal-body"><div class="text-center ">' +
  2170. '<h2>This live chat session has ended.</h2>' +
  2171. '<h4>Thank you so much for all your good work on 7 Cups of Tea!</h4>' +
  2172. '<button type="button" class="btn btn-simple btn-primary" data-dismiss="modal" aria-label="Close">Close</button>' +
  2173. '</div></div></div></div></div>').modal().on('hidden.bs.modal', function () {
  2174. $(this).data('bs.modal', null);
  2175. wrapUp();
  2176. });
  2177. } else if (ChatSession.ratingPopped && window.ratingModal) {
  2178. window.ratingModal.modal('show').on('hidden.bs.modal', function () {
  2179. wrapUp();
  2180. });
  2181. } else {
  2182. bootbox.alert('<h2 class="text-center">Live Chat Session Complete<small><br />We hope you had a great conversation &amp; are feeling better.</small></h2>', function () {
  2183. wrapUp();
  2184. });
  2185. }
  2186. }
  2187.  
  2188. function wrapUp() {
  2189. if (isMobileApp()) {
  2190. requestRedirect = true;
  2191. window.location.href = '/conversations.php';
  2192. } else {
  2193. if (ChatSession.nodeRoom) {
  2194. ListMessagesSocket.emit('leave', [ChatSession.nodeRoom]);
  2195. }
  2196. ChatSession.nodeRoom = null;
  2197. ChatSession.convID = null;
  2198. $('#chatForm').hide();
  2199. $('#MessageDiv').html('');
  2200. $('#selectConvPrompt').show();
  2201. if (ChatSession.goodExperience) {
  2202. $('<div class="modal"><div class="modal-dialog"><div class="modal-content"><div class="modal-body"><div class="text-center ">' +
  2203. '<h1>Awesome!</h1>' +
  2204. '<h3>We are glad to hear that you had a positive experience with your Listener.</h3>' +
  2205. '<h3>Learn more about yourself by reviewing your Personalized Growth Path.</h3>' +
  2206. '<div class="text-center">' +
  2207. '<div><a href="https://www.7cups.com/member/" class="btn btn-success">Visit My Growth Path</a></div>' +
  2208. '<div style="margin-top:1em"><a href="/member/" class="btn btn-link">no thanks</a></div>' +
  2209. '</div>' +
  2210. '</div></div></div></div></div>').modal();
  2211. } else if (ChatSession.goodExperience === false) {
  2212. $('<div class="modal"><div class="modal-dialog"><div class="modal-content"><div class="modal-body"><div class="text-center ">' +
  2213. '<h2>We&rsquo;re sorry that this conversation wasn&rsquo;t very helpful.</h2>' +
  2214. '<h3>Many people try several listeners before finding one that clicks.</h3>' +
  2215. '<div class="text-center">' +
  2216. '<div><button type="button" class="btn btn-success" onclick="$(this).parents(\'div.modal\').modal(\'hide\');connectNowLoad(\'#connectNowAgree\');">Connect to a New Listener</button></div>' +
  2217. '<div style="margin-top:1em"><a href="/BrowseListeners/" class="btn btn-simple btn-primary">Browse Listeners by Issue &amp; Language</a></div>' +
  2218. '<div style="margin-top:1em"><button type="button" onclick="$(this).parents(\'div.modal\').modal(\'hide\');connectNowLoad(\'#connectNowNotReady\');" class="btn btn-link">I&rsquo;m not ready to reconnect</button></div>' +
  2219. '</div>' +
  2220. '</div></div></div></div></div>').modal();
  2221. }
  2222. }
  2223. }
  2224. }
  2225.  
  2226.  
  2227. function muteUser(userTypeID) {
  2228. $('#multiModal').modal('hide');
  2229. var muteArr = $.cookie('muteArr') ? $.cookie('muteArr') : '[]';
  2230. muteArr = JSON.parse(muteArr);
  2231. if ($.inArray(userTypeID, muteArr) === -1) {
  2232. muteArr.push(userTypeID);
  2233. muteArr = JSON.stringify(muteArr);
  2234. $.cookie("muteArr", muteArr, {path: '/'});
  2235. }
  2236. $('.convRow[data-usertypeid="' + userTypeID + '"]').remove();
  2237. showUnmuteButton();
  2238. }
  2239.  
  2240. function globalMuteUsers(userTypeID) {
  2241. if ($.inArray(userTypeID, globalMuteArr) === -1) {
  2242. globalMuteArr.push(userTypeID);
  2243. }
  2244. if (ChatSession.user.userTypeID != userTypeID) {
  2245. $('.convRow[data-usertypeid="' + userTypeID + '"]').remove();
  2246. }
  2247. }
  2248.  
  2249. function heartMsg(msgHash) {
  2250. $('#message_' + msgHash + ' .heartCommentButton').removeClass('compassionHeartFade').addClass('compassionHeart').attr('onclick', '');
  2251. ListMessagesSocket.emit('sendConvAction', {room: ChatSession.nodeRoom, action: 'heartMsg', msgHash: msgHash, me: ChatSession.me});
  2252. $.post('/connect/heartMessage.php', {convID: ChatSession.convID, msgHash: msgHash}, function (json) {
  2253. if (json.error) {
  2254. //alert(json.error);
  2255. } else {
  2256. tracker.emit('chatHeart', {
  2257. convID: ChatSession.convID,
  2258. chatroomName: ChatSession.otherUser.screenName || null,
  2259. roomType: ChatSession.roomType || null
  2260. });
  2261. }
  2262. }, 'json');
  2263. }
  2264.  
  2265. function sendTyping(val) {
  2266. if (val) {
  2267. ChatSession.sendingTyping = true;
  2268. 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});
  2269.  
  2270. } else {
  2271. ChatSession.sendingTyping = false;
  2272. ListMessagesSocket.emit('sendConvAction', {room: ChatSession.nodeRoom, action: 'typingStatus', isTyping: false, me: ChatSession.me});
  2273.  
  2274. }
  2275. }
  2276.  
  2277. function blockLink() {
  2278. if(ChatSession.convID && ChatSession.otherUser){
  2279. ChatSession.otherUser.is = {};
  2280. ChatSession.otherUser.is.userType = {};
  2281. ChatSession.otherUser.is.userType[ChatSession.otherUser.userType] = true;
  2282.  
  2283. render(false, 'Chat_BlockConnection', ChatSession, function ($html) {
  2284. bootbox.dialog({
  2285. title: ChatSession.otherUser.is.userType.l ? 'Block/Report Listener' : 'Block/Report User',
  2286. message: $html
  2287. });
  2288.  
  2289. $html.find('select[name=blockCategoryInput]').on('change',function(){
  2290. $html.find('textarea[name=blockReasonInput]').toggle($(this).val() != 'none');
  2291. });
  2292. });
  2293. }
  2294. }
  2295.  
  2296. function clearConversation() {
  2297. 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?')) {
  2298. $('#msgs-loading').show();
  2299. scrollConversation();
  2300.  
  2301. delete window.chatInfoMemory[userInfo.userIDe + ChatSession.convID].messages;
  2302.  
  2303. $.post('/connect/clearConversation.php', {c: ChatSession.convID}, function (json) {
  2304. if (json.ack == 'success') {
  2305. $('#MessageDiv').html('');
  2306. } else if (json.ack == 'error') {
  2307. alert(json.error);
  2308. }
  2309. }, 'json').always(function () {
  2310. $('#msgs-loading').hide();
  2311. });
  2312. $('#actionsModal').modal('hide');
  2313. }
  2314. }
  2315.  
  2316. function chatRoomRules() {
  2317. if (ChatSession.chatroomRules) {
  2318. var title = (ChatSession.roomType == 'l') ? 'Listener Chat Rules' : 'Group Chat Rules';
  2319.  
  2320. var message = '<ol>';
  2321. for (var i = 0; i < ChatSession.chatroomRules.length; i++) {
  2322. message += '<li>' + ChatSession.chatroomRules[i][0] + '</li>';
  2323. }
  2324. message += '</ol>';
  2325.  
  2326. bootbox.dialog({
  2327. message: message,
  2328. title: title
  2329. });
  2330. }
  2331. }
  2332.  
  2333. function resetChatBox () { if (window.botDatum) $(this).val(window.botDatum) }
  2334.  
  2335. function loadMessage(message, skip) {
  2336. var exisingCheck = $("#message_" + message.msgHash);
  2337.  
  2338. if (message.msgHash && exisingCheck.length === 0 && typeof message.msgBody !== 'undefined' && message.msgBody.length > 0 && ChatSession.convID == message.convID && window.protectedBotMessages.indexOf(message.msgHash) == -1) {
  2339.  
  2340. // My messages have no timestamp
  2341. if (!message.msgTS) {
  2342. var t = (new Date()).getTime()/1000 - serverTimeOffset;
  2343. console.log('Setting msgTS', t, 'With Offset:', serverTimeOffset);
  2344. message.msgTS = t;
  2345. }
  2346.  
  2347. message.isMod = (message.badges && message.badges.indexOf('Mod') !== -1);
  2348.  
  2349. // Stringify and then reparse message objec to break theobject pointer
  2350. message = JSON.stringify(message);
  2351. message = JSON.parse(message);
  2352.  
  2353. // Do not resave messages that already exist in the chat history
  2354. if (!ChatSession.roomType && !skip) {
  2355. var chatMsgs = [];
  2356. var idx = userInfo.userIDe + message.convID;
  2357.  
  2358. window.chatInfoMemory[idx] = window.chatInfoMemory[idx] || {};
  2359. window.chatInfoMemory[idx].messages = window.chatInfoMemory[idx].messages || [];
  2360. window.chatInfoMemory[idx].messages.push(message);
  2361. window.chatInfoMemory[idx].messages = window.chatInfoMemory[idx].messages.slice(-40);
  2362. }
  2363.  
  2364.  
  2365. message.msgBody = ['n','b'].indexOf(message.userType) == -1 ? encodeMsg(message.msgBody) : swapEmoticons(message.msgBody);
  2366. if (ChatSession.roomType ||
  2367. !(
  2368. (ChatSession.otherUser.listType == "therapist" || ChatSession.user.listType == "therapist")
  2369. )) {
  2370. message.msgBody = censorMsgAssist(message.msgBody) ? null : message.msgBody;
  2371. message.msgBody = (censorMsgPhrases(message.msgBody) || (ChatSession.user.userType == 'l' && ChatSession.otherUser.userType &&
  2372. ChatSession.otherUser.userType == 'l' && censorMsgLLpm(message.msgBody))) ? null : message.msgBody;
  2373. }
  2374. message.msgBody = ChatSession.roomType ? censorMsgWords(message.msgBody) : message.msgBody;
  2375.  
  2376. if (message.msgBody) {
  2377.  
  2378. message.screenName = !message.screenName ? '' : message.screenName;
  2379. message.msgHash = strip_tags(message.msgHash);
  2380. message.imgURL = message.imgURL === null ? null : strip_tags(message.imgURL);
  2381. message.imageClass = message.imageClass || '';
  2382. message.userColor = strip_tags(message.userColor);
  2383. message.msgTime = strip_tags(message.msgTime);
  2384. message.convSide = message.convSide || ((ChatSession.user.userTypeID == message.userTypeID) ? 'mine' : 'other');
  2385.  
  2386. if (ChatSession.otherUser && ChatSession.otherUser.userType == 'b') {
  2387. // Update chat bar
  2388. if (!skip) {
  2389. var simple = strip_tags(message.msgBody);
  2390. var newHTML = message.msgTime + ' ' + (simple.length > 50 ? simple.substr(0,47) + '...': simple);
  2391. $('#convListItem_'+message.convID+' .userInfo small').html(newHTML);
  2392. $('#botInformation').html(newHTML);
  2393. }
  2394.  
  2395. console.log('[APPEND]', message.msgID, window.activeButton, window.stateLocked);
  2396. if (window.stateLocked && window.activeButton < parseInt(message.msgID))
  2397. resetState();
  2398. }
  2399.  
  2400. ChatSession.allowEndPop = true;
  2401.  
  2402. var muteArr = $.cookie('muteArr') ? $.cookie('muteArr') : '[]';
  2403. muteArr = JSON.parse(muteArr);
  2404. muteArr = $.merge(muteArr, globalMuteArr);
  2405.  
  2406. if (!ChatSession.roomType || $.inArray(message['userTypeID'], muteArr) === -1 || ChatSession.user.userTypeID == message['userTypeID']) {
  2407. 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'] + '">';
  2408.  
  2409.  
  2410. var screenName = '';
  2411. if (message['userType'] == 'l') {
  2412. screenName = '<a href="/@' + message['screenName'] + '" data-usercard="' + message['screenName'] + '"><span class="userScreenName">' + message['screenName'] + '</span></a>';
  2413. } else if (message['userType'] == 'm') {
  2414. screenName = '<a href="/@' + message['screenName'] + '/" data-usercard="' + message['screenName'] + '"><span class="userScreenName">' + message['screenName'] + '</span></a>';
  2415. } else if (message['userType'] == 'n') {
  2416. screenName += '<span class="userScreenName">' + message['screenName'] + '</span>';
  2417. } else {
  2418. screenName += '<span class="userScreenName">' + message['screenName'] + '</span>';
  2419. }
  2420.  
  2421. var img = '<div class="img-profile ' + message['imageClass'] + '" style="background-image:url(' + message['imgURL'] + ')"></div>';
  2422. if (message['userType'] == 'l' || message['userType'] == 'm') {
  2423. img = '<a href="/@' + message['screenName'] + '">' + img + '</a>';
  2424. }
  2425.  
  2426. var testTime = message['msgTime'].split(' ');
  2427.  
  2428. if (testTime.length > 2 || skip) {
  2429. testTime = true;
  2430. } else {
  2431. testTime = false;
  2432. }
  2433.  
  2434. var heart = '';
  2435.  
  2436. if (message['convSide'] == 'other' && message['userType'] != 'n' && message['userType'] != 'b') {
  2437. heart = ' <span style="cursor:pointer" class="heartCommentButton compassionHeartFade" onclick="heartMsg(\'' + message['msgHash'] + '\');"><i class="fa fa-heart"></i><span class="pointHolder"></span></span>';
  2438. } else if (message['convSide'] == 'mine') {
  2439. heart = ' <span class="heartCommentButton compassionHeart" style="display:none"><i class="fa fa-heart"></i><span class="pointHolder"></span></span>';
  2440. }
  2441.  
  2442. 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>' : '';
  2443.  
  2444. var refer = '';
  2445. var mute = '';
  2446. var warn = '';
  2447. if (ChatSession.roomType && message['convSide'] == 'other' && message['userType'] != 'n' && message['userType'] != 'b' && !message.isMod) {
  2448. if (ChatSession.user.isMod) {
  2449. 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>';
  2450. }
  2451.  
  2452. if (message['userType'] != 'l') {
  2453. 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>';
  2454. }
  2455. 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>';
  2456.  
  2457. }
  2458.  
  2459. var badges = '';
  2460. var uType = '';
  2461. if (message['userType'] == 'm') {
  2462. uType = ' (M) ';
  2463. } else if (message['userType'] == 'l') {
  2464. if (message.listType && message.listType == 'therapist') {
  2465. uType = ' (T) ';
  2466. } else {
  2467. uType = ' (L) ';
  2468. }
  2469. }
  2470.  
  2471. if (ChatSession.roomType) {
  2472. badges += ' <span class="badgeHolder">';
  2473. if (message.badges) {
  2474. badges += message.badges;
  2475. }
  2476. badges += '</span>';
  2477. }
  2478.  
  2479. var icons = '<span class="chatIconHolder">';
  2480. if (message.shareIcons && message.shareIcons.sustainability) {
  2481. icons += message.shareIcons.sustainability.display;
  2482. }
  2483. icons += '</span>';
  2484. var fadeIn = false;
  2485.  
  2486. if (message['convSide'] == 'mine') {
  2487. var detailString = false;
  2488. if (message['userType'] == 'g')
  2489. detailString = screenName;
  2490.  
  2491. if (!ChatSession.roomType || testTime)
  2492. detailString = (detailString ? detailString + ' ' : '') + '<span class="msgTime">' + message['msgTime'] + '</span>';
  2493. else
  2494. detailString = (detailString ? detailString + ' ' : '') + '<span class="msgTime" style="display:none" data-msgTime="' + (new Date()).getTime() + '">' + message['msgTime'] + '</span>';
  2495.  
  2496. if (ChatSession.user.crisisMessage) {
  2497. message['msgBody'] = ChatSession.user.crisisMessage;
  2498. ChatSession.user.crisisMessage = null;
  2499. }
  2500. newRow +=
  2501. '<div class="meArea clearfix">' + heart +
  2502. ' <div class="meWrap">' + message['msgBody'].replace(/\n/g, '<br/>') + '</div>' +
  2503. (detailString ? ' <div class="details">' + detailString + '</div>' : '') +
  2504. '</div>';
  2505. } else {
  2506.  
  2507. if (message['userType'] == 'b' && message['msgBody'].indexOf("<button") != -1) {
  2508. newRow += '<div class="youArea clearfix buttonArea" style="text-align:center;">'+
  2509. message['msgBody']+
  2510. '</div>';
  2511. fadeIn = true;
  2512. } else {
  2513. var imageWrap = (message['userType'] == 'b' && message['msgBody'].indexOf("<img ") === 0 && message.msgBody.match(/\<img/g).length == 1);
  2514.  
  2515. newRow += '<div class="youArea clearfix">' + '<div class="youImg">' + img + '</div>' +
  2516. ' <div class="youWrap' + (imageWrap ? ' imageWrap' : '') + '">' +
  2517. modLink + message['msgBody'].replace(/\n/g, '<br/>') + '</div>' + heart +
  2518. ' <div class="details">' +
  2519. (ChatSession.roomType || message['userType'] == 'n' || message['userType'] == 'b' ? screenName + ' ' : '') +
  2520. (ChatSession.roomType && uType != '' ? uType : '') +
  2521. (ChatSession.roomType && message.zodiac && message.zodiac.html ? message.zodiac.html : '') +
  2522. (!ChatSession.roomType || testTime ? ' ' + message['msgTime'] + ' ' : '<span style="display:none" data-msgTime="' + (new Date()).getTime() + '">' + message['msgTime'] + '</span> ') +
  2523. badges + warn + refer + mute + icons + '</div>' +
  2524. '</div>';
  2525. }
  2526. }
  2527.  
  2528. newRow += '</div>';
  2529.  
  2530.  
  2531. // When mass loading see where it goes
  2532. newRow = $(newRow);
  2533.  
  2534. // Lets look for functional buttons in the chat logs
  2535. if (message['userType'] == 'b' && !message['func']) {
  2536. //console.log('CHECKING', newRow.find('button'));
  2537. var func = newRow.find('button').data('func');
  2538. if (func)
  2539. message.func = func;
  2540. else {
  2541. var func = newRow.find('i').data('func');
  2542. if (func)
  2543. message.func = func;
  2544. }
  2545. }
  2546.  
  2547. if (fadeIn)
  2548. newRow.find('.buttonArea').hide();
  2549.  
  2550. // Whenever user inputs, lets remove wait buttons (theyll reappear if needed)
  2551. if (!skip && message['userType'] != 'b' && window.activeButtonHash) {
  2552. removeMessage(window.activeButtonHash);
  2553. window.activeButtonHash = false;
  2554. window.activeButton = false;
  2555. }
  2556.  
  2557. var e = findLater(message['msgTS']);
  2558. if (e)
  2559. newRow.insertBefore(e);
  2560. else
  2561. $('#MessageDiv').append(newRow);
  2562.  
  2563. if (fadeIn)
  2564. newRow.find('.buttonArea').fadeIn(400, 'swing');
  2565.  
  2566. var noSound = false;
  2567.  
  2568. // Run these each time for bot messages
  2569. if (message['userType'] == 'b' && message['func']) {
  2570. console.log('Switching2', message['func']);
  2571. switch (message['func']) {
  2572. case 'waitForChoice' :
  2573. case 'waitForButton' :
  2574. noSound = true;
  2575. handleBotButton(message, newRow);
  2576. break;
  2577. case 'creditcard' :
  2578. noSound = true;
  2579. handleBotCreditCard2(message, newRow);
  2580. break;
  2581. case 'popModal' : $("#"+message['funcProp']).modal(); break;
  2582. case 'personalDetails' :
  2583. noSound = true;
  2584. personalDetails(message, newRow);
  2585. break;
  2586. case 'datePicker' :
  2587. window.stateLocked = true;
  2588. $('#Comment').datepicker("destroy");
  2589. $('#Comment').val("");
  2590. $('#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); });
  2591. $('#Comment').focus();
  2592. $('#Comment').on('keyup', resetChatBox);
  2593. window.stateLocked = true;
  2594. window.activeButton = parseInt(message.msgID);
  2595. window.stateLocked = true;
  2596. break;
  2597. default: break;
  2598. }
  2599. }
  2600.  
  2601. if (typeof (soundManager) != 'undefined' && !ChatSession.initialLoad && message['convSide'] == 'other') {
  2602. if (soundOn && !noSound) {
  2603. soundManager.play('newMessage');
  2604. }
  2605. $.titleAlert("*** NEW Message ***", {
  2606. requireBlur: true,
  2607. stopOnFocus: true,
  2608. duration: 30000,
  2609. interval: 500
  2610. });
  2611. }
  2612.  
  2613. if (!skip && typeof message.fill !== "undefined")
  2614. $('#Comment').val(message.fill);
  2615.  
  2616.  
  2617. var messageE = $('#message_'+message['msgHash']);
  2618. if (message.funcEmbed) {
  2619. var lastRow = messageE;
  2620. var button = lastRow.find('button')
  2621. button.data('payload', JSON.stringify(message));
  2622. }
  2623.  
  2624. if (skip && messageE.find('button').data('norerender'))
  2625. messageE.remove();
  2626. else if (!skip && message['func']) {
  2627. console.log('Switching', message['func']);
  2628.  
  2629. switch (message['func']) {
  2630. case 'clearButtons' :
  2631. $('#MessageDiv button[data-func]').each(function() {
  2632. var parent = $(this).closest('div.convRow');
  2633. var id = $(parent).attr('id');
  2634.  
  2635. removeMessage(id.split('_')[1]);
  2636. });
  2637.  
  2638. break;
  2639. case 'launchConnect' : startConnection(); break;
  2640. case 'emptyPing' :
  2641. window.botPing = setTimeout(function () {
  2642. if (ChatSession.otherUser && ChatSession.otherUser.userType == 'b') {
  2643. window.allowEmpty = true;
  2644. $('#Comment').val('');
  2645. sendMessage();
  2646. }
  2647. }, message['funcArg'] * 1000);
  2648. break;
  2649. case 'updateCSRF' : $('#chatForm input[name="csrf"]').val(message['funcProp']); break;
  2650. case 'checkRequests' : checkRequest(); break;
  2651. case 'popModal' : $("#"+message['funcProp']).modal(); break;
  2652. case 'setupSelect' : setupSelect(message['funcProp']); break;
  2653. case 'showElement' : console.log('SHOWING', message['funcProp']); $(message['funcProp']).show().removeClass('hidden'); break;
  2654. case 'hideElement' : console.log('HIDING', message['funcProp']); $(message['funcProp']).hide(); break;
  2655. case 'memberLogin' : loginModal({
  2656. params: {
  2657. t: 'm',
  2658. intent: 'botLogin',
  2659. bot: ChatSession.convID
  2660. },
  2661. location: (message['funcProp'] ? message['funcProp'] : '/member/connect/conversation.php?c='+ChatSession.convID)
  2662. });
  2663. break;
  2664. case 'gotoURL' : setTimeout(function () { window.location = message['funcArg'] }, 500); break;
  2665. case 'gotoListenerSignup' : setTimeout(function () { window.location = '/listener/become-a-volunteer-listener.php'}, 500); break;
  2666. case 'gotoGrowthPath' : setTimeout(function () { window.location = '/member/'}, 500); break;
  2667. case 'gotoCommunities' : setTimeout(function () { window.location = '/home/'}, 500); break;
  2668. case 'gotoChatrooms' : setTimeout(function () { window.location = '/connect/groupChatrooms.php'}, 500); break;
  2669. case 'gotoListener' : setTimeout(function () { window.location = '/connect/'}, 500); break;
  2670. case 'wellnessTestModal' : wellnessTestModal(); break;
  2671. case 'gotoTherapy' : window.loadTherapyWaiting(); break;
  2672. case 'trackTherapyLead' :
  2673. console.log('Logging FB Lead');
  2674. fbq('track', 'Lead');
  2675. break;
  2676. case 'simClick' :
  2677. // Get Newly appened record:
  2678. var lastRow = $('#message_'+message['msgHash']);
  2679. console.log('Clicking ', '#message_'+message['msgHash'], lastRow);
  2680. autoMessageFunction = setTimeout(function () {
  2681. lastRow.find('button').click();
  2682. console.log('Doing Click', lastRow.find('button'));
  2683. }, message['funcDelay']);
  2684. break;
  2685.  
  2686. case 'autoClick' :
  2687. // Get Newly appened record:
  2688. var lastRow = $('#message_'+message['msgHash']);
  2689. var button = lastRow.find('button')
  2690. console.log('Clicking ', '#message_'+message['msgHash'], button);
  2691. autoMessageFunction = setTimeout(function () {
  2692. button.click();
  2693. console.log('Doing Click', lastRow.find('button'));
  2694. }, message['funcDelay']);
  2695. break;
  2696. case 'disableChat' :
  2697. lockState(true);
  2698. break;
  2699. }
  2700. }
  2701.  
  2702. if (!ChatSession.roomType) {
  2703. if (ChatSession.lastMessage != -1 && ChatSession.relaySide == 'other' && message['convSide'] == 'mine') {
  2704. ga('send', 'event', {'eventCategory': 'Conversation', 'eventAction': 'OneRelay'});
  2705. //tracker.emit("OneRelay");
  2706. }
  2707. ChatSession.relaySide = message['convSide'];
  2708. }
  2709.  
  2710. if (ChatSession.lastMessage != -1 && message['userType'] != 'n' && message['userType'] != 'b') {
  2711. ChatSession.numConvMessages++;
  2712. listTips(ChatSession.numConvMessages);
  2713.  
  2714. if (isMobileApp()) {
  2715. if (typeof (shareContacts) === 'function') {
  2716. 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);
  2717. }
  2718.  
  2719. if (userType == 'l' && typeof (allowPush) === 'function') {
  2720. allowPush('Allow Push Notifications', 'Would you like to be notified when your users respond?', 'No Thanks', 'Notify Me', false);
  2721. }
  2722. }
  2723. }
  2724.  
  2725. if (!ChatSession.initialLoad && ChatSession.roomType)
  2726. chatroomParticipants([message], false);
  2727. }
  2728.  
  2729. if (!ChatSession.initialLoad && ChatSession.roomType)
  2730. chatroomParticipants([message], false);
  2731. }
  2732.  
  2733. }
  2734. return message.msgBody;
  2735. }
  2736.  
  2737. var lastMessageTS = 0;
  2738. function findLater(msgTS) {
  2739.  
  2740. msgTS = parseInt(msgTS);
  2741. if (msgTS >= lastMessageTS) {
  2742. lastMessageTS = msgTS;
  2743. return false;
  2744. }
  2745.  
  2746. var rows = $('#MessageDiv .convRow'), l = rows.length;
  2747. var minIndex = 0, maxIndex = l-1, currentIndex=0, cmpTime = 0;
  2748.  
  2749. if (l > 1) {
  2750. // Binary Search
  2751. while (minIndex <= maxIndex) {
  2752. currentIndex = (minIndex + maxIndex) / 2 | 0;
  2753. cmpTime = parseInt(rows[currentIndex].getAttribute('data-msgts'));
  2754. if (cmpTime < msgTS)
  2755. minIndex = currentIndex+1;
  2756. else if (cmpTime > msgTS)
  2757. maxIndex = currentIndex-1;
  2758. else {
  2759. currentIndex++;
  2760. break;
  2761. }
  2762. }
  2763.  
  2764. if (currentIndex < l-1 && msgTS > cmpTime)
  2765. currentIndex++;
  2766.  
  2767. if (currentIndex < l)
  2768. return rows[currentIndex];
  2769. }
  2770.  
  2771. lastMessageTS = msgTS;
  2772. return false;
  2773. }
  2774.  
  2775. window.botPing = false;
  2776. window.allowEmpty = false;
  2777.  
  2778. function sendMessage(massage='Default') {
  2779. var commentPost = $('#Comment').val();
  2780. if(massage!='Default'){
  2781. commentPost = massage;
  2782. }
  2783.  
  2784. if(commentPost==lastMsgSent){
  2785. return;
  2786. }
  2787.  
  2788. lastMsgSent = commentPost;
  2789.  
  2790.  
  2791. var csrf = $('#chatForm input[name="csrf"]').length ? $('#chatForm input[name="csrf"]').val() : null;
  2792.  
  2793. ChatSession.scrollDelay = 0;
  2794.  
  2795. if (sendTypingStatus) {
  2796. sendTyping(0);
  2797. }
  2798.  
  2799. if (ChatSession.otherUser && ChatSession.otherUser.userType == 'b') {
  2800.  
  2801. if (window.selectData) {
  2802. var hint = $('.tt-hint').val();
  2803. if (hint && typeof hint === "string" && hint.length > 0) {
  2804. commentPost = hint;
  2805. $('#Comment').val(commentPost);
  2806. } else {
  2807. var found = false, re = new RegExp('^'+commentPost.trim()+'$', "i");
  2808.  
  2809. for (var i = 0; i < window.selectData.length; i++)
  2810. if (re.test(window.selectData[i])) {
  2811. found = true;
  2812. break;
  2813. }
  2814. if (!found) return;
  2815. }
  2816. }
  2817.  
  2818. // Update chat bar
  2819. if (window.selectData || window.stateLocked)
  2820. resetState();
  2821. else if (window.botGUIObj)
  2822. window.botGUIObj.closeMenu();
  2823.  
  2824. }
  2825.  
  2826.  
  2827. if (commentPost != '' || window.allowEmpty) {
  2828. window.allowEmpty = false;
  2829. if (ChatSession.user.sendDisabled) {
  2830. switch (ChatSession.user.sendDisabled) {
  2831. case 'memberacct':
  2832. bootbox.confirm({
  2833. 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>',
  2834. buttons: {
  2835. confirm: {
  2836. label: 'Yes, Please',
  2837. className: 'btn-success'
  2838. },
  2839. cancel: {
  2840. label: 'no thanks',
  2841. className: 'btn-link text-muted'
  2842. }
  2843. },
  2844. callback: function (result) {
  2845. if(result){
  2846. MemberAccountModal();
  2847. }
  2848. }
  2849. });
  2850. return false;
  2851. break;
  2852. }
  2853. }
  2854.  
  2855. var sendThisMessage = true;
  2856.  
  2857. if (censorMsgAssist(commentPost) && ChatSession.user.listType != 'therapist' && ChatSession.otherUser.listType != "therapist") {
  2858. if (!(ChatSession.otherUser.userType == 'b')) {
  2859. $('#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>');
  2860. scrollConversation();
  2861. sendThisMessage = false;
  2862. } else {
  2863. //if censor assist message detected and talking to bot, send the code for crisis mode. store the actual message for later use/display
  2864. ChatSession.user.crisisMessage = commentPost;
  2865. commentPost = "/crisisAssist";
  2866. }
  2867.  
  2868. ga('send', 'event', {
  2869. 'eventCategory': 'Conversation',
  2870. 'eventAction': 'CensoredMsgAssist',
  2871. 'eventLabel': ChatSession.user.userType
  2872. });
  2873.  
  2874. } else if (censorMsgPhrases(commentPost) || (ChatSession.user.userType == 'l' && ChatSession.otherUser.userType && ChatSession.otherUser.userType == 'l' && censorMsgLLpm(commentPost))) {
  2875. ChatSession.otherUser.userType = ChatSession.roomType ? ChatSession.roomType : ChatSession.otherUser.userType;
  2876. if (ChatSession.user.listType != 'therapist' && ChatSession.otherUser.listType != "therapist") {
  2877. $('#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>');
  2878. scrollConversation();
  2879. ga('send', 'event', {
  2880. 'eventCategory': 'Conversation',
  2881. 'eventAction': 'CensoredMsg',
  2882. 'eventLabel': ChatSession.user.userType
  2883. });
  2884. sendThisMessage = false
  2885. }
  2886.  
  2887. if (ChatSession.user.userType != 'g' && !(ChatSession.user.userType == 'l' && ChatSession.otherUser.userType == 'l') && ChatSession.otherUser.userType != 'b') {
  2888. $.post('/connect/reportCensoredMsg.php', {msgBody: '[' + ChatSession.user.userType + '->' + ChatSession.otherUser.userType + '] ' + commentPost });
  2889. }
  2890. }
  2891.  
  2892. if (sendThisMessage) {
  2893. if (ChatSession.roomType) {
  2894. switch (ChatSession.roomType) {
  2895. case 'l':
  2896. var roomDesc = 'Listener Chatroom';
  2897. break;
  2898. case 'lm':
  2899. var roomDesc = 'Member Chatroom';
  2900. break;
  2901. case 'lmg':
  2902. var roomDesc = 'Guest Chatroom';
  2903. break;
  2904. default:
  2905. var roomDesc = 'Unknown Chatroom';
  2906. }
  2907. } else {
  2908. var roomDesc = 'Private Message';
  2909. }
  2910.  
  2911. $('#Comment').val('');
  2912.  
  2913. if ($(window).width() <= 767) {
  2914. //$('#Comment').blur();
  2915. }
  2916.  
  2917. var msgHash = randomHash();
  2918. var s = parseInt((new Date()).getTime() - serverTimeOffset*1000);
  2919. var sendmessage = {msgID: null,
  2920. msgHash: msgHash,
  2921. msgBody: commentPost,
  2922. msgTime: moment(s).format("h:mm A"),
  2923. userTypeID: ChatSession.user.userTypeID,
  2924. screenName: ChatSession.user.screenName,
  2925. userType: ChatSession.user.userType,
  2926. listType: ChatSession.user.listType,
  2927. imgURL: ChatSession.user.imgURL,
  2928. imageClass: ChatSession.user.imageClass,
  2929. convSide: "mine",
  2930. userColor: ChatSession.user.userColor,
  2931. convID: ChatSession.convID,
  2932. ua: ChatSession.user.ua,
  2933. badges: ChatSession.user.badges,
  2934. badgesE: ChatSession.user.badgesE,
  2935. shareIcons: ChatSession.user.shareIcons
  2936. };
  2937.  
  2938.  
  2939. if ($.inArray(ChatSession.user.userTypeID, globalMuteArr) === -1) {
  2940. ChatSession.user.currentMessages++;
  2941. if (ChatSession.user.currentMessages >= 3 && ChatSession.convID != "Sophia")
  2942. $('.returnGP').fadeIn(3000);
  2943. else
  2944. $('.returnGP').hide();
  2945.  
  2946. if (!ChatSession.roomType) {
  2947. var prefix = '';
  2948.  
  2949. if (ChatSession.user.userType == 'l')
  2950. prefix = 'listener';
  2951.  
  2952.  
  2953. if (!('privateMessagesSent' in ChatSession)) {
  2954. if (ChatSession.user.userType == 'l' && ChatSession.otherUser.userType == 'l')
  2955. ChatSession.privateMessagesSent = Math.floor(parseInt(ChatSession.numMsgListener) / 2);
  2956. else if (ChatSession.user.userType == 'l')
  2957. ChatSession.privateMessagesSent = parseInt(ChatSession.numMsgListener);
  2958. else
  2959. ChatSession.privateMessagesSent = parseInt(ChatSession.numConvMessages) - parseInt(ChatSession.numMsgListener);
  2960. }
  2961.  
  2962. if (ChatSession.user.messagesSent) {
  2963. ChatSession.user.messagesSent++;
  2964. }
  2965.  
  2966. if (!('privateMessagesSent' in ChatSession)) {
  2967. ChatSession.privateMessagesSent = 0;
  2968. }
  2969. ChatSession.privateMessagesSent++;
  2970.  
  2971. if (ChatSession.otherUser && ChatSession.otherUser.userType == 'b') {
  2972.  
  2973. botMessageCount++;
  2974. var data = {
  2975. bot: window.currentBot.bot,
  2976. botVersion: 2,
  2977. sender: 'user',
  2978. msgCount: botMessageCount,
  2979. mode: window.currentBot.mode,
  2980. stage: window.currentBot.stage
  2981. };
  2982.  
  2983. if (window.currentBot.replyToMode)
  2984. data.replyToMode = window.currentBot.replyToMode;
  2985.  
  2986. if (window.currentBot.replyToStage)
  2987. data.replyToStage = window.currentBot.replyToStage;
  2988.  
  2989. tracker.emit("botMessage", data);
  2990.  
  2991.  
  2992. } else
  2993. tracker.emit("privateMessage", {msgCount: ChatSession.privateMessagesSent});
  2994.  
  2995. } else {
  2996. if (!('groupMessagesSent' in ChatSession)) {
  2997. ChatSession.groupMessagesSent = 0;
  2998. }
  2999. ChatSession.groupMessagesSent++;
  3000. tracker.emit("groupMessage", {msgCount: ChatSession.groupMessagesSent, room: ChatSession.otherUser.screenName});
  3001. }
  3002. }
  3003.  
  3004. if (autoPingExec) {
  3005. autoPingExec = false;
  3006. } else {
  3007. loadMessage(sendmessage);
  3008. scrollConversation();
  3009. stopAutoPing();
  3010. }
  3011.  
  3012. if ($.inArray(ChatSession.user.userTypeID, globalMuteArr) === -1 || !ChatSession.roomType || ChatSession.roomType == 'l') {
  3013. if (ChatSession.nodeRoom && !(ChatSession.otherUser.userType && ChatSession.otherUser.userType == 'b')) {
  3014. sendmessage.convSide = "other";
  3015. ListMessagesSocket.emit('sendConvAction', {room: ChatSession.nodeRoom, action: 'newMessage', message: sendmessage, me: ChatSession.me});
  3016. }
  3017.  
  3018. if (commentPost.trim().toLowerCase() == 'stop') {
  3019. //console.log('Stop Noni');
  3020. stopNoni = true;
  3021. ga('send', 'event', {'eventCategory': 'Conversation', 'eventAction': 'StopNoni'});
  3022.  
  3023. } else if (waitForSend && !stopNoni) {
  3024. waitForSend = false;
  3025. var delayToTyping = 750;
  3026. var delayToOutput = 1250;
  3027.  
  3028. var noniFactor = .65;
  3029. //if (parseInt($.cookie('ab_fastSophia6')) == 1)
  3030. // noniFactor = .6;
  3031.  
  3032. setTimeout(function () {
  3033. $('#offlineMessageDiv').html('<div class="" style="margin-bottom:.5em"><small><em>' + currentNoni.screenName + ' is typing...</em></small></div>');
  3034. scrollConversation();
  3035.  
  3036. var replyopt = ['Got it', 'I see', 'Thank you', 'Alright', 'OK'];
  3037. replyopt = replyopt[Math.floor(Math.random() * replyopt.length)];
  3038.  
  3039. setTimeout(function () {
  3040. $('#offlineMessageDiv').html('');
  3041. var s = parseInt((new Date()).getTime() - serverTimeOffset*1000);
  3042. loadMessage({msgID: null,
  3043. msgHash: randomHash(),
  3044. msgBody: replyopt,
  3045. msgTime: moment(s).format("h:mm A"),
  3046. userTypeID: '0GKvccLHkpyGnA!!',
  3047. screenName: currentNoni.screenName,
  3048. userType: 'n',
  3049. imgURL: currentNoni.imgURL,
  3050. imgClass: currentNoni.imageClass,
  3051. convSide: "other",
  3052. convID: sendmessage.convID});
  3053. scrollConversation();
  3054. noniTimer = setTimeout(talkToNoni, 4000*noniFactor);
  3055. }, delayToOutput);
  3056. }, delayToTyping);
  3057. }
  3058.  
  3059. $.post('/connect/sendMessage.php', {
  3060. comment: commentPost,
  3061. csrf: csrf,
  3062. msgHash: msgHash,
  3063. convID: ChatSession.convID
  3064. }, function (json) {
  3065. if (json.ack && json.ack == 'success') {
  3066. if (json.convID == ChatSession.convID) {
  3067. if (false && json.otherScreenName && parseInt(json.otherOnline) != 2 && $.inArray(ChatSession.reqType, ['general', 'personal']) !== -1) {
  3068. if ($.inArray(userInfo.userType, ['g', 'm']) !== -1 && (!userInfo.age || userInfo.age >= 18)) {
  3069. $('#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>');
  3070. } else {
  3071. $('#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>');
  3072. }
  3073. } else {
  3074. $('#offlineMessageDiv').html('');
  3075. }
  3076. scrollConversation();
  3077.  
  3078. switch (json.action) {
  3079. case 'sendToBot' :
  3080. sendToBot(json.bot, json.autoPing);
  3081. break;
  3082. case 'createAccount':
  3083. MemberAccountModal();
  3084. $.cookie("permaCreateAccount", 1, {expires: 90, path: '/'});
  3085. if (isMobileApp()) {
  3086. $('#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>');
  3087. } else {
  3088. if (!$('#permCreateAcctButton').length) {
  3089. $('#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>');
  3090. }
  3091. }
  3092. break;
  3093.  
  3094. case 'requestRating':
  3095. if(window.ratingModal){
  3096. $('[data-actionid=rateListenerButton]').show();
  3097. $('[data-actionid=rateListenerButton] i').addClass('star-blink');
  3098. ChatSession.ratingPopped = true;
  3099. }
  3100. break;
  3101.  
  3102. case 'requestRatingShow':
  3103. if(window.ratingModal){
  3104. $('[data-actionid=rateListenerButton]').show();
  3105. $('[data-actionid=rateListenerButton] i').addClass('star-blink');
  3106. window.ratingModal.modal('show');
  3107. ChatSession.ratingPopped = true;
  3108. }
  3109. break;
  3110.  
  3111. case 'selfCareModal':
  3112. 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>');
  3113. break;
  3114. }
  3115.  
  3116. }
  3117. } else if (json.error) {
  3118. if (json.error == 'Message not sent. (Code 300)') {
  3119. var errdisp = 'Invalid login or deactivated account.';
  3120. } else if (json.error.indexOf("(Code 304)") > -1) {
  3121. var errdisp = 'This user is unavailable to chat with you, please select another.';
  3122. } else {
  3123. var errdisp = json.error;
  3124. }
  3125. $('#MessageDiv').append('<div class="alert alert-danger pull-left">' + errdisp + '</div>');
  3126.  
  3127. scrollConversation();
  3128. }
  3129. }, 'json').always(function () {
  3130. $('#msgs-loading').hide();
  3131. });
  3132.  
  3133.  
  3134. //ga('send', 'event', {'eventCategory': 'Conversation', 'eventAction': 'MessageSent', 'eventLabel': roomDesc});
  3135. //Fix via HTTP API
  3136. //mixpanel.people.increment("MessageSent");
  3137.  
  3138.  
  3139. }
  3140. }
  3141. }
  3142. }
  3143.  
  3144. function muteUserPopup(userTypeID, screenName) {
  3145. var modalhtml = '<div class="text-center">';
  3146. modalhtml += '<h2>Has <strong>' + screenName + '</strong> acted inappropriately or in violation of our Terms of Service?</h2>';
  3147. 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>';
  3148. modalhtml += '<div class="row" id="chatroomReportOptions" style="margin-top: 2em;">';
  3149. 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>';
  3150. if (ChatSession.user.userType != 'g') {
  3151. 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">';
  3152. modalhtml += ChatSession.user.isMod && false ? 'Moderator Mute for All!' : 'Yes, <strong>FILE REPORT!</strong>';
  3153. modalhtml += '</button></div>';
  3154. }
  3155. modalhtml += '</div>';
  3156. modalhtml += '<div style="margin-top:1em"><span data-dismiss="modal" style="cursor:pointer;color:#999;">Cancel</span></div></div>';
  3157. $('#multiModal .modal-body').html(modalhtml);
  3158. $('#multiModal').modal({backdrop: true, keyboard: true});
  3159. }
  3160.  
  3161. function referUserPopup(userTypeID, screenName) {
  3162. var modalhtml = '<div class="text-center"><h2 style="margin:1em 0 .5em 0;">Refer ' + screenName + '</h2>';
  3163. 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>';
  3164. modalhtml += '<div class="row">';
  3165. 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>';
  3166. 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>';
  3167. modalhtml += '</div></div>';
  3168. $('#multiModal .modal-body').html(modalhtml);
  3169. $('#multiModal').modal({backdrop: true, keyboard: true});
  3170. }
  3171.  
  3172. function referUser(userTypeID) {
  3173. if (ChatSession.nodeRoom) {
  3174. ListMessagesSocket.emit('sendConvAction', {room: ChatSession.nodeRoom, action: 'referalResources', userTypeID: userTypeID, me: ChatSession.me});
  3175. }
  3176. $('#multiModal').modal('hide');
  3177. }
  3178.  
  3179. function reportUser(userTypeID) {
  3180. if ($('#chatroomReportReason > textarea').val() != undefined && $('#chatroomReportReason > textarea').val() != '') {
  3181. $.post('/connect/reportChatroomUser.php', {userTypeID: userTypeID, reason: $('#chatroomReportReason > textarea').val(), convID: ChatSession.convID});
  3182. muteUser(userTypeID);
  3183. $('#multiModal').modal('hide');
  3184. } else {
  3185. $('#chatroomReportReason').addClass('has-error');
  3186. }
  3187. }
  3188.  
  3189. function listTips(msgNum) {
  3190.  
  3191. if (typeof ChatSession.otherUser !== "undefined" && ChatSession.otherUser.userType && ChatSession.otherUser.userType == 'b')
  3192. return false;
  3193.  
  3194. function showTip(msgNum) {
  3195. msgNum = ChatSession.roomType ? ChatSession.numConvMessages - ChatSession.init_numConvMessages : msgNum;
  3196. ChatSession.tips.shown = ChatSession.tips.shown || [];
  3197. if (ChatSession.tips.copy && ChatSession.tips.copy[msgNum] && $.inArray(msgNum, ChatSession.tips.shown) === -1) {
  3198. ChatSession.tips.shown.push(msgNum);
  3199. $('#MessageDiv').append('<div class="alert" style="color:#999;font-size:0.9em"><i class="fa fa-info-circle"></i> ' + ChatSession.tips.copy[msgNum] + '</div>');
  3200. scrollConversation();
  3201. }
  3202. }
  3203.  
  3204. if (ChatSession.tips.copy) {
  3205. showTip(msgNum);
  3206. } else {
  3207. $.post('/connect/chatTips.php', {convID: ChatSession.convID}, function (json) {
  3208. if (json) {
  3209. ChatSession.tips.copy = json.tips;
  3210. showTip(msgNum);
  3211. }
  3212. }, 'json');
  3213. }
  3214. }
  3215.  
  3216. function showCaptcha() {
  3217. if (!window.bootboxCaptcha) {
  3218. var tvar = {origin: window.location.pathname};
  3219.  
  3220. if (ChatSession.convID) {
  3221. tvar.origin += '?c=' + ChatSession.convID;
  3222. } else if (getQSval('c')) {
  3223. tvar.origin += '?c=' + getQSval('c');
  3224. }
  3225.  
  3226. render(false, 'Forms_Captcha_ChatCaptcha', tvar, function (content) {
  3227. window.bootboxCaptcha = bootbox.dialog({
  3228. message: content,
  3229. closeButton: false,
  3230. onEsacape: false,
  3231. size: 'small'
  3232. }).on('shown.bs.modal', function () {
  3233. $(this).find('.captchaParent').load('/objects/captcha/renderCaptcha.php?captcha-w=225&captcha-h=60');
  3234. $(this).find('[name="vscu"]').focus();
  3235. }).on('hidden.bs.modal', function () {
  3236. delete window.bootboxCaptcha;
  3237. });
  3238. });
  3239. }
  3240. }
  3241.  
  3242. function bindSocket() {
  3243.  
  3244. console.log('PRE-BINDING JS FUNCTIONS');
  3245.  
  3246. // Delay execution until async scripts are downloaded
  3247. if (typeof window.ListMessagesSocket.on === 'undefined') {
  3248. initTimer = setTimeout(bindSocket, 25);
  3249. return;
  3250. }
  3251. window.ListMessagesSocket.bindTime = (new Date()).getTime();
  3252. console.log('BINDING JS FUNCTIONS', window.ListMessagesSocket.bindTime);
  3253.  
  3254. ListMessagesSocket.on('reconnect_failed', function () {
  3255. alert('Error: Unable to connect to Chat Server');
  3256. });
  3257.  
  3258. ListMessagesSocket.on('reconnect', function () {
  3259. if (ChatSession.nodeRoom) {
  3260. ListMessagesSocket.emit('addToRooms', [ChatSession.nodeRoom]);
  3261. }
  3262. });
  3263.  
  3264. ListMessagesSocket.on('notification', function (notification) {
  3265. if (ChatSession.convID && ChatSession.nodeRoom == notification.roomID) {
  3266. if (notification.msg && notification.msg.indexOf("globalMute_") === 0) {
  3267. var muteUserTypeID = notification.msg.replace('globalMute_', '');
  3268. globalMuteUsers(muteUserTypeID);
  3269. } else if (notification.msg) {
  3270. switch (notification.msg) {
  3271. case 'startTopic':
  3272. ChatSession.discussion = {Topic: notification.Topic, endTime: notification.endTime};
  3273. processTopic();
  3274. break;
  3275. case 'endTopic':
  3276. delete ChatSession.discussion;
  3277. processTopic();
  3278. break;
  3279. }
  3280. }
  3281. } else {
  3282. try {
  3283. var json = JSON.parse(notification.msg);
  3284. if (json.alert) {
  3285. bootbox.alert(json.alert);
  3286. }
  3287. }
  3288. catch (e) {
  3289. }
  3290. }
  3291. });
  3292.  
  3293. ListMessagesSocket.on('recConvAction', function (data) {
  3294. console.log(data);
  3295. if (ChatSession.nodeRoom == data.room) {
  3296. switch (data.action) {
  3297. case 'authexp':
  3298. if (ChatSession && ChatSession.convID) {
  3299. setConversation(ChatSession.convID, true);
  3300. }
  3301. break;
  3302.  
  3303. case 'endLiveChat':
  3304. endLiveChat(true);
  3305. break;
  3306.  
  3307. case 'modRemove':
  3308. removeMessage(data.msgHash);
  3309. break;
  3310.  
  3311. case 'typingStatus':
  3312. if (!ChatSession.roomType && data.screenName && data.screenName != ChatSession.user.screenName) {
  3313. var msg = data.isTyping ? '<em>' + data.screenName + ' is typing...</em>' : '';
  3314. $('#offlineMessageDiv').html('<div class="" style="margin-bottom:1em;"><small>' + msg + '</small></div>');
  3315. scrollConversation();
  3316. }
  3317. break;
  3318.  
  3319. case 'newMessage':
  3320. if (data.message.convID == ChatSession.convID && data.message.userType != 'n') {
  3321. if (data.message.msgTS)
  3322. var s = data.message.msgTS*1000;
  3323. else
  3324. var s = parseInt((new Date()).getTime() - serverTimeOffset*1000);
  3325.  
  3326. data.message.msgTime = moment(s).format("h:mm A");
  3327. console.log(data.message.msgBody);
  3328. var censoredMsg = loadMessage(data.message);
  3329. // console.log(data.message.msgBody.split(" "));
  3330. if(censoredMsg != data.message.msgBody){
  3331. console.log("Gaali Bak delas");
  3332. }
  3333. var censorArr = censoredMsg.split(" ");
  3334. var uncensorArr = data.message.msgBody.split(" ");
  3335. var lenth = uncensorArr.length;
  3336. var isGaali = false;
  3337. var newMsg = "";
  3338. for (var i=0;i<lenth;i++){
  3339. if((censorArr[i]!=uncensorArr[i]) && censorArr[i]=="***"){
  3340. isGaali = true;
  3341. var newWord = "";
  3342. for(var j=0;j<uncensorArr[i].length;j++){
  3343. newWord+=uncensorArr[i][j];
  3344. newWord+="_";
  3345. }
  3346. newMsg = newMsg + newWord + " ";
  3347. }
  3348. else{
  3349. newMsg = newMsg + uncensorArr[i] + " ";
  3350. }
  3351. }
  3352. if(isGaali){
  3353. console.log("Gaali = " + newMsg);
  3354. }
  3355. scrollConversation();
  3356. }
  3357. break;
  3358.  
  3359. case 'enterRoom':
  3360. if (data.screenName && data.screenName != ChatSession.user.screenName) {
  3361. $('#MessageDiv').append('<div class="enterRoom"><i class="fa fa-user"></i> ' + data.screenName + ' has entered this room.</div>');
  3362. scrollConversation();
  3363. }
  3364. break;
  3365.  
  3366. case 'heartMsg':
  3367. var curPoints = $('#message_' + data.msgHash + ' .pointHolder').text() != '' ? parseInt($('#message_' + data.msgHash + ' .pointHolder').text()) : 0;
  3368. var newPoints = curPoints + 1;
  3369. if (newPoints <= 20) {
  3370. $('#message_' + data.msgHash + ' .pointHolder').text(' +' + newPoints);
  3371. $('#message_' + data.msgHash + ' .heartCommentButton').removeClass('compassionHeartFade').addClass('compassionHeart').show();
  3372.  
  3373. if (!someheartedyou && ChatSession.user.userType == 'g' && $('#message_' + data.msgHash).attr('data-usertypeid') == ChatSession.user.userTypeID) {
  3374. $('#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&rsquo;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>');
  3375. $('#multiModal').modal({backdrop: true, keyboard: true});
  3376. someheartedyou = true;
  3377. }
  3378. }
  3379. break;
  3380.  
  3381. case 'referalResources':
  3382. if (data.userTypeID == ChatSession.user.userTypeID && !$.cookie('resourcesSent')) {
  3383. $('#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>');
  3384. $('#multiModal').modal({backdrop: true, keyboard: true});
  3385. $.cookie("resourcesSent", true, {path: '/'});
  3386. }
  3387. break;
  3388. }
  3389. }
  3390. });
  3391.  
  3392.  
  3393. }
  3394. bindSocket();
  3395.  
  3396. function chatroomParticipants(inChatroom, newlist) {
  3397. window.chatroomParticipantList = !newlist && window.chatroomParticipantList ? window.chatroomParticipantList : [];
  3398.  
  3399. NewParticipantLoop:
  3400. for (var i = 0; i < inChatroom.length; i++) {
  3401. var u = inChatroom[i];
  3402. if(u.screenName && u.userTypeID){
  3403. if(u.userType && $.inArray(u.userType, ['l', 'm']) !== -1){u.profileURL = '/@'+u.screenName;}
  3404.  
  3405. for(var pi =0; pi < window.chatroomParticipantList.length; pi++){
  3406. if(window.chatroomParticipantList[pi].userTypeID === u.userTypeID){
  3407. window.chatroomParticipantList[pi] = u;
  3408. continue NewParticipantLoop;
  3409. }
  3410. }
  3411.  
  3412. window.chatroomParticipantList.push(u);
  3413. }
  3414. }
  3415.  
  3416. window.chatroomParticipantList.sort(function(a, b){
  3417. if (a.screenName.toLowerCase() === b.screenName.toLowerCase()) return 0;
  3418. return a.screenName.toLowerCase() > b.screenName.toLowerCase() ? 1 : -1;
  3419. });
  3420.  
  3421. render(false, 'Chat_CurrentParticipants', {
  3422. participants: window.chatroomParticipantList
  3423. }, function (content) {
  3424. $('#listenersInChatroomModal .modal-body').html(content);
  3425. });
  3426.  
  3427. $('#listenersInChatDiv').html('<div class="text-center "><small><a href="#" onclick="chatRoomRules();" style="color:#5cc8df;font-weight:bold;">Please read the Chatroom Rules</a>&nbsp;&nbsp;|&nbsp;&nbsp;<a href="#" data-toggle="modal" data-target="#listenersInChatroomModal" style="color:##1e90fe;font-weight:bold;">' + window.chatroomParticipantList.length + ' Currently Participating</a></small></div>');
  3428. }
  3429.  
  3430. var checkConvTimeout;
  3431. var debugger1 = '';
  3432. function checkConv(setConvID) {
  3433. clearTimeout(checkConv);
  3434. var setConvReqID = typeof (setConvID) !== 'undefined' ? setConvID : ChatSession.convID;
  3435. if (!requestRedirect && (ChatSession.lastMessage != ChatSession.checkingMessNow)) {
  3436. ChatSession.checkingMessNow = ChatSession.lastMessage;
  3437.  
  3438. if (ChatSession.checkingMessNow == -1) {
  3439. if (window.chatInfoMemory[userInfo.userIDe + setConvID] && window.chatInfoMemory[userInfo.userIDe + setConvID].messages) {
  3440. preloadingMessages = true;
  3441. debugger1 = userInfo.userIDe + setConvID;
  3442. $.each(window.chatInfoMemory[userInfo.userIDe + setConvID].messages, function (key, value) {
  3443. loadMessage(value, true);
  3444. });
  3445. scrollConversation();
  3446. preloadingMessages = false;
  3447. }
  3448. }
  3449.  
  3450. $.post("/connect/checkConvMessages.php", {convID: setConvReqID, lastMessage: ChatSession.checkingMessNow}, function (json) {
  3451. serverTimeOffset = (new Date()).getTime()/1000-json['serverTime'];
  3452. console.log('Setting server time offset:', serverTimeOffset);
  3453. loadConversation(json);
  3454. if (!ChatSession.roomType)
  3455. checkMessages();
  3456.  
  3457. if (ChatSession.otherUser && ChatSession.otherUser.userType == 'b') {
  3458.  
  3459. $('#MessageScrollDiv .alert').hide();
  3460. $('#MessageScrollDiv .alert.alert-noni').show();
  3461. if (typeof json.bot !== 'undefined')
  3462. sendToBot(json.bot, json.autoPing);
  3463.  
  3464. if (typeof json.suppressToast !== 'undefined')
  3465. window.suppressToast = true;
  3466. } else
  3467. $('#MessageScrollDiv .alert.alert-noni').hide();
  3468.  
  3469.  
  3470. }, 'json').always(function () {
  3471. //checkConvTimeout = setTimeout(checkConv, 60000 * 3);
  3472. });
  3473. }
  3474.  
  3475. var loadAttempts = 0;
  3476. function loadConversation(json) {
  3477. if (typeof (setConvID) !== 'undefined' && setConvID != ChatSession.convID) {
  3478. if (loadAttempts <= 100) {
  3479. setTimeout(function () {
  3480. loadConversation(json)
  3481. }, 200);
  3482. loadAttempts++;
  3483. }
  3484. } else {
  3485.  
  3486. if (json.ack && json.ack == 'success') {
  3487. if (ChatSession.convID == json.convID) {
  3488. ChatSession.user.userTypeID = json.user.userTypeID;
  3489. //var newMessages = false;
  3490.  
  3491. // Make sure other message loading isn't also happening
  3492. loadAllMessages = function () {
  3493. if (!preloadingMessages) {
  3494. console.log('Loading Ajax Messages');
  3495.  
  3496. var idx = userInfo.userIDe + ChatSession.convID;
  3497. window.chatInfoMemory[idx] = window.chatInfoMemory[idx] || {};
  3498. window.chatInfoMemory[idx].messages = window.chatInfoMemory[idx].messages || [];
  3499. var chatMsgs = window.chatInfoMemory[idx].messages;
  3500.  
  3501. var histMap = {};
  3502. for (var k = 0; k < chatMsgs.length; k++)
  3503. histMap[chatMsgs[k].msgHash] = k;
  3504.  
  3505.  
  3506. var updated = false;
  3507. var newQueue = [];
  3508.  
  3509.  
  3510. for (var i = 0; i < json.messages.length; i++) {
  3511. 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)) {
  3512. updated = true;
  3513. chatMsgs[histMap[json.messages[i].msgHash]].msgID = json.messages[i].msgID;
  3514. chatMsgs[histMap[json.messages[i].msgHash]].msgTime = json.messages[i].msgTime;
  3515. var msg = $("#message_" + json.messages[i].msgHash);
  3516. if (msg[0]) {
  3517. msg[0].setAttribute('data-msgid', json.messages[i].msgID);
  3518. msg.find('.msgTime').html(json.messages[i].msgTime);
  3519. }
  3520. } else if (!histMap[json.messages[i].msgHash]) {
  3521. newQueue.push(json.messages[i]);
  3522. updated = true;
  3523. chatMsgs.push(json.messages[i]);
  3524. }
  3525. }
  3526.  
  3527. for (var t = 0; t < newQueue.length; t++)
  3528. loadMessage(newQueue[t], true);
  3529.  
  3530.  
  3531. chatMsgs.sort(function (x, y) {
  3532. if (x.msgID < y.msgID) {
  3533. return -1;
  3534. }
  3535. if (x.msgID > y.msgID) {
  3536. return 1;
  3537. }
  3538. return 0;
  3539. });
  3540.  
  3541. if (updated) {
  3542. chatMsgs = chatMsgs.slice(-40);
  3543. window.chatInfoMemory[idx].messages = chatMsgs;
  3544. console.log('Resaving history', idx, window.chatInfoMemory[idx]);
  3545. }
  3546.  
  3547.  
  3548. } else {
  3549. console.log('Waiting to preload messages');
  3550. setTimeout(loadAllMessages, 100);
  3551. }
  3552. };
  3553.  
  3554. loadAllMessages();
  3555.  
  3556. ChatSession.lastMessage = json.lastMessage;
  3557.  
  3558. if (ChatSession.initialLoad) {
  3559. talkToNoni();
  3560.  
  3561. if ((ChatSession.reqType && ChatSession.reqType === 'general_therapy' || ChatSession.reqType === 'personal_therapy') || (ChatSession.convID == "Sophia")) {// && ChatSession.reqStatus && ChatSession.reqStatus === 'request'){
  3562. $('#bottomStatus').slideUp(function () {
  3563. if (typeof resizeChat == 'function') {
  3564. resizeChat();
  3565. }
  3566. });
  3567.  
  3568. $('body').addClass('in-therapy');
  3569. $('#non-therapy-ad').hide();
  3570. window.holdToast = true;
  3571. if (ChatSession.reqStatus === 'request' || ChatSession.convID == "Sophia")
  3572. render(false, 'Ads_Therapyreviews', {}, function (content) {
  3573. var e = $('#therapy-reviews-holder');
  3574. e.empty().hide().html(content);
  3575. e.find('.therapyReviews').carousel();
  3576. e.fadeIn();
  3577. });
  3578. else
  3579. render(false, 'Ads_Therapysupport', {}, function (content) {
  3580. var e = $('#therapy-reviews-holder');
  3581. e.empty().hide().html(content);
  3582. e.fadeIn();
  3583. });
  3584.  
  3585. if (typeof Stripe === 'undefined') {
  3586. (function (e, t) {
  3587. var n = t.createElement("script");
  3588. n.type = "text/javascript";
  3589. n.async = true;
  3590. n.src = "https://js.stripe.com/v2/";
  3591. var s = t.getElementsByTagName("script")[0];
  3592. s.parentNode.insertBefore(n, s);
  3593. })(window, document);
  3594.  
  3595. window.stripeInit = setInterval(function () {
  3596. if (typeof Stripe !== 'undefined') {
  3597. console.log('Stripe Initialized');
  3598. Stripe.setPublishableKey(StripePublishableKey);
  3599. clearInterval(window.stripeInit);
  3600. window.libraryState += '-stripe-';
  3601. }
  3602. }, 100);
  3603. }
  3604. if (!ecAdded && typeof ga !== 'undefined') {
  3605. ecAdded = true;
  3606. ga('require', 'ec');
  3607. ga('ec:addImpression', {
  3608. 'id': 'onlinetherapy',
  3609. 'name': 'Online Therapy',
  3610. 'category': 'therapy',
  3611. 'brand': '7 Cups',
  3612. 'position': 1,
  3613. });
  3614. ga('ec:setAction', 'detail');
  3615.  
  3616. (function (e, t) {
  3617. var n = t.createElement("script");
  3618. n.type = "text/javascript";
  3619. n.async = true;
  3620. n.src = "https://www.googleadservices.com/pagead/conversion_async.js";
  3621. var s = t.getElementsByTagName("script")[0];
  3622. s.parentNode.insertBefore(n, s);
  3623. })(window, document);
  3624. }
  3625. if (typeof __adroll !== "undefined") {
  3626. try {
  3627. __adroll.record_user({"adroll_segments": "acc662f5"})
  3628. } catch(err) {}
  3629. }
  3630.  
  3631. } else {
  3632. $('body').removeClass('in-therapy');
  3633. window.holdToast = false;
  3634. $('#therapy-reviews-holder').hide();
  3635. $('#non-therapy-ad').fadeIn();
  3636. }
  3637. }
  3638.  
  3639. if (json.inChatroom) {
  3640. chatroomParticipants(json.inChatroom, true);
  3641.  
  3642. if (json.overFlow) {
  3643. if ($('#overflowAlert').length) {
  3644. var roomBtns = '';
  3645. for (var i = 0; i < json.overFlow.length; i++) {
  3646. if (ChatSession.user.userType = 'l') {
  3647. var url = '/listener/connect/conversation.php?c=' + json.overFlow[i]['convID'];
  3648. } else {
  3649. var url = '/member/connect/conversation.php?c=' + json.overFlow[i]['convID'];
  3650. }
  3651. roomBtns += '<a href="' + url + '" class="btn btn-default btn-sm">' + json.overFlow[i]['chatroomName'] + ' ' + json.overFlow[i]['reqTime'] + '</a> ';
  3652. }
  3653.  
  3654. 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>';
  3655.  
  3656. $('#offlineMessageDiv').append(roomBtns);
  3657. scrollConversation();
  3658. }
  3659. } else {
  3660. $('#overflowAlert').hide();
  3661. }
  3662. }
  3663.  
  3664. scrollConversation();
  3665. ChatSession.initialLoad = false;
  3666. }
  3667.  
  3668.  
  3669. } else if (json.error) {
  3670. if (json.error == 'Please verify you are human') {
  3671. showCaptcha();
  3672. } else if (console && console.log) {
  3673. $('#MessageDiv').append('<div class="alert alert-danger pull-left">' + json.error + '</div>');
  3674. }
  3675. }
  3676.  
  3677.  
  3678. $('#msgs-loading').hide();
  3679. }
  3680. }
  3681. }
  3682.  
  3683. function groupChatOrientation() {
  3684. /*
  3685. if ($.cookie('newuser_groupsupport') && !isMobileApp()) {
  3686. $.removeCookie('newuser_groupsupport', {path: '/'});
  3687. $('#popoverTarget').popover({
  3688. container: 'body',
  3689. 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 &ldquo;Hello&rdquo; <img src="'+cloudfrontBase+'img/emoticons/smile.png" /></h4>',
  3690. trigger: 'hover',
  3691. placement: 'top',
  3692. html: 'true'
  3693. }).popover('show');
  3694.  
  3695. $("body").append($("<div>").css({
  3696. position: "fixed"
  3697. , width: "100%"
  3698. , height: "100%"
  3699. , "background-color": "#000"
  3700. , opacity: 0.6
  3701. , "z-index": 1001
  3702. , top: 0
  3703. , left: 0
  3704. }).attr("id", "page-cover")).click(function () {
  3705. $('#page-cover').remove();
  3706. $('.popover').popover('hide');
  3707. $('#chatForm').popover('destroy');
  3708. });
  3709. }*/
  3710. }
  3711.  
  3712. loadRatingModalFails = 0;
  3713. function loadRatingModal() {
  3714. //have to wait until handlebars is loaded in
  3715. if(typeof(render) != 'function'){
  3716. if(loadRatingModalFails >= 8){
  3717. throw Error('Error opening modal. Handlebars not loading.')
  3718. } else {
  3719. setTimeout(loadRatingModal, 1000);
  3720. loadRatingModalFails++;
  3721. return;
  3722. }
  3723. }
  3724.  
  3725. render(false, 'Forms_Connect_RateListener', {
  3726. convID: ChatSession.convID,
  3727. screenName: ChatSession.otherUser.screenName
  3728. }, function (content) {
  3729. $('div.modal-rating').remove();
  3730. window.ratingModal = bootbox.dialog({
  3731. message: content,
  3732. show: false,
  3733. className: 'modal-rating'
  3734. });
  3735.  
  3736. window.ratingModal.init(function () {
  3737. if (ChatSession.ratingPopped) {
  3738. $('[data-actionid=rateListenerButton]').show();
  3739. }
  3740. });
  3741.  
  3742. window.ratingModal.on('shown.bs.modal', function(){
  3743. tracker.emit("RatingModalShown");
  3744. });
  3745.  
  3746. if (getQSval('rp') && !window.didRP) {
  3747. window.didRP=1;
  3748. function checkPageReady() {
  3749. if (window.pageReady)
  3750. window.ratingModal.modal('show');
  3751. else
  3752. setTimeout(checkPageReady, 100);
  3753. }
  3754. setTimeout(checkPageReady, 500);
  3755. }
  3756. });
  3757.  
  3758. // $.post('/connect/listenerRating.php', {a: 'req', convID: ChatSession.convID}, function (json) {
  3759. // if (true) {
  3760. // render(false, 'Forms_Connect_RateListener', {
  3761. // convID: ChatSession.convID,
  3762. // screenName: ChatSession.otherUser.screenName
  3763. // }, function (content) {
  3764. // $('div.modal-rating').remove();
  3765. // window.ratingModal = bootbox.dialog({
  3766. // message: content,
  3767. // show: false,
  3768. // className: 'modal-rating'
  3769. // });
  3770.  
  3771. // window.ratingModal.init(function () {
  3772. // if (ChatSession.ratingPopped) {
  3773. // $('[data-actionid=rateListenerButton]').show();
  3774. // }
  3775. // });
  3776.  
  3777. // if (getQSval('rp') && !window.didRP) {
  3778. // window.didRP=1;
  3779. // function checkPageReady() {
  3780. // if (window.pageReady)
  3781. // window.ratingModal.modal('show');
  3782. // else
  3783. // setTimeout(checkPageReady, 100);
  3784. // }
  3785. // setTimeout(checkPageReady, 500);
  3786. // }
  3787.  
  3788.  
  3789. // });
  3790. // }
  3791. // }, 'json');
  3792. }
  3793.  
  3794. $(function () {
  3795. $('body').on('shown.bs.modal', 'div.modal-rating', function () {
  3796. var $modal = $(this).closest('div.modal-rating');
  3797. });
  3798.  
  3799. $('body').on('submit', 'div.modal-rating form[data-id="feedbackForm"]', function () {
  3800. var $modal = $(this).closest('div.modal-rating');
  3801. ga('send', 'event', {eventCategory: 'Conversation', eventAction: 'Review', eventLabel: 'Written'});
  3802. var $form = $(this);
  3803. var starValue = ChatSession.otherUser['rating'];
  3804. var feedbackInput = $form.find('textarea[name="feedbackInput"]').val();
  3805. $form.find('.alert').remove();
  3806. if (!(starValue > 0 && starValue <= 5 && feedbackInput.length > 14)) {
  3807. var warningText = '<div class="alert alert-danger">';
  3808. var starPass = true;
  3809. var feedbackPass = true;
  3810. if(!(starValue > 0 && starValue <= 5)){
  3811. starPass = false;
  3812. }
  3813. if(feedbackInput.length <= 14){
  3814. feedbackPass = false;
  3815. }
  3816.  
  3817. if (!starPass && !feedbackPass) {
  3818. warningText = warningText + 'Please provide a star rating and ensure the review is at least 15 characters.';
  3819. } else if(!starPass) {
  3820. warningText = warningText + 'Please provide a star rating.';
  3821. } else if(!feedbackPass) {
  3822. warningText = warningText + 'Please provide a review with at least 15 characters.';
  3823. } else {
  3824. warningText = warningText + 'Unknown error';
  3825. }
  3826.  
  3827. warningText = warningText + '</div>';
  3828. $form.append(warningText);
  3829. return false;
  3830. }
  3831.  
  3832. $form.find('button[type=submit]').attr('data-html', function () {
  3833. return $(this).html()
  3834. }).html('Processing <i class="fa fa-spin fa-spinner"></i>').attr('disabled', 'true');
  3835.  
  3836. $.post('/connect/listenerRating.php', {
  3837. a: 'rating',
  3838. convID: $form.find('input[name="convID"]').val() || ChatSession.convID,
  3839. overallRating: starValue,
  3840. feedbackInput: feedbackInput
  3841. }, function (json) {
  3842. if (json.ack && json.ack == 'success') {
  3843. $modal.on('hidden.bs.modal', function () {
  3844. if (starValue <= 3) {
  3845. 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>');
  3846. } else {
  3847. 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>');
  3848. }
  3849. }).modal('hide');
  3850. $form.find('textarea[name="feedbackInput"]').val('');
  3851. //hide rate button after submitting a review (should be unavailable for 48hrs)
  3852. $('[data-actionid=rateListenerButton]').hide();
  3853. } else {
  3854. json.error = json.error || 'Feedback text not received';
  3855. $form.append('<div class="alert alert-danger">' + json.error + '</div>');
  3856. }
  3857. }, 'json').always(function () {
  3858. $form.find('button[type=submit]').html(function () {
  3859. return $(this).attr('data-html')
  3860. }).removeAttr('disabled');
  3861. });
  3862.  
  3863. $('[data-actionid=rateListenerButton] i').removeClass('star-blink');
  3864. return false;
  3865. });
  3866.  
  3867. //Submit Ratings
  3868. $('body').on('mouseenter mouseleave click', 'div.modal-rating [data-rating] > i', function (e) {
  3869. var $modal = $(this).closest('div.modal-rating');
  3870. var clickedStar = $(this);
  3871. // var ratingIDint = parseInt(clickedStar.closest('[data-rating]').attr('data-rating'));
  3872.  
  3873. switch (e.type) {
  3874. case 'mouseenter':
  3875. lightStars($modal, parseInt($(this).attr('data-value')));
  3876. ratingDescription($modal, parseInt($(this).attr('data-value')));
  3877. break;
  3878.  
  3879. case 'mouseleave':
  3880. lightStars($modal);
  3881. ratingDescription($modal);
  3882. break;
  3883.  
  3884. case 'click':
  3885. var newRating = parseInt(clickedStar.attr('data-value'));
  3886. ChatSession.otherUser['rating'] = newRating;
  3887.  
  3888. lightStars($modal);
  3889. ratingDescription($modal, newRating);
  3890.  
  3891. // $.post('/connect/listenerRating.php', {
  3892. // a: 'set',
  3893. // convID: clickedStar.closest('form').find('input[name="convID"]').val(),
  3894. // r: ratingIDint,
  3895. // v: newRating
  3896. // });
  3897.  
  3898. $('[data-actionid=rateListenerButton] i').removeClass('star-blink');
  3899.  
  3900. // var overallRating = 0;
  3901. // var numSet = 0;
  3902. // for (var i = 1; i <= 4; i++) {
  3903. // if (parseInt(ChatSession.otherUser['ratingR' + i]) > 0) {
  3904. // overallRating = overallRating + parseInt(ChatSession.otherUser['ratingR' + i]);
  3905. // numSet++;
  3906. // }
  3907. // }
  3908.  
  3909. // if (numSet) {
  3910. // overallRating = overallRating / numSet;
  3911. // ChatSession.goodExperience = overallRating >= 4;
  3912. // if (numSet >= 4) {
  3913. // tracker.emit("ListenerRating", {rating: overallRating});
  3914. // if (ChatSession.goodExperience) {
  3915. // $modal.on('hidden.bs.modal', function () {
  3916. // bootbox.confirm({
  3917. // message: '<h2 class="text-center">Would you consider supporting 7 Cups?</h2>',
  3918. // buttons: {
  3919. // cancel: {
  3920. // label: "no thanks",
  3921. // className: "btn-link"
  3922. // },
  3923. // confirm: {
  3924. // label: "Yes",
  3925. // className: "btn-success"
  3926. // }
  3927. // },
  3928. // callback: function (result) {
  3929. // if (result)
  3930. // window.location.href = '/backus/back7cups.php';
  3931. // }
  3932. // });
  3933. // });
  3934. // }
  3935. // }
  3936. // }
  3937. break;
  3938. }
  3939. });
  3940.  
  3941. function lightStars($modal, hoveredOverInt) {
  3942. hoveredOverInt = (hoveredOverInt != null) ? hoveredOverInt : parseInt(eval('ChatSession.otherUser.rating'));
  3943. $modal.find('[data-rating="1"] > i').removeClass('fa-star').removeClass('text-warning').addClass('fa-star-o');
  3944. $modal.find('[data-rating="1"] > i:lt(' + hoveredOverInt + ')').removeClass('fa-star-o').addClass('fa-star').addClass('text-warning');
  3945. }
  3946.  
  3947. function ratingDescription($modal, ratingValue) {
  3948. text = '';
  3949. ratingValue = (ratingValue != null) ? ratingValue : parseInt(eval('ChatSession.otherUser.rating'));
  3950. switch (ratingValue) {
  3951. case 1:
  3952. text = 'This was not a helpful chat.';
  3953. break;
  3954. case 2:
  3955. text = 'Could have gone better.';
  3956. break;
  3957. case 3:
  3958. text = 'It went okay.';
  3959. break;
  3960. case 4:
  3961. text = 'I liked it, helpful chat.';
  3962. break;
  3963. case 5:
  3964. text = 'Loved it! Awesome chat!';
  3965. break;
  3966. default:
  3967. break;
  3968. }
  3969.  
  3970. $modal.find('[name="ratingText"]').text(text);
  3971. }
  3972. });
  3973.  
  3974. function scrollConversation() {
  3975. ChatSession.scrollDelay = ChatSession.scrollDelay || 0;
  3976. var unix = Math.round(+new Date() / 1000);
  3977. if (unix >= ChatSession.scrollDelay) {
  3978. $("#MessageScrollDiv").animate({scrollTop: $("#MessageScrollDiv").prop("scrollHeight")}, 300);
  3979. }
  3980. }
  3981.  
  3982. function showUnmuteButton() {
  3983. if (!$('#unMuteButton').length && $.cookie('muteArr')) {
  3984. if (isMobileApp()) {
  3985. $('#unMuteButton').show();
  3986. } else {
  3987. $('#actionButtons').append(
  3988. '<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"/>');
  3989. }
  3990. }
  3991. }
  3992.  
  3993. function attachTestResults(data) {
  3994. var jsonObj = JSON.parse(data);
  3995. var resultsDiv = document.createElement("div");
  3996. resultsDiv.id = "resultsDiv";
  3997. resultsDiv.classList.add("resultsMain");
  3998. resultsDiv.innerHTML = "Loading Results...";
  3999.  
  4000. var bbModal = bootbox.dialog({
  4001. title: 'Results',
  4002. message: resultsDiv
  4003. });
  4004.  
  4005. $('#resultsDiv').setWellnessEngineTestInterface(jsonObj.testID, jsonObj.sessionID);
  4006. }
  4007.  
  4008. function wellnessTestModal() {
  4009. if (typeof (gpTest) !== 'undefined') {
  4010. wtRender();
  4011. } else {
  4012. $.getScript('/exercises/js/test.js', function () {
  4013. wtRender();
  4014. });
  4015. }
  4016.  
  4017. function wtRender() {
  4018. $.get('/connect/holdRequest.php', {holdReq: 1});
  4019.  
  4020. render(false, 'SC_WellnessEngine_Test', null, function (content) {
  4021. var bb = bootbox.dialog({
  4022. message: '<div class="text-center" id="TestHolder"><i class="fa fa-spin fa-spinner"></i> Loading Wellness Test</div>',
  4023. size: 'large',
  4024. onEscape: function () {
  4025. $.get('/connect/holdRequest.php', {holdReq: 0});
  4026. }
  4027. });
  4028.  
  4029. bb.on('shown.bs.modal', function () {
  4030. gpTest($('#TestHolder'), {"finishButton": "Return to Noni", "finishCallback": bootbox.hideAll});
  4031. $('body').addClass('modal-open');
  4032. //this page is using bootstrap 3 and we need this styling from bootstrap 4...
  4033. var css = document.createElement("style");
  4034. css.type = "text/css";
  4035. css.innerHTML = ".progress-bar { height: 1rem; color: #fff; background-color: #0275d8; height: 2rem;}";
  4036. css.innerHTML += ".progress { background-color: #eceeef; border-radius: .75rem; overflow: hidden; line-height: 1rem;}";
  4037. css.innerHTML += ".mt-2 { margin-top: 0.5rem;}";
  4038. document.body.appendChild(css);
  4039. });
  4040. });
  4041.  
  4042. }
  4043. }
  4044.  
  4045. function crisisNumberClick() {
  4046. tracker.emit("CrisisNumber", {action: 'click'});
  4047. }
  4048.  
  4049. //crisis resources and helplines
  4050. function popCrisisResources(useModal, location) {
  4051. //render a modal containing the handlebars template if required
  4052. if (useModal) {
  4053. render(false, "WellnessEngine_CrisisResources", null, function($html) {
  4054. bootbox.dialog({
  4055. title: 'Crisis Resources',
  4056. message: $html
  4057. });
  4058. });
  4059. }
  4060.  
  4061. //emit amplitude event specifying the location/source of the event
  4062. tracker.emit("CrisisResources", {action: 'click', location: location});
  4063. }
  4064.  
  4065. //listener advice information
  4066. function popListenerAdvice(useModal, location) {
  4067. //render a modal containing the handlebars template if required
  4068. if (useModal) {
  4069. render(false, "Training_Advice", null, function($html) {
  4070. bootbox.dialog({
  4071. title: 'Advice and Crisis Resources',
  4072. message: $html
  4073. });
  4074. });
  4075. }
  4076.  
  4077. //emit amplitude event specifying the location/source of the event
  4078. tracker.emit("AdviceAndCrisis", {action: 'click', location: location});
  4079. }
  4080.  
  4081. function confirmEmail() {
  4082. render(false, "Forms_Account_VerifyEmail", {
  4083. userInfo: userInfo
  4084. }, function($html){
  4085. bootbox.dialog({
  4086. title: 'Verify Your Email Address',
  4087. message: $html
  4088. }).on('shown.bs.modal', function () {
  4089. console.log('Showing email confirm modal');
  4090. }).on('hidden.bs.modal', function () {
  4091. console.log('Hiding email confirm modal');
  4092. resetState();
  4093. window.allowEmpty = true;
  4094. $('#Comment').val('');
  4095. sendMessage();
  4096. });
  4097. });
  4098. }
  4099.  
  4100. $(function () {
  4101. $('body').on('click','[data-actionid=rateListenerButton]', function(){
  4102. if(window.ratingModal){
  4103. window.ratingModal.modal('show');
  4104. }
  4105. });
  4106.  
  4107. setInterval(function () {
  4108. var now = (new Date()).getTime() - (60000 * 5);
  4109. $('[data-msgTime]').each(function () {
  4110. var time = parseInt(this.getAttribute('data-msgTime'));
  4111. if (time <= now) {
  4112. this.removeAttribute('data-msgTime');
  4113. this.removeAttribute('style');
  4114. }
  4115. });
  4116. }, 15000);
  4117.  
  4118.  
  4119.  
  4120. if (getQSval('c')) {
  4121. setConversation(getQSval('c'));
  4122. } else if (window.therapyConvID) {
  4123. if (window.therapyConvID !== 'reload')
  4124. setConversation(window.therapyConvID, false, window.forceBotMode);
  4125. else {
  4126. tracker.emit('ctaTherapy', {uri: window.location.href, location: 'direct'});
  4127. setTimeout(function () { window.location = '/connect/?r=therapy';}, 25);
  4128. }
  4129. }
  4130.  
  4131. $('#MessageScrollDiv').on('scroll', function (e) {
  4132. if (!$(this).is(':animated')) {
  4133. if ($(this).scrollTop() + $(this).innerHeight() >= $(this)[0].scrollHeight) {
  4134. ChatSession.scrollDelay = 0;
  4135. } else {
  4136. var unix = Math.round(+new Date() / 1000);
  4137. ChatSession.scrollDelay = unix + 30;
  4138. }
  4139. }
  4140. });
  4141.  
  4142. $(window).on('beforeunload', function (e) {
  4143. requestRedirect = true;
  4144. });
  4145.  
  4146. $('#Comment').on('keyup', function () {
  4147. if (sendTypingStatus) {
  4148. if ($('#Comment').val().length === 0) {//Empty message send not typing
  4149. sendTyping(0);
  4150. } else if ($('#Comment').val().length > 1 && !ChatSession.sendingTyping) {//Send on first character
  4151. sendTyping(1);
  4152. }
  4153. }
  4154.  
  4155. if (isMobileApp()) {
  4156. if ($('#Comment').val().length === 0) {
  4157. $('#sendButton').css({'color': '#999999'});
  4158. } else if ($('#Comment').val().length > 1) {
  4159. $('#sendButton').css({'color': '#163e4a'});
  4160. }
  4161. }
  4162. });
  4163.  
  4164. $('#Comment').on('keydown', function (e) {
  4165. var key = e.which || e.keyCode || 0;
  4166. if (key == 13) {
  4167. if (!e.shiftKey) {
  4168. e.preventDefault();
  4169. if (window.showNoniMenu && window.botCommand)
  4170. resetState(window.botCommand);
  4171. sendMessage();
  4172. }
  4173. }
  4174. });
  4175.  
  4176. $('#sendButton').on('click', function (e) {
  4177. e.preventDefault();
  4178. if (window.stateLocked)
  4179. return;
  4180. sendMessage();
  4181. });
  4182.  
  4183. $('#banButtonOnModal').on('click', function (e) {
  4184. if ($('#blockReasonInput').val() == '') {
  4185. alert('Please describe the reason for banning this user.');
  4186. e.preventDefault();
  4187. }
  4188. });
  4189.  
  4190.  
  4191. if (getLocal("hideSafetyAlert")) {
  4192. $('#SafetyAlert').hide();
  4193. }
  4194.  
  4195. if (getLocal("hideReferralAlert")) {
  4196. $('#ReferralAlert').hide();
  4197. }
  4198.  
  4199. $('#MessageScrollDiv').on('click', 'button[data-selectcat]', function () {
  4200. var catID = $(this).attr('data-selectcat');
  4201. var convID = $(this).attr('data-convid');
  4202. var catName = $(this).text();
  4203.  
  4204. if (typeof __adroll !== "undefined" && [37,22,16,23].indexOf(parseInt(catID)) !== -1) {
  4205. try {
  4206. __adroll.record_user({"adroll_segments": "0ab24dd2"})
  4207. } catch(err) {}
  4208. }
  4209.  
  4210. $('button[data-selectcat]').closest('div.row').replaceWith('<h5 class="text-primary">' + catName + ' Selected</h5>');
  4211.  
  4212. if (parseInt(catID) > 0 || catID == '') {
  4213. waitForSend = false;
  4214. if (currentNoni.screenName.indexOf('Noni') !== -1) {
  4215. $('#offlineMessageDiv').html('<div class="" style="margin-bottom:.5em"><small><em>Noni is typing...</em></small></div>');
  4216. scrollConversation();
  4217. setTimeout(function () {
  4218. $('#offlineMessageDiv').html('');
  4219. var s = parseInt((new Date()).getTime() - serverTimeOffset*1000);
  4220. loadMessage({msgID: null,
  4221. msgHash: randomHash(),
  4222. 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 + '.',
  4223. msgTime: moment(s).format("h:mm A"),
  4224. userTypeID: '0GKvccLHkpyGnA!!',
  4225. screenName: 'Noni',
  4226. userType: 'n',
  4227. imgURL: cloudfrontBase + 'img/noniCup.jpg',
  4228. imageClass: 'img-profile-l',
  4229. convSide: "other",
  4230. convID: convID});
  4231. scrollConversation();
  4232.  
  4233. $('#offlineMessageDiv').html('<div class="" style="margin-bottom:.5em"><small><em>Noni is typing...</em></small></div>');
  4234. setTimeout(function () {
  4235. $('#offlineMessageDiv').html('');
  4236. var s = parseInt((new Date()).getTime() - serverTimeOffset*1000);
  4237. loadMessage({msgID: null,
  4238. msgHash: randomHash(),
  4239. msgBody: 'Don&rsquo;t worry, you won&rsquo;t lose your place in line. We&rsquo;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>',
  4240. msgTime: moment(s).format("h:mm A"),
  4241. userTypeID: '0GKvccLHkpyGnA!!',
  4242. screenName: 'Noni',
  4243. userType: 'n',
  4244. imgURL: cloudfrontBase + 'img/noniCup.jpg',
  4245. imageClass: 'img-profile-l',
  4246. convSide: "other",
  4247. convID: convID});
  4248. scrollConversation();
  4249. noniTimer = setTimeout(talkToNoni, 30000);
  4250. }, 2000);
  4251.  
  4252. }, 2000);
  4253. } else {
  4254. talkToNoni();
  4255. }
  4256.  
  4257. if (parseInt(catID) > 0) {
  4258. $.post('/connect/addCategory.php', {convID: convID, catID: catID}, function (resp) {
  4259. if (resp.loadad) {
  4260. setTimeout(function () {
  4261. if (!$('.ModuleHolder-Back7CupsAd > .Module-Back7CupsAd').length) {
  4262. $('.ModuleHolder-Back7CupsAd').hide().html(resp.loadad).slideDown(1500);
  4263. }
  4264. }, 5000);
  4265. }
  4266. }, 'json');
  4267. }
  4268. }
  4269. });
  4270.  
  4271.  
  4272. $('body').on('click', 'button[data-therapyaction="payment"]', function () {
  4273. tracker.emit("OnlineTherapy", {step: 'loadpayment', reqType: ChatSession.reqType});
  4274. if (autoMessageFunction) clearTimeout(autoMessageFunction);
  4275. var planID = $(this).attr('data-planID') ? $(this).attr('data-planID') : NULL;
  4276. var subs = {};
  4277.  
  4278.  
  4279. if (typeof __adroll !== "undefined") {
  4280. try {
  4281. __adroll.record_user({"adroll_segments": "13b73f15"})
  4282. } catch(err) {}
  4283.  
  4284.  
  4285. try {
  4286. __adroll.record_user({product_id: "onlineTherapy", product_action: "AddToCart"})
  4287. } catch (e) { }
  4288. }
  4289.  
  4290.  
  4291. subs['onlinetherapy_monthly_15000'] = {
  4292. planID: 'onlinetherapy_monthly_15000',
  4293. modaltitle: 'Get Started!',
  4294. desc: '',
  4295. topdesc: 'Just like texting with a close friend, you can now message your therapist every day, writing as many times as you want.',
  4296. amt: '150.00',
  4297. recur: 'Monthly',
  4298. submitbutton: 'Start Therapy Now',
  4299. disclaimer: 'Your subscription will begin when you click on the button above. To cancel, go to &ldquo;settings&rdquo; and click on &ldquo;manage subscriptions&rdquo; 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.'
  4300. };
  4301.  
  4302. subs['onlinetherapy_monthly_15000_tr3'] = {
  4303. planID: 'onlinetherapy_monthly_15000_tr3',
  4304. modaltitle: 'Start Free Trial Now!',
  4305. desc: '',
  4306. 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!',
  4307. amt: '150.00',
  4308. recur: 'Monthly',
  4309. submitbutton: 'Start Therapy with 3 Day Trial',
  4310. 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 &ldquo;settings&rdquo; and click on &ldquo;manage subscriptions&rdquo; 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.'
  4311. };
  4312.  
  4313. if(subs[planID]){
  4314. var sub = subs[planID];
  4315. }else{
  4316. bootbox.alert('Error: Therapy plan not found.');
  4317. return false;
  4318. }
  4319.  
  4320. var ccyears = [];
  4321. var year = new Date().getFullYear();
  4322. for (var i = 0; i < 15; i++) {
  4323. ccyears.push(year + i);
  4324. }
  4325.  
  4326. if (typeof ga !== 'undefined') {
  4327. ga('ec:setAction', 'checkout');
  4328. }
  4329.  
  4330. var form = 'SC_Forms_Payment_StripeSubscription2';
  4331. var pt = 'Calmer days are ahead...';
  4332. var ph = 'paymentHeader2.jpg';
  4333.  
  4334. /*var ab = parseInt($.cookie('ab_fancyPaymentCopy'));
  4335. if (ab == 1)
  4336. pt = 'Let us help you find your peace...';
  4337. else if (ab == 2)
  4338. pt = 'Let the healing begin...';*/
  4339.  
  4340. render(false, form, {paymentHeader: ph, paymentText: pt, ccyears: ccyears, sub: sub, ab_paymentpcode: ($.cookie('ab_paymentpcode')==true)}, function (content) {
  4341. tracker.emit('OnlineTherapy', {step: 'loadcreditcard', uri: window.location.href, reqType: ChatSession.reqType});
  4342. bootbox.dialog({
  4343. className: "payment-details-modal",
  4344. title: '<span style="font-size:1.5em" class="text-primary">'+sub.modaltitle+'</span>',
  4345. message: content,
  4346. onEscape: true,
  4347. backdrop: true,
  4348. closeButton: true
  4349. }).off("shown.bs.modal").on("shown.bs.modal", function () {
  4350. var $payModal = $(this);
  4351. var $payForm = $(this).find(".stripe-payment-form");
  4352.  
  4353.  
  4354.  
  4355. $payForm.find('[data-action="applypromo"]').on('click', function () {
  4356. var btn = $(this);
  4357. $payForm.find('.alert-danger').remove();
  4358. btn.attr('data-html', function () {
  4359. return $(this).html()
  4360. }).attr('disabled', 'true').html('<i class="fa fa-spinner fa-spin"></i> Checking');
  4361. $.post($payForm.attr('action'), {action: 'verifypromo', promo: $payForm.find('[name="promo"]').val(), planID: $payForm.find('[name="planID"]').val()}, function (resp) {
  4362. if (resp.success) {
  4363. if (resp.update) {
  4364. for (var key in resp.update) {
  4365. $payModal.find(key).replaceWith(resp.update[key]);
  4366. }
  4367. }
  4368. } else {
  4369. $payForm.prepend('<div class="alert alert-danger"><button type="button" class="close" data-dismiss="alert" aria-label="Close"><span aria-hidden="true">&times;</span></button>Invalid Promo Code</div>');
  4370. btn.html(function () {
  4371. return $(this).attr('data-html')
  4372. }).removeAttr('disabled');
  4373. }
  4374. }, 'json');
  4375. });
  4376.  
  4377. $payForm.on('submit', function (event) {
  4378.  
  4379. var submitCard = function () {
  4380. $('.payment-details-modal').show();
  4381. $('body').addClass('modal-open');
  4382. //$payModal.modal('show');
  4383. tracker.emit('OnlineTherapy', {step: 'creditcardsubmit', uri: window.location.href, reqType: ChatSession.reqType});
  4384. $payForm.find('[name="stripeToken"], .alert').remove();
  4385. $payForm.find('button[type="submit"]').attr("disabled", "disabled").attr("data-text", function () {
  4386. return $(this).html();
  4387. }).html('<i class="fa fa-spin fa-spinner"></i> Processing');
  4388. var card = {
  4389. number: $payForm.find("[data-stripe='number']").val(),
  4390. cvc: $payForm.find("[data-stripe='cvc']").val(),
  4391. exp_month: $payForm.find("[data-stripe='exp_month']").val(),
  4392. exp_year: $payForm.find("[data-stripe='exp_year']").val()
  4393. };
  4394. Stripe.createToken(card, function(status, response) {
  4395. if (response.error) {
  4396. $payForm.find('button[type="submit"]').removeAttr("disabled").html(function () {
  4397. return $(this).attr("data-text")
  4398. });
  4399. $payForm.prepend('<div class="alert alert-danger"><button type="button" class="close" data-dismiss="alert" aria-label="Close"><span aria-hidden="true">&times;</span></button>' + response.error.message + '</div>');
  4400. } else {
  4401. $payForm.append('<input type="hidden" name="stripeToken" value="' + response['id'] + '" />');
  4402. if (!$payForm.find('[name="convID"]').length) {
  4403. $payForm.append('<input type="hidden" name="convID" value="' + ChatSession.convID + '" />');
  4404. }
  4405.  
  4406. $.post($payForm.attr('action'), $payForm.serialize(), function (resp) {
  4407. if (resp.success) {
  4408. tracker.emit("OnlineTherapy", {step: 'completepayment', reqType: ChatSession.reqType});
  4409. talkToNoni();
  4410. if (typeof __adroll !== "undefined")
  4411. try {
  4412. __adroll.record_user({"adroll_segments": "9cb7fee1"})
  4413. __adroll.record_user({product_id: "onlineTherapy", product_action: "Purchased"})
  4414. } catch (e) { }
  4415.  
  4416. if (typeof ga !== 'undefined' && resp.sub) {
  4417. try {
  4418.  
  4419. ga('ec:setAction', 'purchase', {
  4420. 'id': resp.sub.subID,
  4421. 'revenue': sub.amt
  4422. });
  4423.  
  4424. // Record Adwords conversion
  4425. window.google_conversion_id = 991416627;
  4426. window.google_conversion_label = "KjZ_CMnek3EQs6Lf2AM";
  4427. window.google_remarketing_only = false;
  4428. window.google_conversion_format = "3";
  4429. var opt = new Object();
  4430. opt.onload_callback = function() {
  4431. console.log('Transaction Recorded');
  4432. }
  4433. var conv_handler = window['google_trackConversion'];
  4434. if (typeof(conv_handler) == 'function')
  4435. conv_handler(opt);
  4436.  
  4437. } catch (e) { }
  4438. }
  4439. $payModal.modal('hide');
  4440. } else {
  4441. tracker.emit("OnlineTherapy", {step: 'paymentfail', reqType: ChatSession.reqType});
  4442. if (resp.err && resp.err.copy) {
  4443. for (e in resp.err.copy) {
  4444. $payForm.prepend('<div class="alert alert-danger"><button type="button" class="close" data-dismiss="alert" aria-label="Close"><span aria-hidden="true">&times;</span></button>' + resp.err.copy[e] + '</div>');
  4445. }
  4446. }
  4447. $payForm.find('button[type="submit"]').removeAttr("disabled").html(function () {
  4448. return $(this).attr("data-text")
  4449. });
  4450. }
  4451. }, 'json')
  4452. }
  4453. });
  4454. }
  4455.  
  4456. if (1 || window.confirmAuthorization){
  4457. submitCard();
  4458. } else {
  4459. //$payModal.modal('hide');
  4460. $('.payment-details-modal').hide();
  4461. tracker.emit('OnlineTherapy', {step: 'creditcardconfirm', uri: window.location.href, reqType: ChatSession.reqType});
  4462. bootbox.dialog({
  4463. className: "payment-confirm-modal",
  4464. 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.",
  4465. buttons: {
  4466. confirm: {
  4467. label: 'Connect me to my therapist',
  4468. className: 'btn-success',
  4469. callback: submitCard
  4470. }
  4471. },
  4472. onEscape: function() {
  4473. console.log('Dismissed');
  4474. $('.payment-details-modal').show();
  4475. $('body').addClass('modal-open');
  4476. //$payModal.modal('show');
  4477. }
  4478. }).on('hidden.bs.modal', function () {
  4479. $('.payment-details-modal').show();
  4480. $('body').addClass('modal-open');
  4481. });
  4482. }
  4483. return false;
  4484. });
  4485. });
  4486. });
  4487. });
  4488.  
  4489. $('body').on('click', 'a[data-therapyaction="informedconsentstatic"]', function () {
  4490. //tracker.emit("OnlineTherapy", {step: 'loadagreement', reqType: ChatSession.reqType});
  4491. var param = JSON.parse($(this).attr('data-tparams'));
  4492. render(false, 'SC_Forms_Connect_TherapistInformedConsentStatic', param, function (content) {
  4493. bootbox.dialog({
  4494. title: 'Online Therapy Agreement',
  4495. message: content,
  4496. onEscape: true,
  4497. backdrop: true,
  4498. closeButton: true,
  4499. size: 'large'
  4500. });
  4501. });
  4502. });
  4503.  
  4504. $('body').on('click', 'button[data-therapyaction="informedconsent"]', function () {
  4505. tracker.emit("OnlineTherapy", {step: 'loadagreement', reqType: ChatSession.reqType});
  4506. if (autoMessageFunction) clearTimeout(autoMessageFunction);
  4507. var param = JSON.parse($(this).attr('data-tparams'));
  4508. render(false, 'SC_Forms_Connect_TherapistInformedConsent', param, function (content) {
  4509. bootbox.dialog({
  4510. title: 'Online Therapy Agreement',
  4511. message: content,
  4512. onEscape: true,
  4513. backdrop: true,
  4514. closeButton: true,
  4515. size: 'large'
  4516. }).off("shown.bs.modal").on("shown.bs.modal", function () {
  4517. var $thisModal = $(this);
  4518.  
  4519. $thisModal.find('[data-agree="true"]').on('click', function () {
  4520. var $thisBtn = $(this);
  4521. $thisModal.find('.modal-body .alert-danger').remove();
  4522. $thisBtn.attr('data-html', function () {
  4523. return $(this).html()
  4524. }).attr("disabled", "disabled").html('<i class="fa fa-spin fa-spinner"></i> Processing');
  4525. $.post('/connect/therapist_SignConsent.php', {convID: ChatSession.convID}, function (resp) {
  4526. if (resp.err) {
  4527. $thisModal.find('.modal-body').prepend('<div class="alert alert-danger">' + resp.err + '</div>')
  4528. $thisBtn.removeAttr("disabled").html(function () {
  4529. return $(this).attr('data-html')
  4530. });
  4531. } else {
  4532. tracker.emit("OnlineTherapy", {step: 'completeagreement'});
  4533. stopNoni = true;
  4534. var s = parseInt((new Date()).getTime() - serverTimeOffset*1000);
  4535. loadMessage({msgID: null,
  4536. msgHash: randomHash(),
  4537. 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!',
  4538. msgTime: moment(s).format("h:mm A"),
  4539. userTypeID: '0GKvccLHkpyGnA!!',
  4540. screenName: currentNoni.screenName,
  4541. userType: 'n',
  4542. imgURL: currentNoni.imgURL,
  4543. imageClass: currentNoni.imageClass,
  4544. convSide: "other",
  4545. convID: resp.convID});
  4546. scrollConversation();
  4547. $thisModal.modal('hide');
  4548.  
  4549. /*
  4550. setTimeout(function(){
  4551. var s = parseInt((new Date()).getTime() - serverTimeOffset*1000);
  4552. loadMessage({msgID: null,
  4553. msgHash: randomHash(),
  4554. 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.',
  4555. msgTime: moment(s).format("h:mm A"),
  4556. userTypeID: '0GKvccLHkpyGnA!!',
  4557. screenName: currentNoni.screenName,
  4558. userType: 'n',
  4559. imgURL: currentNoni.imgURL,
  4560. imageClass: currentNoni.imageClass,
  4561. convSide: "other",
  4562. convID: resp.convID});
  4563. scrollConversation();
  4564. }, 3000);*/
  4565. }
  4566. }, 'json');
  4567. });
  4568. });
  4569. });
  4570. });
  4571.  
  4572. $('body').on('click', '#therapy-referral button', function () {
  4573. $('#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');
  4574. 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>');
  4575. });
  4576. });
  4577.  
  4578. if (!isMobileApp()) {
  4579. var soundOn = true;
  4580.  
  4581. function setupConvSound() {
  4582. // Delay execution until async scripts are downloaded
  4583. if (typeof soundManager === 'undefined') {
  4584. console.log('delayed');
  4585. initTimer = setTimeout(setupConvSound, 25);
  4586. return;
  4587. }
  4588.  
  4589. soundManager.setup({
  4590. url: '/js/soundManager/swf/',
  4591. flashVersion: 9, // optional: shiny features (default = 8)
  4592. // optional: ignore Flash where possible, use 100% HTML5 mode
  4593. // preferFlash: false,
  4594. onready: function () {
  4595. // Ready to use; soundManager.createSound() etc. can now be called.
  4596. soundManager.createSound({
  4597. id: 'newMessage',
  4598. url: cloudfrontBase+'img/newMessage.mp3'
  4599. });
  4600. }
  4601. });
  4602.  
  4603. }
  4604.  
  4605. setupConvSound();
  4606.  
  4607.  
  4608. var chatExpanded = false;
  4609. function expandChat() {
  4610. chatExpanded = true;
  4611.  
  4612. $('.chatRow').addClass('expanded');
  4613. $('.right-hand-content').addClass('col-lg-9').removeClass('col-lg-7').addClass('col-lg-push-3').removeClass('col-lg-push-4');
  4614. $('.left-hand-content').removeClass('col-lg-pull-6').addClass('col-lg-pull-9');
  4615.  
  4616. $('.expandButton').hide();
  4617. $('.shrinkButton').show();
  4618.  
  4619. resizeChat();
  4620.  
  4621. }
  4622.  
  4623. function shrinkChat() {
  4624.  
  4625. $('.chatRow').removeClass('expanded');
  4626. $('.right-hand-content').removeClass('col-lg-9').addClass('col-lg-7').removeClass('col-lg-push-3').addClass('col-lg-push-4');
  4627. $('.left-hand-content').addClass('col-lg-pull-6').removeClass('col-lg-pull-9');
  4628.  
  4629. $('.expandButton').show();
  4630. $('.shrinkButton').hide();
  4631.  
  4632. chatExpanded = false;
  4633. resizeChat();
  4634. }
  4635.  
  4636. function resizeChat() {
  4637. if ($(window).width() <= 767) {
  4638. setTimeout(function () {
  4639. window.scrollTo(document.body.scrollLeft, document.body.scrollTop);
  4640. }, 0);
  4641. //var bottomBar = 0;
  4642. //if ($('.bottomStatus').is(":visible"))
  4643. //bottomBar = $('.bottomStatus').height();
  4644. var chatHeight = $(window).height() - (chatExpanded ? 20 : 70);
  4645. chatHeight -= (chatExpanded ? 8 : $('#bottomStatus').outerHeight());
  4646. var banner = $('.upperChatBanner');
  4647. if (banner.length)
  4648. chatHeight -= banner.outerHeight();
  4649.  
  4650. if (chatExpanded) {
  4651. $('.chatBox').height($(window).height());
  4652. $('.conversationBox').css('max-height', '');
  4653. if (banner.length)
  4654. banner.hide();
  4655.  
  4656. } else {
  4657. $('.chatBox').height(chatHeight);
  4658. $('.conversationBox').css('max-height', chatHeight + 'px');
  4659. if (banner.length)
  4660. banner.show();
  4661.  
  4662. }
  4663.  
  4664. $('.chatBox .card-block').height($('.chatBox').outerHeight() - $('.chatInput').outerHeight() - $('#conversationHead').outerHeight());
  4665. } else {
  4666.  
  4667. setTimeout(function () {
  4668. window.scrollTo(document.body.scrollLeft, document.body.scrollTop);
  4669. }, 0);
  4670. //var bottomBar = 0;
  4671. //if ($('.bottomStatus').is(":visible"))
  4672. //bottomBar = $('.bottomStatus').height();
  4673. var chatHeight = $(window).height() - (chatExpanded ? 20 : 120);
  4674. chatHeight -= (chatExpanded ? 8 : $('#bottomStatus').outerHeight());
  4675. var banner = $('.upperChatBanner');
  4676. if (banner.length)
  4677. chatHeight -= banner.outerHeight();
  4678.  
  4679. if (chatExpanded) {
  4680. $('.chatBox').height($(window).height() -20);
  4681. $('.conversationBox').css('max-height', '');
  4682. if (banner.length)
  4683. banner.hide();
  4684. } else {
  4685. $('.chatBox').height(chatHeight);
  4686. $('.conversationBox').css('max-height', chatHeight + 'px');
  4687. if (banner.length)
  4688. banner.show();
  4689. }
  4690.  
  4691. $('.chatBox .card-block').height($('.chatBox').outerHeight() - $('.chatInput').outerHeight() - $('#conversationHead').outerHeight());
  4692.  
  4693.  
  4694. }
  4695. }
  4696.  
  4697. $(function () {
  4698.  
  4699. window.pageReady = true;
  4700.  
  4701. if (!getQSval('c')) {
  4702. $('#selectConvPrompt').show();
  4703. }
  4704.  
  4705. resizeChat();
  4706.  
  4707. $('#bottomStatus').resize(function () {
  4708. resizeChat();
  4709. });
  4710.  
  4711. $(window).resize(function () {
  4712. resizeChat();
  4713. });
  4714.  
  4715. $('#chatForm').submit(function (e) {
  4716. e.preventDefault();
  4717. sendMessage();
  4718. });
  4719.  
  4720. //$(".resizableDiv").resizable({handles: 's', minHeight: 150});
  4721.  
  4722. $('#getHelpButton').on('click', function () {
  4723. tracker.emit("ClickChatHelpButton");
  4724.  
  4725. if (ChatSession.user.age < 18) {
  4726. setConversation('k2VowHPgmMxSy5k!');
  4727. } else {
  4728. setConversation('k2dmeXmbkuJO42uXh1iY');
  4729. }
  4730. });
  4731. });
  4732. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement