Guest User

/higor

a guest
May 7th, 2017
193
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 332.15 KB | None | 0 0
  1. /**
  2. * Created by Juliano on 04/02/2016.
  3. */
  4.  
  5. var contentContainer = $("#content-container");
  6. var appHeader = $("#app-header");
  7. window.locale = 'pt-br';
  8.  
  9. (function ($, undefined) {
  10. $.fn.getCursorPosition = function () {
  11. var el = $(this).get(0);
  12. var pos = 0;
  13. if ('selectionStart' in el) {
  14. pos = el.selectionStart;
  15. } else if ('selection' in document) {
  16. el.focus();
  17. var Sel = document.selection.createRange();
  18. var SelLength = document.selection.createRange().text.length;
  19. Sel.moveStart('character', -el.value.length);
  20. pos = Sel.text.length - SelLength;
  21. }
  22. return pos;
  23. }
  24. })(jQuery);
  25.  
  26. var access = {
  27.  
  28. /* Hover open effect on menu */
  29. threeDots: function () {
  30. var optionsBalloon = $("#options-balloon");
  31. var timer;
  32. $("#3-dots-menu").on("mouseleave", function () {
  33. timer = setTimeout(function () {
  34. optionsBalloon.fadeOut("fast");
  35. }, 400);
  36. }).on("click", function () {
  37. clearTimeout(timer);
  38. optionsBalloon.fadeToggle("fast");
  39. event.stopPropagation();
  40. });
  41.  
  42. optionsBalloon.on("mouseenter", function () {
  43. clearTimeout(timer);
  44. optionsBalloon.fadeIn();
  45. event.stopPropagation();
  46. }).on("mouseleave", function (event) {
  47. timer = setTimeout(function () {
  48. optionsBalloon.fadeOut("fast");
  49. event.stopPropagation();
  50. }, 400);
  51. });
  52.  
  53. $("#sign-btn-arrow").on("click", function () {
  54. $("#btn_next").trigger("click");
  55. });
  56.  
  57. $("#forgot-btn-arrow").on("click", function () {
  58. $("#btn_send").trigger("click");
  59. });
  60. },
  61.  
  62. /* This is used to personalize the select element of sign up page
  63. *
  64. * Have to add this on the page (Theter and Select):
  65. * <link rel="stylesheet" href="select-theme-default.css" />
  66. * <script src="tether.min.js"></script>
  67. * <script src="select.min.js"></script>
  68. *
  69. * Then use this code here to use a placeholder and style the element.
  70. *
  71. * More info: http://github.hubspot.com/select/docs/welcome/
  72. */
  73. customSelect: function () {
  74. var signSelect;
  75. var element = document.getElementById('companySize');
  76. signSelect = new Select({
  77. el: element,
  78. className: 'select-theme-inngage'
  79. });
  80. signSelect.on('change', function () {
  81. $(".select-target.select-theme-inngage").css({color: '#444'});
  82. });
  83. element.setAttribute('tabindex', '-1');
  84. },
  85.  
  86. doLogout: function () {
  87. var formData = {
  88. 'logout': true
  89. };
  90. var ajaxSend = $.ajax({
  91. type: 'POST',
  92. url: '/handleLogout',
  93. data: formData,
  94. dataType: 'json',
  95. encode: true,
  96. timeout: 10000
  97. }).done(function (data) {
  98. console.log('done');
  99. //modal.closeModal();
  100. // modal.getModal('success-saved.php', true, {obj: 'Campanha', justShow: true});
  101. }).fail(function (data) {
  102. console.log(data);
  103. //action.verifyBehavior('fail', afterAction);
  104. ajaxSend.abort();
  105. });
  106. }
  107. };
  108.  
  109. var ref = {
  110. // INCLUDES
  111. getIncludes: "/includes",
  112. // INCLUDES APP-PG
  113. getAppPg: "/includes/app-pg",
  114. // INCLUDES MAIN-PG
  115. getMainPg: "includes/main-pg",
  116.  
  117. // PLUGINS PATH
  118. getPlugins: "/resources/plugins",
  119. // UPLOADS PATH
  120. getUploads: "/resources/uploads",
  121. // VIEW PATH
  122. getView: "/view"
  123. };
  124.  
  125. var navigation = {
  126. /* Code to show and hide user pop-up menu in nav bar.
  127. * The arrow behavior is set here too.
  128. * */
  129. userMenu: function () {
  130.  
  131. /* show user pop up menu when mouse enters the user bar space */
  132. var popUpMenu = $("#user-pop");
  133. var userBar = $(".user-bar");
  134. var optionsArrow = $("#options-arrow");
  135. // has to use 2 timers to work when leave popMenu and comes back to userBar
  136. var timerUser; // timer for when leave userBar
  137. var timerPop; // timer for when leave userPopMenu
  138.  
  139. userBar.on("mouseenter", function (event) {
  140. clearTimeout(timerUser);
  141. clearTimeout(timerPop);
  142. //popUpMenu.fadeIn("fast");
  143. event.stopPropagation();
  144. //optionsArrow.addClass('rotate');
  145. }).on("mouseleave", function () {
  146. timerUser = setTimeout(function () {
  147. popUpMenu.fadeOut("fast");
  148. //event.stopPropagation();
  149. optionsArrow.removeClass('rotate-180');
  150. }, 250);
  151. }).off('click').click(function (event) {
  152. event.stopPropagation();
  153. optionsArrow.toggleClass('rotate-180');
  154. popUpMenu.toggle();
  155. });
  156.  
  157. popUpMenu.on("mouseenter", function () {
  158. clearTimeout(timerUser);
  159. clearTimeout(timerPop);
  160. popUpMenu.fadeIn("fast");
  161. //event.stopPropagation();
  162. optionsArrow.addClass('rotate-180');
  163. }).on("mouseleave", function () {
  164. timerPop = setTimeout(function () {
  165. popUpMenu.fadeOut("fast");
  166. //event.stopPropagation();
  167. optionsArrow.removeClass('rotate-180');
  168. }, 250);
  169. });
  170.  
  171. // show the user pop-up menu, and hide it clicking anywhere else in the page
  172. $(document).on("click", function () {
  173. popUpMenu.fadeOut("fast");
  174. optionsArrow.removeClass('rotate-180');
  175. $("#options-balloon").hide();
  176. $("#config-balloon").hide();
  177. });
  178. },
  179.  
  180. /* Menu-side scroll effect */
  181. navSideScroll: function () {
  182. var lastScrollPosition = 0;
  183. var navSide = $("#nav-side");
  184.  
  185. var space = "<div style='height: " + navSide.height() + "px;'></div>";
  186. // var space = "<div style='height: " + navSide.height() + "px;' id='space'></div>";
  187. // $('#space').remove();
  188. $('body').prepend(space);
  189.  
  190. $(window).scroll(function () {
  191. var screenWindow = $(window);
  192. var sp = screenWindow.scrollTop();
  193.  
  194. //scrolling down
  195. if (lastScrollPosition < sp) {
  196. //if screen passes nav-side bottom
  197. if (sp + screenWindow.height() >= navSide.height() + navSide.offset().top) {
  198. navSide.addClass("nav-side-fixed-bot");
  199. }
  200. //else if scrolling up
  201. } else {
  202. //and is fixed bot
  203. if (navSide.hasClass("nav-side-fixed-bot")) {
  204. //set top, pass to absolute
  205. navSide.removeClass('nav-side-fixed-bot');
  206. navSide.css({top: sp + screenWindow.height() - navSide.height()});
  207. }
  208. //and if scroll is above nav-side top, then set nav-side top to scroll
  209. if (sp <= navSide.offset().top) {
  210. navSide.css({top: sp});
  211. }
  212. }
  213. lastScrollPosition = sp;
  214. });
  215.  
  216. $(window).trigger('scroll');
  217. },
  218.  
  219. /* Put shadow on nav-top when user scrolls the screen */
  220. navTopShadow: function () {
  221. $(window).scroll(function () {
  222. var navTop = $(".nav-top");
  223.  
  224. if ($(window).scrollTop() > 0) {
  225. navTop.addClass('nav-top-shadow');
  226. } else {
  227. navTop.removeClass('nav-top-shadow');
  228. }
  229. });
  230. },
  231.  
  232. navTop: function () {
  233. this.userMenu();
  234. this.navTopShadow()
  235. },
  236.  
  237. navSide: function () {
  238. this.navSideScroll();
  239. }
  240. };
  241.  
  242. var behaviors = {
  243. /*
  244. * This function applyes the menu pop behavior to menu buttons and pop menus.
  245. * Call this function with the menu trigger button.
  246. *
  247. * @param popMenu what is the menu ID to be poped-up (pass #id)
  248. * @param buttonID what is the menu button ID to open the pop-up (pass #id)
  249. * @param expandClass class with animation to expand
  250. * @param shrinkClass class with animation to shrink
  251. *
  252. * */
  253. popUp: function (buttonID, popMenuId, expandClass, shrinkClass) {
  254. // has to use 2 timers to work when leave popMenu and comes back to userBar
  255. var timerThis; // timer for when leave 'this'
  256. var timerPop; // timer for when leave popMenu
  257. var popMenu = $(popMenuId);
  258. var button = $(buttonID);
  259. popMenu.css({visibility: 'visible'}).hide();
  260.  
  261. function expand() {
  262. button.children('img').removeClass(shrinkClass);
  263. button.children('img').addClass(expandClass);
  264. }
  265.  
  266. function shrink() {
  267. button.children('img').removeClass(expandClass);
  268. button.children('img').addClass(shrinkClass);
  269. }
  270.  
  271. button.on('click', function (e) {
  272. e.stopPropagation();
  273. popMenu.fadeToggle('fast');
  274. $(document).one('mouseup.popMenu', function (e) {
  275. if (!popMenu.is(e.target) // if the target of the click isn't the container...
  276. && popMenu.has(e.target).length === 0) { // ... nor a descendant of the container
  277. popMenu.fadeOut("fast");
  278. shrink();
  279. }
  280. });
  281. }).on("mouseenter", function () {
  282. clearTimeout(timerThis);
  283. clearTimeout(timerPop);
  284. expand();
  285. }).on("mouseleave", function () {
  286. timerThis = setTimeout(function () {
  287. popMenu.fadeOut("fast");
  288. shrink();
  289. $(document).off('mouseup.popMenu');
  290. }, 300);
  291. });
  292.  
  293. popMenu.on("mouseenter", function () {
  294. clearTimeout(timerThis);
  295. clearTimeout(timerPop);
  296. popMenu.fadeIn("fast");
  297. }).on("mouseleave", function () {
  298. timerPop = setTimeout(function () {
  299. popMenu.fadeOut("fast");
  300. shrink();
  301. $(document).off('mouseup.popMenu');
  302. }, 600);
  303. });
  304.  
  305.  
  306. },
  307.  
  308. //no-app change fill color
  309. plusApp: function () {
  310. $("#plus-app, #new-app-btn").hover(function () {
  311. $("#plus-app").addClass("plus-app-hover");
  312. $("#new-app-btn").addClass("button-blue-hover");
  313. }, function () {
  314. $("#plus-app").removeClass("plus-app-hover");
  315. $("#new-app-btn").removeClass("button-blue-hover");
  316. });
  317. },
  318.  
  319.  
  320. /* Insert a local input field to edit content
  321. *
  322. * @param clicked element to be clicked and trigger the effect
  323. * @param toFadeOut element to get rid of
  324. * @param editCount number of the element to be used in IDs
  325. * @param wordID the identification text of the ID to be used in selector
  326. *
  327. * Update: previous version inserted html to the DOM. This version doesn't
  328. * */
  329. editField: {
  330. // Distinguish between cancel and accept for different fields
  331. function: function (clicked, toFadeOut, toFadeIn, wordId) {
  332.  
  333. //var thisEditCount = editCount;
  334. var fadeOutThis = $(toFadeOut);
  335. var fadeInThis = $(toFadeIn);
  336.  
  337. //var textValue = $.trim(fadeOutThis.text());
  338.  
  339. $(clicked).on('click', function (e) {
  340. fadeOutThis.fadeOut('fast', function () {
  341. fadeInThis.fadeIn('fast', function () {
  342.  
  343. var inputElem = fadeInThis.find('input');
  344. // var originalValue = inputElem.val();
  345.  
  346. $(document).on('keyup', function (e) {
  347. if (e.keyCode == 13) {
  348. $("#accept" + wordId).trigger('click');
  349. }
  350. if (e.keyCode == 27) {
  351. $("#cancel" + wordId).trigger('click');
  352. }
  353. });
  354.  
  355. $("#accept" + wordId).on('click', function () {
  356. //var newName = editionInput.val();
  357.  
  358. $('#cancel' + wordId).trigger('click');
  359.  
  360. });
  361.  
  362. $('#cancel' + wordId).on('click', function () {
  363. fadeInThis.fadeOut('fast', function () {
  364. fadeOutThis.fadeIn('fast');
  365. // inputElem.val(originalValue);
  366. });
  367. //$('.input-div').css({textAlign: 'right'});
  368. $(document).off('**');
  369.  
  370. });
  371.  
  372. $('#input' + wordId).select();
  373. });
  374. });
  375. });
  376. }
  377. },
  378.  
  379. /* Change SVG color
  380. * Takes the image source attribute and change the last name to the color to use
  381. * @param imgTag pass selector of the IMG to switch
  382. * @param color name of the color */
  383. svgChangeTo: {
  384.  
  385. color: function (imgTag, color) {
  386. var image = $(imgTag);
  387.  
  388. var imgSource = image.attr('src');
  389.  
  390. var splited = imgSource.split('-');
  391. splited[splited.length - 1] = color + '.svg';
  392. imgSource = splited.join('-');
  393.  
  394. image.attr('src', imgSource);
  395. },
  396.  
  397. hover: function (imgTag) {
  398. var image = $(imgTag);
  399.  
  400. var imgSource = image.attr('src');
  401.  
  402. var splited = imgSource.split('-');
  403. var last = splited[splited.length - 1];
  404. if (last == 'hover.svg') {
  405. splited[splited.length - 1] = '.svg';
  406. imgSource = splited.join('-').replace('-.', '.');
  407. } else {
  408. splited = imgSource.split('.');
  409. splited[splited.length - 1] = '-hover.svg';
  410. imgSource = splited.join('');
  411. }
  412.  
  413. image.attr('src', imgSource);
  414. },
  415.  
  416. white: function (imgTag) {
  417. this.color(imgTag, 'white');
  418. },
  419.  
  420. blue: function (imgTag) {
  421. this.color(imgTag, 'blue');
  422. },
  423.  
  424. gray: function (imgTag) {
  425. this.color(imgTag, 'gray');
  426. }
  427.  
  428. },
  429.  
  430. /* auto adjust textarea */
  431. autoTextArea: function () {
  432. var textArea = $('.textarea');
  433. textArea.each(function () {
  434. $(this).on('keyup', function () {
  435. $(this).height(0);
  436. $(this).height(this.scrollHeight);
  437. });
  438. $(this).keyup();
  439. });
  440. },
  441.  
  442. sendPush: function () {
  443. modal.closeModal();
  444. navigateTo.app.push.notificationsSent();
  445. },
  446.  
  447. schedulePush: function () {
  448. modal.closeModal();
  449. navigateTo.app.push.notificationsScheduled();
  450. },
  451.  
  452. sendPushFail: function (message) {
  453. modal.closeModal(['modal-fail-push.php', undefined, {message: message}]);
  454. },
  455.  
  456. saveAudienceFail: function () {
  457. modal.closeModal(['modal-fail-push.php']);
  458. },
  459.  
  460. saveSecurityParameter: function () {
  461. modal.closeModal(['modal-fail-security-parameter.php']);
  462. },
  463.  
  464. saveAutomationFail: function () {
  465. modal.closeModal(['modal-fail-automation.php']);
  466. },
  467.  
  468. saveApiTemplateFail: function () {
  469. modal.closeModal(['modal-fail-api-template.php']);
  470. },
  471.  
  472. saveCamp: function () {
  473. modal.closeModal(['success-saved.php', true, {
  474. obj: 'Campanha salva',
  475. navigate_method: 'navigateTo.app.push.campaigns();'
  476. }]);
  477.  
  478. },
  479.  
  480. saveCampFail: function () {
  481. modal.closeModal(['modal-failed.php', false, {obj: 'Campanha'}]);
  482. },
  483.  
  484. saveSendCamp: function (campId) {
  485. $.ajax({
  486. url: '/getCampaign',
  487. type: "POST",
  488. data: {'campId': campId, 'action': 'send'},
  489. success: function (data) {
  490. contentContainer.html(data);
  491. modal.closeModal();
  492. // modal.getModal('success-saved.php', true, {obj: 'Campanha', justShow: true});
  493. },
  494. fail: function (data) {
  495. alert(data);
  496. }
  497. });
  498. },
  499.  
  500. sendSaveCampFail: function () {
  501. this.sendPushFail();
  502. },
  503.  
  504. saveAudience: function () {
  505. modal.closeModal(['success-saved.php', true, {
  506. obj: 'Audiência salva',
  507. navigate_method: 'navigateTo.app.audience.audiences();'
  508. }]);
  509. },
  510.  
  511. saveAutomation: function () {
  512. modal.closeModal(['success-saved.php', true, {
  513. obj: 'Automação salva',
  514. navigate_method: 'navigateTo.app.push.automations();'
  515. }]);
  516. },
  517.  
  518. saveApiTemplate: function () {
  519. modal.closeModal(['success-saved.php', true, {
  520. obj: 'API Template salva',
  521. navigate_method: 'navigateTo.app.push.apiTemplate();'
  522. }]);
  523. },
  524.  
  525. inactivateAudience: function () {
  526. modal.closeModal();
  527.  
  528. // update page values
  529. // lastRegister
  530. var lastRegister = $('#lastRegister');
  531. var lastItemValue = lastRegister.html();
  532. lastRegister.html(lastItemValue - 1);
  533. // totalRegsiter
  534. var totalRegisters = $('#totalRegisters');
  535. var totalRegistersValue = totalRegisters.html();
  536. totalRegisters.html(totalRegistersValue - 1);
  537. },
  538.  
  539. tagTemplateSelection: function () {
  540. function insertText(context, open, close) {
  541. var aim = context.parent('div').attr('data-box');
  542. console.log(aim);
  543. var emojiDiv = $('.emoji-wysiwyg-editor').eq(aim);
  544.  
  545. var tag = context.children('span').html();
  546. emojiDiv.html(emojiDiv.html() + open + tag + close);
  547. emojiDiv.trigger('keyup');
  548. $('#tagTemplateMenu').fadeOut('fast');
  549. }
  550.  
  551. $('#tagTemplateMenu').on('click', '.js-customField', function () {
  552. insertText($(this), '|*', '*|');
  553. }).on('click', '.js-tagField', function () {
  554. insertText($(this), '{{', '}}');
  555. });
  556. },
  557.  
  558. /* Insert new row to add data
  559. *
  560. * @param context String selector which is the context of the list (maxRows will be used there)
  561. * @param maxRows number max number of rows
  562. * */
  563. listData: {
  564. add: function (context, maxRows) {
  565. if (context == undefined) {
  566. context = $('body');
  567. } else {
  568. context = $(context);
  569. }
  570. if (maxRows === undefined) {
  571. maxRows = Number.POSITIVE_INFINITY;
  572. }
  573.  
  574. context.find('.addNewData').hover(function () {
  575. $(this).css({fontWeight: '400'});
  576. behaviors.svgChangeTo.hover($(this).children('img'));
  577. }, function () {
  578. $(this).attr('style', '');
  579. behaviors.svgChangeTo.hover($(this).children('img'));
  580. }).on("click", function () {
  581. var context = $(this).parents('.control-panel');
  582. if (context.find('.js-dataRow').length < maxRows) {
  583. var $template = context.find('.js-dataTemplate');
  584.  
  585. // var $clone = $template
  586. $template.clone()
  587. .removeClass('hide')
  588. .removeClass('js-dataTemplate')
  589. .addClass('js-dataRow')
  590. .insertBefore($template);
  591.  
  592. // var amountData = $('.template').length - 1;
  593. var amountData = context.find('.js-dataRow').length;
  594.  
  595. // if more than 1, show del to all
  596. // if (amountData != 1) {
  597. // context.find(".js-removeData").removeClass('hide');
  598. // }
  599.  
  600. // Update the name attributes
  601. // $clone
  602. // .find('[name="' + sectionName + '-key"]').attr('name', 'data[' + amountData + '].' + sectionName + '-key').end()
  603. // .find('[name="' + sectionName + '-value"]').attr('name', 'data[' + amountData + '].' + sectionName + '-value').end();
  604.  
  605. //add click atribute
  606. // behaviors.listData.remove(maxRows);
  607. if (amountData == maxRows) {
  608. context.find(".addData").addClass('hide');
  609. }
  610. }
  611. });
  612.  
  613. context.on('hover', '.js-removeData', function () {
  614. behaviors.svgChangeTo.hover($(this).children('img'));
  615. }, function () {
  616. behaviors.svgChangeTo.hover($(this).children('img'));
  617. }).on("click", '.js-removeData', function () {
  618. var context = $(this).parents('.control-panel');
  619. // Remove element containing the fields
  620. $(this).parents('.control-panel-row').remove();
  621. // Count lines
  622. var amountData = context.find('.js-dataRow').length;
  623.  
  624. if (amountData < maxRows) {
  625. $(".addData").removeClass('hide');
  626. // if (amountData == 1) {
  627. // context.find(".js-removeData").addClass('hide');
  628. // }
  629. } else {
  630. $(".addData").addClass('hide');
  631. }
  632.  
  633. });
  634. },
  635.  
  636. populate: function (contextId, object) {
  637. var context = $(contextId);
  638. var addButton = context.find('.addNewData');
  639.  
  640. $.each(object, function (key, obj) {
  641. addButton.trigger('click');
  642. var lastRow = context.find('.js-dataRow').last();
  643.  
  644. if (obj === Object(obj)) {
  645. $.each(obj, function (key, value) {
  646. lastRow.find(key).val(value);
  647. })
  648. } else {
  649. lastRow.find('input').val(obj);
  650. }
  651.  
  652. })
  653. }
  654.  
  655. },
  656.  
  657. togglePassword: function (context, id) {
  658. var elm = document.getElementById(id);
  659. if (elm.type == "password") {
  660. elm.type = "text";
  661. //$(context).removeClass("glyphicon-eye-open");
  662. $(context).addClass("blue-flat");
  663. } else if (elm.type == "text") {
  664. elm.type = "password";
  665. $(context).removeClass("blue-flat");
  666. //$(context).toggleClass("glyphicon-eye-close");
  667. }
  668. }
  669. };
  670.  
  671. var action = {
  672.  
  673. verifyBehavior: function (result, afterAction, message) {
  674.  
  675. var behavior;
  676.  
  677. if (result == 'success') {
  678. switch (afterAction) {
  679. case 'justSend':
  680. behavior = behaviors.sendPush();
  681. break;
  682. case 'scheduleSend':
  683. behavior = behaviors.schedulePush();
  684. break;
  685. case 'saveCamp':
  686. behavior = behaviors.saveCamp();
  687. break;
  688. case 'saveSendCamp':
  689. behavior = behaviors.saveSendCamp;
  690. break;
  691. case 'saveAudience':
  692. behavior = behaviors.saveAudience();
  693. break;
  694. case 'saveAutomation':
  695. behavior = behaviors.saveAutomation();
  696. break;
  697. case 'inactivateAudience':
  698. behavior = behaviors.inactivateAudience();
  699. break;
  700. case 'saveApiTemplate':
  701. behavior = behaviors.saveApiTemplate();
  702. break;
  703. default:
  704. break;
  705. }
  706. } else if (result == 'fail') {
  707. switch (afterAction) {
  708. case 'justSend':
  709. behavior = behaviors.sendPushFail(message);
  710. break;
  711. case 'saveCamp':
  712. behavior = behaviors.saveCampFail();
  713. break;
  714. case 'saveSendCamp':
  715. behavior = behaviors.sendSaveCampFail();
  716. break;
  717. case 'saveAudience':
  718. behavior = behaviors.saveAudienceFail();
  719. break;
  720. case 'saveAutomation':
  721. behavior = behaviors.saveAutomationFail();
  722. break;
  723. case 'saveApiTemplate':
  724. behavior = behaviors.saveApiTemplateFail();
  725. break;
  726. case 'saveSecurityParameter':
  727. behavior = behaviors.saveSecurityParameter();
  728. break;
  729. default:
  730. break;
  731. }
  732. }
  733.  
  734. return behavior;
  735. },
  736.  
  737. /* AJAX to send push (used in Send Push and Campaign)
  738. *
  739. * audiencesSelected array audiences in string ('audience1,audience2,audience3')
  740. * if private msg, audiencesSelected = 'false,identifier'
  741. * */
  742. sendPush: function (appId, appToken, afterAction, campId, audiencesSelected) {
  743. if (campId == null || campId == '') {
  744. campId = 0;
  745. }
  746.  
  747. var pushContent = $('#pushContent');
  748. isScheduler = $('.js-check-showUpSend').is(':checked');
  749.  
  750. if (!isScheduler) {
  751. modal.closeModal(); //don't put modal in closeModal because of undesired async behavior
  752. modal.getModal('modal-sending-push.php', true);
  753. } else {
  754. modal.closeModal();
  755. modal.getModal('modal-scheduling-push.php', true);
  756. }
  757.  
  758. var pushMsgToPersist = pushContent.val();
  759. var msgContent = window.emojiPicker.colonToUnicode(pushMsgToPersist);
  760.  
  761. var additionalData = scriptForPage.getAdditionalData();
  762. var flagAdditional = false;
  763.  
  764. if (additionalData.length > 0)
  765. flagAdditional = true;
  766.  
  767. var formData = {
  768. 'msgTitle': $('input[name=msg-title]').val(),
  769. 'msgContent': msgContent,
  770. 'appId': appId,
  771. 'appToken': appToken,
  772. 'action': 'doSendPush',
  773. 'flagSchedule': $('.js-check-showUpSend').is(':checked'),
  774. 'sendDate': $('input[name=sendDate]').val(),
  775. 'sendHour': $('select[name=sendHour]').val(),
  776. 'sendMinute': $('select[name=sendMinute]').val(),
  777. 'persistMsg': pushMsgToPersist,
  778. 'campId': campId,
  779. 'flagUrl': $('.js-check-showUpURL').is(':checked'),
  780. 'urlPush': $('input[name=open-url]').val(),
  781. 'imgPush': $('input[name=msg-image]').val(),
  782. 'flagAdditional': flagAdditional,
  783. 'additionalData': additionalData,
  784. 'audiences': audiencesSelected
  785. };
  786.  
  787. var ajaxSend = $.ajax({
  788. type: 'POST',
  789. url: '/sendPushValidation',
  790. data: formData,
  791. dataType: 'json',
  792. encode: true,
  793. //timeout: 10000
  794. //timeout: 120000
  795. })
  796. .done(function (data) {
  797. console.log(data);
  798. if (data.errors == null) {
  799. if (campId == 0) {
  800. action.saveAdditionalData(0, data.message_control_id, 0);
  801. action.savePushAdresses('NULL', data.message_control_id, audiencesSelected);
  802. }
  803. while ($(".modal-container").length == 0) {
  804. // wait until previous modal is loaded, so it will be correctly closed on afterAction
  805. }
  806. action.verifyBehavior('success', afterAction);
  807. } else {
  808. action.verifyBehavior('fail', afterAction, data.message);
  809. }
  810.  
  811. })
  812. .fail(function (data) {
  813. console.log(data);
  814. action.verifyBehavior('fail', afterAction);
  815. ajaxSend.abort();
  816. });
  817. },
  818.  
  819. saveCampaign: function (appId, appToken, campId, afterAction) {
  820.  
  821. var flDraft = 1; //rascunho
  822.  
  823. if (afterAction == undefined || afterAction == 'saveSendCamp') { //if there is no afterAction (send Campaign), change to "active" campaign
  824. flDraft = 0; //enviado
  825. }
  826.  
  827. var formData = {
  828. 'msgTitle': $('input[name=msg-title]').val(),
  829. 'msgBody': $('#pushContent').val(),
  830. 'appId': appId,
  831. 'campId': campId,
  832. 'campName': $('#componentName').val(),
  833. 'campDescription': $('#componentDescription').val(),
  834. 'campFlDraft': flDraft,
  835. 'campStatus': 0,
  836. // 'flagSchedule': $('.js-check-showUpSend').is(':checked'),
  837. // 'sendDate': $('input[name=sendDate]').val(),
  838. // 'sendHour': $('select[name=sendHour]').val(),
  839. // 'sendMinute': $('select[name=sendMinute]').val(),
  840. 'flagUrl': $('.js-check-showUpURL').is(':checked'),
  841. 'urlPush': $('input[name=open-url]').val(),
  842. 'imgPush': $('input[name=msg-image]').val()
  843. };
  844.  
  845. var ajaxSave = $.ajax({
  846. type: 'POST',
  847. url: '/handleCampaign',
  848. data: formData,
  849. timeout: 10000
  850. })
  851. .done(function (data) {
  852. var campId = data;
  853. console.log('done');
  854. action.saveAdditionalData(campId, 0, 0, '');
  855. var goToSendCamp = action.verifyBehavior('success', afterAction);
  856. if (afterAction == 'saveSendCamp')
  857. goToSendCamp(campId);
  858. })
  859. .fail(function () {
  860. console.log('fail');
  861. action.verifyBehavior('fail', afterAction);
  862. }).error(function () {
  863. action.verifyBehavior('fail', afterAction);
  864. ajaxSave.abort();
  865. });
  866.  
  867. },
  868.  
  869. saveAdditionalData: function (campaignId, controlMessageId, automationId, afterAction, apiTemplateId) {
  870. function getAdditionalData() {
  871. var elements = $('#additionalBlock').find('.js-dataRow');
  872. var dict = [];
  873.  
  874. $.each(elements, function (num, obj) {
  875. var key = $(obj).find('input[name="additional-key"]').val();
  876. var value = $(obj).find('input[name="additional-value"]').val();
  877.  
  878. if ((key !== '') && (value !== '')) {
  879. dict.push({key: key, value: value});
  880. }
  881. });
  882.  
  883. return dict;
  884. }
  885.  
  886. var additionalData = getAdditionalData();
  887. var flagAdditional = false;
  888.  
  889. if (additionalData.length > 0)
  890. flagAdditional = true;
  891.  
  892. var formData = {
  893. 'controlMessageId': controlMessageId,
  894. 'campaignId': campaignId,
  895. 'automationId': automationId,
  896. 'flagAdditional': flagAdditional,
  897. 'additionalData': additionalData,
  898. 'apiTemplateId': apiTemplateId
  899. };
  900.  
  901. var ajaxSave = $.ajax({
  902. type: 'POST',
  903. url: '/handleAdditional',
  904. data: formData,
  905. timeout: 10000
  906. })
  907. .done(function () {
  908. if (afterAction != undefined && afterAction != '') {
  909. action.verifyBehavior('success', afterAction);
  910. }
  911. })
  912. .fail(function (data) {
  913. console.log('fail');
  914. console.log(data);
  915. // action.verifyBehavior('fail', afterAction);
  916. ajaxSave.abort();
  917. // }).error(function () {
  918. // action.verifyBehavior('fail', afterAction);
  919. // ajaxSave.abort();
  920. });
  921. },
  922.  
  923. savePushAdresses: function (campId, controlMessageId, audiencesSelected) {
  924. var formData = {'audiences': audiencesSelected, 'controlMessageId': controlMessageId, 'campaignId': campId};
  925.  
  926. var ajaxSave = $.ajax({
  927. type: 'POST',
  928. url: '/handlePushAdresses',
  929. data: formData,
  930. timeout: 10000
  931. })
  932. .done(function (data) {
  933. console.log(data);
  934. console.log('done');
  935. })
  936. .fail(function (data) {
  937. console.log('fail');
  938. console.log(data);
  939. ajaxSave.abort();
  940. });
  941. },
  942.  
  943. saveAudience: function (audienceId, appId, showModalSuccess) {
  944. var criteria = scriptForPage.getAudienceCriteria();
  945. var recentAudience = 0;
  946.  
  947. var formData = {
  948. 'appId': appId,
  949. 'audienceId': audienceId,
  950. 'audienceName': $("#componentName").val(),
  951. 'audienceDescription': $("#componentDescription").val(),
  952. 'criteria': criteria
  953. };
  954.  
  955. var ajaxSave = $.ajax({
  956. type: 'POST',
  957. url: '/handleAudience',
  958. data: formData,
  959. async: false,
  960. timeout: 10000
  961. })
  962. .done(function (data) {
  963. console.log(data);
  964. console.log('done');
  965. if (showModalSuccess) {
  966. action.verifyBehavior('success', 'saveAudience');
  967. }
  968. recentAudience = data;
  969. })
  970. .fail(function (data) {
  971. console.log('fail');
  972. console.log(data);
  973. action.verifyBehavior('fail', 'saveAudience');
  974. ajaxSave.abort();
  975. });
  976. return recentAudience;
  977. },
  978.  
  979. saveParameterBlockLogin: function (customerId) {
  980. var formData = {
  981. 'customerId': customerId,
  982. 'maxNumberRetries': $("#openInputQuantity").val(),
  983. 'action': 'saveParameterBlockLogin'
  984. };
  985.  
  986. var ajaxSave = $.ajax({
  987. type: 'POST',
  988. url: '/handleSecurityParameter',
  989. data: formData,
  990. async: false,
  991. timeout: 10000
  992. })
  993. .done(function (data) {
  994. console.log('done');
  995. })
  996. .fail(function (data) {
  997. console.log('fail');
  998. console.log(data);
  999. action.verifyBehavior('fail', 'saveSecurityParameter');
  1000. ajaxSave.abort();
  1001. });
  1002. },
  1003.  
  1004. saveParameterChangePassword: function (customerId) {
  1005. var formData = {
  1006. 'customerId': customerId,
  1007. 'changePassword': $('.js-check-showUpChangePassword').is(':checked'),
  1008. 'action': 'saveParameterChangePassword'
  1009. };
  1010.  
  1011. var ajaxSave = $.ajax({
  1012. type: 'POST',
  1013. url: '/handleSecurityParameter',
  1014. data: formData,
  1015. async: false,
  1016. timeout: 10000
  1017. })
  1018. .done(function (data) {
  1019. console.log('done');
  1020. })
  1021. .fail(function (data) {
  1022. console.log('fail');
  1023. console.log(data);
  1024. action.verifyBehavior('fail', 'saveSecurityParameter');
  1025. ajaxSave.abort();
  1026. });
  1027. },
  1028.  
  1029. saveParameterStrengthPassword: function (customerId, strengthId) {
  1030. console.log('saveParameterStrengthPassword');
  1031. var formData = {
  1032. 'customerId': customerId,
  1033. 'passwordStrengthId': strengthId,
  1034. 'action': 'saveParameterStrengthPassword'
  1035. };
  1036.  
  1037. var ajaxSave = $.ajax({
  1038. type: 'POST',
  1039. url: '/handleSecurityParameter',
  1040. data: formData,
  1041. async: false,
  1042. timeout: 10000
  1043. })
  1044. .done(function (data) {
  1045. console.log('done');
  1046. })
  1047. .fail(function (data) {
  1048. console.log('fail');
  1049. console.log(data);
  1050. action.verifyBehavior('fail', 'saveSecurityParameter');
  1051. ajaxSave.abort();
  1052. });
  1053. },
  1054.  
  1055. saveParameterLoginScheduled: function (securityParameterId, selectedDays) {
  1056. var formData = {
  1057. 'securityParameterId': securityParameterId,
  1058. 'selectedDays': '"' + selectedDays.toString() + '"',
  1059. 'timeInit': $("#timeIntervalRange").slider("values", 0),
  1060. 'timeEnd': $("#timeIntervalRange").slider("values", 1),
  1061. 'action': 'saveParameterLoginScheduled'
  1062. };
  1063.  
  1064. var ajaxSave = $.ajax({
  1065. type: 'POST',
  1066. url: '/handleSecurityParameter',
  1067. data: formData,
  1068. async: false,
  1069. timeout: 10000
  1070. })
  1071. .done(function (data) {
  1072. console.log('done');
  1073. })
  1074. .fail(function (data) {
  1075. console.log('fail');
  1076. console.log(data);
  1077. action.verifyBehavior('fail', 'saveSecurityParameter');
  1078. ajaxSave.abort();
  1079. });
  1080. },
  1081.  
  1082. saveCollaborator: function (customerId, userName) {
  1083. var formData = {
  1084. 'customerId': customerId,
  1085. 'email': $('#addEmail').val(),
  1086. 'profileId': $('#addNewSelect').val(),
  1087. 'action': 'saveCollaborator'
  1088. };
  1089.  
  1090. var ajaxSave = $.ajax({
  1091. type: 'POST',
  1092. url: '/handleCollaborator',
  1093. data: formData,
  1094. async: false,
  1095. timeout: 10000
  1096. })
  1097. .done(function (data) {
  1098. var json = $.parseJSON(data);
  1099.  
  1100. if (json.success == true) {
  1101. //send invitation
  1102. action.sendInvitationCollaborator(userName);
  1103. } else {
  1104. action.verifyBehavior('fail', 'saveSecurityParameter');
  1105. }
  1106. })
  1107. .fail(function (data) {
  1108. console.log('fail');
  1109. console.log(data);
  1110. action.verifyBehavior('fail', 'saveSecurityParameter');
  1111. ajaxSave.abort();
  1112. });
  1113. },
  1114.  
  1115. deleteCollaborator: function (email, buttonDelete, context, collaboratorNumber) {
  1116. console.log('deleteCollaborator');
  1117. var formData = {
  1118. 'email': email,
  1119. 'action': 'deleteCollaborator'
  1120. };
  1121. console.log(formData);
  1122. var ajaxSave = $.ajax({
  1123. type: 'POST',
  1124. url: '/handleCollaborator',
  1125. data: formData,
  1126. async: false,
  1127. timeout: 10000
  1128. })
  1129. .done(function (data) {
  1130. console.log('success');
  1131. var json = $.parseJSON(data);
  1132.  
  1133. if (json.success == true) {
  1134. console.log('json success');
  1135. $(buttonDelete).parents('.styleNewCollaborator').remove();
  1136. $.each(context.find('.element-counter'), function (index, elem) {
  1137. $(elem).html(index + 1);
  1138. });
  1139. collaboratorNumber--;
  1140. }
  1141. })
  1142. .fail(function (data) {
  1143. console.log('fail');
  1144. console.log(data);
  1145. action.verifyBehavior('fail', 'saveSecurityParameter');
  1146. ajaxSave.abort();
  1147. });
  1148. },
  1149.  
  1150. sendInvitationCollaborator: function (userName) {
  1151. var formData = {
  1152. 'email': $('#addEmail').val(),
  1153. 'userName': userName,
  1154. 'action': 'sendInvite'
  1155. };
  1156.  
  1157. var ajaxSave = $.ajax({
  1158. type: 'POST',
  1159. url: '/handleCollaborator',
  1160. data: formData,
  1161. async: false,
  1162. timeout: 10000
  1163. })
  1164. .done(function (data) {
  1165. //console.log('done');
  1166. })
  1167. .fail(function (data) {
  1168. console.log('fail');
  1169. console.log(data);
  1170. action.verifyBehavior('fail', 'saveSecurityParameter');
  1171. ajaxSave.abort();
  1172. });
  1173. },
  1174.  
  1175. saveApiTemplate: function (apiTemplateId, appId) {
  1176.  
  1177. if ($('.js-check-showUpURL').is(':checked')) {
  1178. var url = $('input[name=open-url]').val();
  1179. } else {
  1180. url = '';
  1181. }
  1182.  
  1183. function getTags() {
  1184. var elements = $('.js-dataRow');
  1185. var tags = [];
  1186.  
  1187. $.each(elements, function (num, obj) {
  1188. var tag = $(obj).find('input[name="tag-value"]').val();
  1189.  
  1190. if (tag !== '') {
  1191. tags.push(tag);
  1192. }
  1193. });
  1194.  
  1195. if (tags != null && tags != '') {
  1196. return tags;
  1197. } else {
  1198. return '';
  1199. }
  1200. }
  1201.  
  1202. // var additionalData = scriptForPage.getAdditionalData();
  1203.  
  1204. var formData = {
  1205. 'apiTemplateId': apiTemplateId,
  1206. 'apiTemplateName': $("#componentName").val(),
  1207. 'apiTemplateDescription': $("#componentDescription").val(),
  1208. 'msgTitle': $('input[name=msg-title]').val(),
  1209. 'msgBody': $('#pushContent').val(),
  1210. 'urlPush': url,
  1211. 'appId': appId,
  1212. 'tags': getTags()
  1213. };
  1214.  
  1215. var ajaxSave = $.ajax({
  1216. type: 'POST',
  1217. url: '/handleApiTemplate',
  1218. data: formData,
  1219. timeout: 10000
  1220. })
  1221. .done(function (data) {
  1222. console.log('done');
  1223. console.log(data);
  1224. var json = $.parseJSON(data);
  1225.  
  1226. if (json.success == true) {
  1227. action.saveAdditionalData('', '', '', 'saveApiTemplate', json.apiId);
  1228. // action.verifyBehavior('success', 'saveApiTemplate');
  1229. } else {
  1230. console.log(data.error);
  1231. // action.verifyBehavior('fail', 'saveApiTemplate');
  1232. }
  1233.  
  1234. })
  1235. .fail(function (data) {
  1236. console.log('fail');
  1237. console.log(data);
  1238. action.verifyBehavior('fail', 'saveApiTemplate');
  1239. ajaxSave.abort();
  1240. });
  1241. },
  1242.  
  1243. findReachAudience: function (appId) {
  1244. var criteria = scriptForPage.getAudienceCriteria();
  1245.  
  1246. if (criteria.length > 0) {
  1247. $.ajax({
  1248. type: 'POST',
  1249. url: '/handleRangeAudience',
  1250. data: {'criteria': criteria, 'appId': appId},
  1251. dataType: 'json',
  1252. encode: true
  1253. })
  1254. .done(function (data) {
  1255. if (data.success) {
  1256. /*console.log('query:');
  1257. console.log(data.query);*/
  1258. console.log(data);
  1259. $("#rangeNumber").text(data.result);
  1260. }
  1261. })
  1262. .fail(function () {
  1263. console.log('fail');
  1264. });
  1265. }
  1266. },
  1267.  
  1268. inactivateAudience: function (audienceId) {
  1269.  
  1270. var formData = {
  1271. 'audienceId': audienceId
  1272. };
  1273.  
  1274. var ajaxSave = $.ajax({
  1275. type: 'POST',
  1276. url: '/handleInactivateAudience',
  1277. data: formData,
  1278. dataType: 'json',
  1279. encode: true,
  1280. timeout: 10000
  1281. })
  1282. .done(function (data) {
  1283. console.log(data);
  1284. console.log('done');
  1285. action.verifyBehavior('success', 'inactivateAudience');
  1286. })
  1287. .fail(function (data) {
  1288. console.log('fail');
  1289. console.log(data);
  1290. action.verifyBehavior('fail', 'saveAudience');
  1291. }).error(function () {
  1292. console.log('error');
  1293. action.verifyBehavior('fail', 'saveAudience');
  1294. ajaxSave.abort();
  1295. });
  1296. },
  1297.  
  1298. getSubscribersAudience: function (audiencesSelected) {
  1299. var data = {'audiencesSelected': audiencesSelected};
  1300.  
  1301. // if(data.findIndex())
  1302.  
  1303. console.log(data);
  1304.  
  1305. var ajaxSend = $.ajax({
  1306. type: 'POST',
  1307. url: '/handleSubscribersAudience',
  1308. data: data,
  1309. dataType: 'json',
  1310. encode: true,
  1311. timeout: 10000
  1312. })
  1313. .done(function (data) {
  1314. var qtyLocalFormat = parseInt(data.quantitySubscribers).toLocaleString(locale);
  1315. $('.range-full-number').html(qtyLocalFormat);
  1316. $('#qtRecipients').html(qtyLocalFormat);
  1317. })
  1318. .fail(function (data) {
  1319. // show any errors
  1320. // best to remove for production
  1321. console.log('fail');
  1322. console.log(data);
  1323. $('.range-full-number').html('-');
  1324. $('#qtRecipients').html('-');
  1325. ajaxSend.abort();
  1326. });
  1327. },
  1328.  
  1329. saveAutomation: function (appId, campId, automationId, audiencesSelected, timeInit, timeEnd, selectedDays) {
  1330. var statusId = 1; //ativo
  1331.  
  1332. var formData = {
  1333. 'automationId': automationId,
  1334. 'campId': campId,
  1335. 'name': $('#componentName').val(),
  1336. 'description': $('#componentDescription').val(),
  1337. 'statusId': statusId,
  1338. 'appId': appId,
  1339. 'action': 'saveAutomation'
  1340. };
  1341. var ajaxSave = $.ajax({
  1342. type: 'POST',
  1343. url: '/handleAutomation',
  1344. data: formData,
  1345. timeout: 10000
  1346. })
  1347. .done(function (data) {
  1348. var objJson = $.parseJSON(data);
  1349. if (objJson.success) {
  1350. action.saveAutomationAudience(objJson.automation_id, audiencesSelected, timeInit, timeEnd, selectedDays);
  1351. } else {
  1352. action.verifyBehavior('fail', 'saveAutomation');
  1353. }
  1354. })
  1355. .fail(function () {
  1356. console.log('fail');
  1357. action.verifyBehavior('fail', 'saveAutomation');
  1358. }).error(function () {
  1359. action.verifyBehavior('fail', 'saveAutomation');
  1360. ajaxSave.abort();
  1361. });
  1362. },
  1363.  
  1364. saveAutomationScheduled: function (automationId, timeInit, timeEnd, selectedDays) {
  1365. var formData = {
  1366. 'automationId': automationId,
  1367. 'selectedDays': selectedDays,
  1368. 'timeInit': timeInit,
  1369. 'timeEnd': timeEnd,
  1370. 'action': 'automationScheduled'
  1371. };
  1372.  
  1373. var ajaxSave = $.ajax({
  1374. type: 'POST',
  1375. url: '/handleAutomation',
  1376. data: formData,
  1377. timeout: 10000
  1378. })
  1379. .done(function (data) {
  1380. var objJson = $.parseJSON(data);
  1381. if (objJson.success) {
  1382. action.saveAdditionalData(0, 0, automationId, 'saveAutomation');
  1383. }
  1384. })
  1385. .fail(function () {
  1386. console.log('fail');
  1387. action.verifyBehavior('fail', 'saveAutomation');
  1388. }).error(function () {
  1389. action.verifyBehavior('fail', 'saveAutomation');
  1390. ajaxSave.abort();
  1391. });
  1392. },
  1393.  
  1394. saveAutomationAudience: function (automationId, audiencesSelected, timeInit, timeEnd, selectedDays) {
  1395. if (parseInt(audiencesSelected) > 0) {
  1396. var formData = {
  1397. 'audiences': audiencesSelected,
  1398. 'automationId': automationId,
  1399. 'action': 'automationAudience'
  1400. };
  1401.  
  1402. var ajaxSave = $.ajax({
  1403. type: 'POST',
  1404. url: '/handleAutomation',
  1405. data: formData,
  1406. timeout: 10000
  1407. })
  1408. .done(function (data) {
  1409. var objJson = $.parseJSON(data);
  1410. if (objJson.success) {
  1411. action.saveAutomationCriteria(automationId, timeInit, timeEnd, selectedDays);
  1412. } else {
  1413. action.verifyBehavior('fail', 'saveAutomation');
  1414. }
  1415. })
  1416. .fail(function (data) {
  1417. console.log('fail');
  1418. console.log(data);
  1419. action.verifyBehavior('fail', 'saveAutomation');
  1420. ajaxSave.abort();
  1421. });
  1422. } else {
  1423. action.saveAutomationCriteria(automationId, timeInit, timeEnd, selectedDays);
  1424. }
  1425. },
  1426.  
  1427. saveAutomationCriteria: function (automationId, timeInit, timeEnd, selectedDays) {
  1428. var criteria = scriptForPage.getAudienceCriteria();
  1429.  
  1430. if (criteria.length > 0) {
  1431. var formData = {
  1432. 'automationId': automationId,
  1433. 'criteria': criteria,
  1434. 'action': 'pushCriteria'
  1435. };
  1436.  
  1437. $.ajax({
  1438. type: 'POST',
  1439. url: '/handleAutomation',
  1440. data: formData,
  1441. timeout: 10000
  1442. })
  1443. .done(function (data) {
  1444. console.log(data);
  1445. var objJson = $.parseJSON(data);
  1446. if (objJson.success) {
  1447. action.saveAutomationScheduled(automationId, timeInit, timeEnd, selectedDays);
  1448. } else {
  1449. action.verifyBehavior('fail', 'saveAutomation');
  1450. }
  1451. })
  1452. .fail(function () {
  1453. console.log('fail');
  1454. action.verifyBehavior('fail', 'saveAutomation');
  1455. });
  1456. } else {
  1457. action.saveAutomationScheduled(automationId, timeInit, timeEnd, selectedDays);
  1458. }
  1459. },
  1460.  
  1461. /*
  1462. * This method paginate the page
  1463. *
  1464. * @param string container Where the retrieved data should be put
  1465. * @param string target What is the target URL
  1466. * @param string rowNumber
  1467. * @param JSON data parameters to send with GET
  1468. *
  1469. * return AJAX fill the container with retrieved data
  1470. *
  1471. * */
  1472. paginate: function (container, target, rowNumber) {
  1473.  
  1474. var viewsPerPage = $("#viewsPerPage").val();
  1475. if (viewsPerPage == undefined || viewsPerPage == '') {
  1476. viewsPerPage = 15;
  1477. }
  1478.  
  1479. var params = 'viewsPerPage=' + viewsPerPage + '&rowNumber=' + rowNumber;
  1480.  
  1481. // look for params in the url, if there is params just insert the page params, else create new params field
  1482. if (target.search('/?') == -1) {
  1483. params = '?' + params;
  1484. } else {
  1485. params = '&' + params;
  1486. }
  1487.  
  1488. var targetURL = '/' + target + params;
  1489. window.scrollTo(0, 0);
  1490. $(container).load(targetURL).hide().fadeIn('300');
  1491. console.log(targetURL);
  1492. console.log(params);
  1493. },
  1494.  
  1495. download: function (text, name, type) {
  1496. var a = document.createElement("a");
  1497. if (type == 'csv') {
  1498. var file = new Blob([text], {type: 'text/plain'});
  1499. a.href = URL.createObjectURL(file);
  1500. } else if (type == 'xls') {
  1501. a.href = text;
  1502. }
  1503. a.download = name;
  1504. a.click();
  1505. a.remove();
  1506. }
  1507. };
  1508.  
  1509. var transform = {
  1510.  
  1511. /* Get all checkbox inputs with class '.js-switch' and put their design like iOS7 */
  1512. iOSswitch: function () {
  1513. var checkboxes = Array.prototype.slice.call(document.querySelectorAll('.js-switch'));
  1514.  
  1515. checkboxes.forEach(function (html) {
  1516. var switchery = new Switchery(html, {size: 'small', secondaryColor: '#DFDFDF'});
  1517. });
  1518. },
  1519.  
  1520. /* Style the select element
  1521. * This is used to personalize the select element of sign up page
  1522. *
  1523. * Have to add this on the page (Theter and Select):
  1524. * <link rel="stylesheet" href="select-theme-default.css" />
  1525. * <script src="tether.min.js"></script>
  1526. * <script src="select.min.js"></script>
  1527. *
  1528. * Then use this code here to use a placeholder and style the element.
  1529. *
  1530. * selectID must be just an ID NAME
  1531. *
  1532. * More info: http://github.hubspot.com/select/docs/welcome/
  1533. */
  1534. customSelect: function (selectID) {
  1535. if (selectID.charAt(0) == '#' || selectID.charAt(0) == '.') {
  1536. selectID = selectID.substr(1);
  1537. }
  1538.  
  1539. var element = document.getElementById(selectID);
  1540. var select = new Select({
  1541. el: element,
  1542. className: 'select-theme-inngage'
  1543. });
  1544.  
  1545. function addOptGroup() {
  1546. var optgroup = $(element).find('optgroup');
  1547.  
  1548. $.each(optgroup, function (index, obj) {
  1549. var optgroupLabel = $(obj).attr('label');
  1550. var addElement = '<div class="custom-optgroup">' + optgroupLabel + '</div>';
  1551.  
  1552. var nextElemValue = ($(obj).children().first()).val();
  1553. var searchOption = 'li[data-value=' + nextElemValue + ']';
  1554.  
  1555. $(select.drop).find(searchOption).before(addElement);
  1556. });
  1557. }
  1558.  
  1559. addOptGroup();
  1560.  
  1561. select.on('change', function () {
  1562. addOptGroup();
  1563. });
  1564.  
  1565. return select;
  1566. },
  1567.  
  1568. emojiPicker: function () {
  1569. // Initializes and creates emoji set from sprite sheet
  1570. window.emojiPicker = new EmojiPicker({
  1571. emojiable_selector: '[data-emojiable=true]',
  1572. assetsPath: ref.getPlugins + '/emoji-area/img/',
  1573. popupButtonClasses: 'fa fa-smile-o',
  1574. iconSize: 19,
  1575. norealTime: false
  1576. });
  1577. // Finds all elements with `emojiable_selector` and converts them to rich emoji input fields
  1578. // You may want to delay this step if you have dynamically created input fields that appear later in the loading process
  1579. // It can be called as many times as necessary; previously converted input fields will not be converted again
  1580. window.emojiPicker.discover();
  1581. },
  1582.  
  1583. counter: function (decimal) {
  1584. $('.js-count').each(function () {
  1585. $(this).stop();
  1586. var value = $(this).text();
  1587.  
  1588. $(this).prop('Counter', 0).animate({
  1589. Counter: $(this).text()
  1590. }, {
  1591. duration: 1000,
  1592. easing: 'easeOutQuart',
  1593. step: function (now) {
  1594. $(this).text(now.toLocaleString(locale, {maximumFractionDigits: decimal}));
  1595. },
  1596. complete: function () {
  1597. $(this).text(value);
  1598. transform.breakThousandsId([$(this)]);
  1599. }
  1600. });
  1601. });
  1602. },
  1603.  
  1604. /* Convert a message with emoji in Unicode format to rich text
  1605. *
  1606. * @param obj Object which has the message, may be json, string...
  1607. * @param selector Where to insert the new message with images
  1608. * @param countIndex boolean True if the obj is a json or array and must use the index to identify the selector
  1609. * */
  1610. unicodeToEmoji: function (obj, selector, countIndex) {
  1611.  
  1612. // transform.emojiPicker();
  1613. window.emojiPicker.discover();
  1614.  
  1615. if (countIndex == true) {
  1616. $.each(obj, function (index, elem) {
  1617. $(selector + index).html(window.emojiPicker.unicodeToImage(elem));
  1618. // console.log(elem);
  1619. });
  1620. } else {
  1621. $(selector).html(window.emojiPicker.unicodeToImage(obj));
  1622. }
  1623. },
  1624.  
  1625. /*
  1626. * @param boolean countIndex If the obj has to be count with an "index" increment
  1627. * */
  1628. colonToEmoji: function (obj, selector, countIndex) {
  1629.  
  1630. transform.emojiPicker();
  1631. window.emojiPicker.discover();
  1632.  
  1633. if (countIndex == true) {
  1634. $.each(obj, function (index, elem) {
  1635. $(selector + index).html(window.emojiPicker.colonToImage(elem));
  1636. });
  1637.  
  1638. } else {
  1639. $(selector).html(window.emojiPicker.colonToImage(obj));
  1640. }
  1641. },
  1642.  
  1643. highlightAppMenu: function () {
  1644. var path = (window.location.pathname).substr(1);
  1645. var dirs = path.split('/');
  1646.  
  1647. $.each(dirs, function (index, val) {
  1648. var name = val.split('-');
  1649. for (var i = 1; i < name.length; i++) {
  1650. var firstLetter = name[i].substring(0, 1);
  1651. name[i] = name[i].replace(firstLetter, firstLetter.toUpperCase());
  1652. }
  1653. dirs[index] = name.join('');
  1654. });
  1655.  
  1656. var pageGroup = '#' + dirs[1];
  1657. var page = '#' + dirs[2];
  1658.  
  1659. $(pageGroup).addClass('nav-side-title-selected');
  1660. if (page) {
  1661. var obj = $(page);
  1662. obj.addClass('nav-side-item-selected');
  1663. }
  1664. },
  1665.  
  1666. highlightSubMenu: function (menuItem) {
  1667. $(menuItem).addClass('nav-side-item-selected');
  1668. },
  1669.  
  1670. /* API to work with tawk.to */
  1671. tawkChat: function () {
  1672. function tawkChatAPI() {
  1673. var Tawk_API = Tawk_API || {}, Tawk_LoadStart = new Date();
  1674. (function () {
  1675. var s1 = document.createElement("script"), s0 = document.getElementsByTagName("script")[0];
  1676. s1.async = true;
  1677. s1.src = 'https://embed.tawk.to/5782b19274888c1b4a85ea3e/default';
  1678. s1.charset = 'UTF-8';
  1679. s1.setAttribute('crossorigin', '*');
  1680. s0.parentNode.insertBefore(s1, s0);
  1681. })();
  1682. }
  1683.  
  1684. tawkChatAPI.call(window);
  1685. },
  1686.  
  1687. /*
  1688. * Separate thousands
  1689. *
  1690. * @param array identificators array of any kind of selector as string
  1691. * @return null
  1692. * */
  1693. breakThousandsId: function (identificators) {
  1694. $.each(identificators, function (key, obj) {
  1695. var number = Number($(obj).html());
  1696. $(obj).html(number.toLocaleString(locale));
  1697. });
  1698. }
  1699.  
  1700. };
  1701.  
  1702. var modal = {
  1703.  
  1704. scrollPosition: 0,
  1705.  
  1706. /* Close block if ESC is pressed */
  1707. typeKeyboardBehavior: function () {
  1708. $(document).on('keyup.keyBlock', function (e) {
  1709. e.stopPropagation();
  1710. if (e.keyCode == 27) {
  1711. modal.closeModal();
  1712. }
  1713. if (e.keyCode == 13) {
  1714. e.preventDefault();
  1715. $('.modal button[type=submit]').first().trigger('click');
  1716. }
  1717. });
  1718. },
  1719.  
  1720. getGrayCover: function () {
  1721. var grayCover = "<div class='gray-cover'></div>";
  1722. $(".modal-container").prepend(grayCover);
  1723. $("body").children("*:not(.gray-cover, .modal-container, .emoji-menu, .tether-element)").addClass("blur");
  1724. $("body,html").css({overflow: "hidden"});
  1725. window.scrollTo(0, 0);
  1726. },
  1727.  
  1728. /**
  1729. * Closes all modals on screen
  1730. * If you need to open another modal after the first is called, pass a object parameter with the data as:
  1731. *
  1732. * @param nextModal array Modal to be opened with options:
  1733. * [file, noClose, data]
  1734. * */
  1735. closeModal: function (nextModal) {
  1736. $('.modal-resource').remove();
  1737. $('.emoji-menu').not(':eq(0)').remove();
  1738. $("*").removeClass("blur");
  1739.  
  1740. function getNextModal() {
  1741. if (nextModal != undefined) {
  1742. var opt = [];
  1743. $.each(nextModal, function (key, value) {
  1744. opt[key] = value;
  1745. });
  1746. modal.getModal(opt[0], opt[1], opt[2]);
  1747. }
  1748. }
  1749.  
  1750. if ($(".modal-container").length != 0) {
  1751.  
  1752. $(".modal-container").fadeOut(300, function () {
  1753. $(window).scrollTop(modal.scrollPosition);
  1754. $('.interferingStyleSheet').prop('disabled', false);
  1755. $(this).remove();
  1756. getNextModal();
  1757. });
  1758.  
  1759. } else {
  1760. getNextModal();
  1761. }
  1762.  
  1763. $("body,html").css({overflow: "visible"});
  1764. $(document).off('keyup.keyBlock');
  1765. getData = window.previousGetData;
  1766. },
  1767.  
  1768. /**
  1769. * Closes all modals on screen and back to previous page
  1770. * */
  1771. backPage: function () {
  1772. modal.closeModal();
  1773. history.back();
  1774. },
  1775.  
  1776. reposition: function () {
  1777. $('.modal-container').css({top: $(window).scrollTop()});
  1778.  
  1779. var block = $('.modal');
  1780. var height = block.height();
  1781. var winHeight = $(window).height();
  1782. if (winHeight < height + 50) {
  1783. var top = 59.5;
  1784. grayHeight = (block.outerHeight(true) + top) + 'px';
  1785. } else {
  1786. top = (winHeight - height) / 2;
  1787. var grayHeight = '100vh';
  1788. }
  1789. var topPixels = top + 'px';
  1790. block.css({top: topPixels});
  1791.  
  1792. $('.gray-cover').css({height: grayHeight});
  1793. document.getElementsByClassName('modal-container')[0].scrollTop = 0;
  1794. },
  1795.  
  1796. modal: function () {
  1797. this.typeKeyboardBehavior();
  1798. this.getGrayCover();
  1799. },
  1800.  
  1801. /*
  1802. * file to be opened
  1803. * noClose boolean is it to be closed on out click or not?
  1804. * data JSON any data to be passed to the block
  1805. * */
  1806. getModal: function (file, noClose, data) {
  1807. console.log('inicio');
  1808. modal.scrollPosition = $(window).scrollTop();
  1809. // console.log(getData);
  1810. if (typeof(getData) != "undefined") {
  1811. window.previousGetData = getData;
  1812. }
  1813.  
  1814. $.post(ref.getIncludes + "/modal/" + file, data, function (code) {
  1815.  
  1816. $(document).ready(function () {
  1817. // code.replace('\<script', '\<script class="modal-resource"');
  1818. // code.replace('<style', '<style class="modal-resource"');
  1819. console.log('ready');
  1820. $("body").prepend(code);
  1821.  
  1822. modal.modal();
  1823. $('.modal').find('button:only-of-type').focus();
  1824. $('.modal').find('input').focus();
  1825.  
  1826. modal.reposition();
  1827. // reposition modal when screen is resized
  1828. $(window).on('resize', function () {
  1829. modal.reposition();
  1830. });
  1831.  
  1832. // the modal is not to be closed by the user (ex: LOADING EVENT)
  1833. if (noClose) {
  1834. $(document).off('keyup.keyBlock');
  1835. } else {
  1836. $('.gray-cover').on('click', function () {
  1837. modal.closeModal();
  1838. });
  1839. }
  1840.  
  1841. /* observe for node manipulation in the modal to resize it if needed */
  1842. var modalObserver = new MutationObserver(function () {
  1843. modal.reposition();
  1844. });
  1845. modalObserver.observe(document.getElementsByClassName('modal')[0], {childList: true, subtree: true});
  1846.  
  1847. // so it don't close when clicked (don't trigger .block-container)
  1848. // $('.modal').on('click', function (e) {
  1849. // console.log(e);
  1850. // e.stopPropagation();
  1851. // });
  1852.  
  1853. });
  1854.  
  1855. });
  1856. }
  1857. };
  1858.  
  1859. var balloon = {
  1860.  
  1861. //close balloon. Pass the balloon ID to close
  1862. closeBalloon: function (id) {
  1863. $(id).hide();
  1864. }
  1865. };
  1866.  
  1867.  
  1868. /* OPEN CONTENTS
  1869. * Procedures to navigate through pages
  1870. * For the window.popstate to work properly, keep the object names the same as the corresponding folders
  1871. * */
  1872. var navigateTo = {
  1873.  
  1874. //MAIN - MY APPS
  1875. myApps: function () {
  1876. window.open('/main-dashboard', '_self');
  1877. },
  1878.  
  1879. // APP PAGE: Run this before opening an item in menu-side
  1880. procedure: function (title, path, item, callback) {
  1881. appHeader.hide();
  1882. $('.select-theme-inngage').remove(); // clean all select DIV created
  1883. $('.modal-resource').remove(); // clean all modal resources (script and style tags)
  1884. $('.js-clean-resource').remove(); // clean all resources not used (script and style tags)
  1885. $('.tether-element').remove(); // clean all resources from TETHER plugin
  1886. $('.select-theme-inngage').remove(); // clean all resources from SELECT plugin
  1887. // $('.emoji-menu').not(':eq(0)').remove(); // clean all emoji menus created
  1888. $('.emoji-menu').remove(); // clean all emoji menus created
  1889. $('.ui-datepicker').remove(); // clean all datepickers
  1890.  
  1891. $('.nav-side-title-selected').removeClass('nav-side-title-selected');
  1892. $('.nav-side-item-selected').removeClass('nav-side-item-selected');
  1893.  
  1894. $(title).addClass('nav-side-title-selected');
  1895. if (item) {
  1896. var obj = $(item);
  1897. obj.addClass('nav-side-item-selected');
  1898. }
  1899.  
  1900. var appToken = window.location.search;
  1901.  
  1902. if (history.state) {
  1903. if (history.state['inn'] != path) {
  1904. history.pushState({'inn': path}, '', '/app' + path + appToken);
  1905. }
  1906. } else {
  1907. history.pushState({'inn': path}, '', '/app' + path + appToken);
  1908. }
  1909.  
  1910. contentContainer.load(ref.getAppPg + path, function () {
  1911. window.scrollTo(0, 0); //if page was scrolled down, then go back to top
  1912. if (callback != undefined && callback != '') {
  1913. callback();
  1914. }
  1915. });
  1916. },
  1917.  
  1918. app: {
  1919. //APP-DASHBOARD
  1920. dashboard: function () {
  1921. navigateTo.procedure('#dashboard', '/dashboard');
  1922. contentContainer.empty();
  1923. appHeader.load(ref.getIncludes + '/app-pg/dashboard/app-header.php').show();
  1924. },
  1925.  
  1926. audience: {
  1927. title: '#audience',
  1928.  
  1929. audiences: function () {
  1930. navigateTo.procedure(this.title, "/audience/audiences", "#audiences");
  1931. },
  1932. newAudience: function () {
  1933. navigateTo.procedure(this.title, "/audience/new-audience", "#audiences");
  1934. },
  1935. subscribers: function () {
  1936. navigateTo.procedure(this.title, "/audience/subscribers", "#subscribers");
  1937. },
  1938. importData: function () {
  1939. navigateTo.procedure(this.title, "/audience/import-data");
  1940. }
  1941. },
  1942.  
  1943. push: {
  1944. title: '#push',
  1945.  
  1946. campaigns: function () {
  1947. navigateTo.procedure(this.title, "/push/campaigns", '#campaigns');
  1948. },
  1949. newCampaign: function () {
  1950. navigateTo.procedure(this.title, "/push/new-campaign", '#campaigns');
  1951. },
  1952. sendPush: function () {
  1953. navigateTo.procedure(this.title, "/push/send-push", '#sendPush');
  1954. },
  1955. notificationsSent: function () {
  1956. navigateTo.procedure(this.title, "/push/notifications-sent", '#sendPush');
  1957. },
  1958. notificationsScheduled: function () {
  1959. navigateTo.procedure(this.title, "/push/notification-scheduled", '#sendPush');
  1960. },
  1961. directMail: function () {
  1962. navigateTo.procedure(this.title, "/push/direct-mail");
  1963. },
  1964. automations: function () {
  1965. navigateTo.procedure(this.title, "/push/automations", '#automations');
  1966. },
  1967. newAutomation: function () {
  1968. navigateTo.procedure(this.title, "/push/new-automation", '#automations');
  1969. },
  1970. apiTemplate: function () {
  1971. navigateTo.procedure(this.title, "/push/api-template", '#apiTemplate');
  1972. },
  1973. newApiTemplate: function () {
  1974. navigateTo.procedure(this.title, "/push/new-api-template", '#apiTemplate');
  1975. },
  1976. massUpload: function () {
  1977. navigateTo.procedure(this.title, "/push/mass-upload", '#massUpload');
  1978. },
  1979. massMatch: function () {
  1980. navigateTo.procedure(this.title, "/push/mass-match", '#massMatch');
  1981. },
  1982. massPush: function () {
  1983. navigateTo.procedure(this.title, "/push/mass-push", '#massPush');
  1984. },
  1985. },
  1986.  
  1987. status: {
  1988. title: '#status',
  1989.  
  1990. sent: function () {
  1991. navigateTo.procedure(this.title, "/status/sent", '#sent');
  1992. },
  1993. scheduled: function () {
  1994. navigateTo.procedure(this.title, "/status/scheduled", '#scheduled');
  1995. },
  1996. sentApi: function () {
  1997. navigateTo.procedure(this.title, "/status/sent-api");
  1998. },
  1999. autosent: function () {
  2000. navigateTo.procedure(this.title, "/status/autosent", '#autosent');
  2001. }
  2002. },
  2003.  
  2004. configuration: {
  2005. title: '#configuration',
  2006.  
  2007. general: function () {
  2008. navigateTo.procedure(this.title, "/configuration/general", '#general');
  2009.  
  2010. },
  2011. platform: function () {
  2012. navigateTo.procedure(this.title, "/configuration/platform", "#platform");
  2013. },
  2014. fontCode: function () {
  2015. // navigateTo.procedure(this.title, "/configuration/(UNUSED) font-code", '#fontCode');
  2016. window.open('https://inngage.readme.io/');
  2017. },
  2018. teamNew: function () {
  2019. navigateTo.procedure(this.title, "/configuration/teamNew", '#team');
  2020. },
  2021. team: function () {
  2022. navigateTo.procedure(this.title, "/configuration/team", '#team');
  2023. }
  2024. }
  2025. },
  2026.  
  2027. appPopState: function () {
  2028. var path = (window.location.pathname).substr(1);
  2029. var dirs = path.split('/');
  2030.  
  2031. $.each(dirs, function (index, val) {
  2032. var name = val.split('-');
  2033. for (var i = 1; i < name.length; i++) {
  2034. var firstLetter = name[i].substring(0, 1);
  2035. name[i] = name[i].replace(firstLetter, firstLetter.toUpperCase());
  2036. }
  2037. dirs[index] = name.join('');
  2038. });
  2039.  
  2040. var pageGroup = dirs[1];
  2041. var page = dirs[2];
  2042.  
  2043. if (page) {
  2044. window['navigateTo']['app'][pageGroup][page]();
  2045. } else {
  2046. window['navigateTo']['app'][pageGroup]();
  2047. }
  2048. }
  2049. };
  2050.  
  2051. /* Start immediately */
  2052. $(document).ready(function () {
  2053. behaviors.autoTextArea();
  2054. });
  2055.  
  2056.  
  2057. var scriptForPage = {
  2058.  
  2059. showConditionField: function (rowId, varType) {
  2060. $(rowId).find('.js-condition').hide();
  2061. $(rowId).find('.js-' + varType + '-condition').css({display: 'inline-block'});
  2062. },
  2063.  
  2064. newAudience: function (audienceId, audienceJson, criteriaJson, appId, insertEventsFooter) {
  2065.  
  2066. var num = 0;
  2067. var conditionNumber = 0;
  2068.  
  2069. function insertNewCondition(context) {
  2070. var thisNum = num;
  2071. conditionNumber++;
  2072. num++; //increment the number of conditions
  2073.  
  2074. var clone = $(context.find('#jsNewConditionRow')).clone();
  2075. // PREPARE THE CLONED ELEMENT
  2076. var rowId = 'jsConditionRow' + thisNum;
  2077. clone.attr('id', rowId).removeClass('js-new-condition-row').addClass('js-condition-row');
  2078. clone.find('#removeCondition').attr('id', 'removeCondition' + thisNum);
  2079. $.each($(clone.find('.js-select')), function (index, elem) {
  2080. $(elem).attr('id', 'select' + thisNum + index);
  2081. });
  2082. $.each($(clone.find('input[name=val]')), function (index, elem) {
  2083. $(elem).attr('id', 'val' + thisNum + index);
  2084. });
  2085. clone.find('.element-counter').text(conditionNumber);
  2086. clone.find('.true-false-tab').attr('id', 'trueFalse' + thisNum);
  2087. $.each($(clone.find('.date')), function (index, elem) {
  2088. $(elem).attr('id', 'date' + thisNum + index);
  2089. $(elem).datepicker({
  2090. format: 'dd/mm/yyyy',
  2091. language: locale,
  2092. beforeShow: function (input, obj) {
  2093. // $(input).after($(input).datepicker('widget'));
  2094. // $(input).datepicker("refresh");
  2095. $('.ui-datepicker').removeClass('blur');
  2096. },
  2097. onSelect: function (textData, objDatepicker) {
  2098. action.findReachAudience(appId);
  2099. }
  2100. });
  2101. });
  2102.  
  2103. //INSERT THE PREPARED ELEMENT
  2104. clone.insertBefore(context.find('.js-newCondition')); // use class because of the elements order in modal-new-audience
  2105.  
  2106.  
  2107. //DEFINE BEHAVIORS
  2108. $.each($('#' + rowId).find('.js-select'), function (index, elem) {
  2109. transform.customSelect('select' + thisNum + index);
  2110. $('#select' + thisNum + index).change(function () {
  2111. $(this).next('a').css({color: 'inherit'});
  2112. });
  2113. });
  2114. $('#select' + thisNum + 0).on('change', function () {
  2115. var varType = $(this).find('option[value=' + $(this).val() + ']').attr('data-type');
  2116. scriptForPage.showConditionField('#' + rowId, varType);
  2117. action.findReachAudience(appId);
  2118. });
  2119. var tab = $("#trueFalse" + thisNum).tabs();
  2120.  
  2121. // Set dateInput on change to refresh range
  2122. var dateInput = $('#date' + thisNum + 0);
  2123. dateInput.on('change', function () {
  2124. action.findReachAudience(appId);
  2125. });
  2126. // Date behavior: hide or change the condition input field
  2127. $('#select' + thisNum + 3).on('change', function () {
  2128. var dateType = $(this).val();
  2129. // show Datepicker
  2130. if (dateType <= 13) {
  2131. dateInput.datepicker({
  2132. format: 'dd/mm/yyyy',
  2133. language: locale,
  2134. onSelect: function (textData, objDatepicker) {
  2135. action.findReachAudience(appId);
  2136. }
  2137. });
  2138. dateInput.parent().show(); // show the span with the input
  2139. dateInput.attr('type', 'text').removeClass('days-input');
  2140. $(dateInput.next('span')).css({'display': 'none'});
  2141. // show int and span "Days"
  2142. } else if (dateType <= 16) {
  2143. dateInput.datepicker('destroy');
  2144. dateInput.parent().show();
  2145. dateInput.attr('type', 'number').attr('placeholder', 'Número de dias').addClass('days-input');
  2146. $(dateInput.next('span')).css({'display': 'inline-block'});
  2147. // don't show
  2148. } else if (dateType == 17) {
  2149. $(dateInput.parent()).css({'display': 'none'});
  2150. dateInput.attr('type', 'text').val('today'); // hide the span with the input
  2151. }
  2152. });
  2153.  
  2154. $('#removeCondition' + thisNum).hover(function () {
  2155. behaviors.svgChangeTo.hover($(this).children('img'));
  2156. }, function () {
  2157. behaviors.svgChangeTo.hover($(this).children('img'));
  2158. }).click(function () {
  2159. $(this).parents('.filter-row').remove();
  2160. $.each(context.find('.element-counter'), function (index, elem) {
  2161. $(elem).html(index + 1);
  2162. });
  2163. conditionNumber--;
  2164. if (conditionNumber == 1) {
  2165. $('.remove-icon').fadeOut(200);
  2166. }
  2167. action.findReachAudience(appId);
  2168. });
  2169.  
  2170. // show remove-icon again
  2171. if (conditionNumber > 1) {
  2172. $('.remove-icon').fadeIn(100);
  2173. }
  2174.  
  2175. insertEventToFindReachAudience(appId);
  2176. }
  2177.  
  2178. insertNewCondition($('#addNewCondition').parents('.filter-panel')); // starts with a condition row
  2179.  
  2180. $('#addNewCondition').hover(function () {
  2181. $('#plus').addClass('hover-green');
  2182. $(this).css({fontWeight: '400'});
  2183. behaviors.svgChangeTo.hover($(this).children('img'));
  2184. }, function () {
  2185. $('#plus').removeClass('hover-green');
  2186. $(this).attr('style', '');
  2187. behaviors.svgChangeTo.hover($(this).children('img'));
  2188. }).click(function () {
  2189. insertNewCondition($(this).parents('.filter-panel'));
  2190. });
  2191.  
  2192. function insertEventToFindReachAudience(appId) {
  2193. var elements = $(".js-condition-row");
  2194.  
  2195. for (var i = 0; i < elements.length; i++) {
  2196. var row = "#" + elements[i].id;
  2197.  
  2198. $(row).find('select[name=operator]').on('change', function () {
  2199. action.findReachAudience(appId);
  2200. });
  2201.  
  2202. $(row).find('.ui-state-default').on('click', function () {
  2203. action.findReachAudience(appId);
  2204. });
  2205.  
  2206. $(row).find('input[name=val]').on('change', function () {
  2207. action.findReachAudience(appId);
  2208. });
  2209. }
  2210. }
  2211.  
  2212. populateAudience(audienceId, audienceJson, criteriaJson, appId);
  2213.  
  2214. function populateAudience(audienceId, audienceJson, criteriaJson, appId) {
  2215. if (audienceId > 0) {
  2216. var audienceName = audienceJson['audience_name'];
  2217. var audienceDescription = audienceJson['audience_description'];
  2218.  
  2219. populateAudienceCriteria(criteriaJson);
  2220.  
  2221. $('#componentName').val(audienceName);
  2222. $('#componentDescription').val(audienceDescription);
  2223.  
  2224. action.findReachAudience(appId);
  2225.  
  2226. $('.page-title').html(audienceName);
  2227. }
  2228. }
  2229.  
  2230. function populateAudienceCriteria(criteriaJson) {
  2231. if (criteriaJson) {
  2232. var i = 0;
  2233. $.each(criteriaJson, function (index, value) {
  2234. if ((i > 0) && (value !== null) && (value !== undefined)) {
  2235. $("#addNewCondition").trigger("click");
  2236. }
  2237. var selectField = $("#select" + i + "0").attr('value', value.audience_criteria_id);
  2238. selectField.val(value.audience_field_id);
  2239. selectField.next('a').css({color: 'inherit'});
  2240.  
  2241. var varType = selectField.find('option[value=' + selectField.val() + ']').attr('data-type');
  2242. scriptForPage.showConditionField('#jsConditionRow' + i, varType);
  2243.  
  2244. var objectTypeCondition = $('#jsConditionRow' + i).find('.js-' + varType + '-condition');
  2245.  
  2246. if (varType == 'boolean') {
  2247. objectTypeCondition.find('a[href="#' + value.audience_value + '"]').trigger('click');
  2248. } else {
  2249. objectTypeCondition.find('select[name=operator]').val(value.audience_field_condition_id);
  2250. objectTypeCondition.find('select[name=operator]').attr('value', value.audience_field_condition_id);
  2251. objectTypeCondition.find('select[name=operator]').next('a').css({color: 'inherit'});
  2252.  
  2253. objectTypeCondition.find('input[name=val]').val(value.audience_value);
  2254. }
  2255. i++;
  2256. });
  2257. }
  2258. }
  2259.  
  2260. if (insertEventsFooter) {
  2261. $('#footerSave').on('click', function () {
  2262. if ((validate.field('#componentName', 'Qual o nome da sua audiência?')) && (validate.fieldsAudienceCriteria(true))) {
  2263. action.saveAudience(audienceId, appId, true);
  2264. }
  2265. });
  2266.  
  2267. $('#footerCancel').on('click', function () {
  2268. navigateTo.app.audience.audiences();
  2269. });
  2270. }
  2271.  
  2272. },
  2273.  
  2274. newCollaborator: function (collaboratorJson) {
  2275.  
  2276. var num = 0;
  2277. var collaboratorNumber = 0;
  2278.  
  2279. function insertNewCollaborator(context) {
  2280. var thisNum = num;
  2281. collaboratorNumber++;
  2282. num++; //increment the number of conditions
  2283.  
  2284. var clone = $(context.find('#jsNewCollaboratorRow')).clone();
  2285. // PREPARE THE CLONED ELEMENT
  2286. var rowId = 'jsCollaboratorRow' + thisNum;
  2287. clone.attr('id', rowId).removeClass('js-new-row').addClass('js-collaborator-row');
  2288. clone.find('#removeMember').attr('id', 'removeMember' + thisNum);
  2289. $.each($(clone.find('.js-select')), function (index, elem) {
  2290. $(elem).attr('id', 'select' + thisNum + index);
  2291. });
  2292. $.each($(clone.find('input[name=member-name]')), function (index, elem) {
  2293. $(elem).attr('id', 'member-name' + thisNum + index);
  2294. });
  2295. $.each($(clone.find('input[name=member-email]')), function (index, elem) {
  2296. $(elem).attr('id', 'member-email' + thisNum + index);
  2297. });
  2298. clone.find('.element-counter').text(collaboratorNumber);
  2299.  
  2300. //INSERT THE PREPARED ELEMENT
  2301. clone.insertBefore(context.find('.js-newCollaborator'));
  2302.  
  2303. //DEFINE BEHAVIORS
  2304. $.each($('#' + rowId).find('.js-select'), function (index, elem) {
  2305. transform.customSelect('select' + thisNum + index);
  2306. $('#select' + thisNum + index).change(function () {
  2307. $(this).next('a').css({color: 'inherit'});
  2308. });
  2309. });
  2310.  
  2311. $('#removeMember' + thisNum).hover(function () {
  2312. behaviors.svgChangeTo.hover($(this).children('img'));
  2313. }, function () {
  2314. behaviors.svgChangeTo.hover($(this).children('img'));
  2315. }).click(function () {
  2316. //updates user indicating that he has been deleted
  2317. var idFieldName = '#' + $(this)[0].id.replace('removeMember', 'member-email') + '0';
  2318. action.deleteCollaborator($(idFieldName).val(), this, context, collaboratorNumber);
  2319. /*-------
  2320. *TODO: implementar uma verificação se o usuário excluído é o usuário logado, se for deslogar o usuário
  2321. -------*/
  2322. });
  2323.  
  2324. insertEventToSaveCollaborator();
  2325. }
  2326.  
  2327. insertNewCollaborator($('#addNewCollaborator').parents('.control-panel')); // starts with a condition row
  2328.  
  2329. $('#addNewCollaborator').hover(function () {
  2330. $('#plus').addClass('hover-green');
  2331. $(this).css({fontWeight: '400'});
  2332. behaviors.svgChangeTo.hover($(this).children('img'));
  2333. }, function () {
  2334. $('#plus').removeClass('hover-green');
  2335. $(this).attr('style', '');
  2336. behaviors.svgChangeTo.hover($(this).children('img'));
  2337. }).click(function () {
  2338. insertNewCollaborator($(this).parents('.control-panel'));
  2339. });
  2340.  
  2341. function insertEventToSaveCollaborator() {
  2342. var elements = $(".js-collaborator-row");
  2343.  
  2344. for (var i = 0; i < elements.length; i++) {
  2345. var row = "#" + elements[i].id;
  2346.  
  2347. $(row).find('select[name=profile]').on('change', function () {
  2348. scriptForPage.collaborator.saveCollaborator();
  2349. });
  2350.  
  2351. $(row).find('input[name=member-name]').on('change', function () {
  2352. scriptForPage.collaborator.saveCollaborator();
  2353. });
  2354.  
  2355. $(row).find('input[name=member-email]').on('change', function () {
  2356. scriptForPage.collaborator.saveCollaborator();
  2357. });
  2358. }
  2359. }
  2360.  
  2361. populateCollaborator(collaboratorJson);
  2362.  
  2363. function populateCollaborator(collaboratorJson) {
  2364. var i = 0;
  2365. $.each(collaboratorJson, function (index, value) {
  2366. if ((i > 0) && (value !== null) && (value !== undefined)) {
  2367. $("#addNewCollaborator").trigger("click");
  2368. }
  2369. var selectProfile = $("#select" + i + "0").attr('value', value.profile_id);
  2370. selectProfile.val(value.profile_id);
  2371. selectProfile.next('a').css({color: 'inherit'});
  2372.  
  2373. $("#member-name" + i + "0").val(value.name);
  2374. $("#member-email" + i + "0").val(value.email);
  2375. //objectTypeCondition.find('select[name=operator]').next('a').css({color: 'inherit'});
  2376.  
  2377. //objectTypeCondition.find('input[name=val]').val(value.audience_value);
  2378. i++;
  2379. });
  2380. }
  2381.  
  2382. /*if (insertEventsFooter) {
  2383. $('#footerSave').on('click', function () {
  2384. if ((validate.field('#componentName', 'Qual o nome da sua audiência?')) && (validate.fieldsAudienceCriteria(true))) {
  2385. action.saveAudience(audienceId, appId, true);
  2386. }
  2387. });
  2388. }*/
  2389.  
  2390. },
  2391.  
  2392. dashboard: function () {
  2393.  
  2394. $('#selectAudience').on('change', function () {
  2395. getData();
  2396. });
  2397.  
  2398. function getData() {
  2399. var selectedId = $('#selectAudience').val();
  2400. var audienceId = selectedId.replace('audience', '');
  2401. $.ajax({
  2402. type: 'POST',
  2403. url: '/handleReports',
  2404. data: {audienceId: audienceId}
  2405. }).done(function (data) {
  2406.  
  2407. var json = JSON.parse(data);
  2408. console.log(json);
  2409. updateDataJson(json);
  2410. refreshData();
  2411. }).fail(function (data) {
  2412. console.log(data);
  2413. });
  2414. }
  2415.  
  2416. transform.customSelect('selectAudience');
  2417.  
  2418. window.doughnutChart = charts.createDonutChart('#doughnutChart', 1);
  2419.  
  2420. window.doughnutInfo = 'openedDoughnut'; // initial selected info-bot doughnut
  2421. window.interval = 'week'; // initial selected interval
  2422.  
  2423. function refreshData() {
  2424. $('#' + window.interval).trigger('click');
  2425. $('#' + window.doughnutInfo).trigger('click');
  2426. updateBarChart();
  2427. $(".number-bar-chart").html((window.dataJson.week.sentNum).toLocaleString());
  2428. }
  2429.  
  2430. charts.resizeChartDiv();
  2431. transform.counter(0);
  2432.  
  2433. $("#tabs").tabs();
  2434.  
  2435. /* Render week line chart */
  2436. function renderLineChart() {
  2437.  
  2438. var color = "#2ecc71";
  2439.  
  2440. var data = {
  2441. labels: ['dummy'],
  2442. datasets: [{
  2443. fill: false,
  2444. tension: 0,
  2445. borderCapStyle: 'round',
  2446. pointBackgroundColor: "#fff",
  2447. pointBorderWidth: 3,
  2448. pointHoverRadius: 3,
  2449. pointHoverBorderWidth: 4,
  2450. backgroundColor: color,
  2451. borderColor: color,
  2452. pointHoverBackgroundColor: color,
  2453. pointHoverBorderColor: color,
  2454. pointBorderColor: color,
  2455. data: ["0"]
  2456. }]
  2457. };
  2458.  
  2459. window.lineChart = new Chart($('#lineChart'), {
  2460. type: 'line',
  2461. data: data,
  2462. options: {
  2463. maintainAspectRatio: false,
  2464. legend: {
  2465. display: false
  2466. },
  2467. elements: {
  2468. point: {
  2469. radius: 4
  2470. }
  2471. },
  2472. tooltips: {
  2473. callbacks: {
  2474. title: function (tooltipItem, data) {
  2475.  
  2476. },
  2477. label: function (tooltipItem, data) {
  2478. return tooltipItem.yLabel;
  2479. },
  2480. footer: function (tooltipItem, data) {
  2481.  
  2482. }
  2483. }
  2484. },
  2485. scales: {
  2486. yAxes: [{
  2487. ticks: {
  2488. min: 0,
  2489. suggestedMax: 20
  2490. }
  2491. }]
  2492. }
  2493. }
  2494. });
  2495. }
  2496.  
  2497. renderLineChart();
  2498.  
  2499. function updateDataJson(json) {
  2500. console.log(json);
  2501. window.dataJson = json;
  2502. }
  2503.  
  2504. function updateDoughnutChart() {
  2505.  
  2506. var interval = window.interval;
  2507.  
  2508. var sent = window['dataJson'][interval]['sentNum'];
  2509. var received = window['dataJson'][interval]['received'];
  2510. var opened = window['dataJson'][interval]['openedNum'];
  2511.  
  2512. function update(value) {
  2513. $('#doughnutChartLabel').text(value);
  2514. return [value, (100 - value)];
  2515. }
  2516.  
  2517. if (document.getElementById('doughnutChart').style.display == 'none' &&
  2518. window.doughnutInfo != 'sentDoughnut') {
  2519. $('#doughnutChartLabel').stop();
  2520. $('.cuv-percent').fadeIn();
  2521. $('.chart-background').fadeIn();
  2522. $('#doughnutChart').fadeIn();
  2523. }
  2524.  
  2525. switch (window.doughnutInfo) {
  2526. case 'sentDoughnut':
  2527. $('.cuv-percent').hide();
  2528. $('.chart-background').hide();
  2529. $('#doughnutChart').hide();
  2530.  
  2531. $('#doughnutChartLabel').text(sent);
  2532. transform.counter(0);
  2533.  
  2534. $('#doughnutChartTitle').text('Pushes Enviados');
  2535.  
  2536. return;
  2537.  
  2538. case 'receivedDoughnut':
  2539. window.doughnutChart.data.datasets[0].data = update(received);
  2540. transform.counter(0);
  2541.  
  2542. $('#doughnutChartTitle').text('Pushes Recebidos');
  2543.  
  2544. break;
  2545.  
  2546. case 'openedDoughnut':
  2547. window.doughnutChart.data.datasets[0].data = update(opened);
  2548. transform.counter(0);
  2549.  
  2550. $('#doughnutChartTitle').text('Pushes Abertos');
  2551.  
  2552. break;
  2553.  
  2554. }
  2555.  
  2556. window.doughnutChart.update();
  2557.  
  2558. }
  2559.  
  2560. function updateLineChart() {
  2561.  
  2562. var labels;
  2563. var data;
  2564. var sentNum;
  2565. var received;
  2566. var openedNum;
  2567.  
  2568.  
  2569. function updateDoughnutBotInfo() {
  2570.  
  2571. var interval = window.interval;
  2572.  
  2573. var sent = window['dataJson'][interval]['sentNum'].toLocaleString();
  2574. var received = window['dataJson'][interval]['received'];
  2575. var opened = window['dataJson'][interval]['openedNum'];
  2576.  
  2577. var doughnutBotInfo = $('.doughnut-bot-info');
  2578. doughnutBotInfo.children('#sentDoughnut').children('.number').text(parseInt(sent).toLocaleString(locale));
  2579. doughnutBotInfo.children('#receivedDoughnut').children('.number').text(received + '%');
  2580. doughnutBotInfo.children('#openedDoughnut').children('.number').text(opened + '%');
  2581. }
  2582.  
  2583. function updateInterval(interval) {
  2584.  
  2585. labels = window['dataJson'][interval]['labels'];
  2586. console.log("Labels:");
  2587. console.log(labels);
  2588. data = window['dataJson'][interval]['sent'];
  2589. console.log("Sent:");
  2590. console.log(data);
  2591.  
  2592. window.lineChart.data.labels = labels;
  2593. window.lineChart.data.datasets[0].data = data;
  2594. }
  2595.  
  2596. updateInterval(window.interval);
  2597. updateDoughnutChart();
  2598. updateDoughnutBotInfo();
  2599.  
  2600. // duas linhas no grafico
  2601. /*
  2602. var green = "#2ecc71";
  2603. var blue = "#4ad1ed";
  2604.  
  2605.  
  2606. case 'lineSent':
  2607. // add new line
  2608. if ($('#lineSent').prop('checked')) {
  2609.  
  2610. var interval = $('.line-chart-interval').find('.chart-range-active').attr('id');
  2611.  
  2612. var color = green;
  2613.  
  2614. var dataset = {};
  2615.  
  2616. dataset.fill = false;
  2617. dataset.lineTension = 0.1;
  2618. dataset.borderCapStyle = 'round';
  2619. dataset.pointBackgroundColor = "#fff";
  2620. dataset.pointBorderWidth = 3;
  2621. dataset.pointHoverRadius = 3;
  2622. dataset.pointHoverBorderWidth = 4;
  2623. dataset.backgroundColor = color;
  2624. dataset.borderColor = color;
  2625. dataset.pointHoverBackgroundColor = color;
  2626. dataset.pointHoverBorderColor = color;
  2627. dataset.pointBorderColor = color;
  2628.  
  2629. dataset.data = window['dataJson'][interval]['opened'];
  2630.  
  2631. if (window.lineChart.data.datasets[0] == undefined) {
  2632. window.lineChart.data.datasets[0] = dataset;
  2633. } else {
  2634. window.lineChart.data.datasets[1] = dataset;
  2635. }
  2636.  
  2637. } else {
  2638. window.lineChart.data.datasets.splice(1);
  2639. }
  2640.  
  2641. break;
  2642.  
  2643. case 'lineOpened':
  2644. // add new line
  2645. if ($('#lineOpened').prop('checked')) {
  2646.  
  2647. var interval = $('.line-chart-interval').find('.chart-range-active').attr('id');
  2648.  
  2649. var color = blue;
  2650.  
  2651. var dataset = {};
  2652.  
  2653. dataset.fill = false;
  2654. dataset.lineTension = 0.1;
  2655. dataset.borderCapStyle = 'round';
  2656. dataset.pointBackgroundColor = "#fff";
  2657. dataset.pointBorderWidth = 3;
  2658. dataset.pointHoverRadius = 3;
  2659. dataset.pointHoverBorderWidth = 4;
  2660. dataset.backgroundColor = color;
  2661. dataset.borderColor = color;
  2662. dataset.pointHoverBackgroundColor = color;
  2663. dataset.pointHoverBorderColor = color;
  2664. dataset.pointBorderColor = color;
  2665.  
  2666. dataset.data = window['dataJson'][interval]['opened'];
  2667.  
  2668. if (window.lineChart.data.datasets[0] == undefined) {
  2669. window.lineChart.data.datasets[0] = dataset;
  2670. } else {
  2671. window.lineChart.data.datasets[1] = dataset;
  2672. }
  2673.  
  2674. } else {
  2675. window.lineChart.data.datasets.splice(1);
  2676. }
  2677.  
  2678. break; */
  2679.  
  2680. window.lineChart.update();
  2681. window.doughnutChart.update();
  2682. }
  2683.  
  2684.  
  2685. // select the interval of the chart
  2686. $('.line-chart-interval').on('click', function (e) {
  2687. // only trigger if a button is pressed
  2688. if (e.target.className != 'line-chart-interval') {
  2689. $($(this).children('.chart-range-item')).removeClass('chart-range-active');
  2690. var interval = $(e.target).addClass('chart-range-active').attr('id');
  2691. }
  2692. window.interval = interval;
  2693. updateLineChart(interval);
  2694. });
  2695.  
  2696. // select the filter to see the chart
  2697. $('.js-line-label').on('change', function (e) {
  2698. var intervalElem = $(e.target);
  2699. var interval = intervalElem.attr('id');
  2700.  
  2701. if ($(e.target).prop('checked')) {
  2702. $('#' + interval + 'Label').show();
  2703. } else {
  2704. $('#' + interval + 'Label').hide();
  2705. // keep always one filter selected
  2706. $.each($('.js-line-label'), function (key, elem) {
  2707. var once = false;
  2708. if ($(elem).attr('id') != interval && once == false) {
  2709. $(elem).prop('checked', true);
  2710. $('#' + $(elem).attr('id') + 'Label').show();
  2711. once = true; // loop just for the first matched element
  2712. // interval = $(elem).attr('id'); // change the id so update chart will be right
  2713. }
  2714. });
  2715. }
  2716. });
  2717.  
  2718. // put gray background and green letters when select doughnut chart info
  2719. $('.doughnut-bot-info').on('click', function (e) {
  2720. // only trigger if a button is pressed
  2721. if (e.target.className != 'doughnut-bot-info') {
  2722. $($(this).find('*')).removeClass('darker-bot-info green');
  2723. if (e.target.localName == 'span') {
  2724. var button = $(e.target).parent('button');
  2725. } else {
  2726. var button = $(e.target);
  2727. }
  2728. var doughnutInfo = button.addClass('darker-bot-info').attr('id');
  2729. button.children('.number').addClass('green');
  2730.  
  2731. var older = window.doughnutInfo;
  2732. if (older != doughnutInfo) {
  2733. window.doughnutInfo = doughnutInfo;
  2734. updateDoughnutChart();
  2735. }
  2736. }
  2737. });
  2738.  
  2739. function renderBarChart() {
  2740. var dataBarChart = {
  2741. labels: ['dummy'],
  2742. datasets: [
  2743. {
  2744. backgroundColor: "#d0d0d0",
  2745. borderColor: "#d0d0d0",
  2746. borderWidth: 1,
  2747. hoverBackgroundColor: "#3ec556",
  2748. hoverBorderColor: "#3ec556",
  2749. data: [0]
  2750. }
  2751. ]
  2752. };
  2753.  
  2754. window.barChart = new Chart($('#barChart'), {
  2755. type: 'bar',
  2756. data: dataBarChart,
  2757. options: {
  2758. maintainAspectRatio: false,
  2759. legend: {
  2760. display: false
  2761. },
  2762. scales: {
  2763. xAxes: [{
  2764. gridLines: {
  2765. drawTicks: false,
  2766. zeroLineColor: 'rgba(0, 0, 0, 0.0)',
  2767. color: 'rgba(0, 0, 0, 0.0)'
  2768. }
  2769. }],
  2770. yAxes: [{
  2771. ticks: {
  2772. labelOffset: 0,
  2773. padding: 10,
  2774. min: 0,
  2775. suggestedMax: 20
  2776. }
  2777. }]
  2778. },
  2779. tooltips: {
  2780. titleFontSize: 0,
  2781. titleMarginBottom: 0,
  2782. titleSpacing: 0,
  2783. callbacks: {
  2784. label: function (tooltipItem, data) {
  2785. return tooltipItem.yLabel;
  2786. }
  2787. }
  2788. }
  2789. }
  2790. });
  2791. }
  2792.  
  2793.  
  2794. renderBarChart();
  2795.  
  2796. function updateBarChart() {
  2797. window.barChart.data.datasets[0].data = window.dataJson.week.sent;
  2798. window.barChart.data.labels = window.dataJson.week.labels;
  2799.  
  2800. window.barChart.update();
  2801. }
  2802.  
  2803. refreshData();
  2804. },
  2805.  
  2806. getCampaignRecipients: function (audiencesJson, countSubscribers) {
  2807. if ((audiencesJson !== null) && (audiencesJson !== undefined)) {
  2808. $.each(audiencesJson, function (index, value) {
  2809. if ((value !== null) && (value !== undefined) && (value.audience_id !== undefined)) {
  2810. var $template = $('#templateRowAudience'),
  2811. $clone = $template
  2812. .clone()
  2813. .removeClass('hide')
  2814. .removeAttr('id')
  2815. .insertBefore($template);
  2816.  
  2817. var amountData = $('.templateRowAudience').length - 1;
  2818. var rangeLocalFormat = parseInt(value.range_number).toLocaleString(locale);
  2819.  
  2820. $clone
  2821. .find('input[type=checkbox]').attr('value', value.audience_id).end()
  2822. .find('input[id=audienceSelected]').attr('id', 'audienceSelected' + amountData).end()
  2823. .find('label[for=audienceSelected]').attr('for', 'audienceSelected' + amountData).end()
  2824. .find('[name="name"]').attr('name', 'nameAudience' + amountData).html(value.audience_name).end()
  2825. .find('[name="size"]').attr('name', 'sizeAudience' + amountData).html(rangeLocalFormat).end()
  2826. .find('[name="rank"]').attr('name', 'rankAudience' + amountData).html('-').end()
  2827. .find('[name="dateCreation"]').attr('name', 'dateCreationAudience' + amountData).html(value.audience_creation).end();
  2828. }
  2829.  
  2830. var listAudiencesSelected = [];
  2831.  
  2832. $('#audienceSelected' + amountData).on('change', function () {
  2833. var audiencesSelected = scriptForPage.getSelectedAudiences();
  2834.  
  2835. if (audiencesSelected != listAudiencesSelected) {
  2836. listAudiencesSelected = audiencesSelected;
  2837. action.getSubscribersAudience(audiencesSelected);
  2838. }
  2839. });
  2840. });
  2841. }
  2842.  
  2843. $('.push-row').on('click', function () {
  2844. var checkbox = $(this).find('input[type=checkbox]');
  2845. var check = checkbox.prop('checked');
  2846. checkbox.prop('checked', !check);
  2847. // if all public is checked, then don't need any update
  2848. if (checkbox.attr('id') == 'audienceSelected0' || !$('#audienceSelected0').prop('checked')) {
  2849. checkbox.trigger('change');
  2850. }
  2851. });
  2852.  
  2853. $("#sumSize").html(countSubscribers.toLocaleString(locale));
  2854. },
  2855.  
  2856. getStatusAutomation: function () {
  2857. var filterAutomation = $("#filterAutomation");
  2858. var sendHourIni = $("#sendHourIni");
  2859. var sendHourEnd = $("#sendHourEnd");
  2860. var sendMinuteIni = $("#sendMinuteIni");
  2861. var sendMinuteEnd = $("#sendMinuteEnd");
  2862. var sendDateIni = $("#sendDateIni");
  2863. var sendDateEnd = $("#sendDateEnd");
  2864.  
  2865. var selectAutomation = transform.customSelect('filterAutomation');
  2866. $(selectAutomation.content).css({width: '230px'}); //style the automation selector
  2867. transform.customSelect('sendHourIni');
  2868. transform.customSelect('sendMinuteIni');
  2869. transform.customSelect('sendHourEnd');
  2870. transform.customSelect('sendMinuteEnd');
  2871.  
  2872. // var date = new Date();
  2873. // var dd = date.getDate();
  2874. // var mm = date.getMonth() + 1;
  2875. // var yyyy = date.getFullYear();
  2876. // if (dd < 10) {
  2877. // dd = '0' + dd;
  2878. // }
  2879. // if (mm < 10) {
  2880. // mm = '0' + mm;
  2881. // }
  2882. //
  2883. // var today = dd + '/' + mm + '/' + yyyy;
  2884.  
  2885. window.dateIni = sendDateIni.val();
  2886. window.hourIni = sendHourIni.val();
  2887. window.minuteIni = sendMinuteIni.val();
  2888.  
  2889. window.dateEnd = sendDateEnd.val();
  2890. window.hourEnd = sendHourEnd.val();
  2891. window.minuteEnd = sendMinuteEnd.val();
  2892.  
  2893. window.automation = filterAutomation.val();
  2894.  
  2895. sendDateIni.datepicker({
  2896. format: 'dd/mm/yyyy',
  2897. language: locale,
  2898. beforeShow: function (input, obj) {
  2899. $('.ui-datepicker').removeClass('blur');
  2900. },
  2901. onSelect: function (textData, objDatepicker) {
  2902. dateIni = sendDateIni.val();
  2903. window.scrollTo(0, 0);
  2904. getData(0);
  2905. }
  2906. });
  2907.  
  2908. sendDateEnd.datepicker({
  2909. format: 'dd/mm/yyyy',
  2910. language: locale,
  2911. beforeShow: function (input, obj) {
  2912. $('.ui-datepicker').removeClass('blur');
  2913. },
  2914. onSelect: function (textData, objDatepicker) {
  2915. dateEnd = $(this).val();
  2916. window.scrollTo(0, 0);
  2917. getData(0);
  2918. }
  2919. });
  2920.  
  2921. filterAutomation.change(function () {
  2922. automation = $(this).val();
  2923. window.scrollTo(0, 0);
  2924. getData(0);
  2925. });
  2926.  
  2927. sendHourIni.change(function () {
  2928. hourIni = $(this).val();
  2929. window.scrollTo(0, 0);
  2930. console.log(automation);
  2931. getData(0);
  2932. });
  2933.  
  2934. sendHourEnd.change(function () {
  2935. hourEnd = $(this).val();
  2936. window.scrollTo(0, 0);
  2937. getData(0);
  2938. });
  2939.  
  2940. sendMinuteIni.change(function () {
  2941. minuteIni = $(this).val();
  2942. window.scrollTo(0, 0);
  2943. getData(0);
  2944. });
  2945.  
  2946. sendMinuteEnd.change(function () {
  2947. minuteEnd = $(this).val();
  2948. window.scrollTo(0, 0);
  2949. getData(0);
  2950. });
  2951.  
  2952. },
  2953.  
  2954. // @param calls this variable gets the function which calls the functions inside "pushScript"
  2955. pushScript: function (calls) {
  2956.  
  2957. function resizePreview() {
  2958. var height = $('#preInfo').height();
  2959. $('#preVisualization').css({height: height});
  2960. }
  2961.  
  2962. function showUpSend() {
  2963.  
  2964. var changeCheckbox = $('.js-check-showUpSend');
  2965. var showUp = $('.js-showUpSend');
  2966.  
  2967. changeCheckbox.on('change', function () {
  2968. if ($(this).is(':checked')) {
  2969. showUp.css({visibility: 'visible'}).hide().fadeIn('fast');
  2970. dateTimePreview.changeSendSchedule();
  2971. } else {
  2972. showUp.fadeOut('fast', function () {
  2973. showUp.show().css({visibility: 'hidden'});
  2974. $('#pushSchedule').text('Imediato').removeClass('red');
  2975. });
  2976. }
  2977. });
  2978. }
  2979.  
  2980. function showUpExp() {
  2981.  
  2982. var changeCheckbox = $('.js-check-showUpExp');
  2983. var showUp = $('.js-showUpExp');
  2984.  
  2985. changeCheckbox.on('change', function () {
  2986. if ($(this).is(':checked')) {
  2987. showUp.css({visibility: 'visible'}).hide().fadeIn('fast');
  2988. $('#pushExpiration').text('Informe o tempo').removeClass('orange').addClass('red');
  2989. } else {
  2990. showUp.fadeOut('fast', function () {
  2991. showUp.show().css({visibility: 'hidden'});
  2992. $('#pushExpiration').text('Não').removeClass('red').addClass('orange');
  2993. });
  2994. }
  2995. });
  2996. }
  2997.  
  2998. function showUpURL() {
  2999.  
  3000. var changeCheckbox = $('.js-check-showUpURL');
  3001. var showUp = $('.js-showUpURL');
  3002.  
  3003. changeCheckbox.on('change', function () {
  3004. if ($(this).is(':checked')) {
  3005. showUp.css({visibility: 'visible'}).hide().fadeIn('fast');
  3006. var url = $('input[name=open-url]').val();
  3007.  
  3008. if (url == '') {
  3009. $('.js-pushUrl').text('Informe a URL').removeClass('orange').addClass('red');
  3010. } else {
  3011. $('.js-pushUrl').text(url).removeClass('orange').removeClass('red');
  3012. }
  3013. } else {
  3014. showUp.fadeOut('fast', function () {
  3015. showUp.show().css({visibility: 'hidden'});
  3016. $('.js-pushUrl').text('Não').removeClass('red').addClass('orange');
  3017. });
  3018. }
  3019. });
  3020. }
  3021.  
  3022. function checkYesNo(checkbox, content) {
  3023.  
  3024. var checkbox = $(checkbox);
  3025. var info = $(content);
  3026.  
  3027. checkbox.on('change', function () {
  3028. if ($(this).is(':checked')) {
  3029. info.text('Sim').removeClass('orange').addClass('green');
  3030. } else {
  3031. info.text('Não').removeClass('green').addClass('orange');
  3032. }
  3033. }
  3034. );
  3035. }
  3036.  
  3037. /* Resize emoji for phone preview and DIV (use size param for this) */
  3038. function resizeEmoji(platform, size) {
  3039. var emojis,
  3040. proportion;
  3041.  
  3042. if (platform == 'android') {
  3043. emojis = $('#' + platform + 'Content .img');
  3044. proportion = 0.6;
  3045. } else if (platform == 'iOS') {
  3046. emojis = $('#' + platform + 'Content .img');
  3047. proportion = 0.65;
  3048. } else {
  3049. emojis = $(platform);
  3050. proportion = size;
  3051. }
  3052.  
  3053.  
  3054. emojis.each(function () {
  3055. var width = $(this).width() * proportion;
  3056. var height = $(this).height() * proportion;
  3057.  
  3058. var bgPosition = $(this).css('backgroundPosition');
  3059. var position = bgPosition.replace(/px/g, '').split(' ');
  3060. var posX = position[0] * proportion;
  3061. var posY = position[1] * proportion;
  3062.  
  3063. var bgSize = $(this).css('backgroundSize');
  3064. var size = bgSize.replace(/px/g, '').split(' ');
  3065. var sizeX = size[0] * proportion;
  3066. var sizeY = size[1] * proportion;
  3067.  
  3068. $(this).width(width);
  3069. $(this).height(height);
  3070. $(this).css('backgroundPosition', posX + 'px ' + posY + 'px');
  3071. $(this).css('backgroundSize', sizeX + 'px ' + sizeY + 'px');
  3072. })
  3073. }
  3074.  
  3075. /* @param lastPushMessage Last push returned to preview. Just to be unique, this is 'ççç'
  3076. * @param androidChars Max number of chars in android preview
  3077. * @param iOSChars Max number of chars in iPhone preview
  3078. * @param iOSfirst First time iOS passes sliceMessage, it has to change lastPreview, so it recreates array
  3079. * */
  3080. var lastPushMessage = 'ççç',
  3081. androidChars = 64,
  3082. iOSChars = 120,
  3083. iOSfirst = true;
  3084.  
  3085. /* Slice the message leaving <img> tags and &nbsp; undivided */
  3086. function sliceMessage(typed, size) {
  3087.  
  3088. var lastPreview = typed.substr(0, lastPushMessage.length);
  3089.  
  3090. /* Checks if it is the first iOS preview change, so it has to recreate array and lastPushMessage */
  3091. if (size == iOSChars && iOSfirst) {
  3092. lastPreview = '';
  3093. iOSfirst = false;
  3094. }
  3095.  
  3096. if (lastPreview == lastPushMessage) {
  3097. return lastPushMessage; // if typed piece is the same of the last preview, keep it
  3098. } else {
  3099. var textArray = [],
  3100. wordArray,
  3101. rest = typed,
  3102. pos,
  3103. emojiSpace;
  3104.  
  3105. rest = rest.replace(/&nbsp;/g, ' '); // unseparated &nbsp;
  3106.  
  3107. do {
  3108. pos = rest.search('<img'); // unseparated img
  3109. if (pos != -1) {
  3110. wordArray = rest.substr(0, pos).split('');
  3111. textArray = textArray.concat(wordArray);
  3112.  
  3113. rest = rest.substr(pos);
  3114. pos = rest.search(':">');
  3115. emojiSpace = rest.substr(0, pos + 3);
  3116. textArray.push(emojiSpace, '');
  3117.  
  3118. rest = rest.substr(pos + 3);
  3119. }
  3120. } while (pos != -1 && textArray.length < size);
  3121.  
  3122. textArray = textArray.concat(rest.split(''));
  3123. textArray.map(function (val, index) {
  3124. if (val == ' ') {
  3125. textArray[index] = '&nbsp;'; // bring back &nbsp;
  3126. }
  3127. });
  3128. lastPushMessage = textArray.slice(0, size).join('');
  3129.  
  3130. if (size == androidChars) {
  3131. return lastPushMessage; // return preview TEXT
  3132. }
  3133. return textArray; // return preview ARRAY (for different Android and iOS slices)
  3134. }
  3135. }
  3136.  
  3137. /* Change TITLE while typing */
  3138. function titleMessagePreview() {
  3139. $('#pushTitle').on('keyup', function () {
  3140. var typed = $(this).val();
  3141. $('.js-title').text(typed);
  3142. });
  3143. }
  3144.  
  3145. function doURLPreview(url) {
  3146. if (url == '') {
  3147. $('.js-pushUrl').text('Informe uma URL').removeClass('red').addClass('red');
  3148. } else {
  3149. $('.js-pushUrl').text(url).removeClass('red');
  3150. }
  3151. }
  3152.  
  3153. function URLPreview() {
  3154. $('#openURL').on('keyup', function () {
  3155. var url = $(this).val();
  3156. doURLPreview(url);
  3157. });
  3158. }
  3159.  
  3160. /*
  3161. * @param iOSContent Selector for iOS preview
  3162. * @param androidContent Selector for Android preview
  3163. * @param preMsg selector For message field preview
  3164. * @param observeOnce Boolean to stop Observer at the first time
  3165. * */
  3166. var iOSContent = $('#iOSContent'),
  3167. androidContent = $('#androidContent'),
  3168. preMsg = $('.js-msg'),
  3169. observeOnce = true;
  3170.  
  3171. var target = $('#pushContent').next('div'); // message content DIV
  3172. /* Reset observer boolean */
  3173. $(target).on('keyup', function () {
  3174. observeOnce = true;
  3175. });
  3176. $('.emoji-menu').on('mousedown', function () {
  3177. observeOnce = true;
  3178. });
  3179.  
  3180. function doMessagePreview(typed) {
  3181. /* count how many real chars there is */
  3182. var typedNum = typed.replace(/&nbsp;/g, ' '); // &nbsp; counts 1
  3183.  
  3184. var matches = typed.match(/\<img[^>]*>/g); // <img> counts 2
  3185. if (matches != null) {
  3186. for (var i = 0; i < matches.length; i++) {
  3187. typedNum = typedNum.replace(matches[i], '12');
  3188. }
  3189. var count = typedNum.length;
  3190.  
  3191. } else {
  3192. count = typed.length;
  3193. }
  3194.  
  3195. preMsg.html(typed);
  3196. resizeEmoji();
  3197.  
  3198. /* More than iOS preview space */
  3199. if (count > iOSChars) {
  3200. var textArray = sliceMessage(typed, iOSChars);
  3201.  
  3202. // if textArray isn't array, then the message is the same and don't need to be changed
  3203. if (Array.isArray(textArray)) {
  3204. /* iOS push */
  3205. var textLarge = textArray.slice(0, iOSChars).join('') + '...';
  3206. iOSContent.html(textLarge);
  3207. resizeEmoji('iOS');
  3208. /* Android push */
  3209. var textSmall = textArray.slice(0, androidChars).join('') + '...';
  3210. androidContent.html(textSmall);
  3211. resizeEmoji('android');
  3212. }
  3213.  
  3214. } else if (count > androidChars) {
  3215. iOSContent.html(typed);
  3216. resizeEmoji('iOS');
  3217.  
  3218. /* Change just Android push */
  3219. var text = sliceMessage(typed, androidChars) + '...';
  3220. androidContent.html(text);
  3221. resizeEmoji('android');
  3222. iOSfirst = true;
  3223. } else {
  3224. androidContent.html(typed);
  3225. resizeEmoji('android');
  3226.  
  3227. iOSContent.html(typed);
  3228. resizeEmoji('iOS');
  3229.  
  3230. iOSfirst = true;
  3231. }
  3232. resizePreview(); // if message is to long, resize phone preview DIV
  3233. }
  3234.  
  3235. /* Change MESSAGE while typing */
  3236. function messagePreview() {
  3237. var observer = new MutationObserver(function (mutations) { // create an observer instance
  3238. mutations.forEach(function (mutation) {
  3239. if (observeOnce) {
  3240.  
  3241. // var lastEmoji = target.children('[alt="' + mutation.addedNodes[0].alt + '"]');
  3242. // resizeEmoji(lastEmoji, 0.76);
  3243.  
  3244. var typed = $(mutation.target).html();
  3245.  
  3246. doMessagePreview(typed);
  3247.  
  3248. observeOnce = false;
  3249. }
  3250. });
  3251. });
  3252.  
  3253. observer.observe(target[0], {attributes: true, childList: true});
  3254.  
  3255. }
  3256.  
  3257. function refreshPreview() {
  3258. $('#pushTitle').trigger('keyup');
  3259. }
  3260.  
  3261. var dateTimePreview = {
  3262.  
  3263. /* SEND TIME */
  3264. sendDateTime: {
  3265. proxy: new Proxy(['', '', ''], {
  3266. get: function (target, property) {
  3267. return target[property];
  3268. },
  3269. set: function (target, property, value) {
  3270. target[property] = value;
  3271. dateTimePreview.changeSendSchedule();
  3272. return true;
  3273. }
  3274. })
  3275. },
  3276.  
  3277. setSendDate: function () {
  3278. var nomesMes = [
  3279. "Janeiro", "Fevereiro", "Março",
  3280. "Abril", "Maio", "Junho", "Julho",
  3281. "Agosto", "Setembro", "Outubro",
  3282. "Novembro", "Dezembro"
  3283. ];
  3284.  
  3285. var nomesSemana = [
  3286. "Domingo", "Segunda-feira", "Terça-feira",
  3287. "Quarta-feira", "Quinta-feira",
  3288. "Sexta-feira", "Sábado-feira"
  3289. ];
  3290.  
  3291. var input = $('#sendDate').val().split('/');
  3292. input = input[2] + '-' + input[1] + '-' + input[0];
  3293.  
  3294. var date = new Date(input);
  3295. var fixTime = date.getTimezoneOffset() / 60;
  3296. date.setHours(date.getHours() + fixTime);
  3297.  
  3298. var today = new Date().setHours(0, 0, 0, 0);
  3299. var tomorrow = today + 24 * 60 * 60000;
  3300.  
  3301. var dateString = '';
  3302.  
  3303. if (date.getTime() == today) {
  3304. dateString = 'Hoje, ';
  3305. } else if (date.getTime() == tomorrow) {
  3306. dateString = 'Amanhã, ';
  3307. } else {
  3308. var day = date.getDate();
  3309. var monthIndex = date.getMonth();
  3310. var year = date.getFullYear();
  3311. var weekIndex = date.getDay();
  3312.  
  3313. dateString = nomesSemana[weekIndex] + ', ' + day + ' ' + nomesMes[monthIndex] + ' ' + year + ', ';
  3314. }
  3315.  
  3316. this.sendDateTime.proxy[0] = dateString;
  3317. this.sendDateTime.proxy[4] = date.getTime();
  3318. },
  3319.  
  3320. setSendHour: function () {
  3321. this.sendDateTime.proxy[1] = $('#sendHour').val();
  3322. },
  3323.  
  3324. setSendMinute: function () {
  3325. this.sendDateTime.proxy[2] = $('#sendMinute').val();
  3326. },
  3327.  
  3328. changeSendSchedule: function () {
  3329. var flagSchedule = $('.js-check-showUpSend').is(':checked');
  3330. var date = this.sendDateTime.proxy[0];
  3331. if (flagSchedule && date == '') {
  3332. date = $('#sendDate').val();
  3333. }
  3334.  
  3335. var h = this.sendDateTime.proxy[1];
  3336. if (flagSchedule && h == '') {
  3337. h = $('#sendHour').val();
  3338. }
  3339.  
  3340. var min = this.sendDateTime.proxy[2];
  3341. if (flagSchedule && min == '') {
  3342. min = $('#sendMinute').val();
  3343. }
  3344.  
  3345. var dateMillis = this.sendDateTime.proxy[4] + 60000 * (60 * h) + 60000 * min;
  3346.  
  3347. var today = new Date().getTime();
  3348.  
  3349. window.scheduleValid = false; // if time is valid, set to true and allow push sending
  3350.  
  3351. // if (date == '' || date.search('undefined') != -1) {
  3352. if (date == '' && flagSchedule) {
  3353. $('#pushSchedule').text('Agende o envio').addClass('red bold');
  3354. } else if (dateMillis < today) {
  3355. $('#pushSchedule').text('Escolha uma data futura').addClass('red bold');
  3356. resizePreview();
  3357. } else if (flagSchedule) {
  3358. var dateTime = date + h + ':' + min + 'h';
  3359. $('#pushSchedule').text(dateTime).removeClass('red bold');
  3360. $('#iOS .time').text('Hoje ' + h + ':' + min);
  3361. $('#android .time').text(h + ':' + min);
  3362. window.scheduleValid = true;
  3363. resizePreview();
  3364. }
  3365. }
  3366.  
  3367.  
  3368. };
  3369.  
  3370. function changeExpirationTime() {
  3371. var h = $('#expirationHour').val();
  3372. var min = $('#expirationMinutes').val();
  3373. var hours = '';
  3374. var minutes = '';
  3375.  
  3376. var plural = ['hora', 'horas', 'minuto', 'minutos'];
  3377.  
  3378. if (h != 0) {
  3379. if (h == 1) {
  3380. hours = h + ' ' + plural[0] + ' ';
  3381. } else {
  3382. hours = h + ' ' + plural[1] + ' ';
  3383. }
  3384. }
  3385.  
  3386. if (min != 0) {
  3387. if (min == 1) {
  3388. minutes = min + ' ' + plural[2];
  3389. } else {
  3390. minutes = min + ' ' + plural[3]
  3391. }
  3392. }
  3393.  
  3394. if (min == 0 && h == 0) {
  3395. $('#pushExpiration').text('Informe o tempo').removeClass('red').addClass('red');
  3396. } else if (min != 0 && h != 0) {
  3397. var time = hours + 'e ' + minutes;
  3398. $('#pushExpiration').text(time).removeClass('red');
  3399. } else if (min != 0 ^ h != 0) {
  3400. var time = hours + minutes;
  3401. $('#pushExpiration').text(time).removeClass('red');
  3402. }
  3403. }
  3404.  
  3405. // get the functions to be called here
  3406. if (calls == 'sendPush') {
  3407.  
  3408. // transform.customSelect('expirationMinutes');
  3409. // transform.customSelect('expirationHour');
  3410. transform.customSelect('sendHour');
  3411. transform.customSelect('sendMinute');
  3412.  
  3413. $('#preVisualization').tabs();
  3414.  
  3415. //set time only when checkbox is clicked, so the Proxy isn't triggered in advance
  3416. $('#scheduleSend').one('change', function () {
  3417. dateTimePreview.setSendDate(); // Initializes the date for Send Schedule
  3418. dateTimePreview.setSendHour(); // Initializes the date for Send Schedule
  3419. dateTimePreview.setSendMinute(); // Initializes the date for Send Schedule
  3420. });
  3421.  
  3422. $('#sendDate').datepicker({minDate: 0}).on('change', function () {
  3423. dateTimePreview.setSendDate();
  3424. });
  3425. $('#sendHour').on('change', function () {
  3426. dateTimePreview.setSendHour();
  3427. });
  3428. $('#sendMinute').on('change', function () {
  3429. dateTimePreview.setSendMinute();
  3430. });
  3431.  
  3432. // $('#expirationHour').on('change', function () {
  3433. // changeExpirationTime();
  3434. // });
  3435. // $('#expirationMinutes').on('change', function () {
  3436. // changeExpirationTime();
  3437. // });
  3438.  
  3439. transform.iOSswitch();
  3440.  
  3441. resizePreview();
  3442. showUpSend();
  3443. showUpExp();
  3444. showUpURL();
  3445. // checkYesNo('.js-check-sound', '#pushSound');
  3446. // checkYesNo('.js-check-increment', '#pushIncrement');
  3447. titleMessagePreview();
  3448. URLPreview();
  3449. messagePreview();
  3450. dateTimePreview.changeSendSchedule();
  3451. behaviors.listData.add(undefined, 5);
  3452. // behaviors.listData.remove();
  3453. refreshPreview();
  3454.  
  3455. } else if (calls == 'newCampaign') {
  3456. $('#preVisualization').tabs();
  3457.  
  3458. transform.iOSswitch();
  3459.  
  3460. resizePreview();
  3461. showUpSend();
  3462. showUpExp();
  3463. showUpURL();
  3464. // checkYesNo('.js-check-sound', '#pushSound');
  3465. // checkYesNo('.js-check-increment', '#pushIncrement');
  3466. titleMessagePreview();
  3467. URLPreview();
  3468. messagePreview();
  3469. behaviors.listData.add(undefined, 5);
  3470. // behaviors.listData.remove();
  3471.  
  3472. } else if (calls == 'newAutomation') {
  3473.  
  3474. $('#preVisualization').tabs();
  3475.  
  3476. transform.iOSswitch();
  3477.  
  3478. resizePreview();
  3479. // showUpSend();
  3480. // showUpExp();
  3481. // showUpURL();
  3482. // checkYesNo('.js-check-sound', '#pushSound');
  3483. // checkYesNo('.js-check-increment', '#pushIncrement');
  3484. // titleMessagePreview();
  3485. // URLPreview();
  3486. // messagePreview();
  3487. behaviors.listData.add(undefined, 5);
  3488. // behaviors.listData.remove();
  3489.  
  3490. $('#campaignsList').on('click', 'button', function () {
  3491. $('.js-title').html($('#msgTitle').html());
  3492. doMessagePreview($('#msgBody').html());
  3493. doURLPreview($('#urlPushField').html());
  3494.  
  3495. });
  3496.  
  3497. } else if (calls == 'newApi') {
  3498.  
  3499. $('#preVisualization').tabs();
  3500.  
  3501. transform.iOSswitch();
  3502.  
  3503. resizePreview();
  3504. showUpURL();
  3505. // checkYesNo('.js-check-sound', '#pushSound');
  3506. // checkYesNo('.js-check-increment', '#pushIncrement');
  3507. titleMessagePreview();
  3508. URLPreview();
  3509. messagePreview();
  3510. // dateTimePreview.changeSendSchedule();
  3511. behaviors.listData.add('#tagBlock');
  3512. behaviors.listData.add('#additionalBlock', 5);
  3513. // behaviors.listData.remove();
  3514. refreshPreview();
  3515. }
  3516. },
  3517.  
  3518. automation: {
  3519. setTime: function (text) {
  3520. $("#timeInterval").html(text);
  3521. $("#pushScheduleHour").html(text);
  3522. },
  3523.  
  3524. timeSlider: function (selectedDays, timeJson, days) {
  3525. var daysName = [];
  3526. var pushSchedule = $('#pushSchedule');
  3527. var daysSelectors = $('input[name=day]');
  3528.  
  3529. daysSelectors.on('change', function () {
  3530. $.each($('input[name=day]'), function (key, obj) {
  3531. selectedDays[key] = $(obj).prop('checked');
  3532. });
  3533.  
  3534. daysName.length = 0;
  3535. $.each(selectedDays, function (key, value) {
  3536. if (value == true)
  3537. daysName.push(days[key]);
  3538. });
  3539.  
  3540. if (selectedDays[0] == true) {
  3541. daysName.push(daysName.shift());
  3542. }
  3543.  
  3544. var daysInterval = selectedDays.slice();
  3545. var sunday = daysInterval.shift();
  3546. var saturday = daysInterval.pop();
  3547.  
  3548. if (daysName.length == 7) {
  3549. pushSchedule.html('Todos os dias');
  3550. } else if (daysName.length == 5 && sunday == false && saturday == false) {
  3551. $('#pushSchedule').html('Dias de semana');
  3552. } else if (daysName.length == 2) {
  3553. $('#pushSchedule').html(daysName.join(' e '));
  3554. } else {
  3555. $('#pushSchedule').html(daysName.join(', '));
  3556. }
  3557. });
  3558.  
  3559. daysSelectors.first().trigger('change');
  3560.  
  3561. var timeIntervalRange = $("#timeIntervalRange");
  3562.  
  3563. timeIntervalRange.slider({
  3564. range: true,
  3565. min: 0,
  3566. max: 24,
  3567. values: [0, 24],
  3568. slide: function (event, ui) {
  3569. var text = 'Entre ' + ui.values[0] + " e " + ui.values[1] + " horas.";
  3570. scriptForPage.automation.setTime(text);
  3571. $(ui.handle).attr('data-value', ui.value);
  3572. timeJson = {'init': ui.values[0], 'end': ui.values[1]};
  3573. }
  3574. });
  3575.  
  3576. var init = timeIntervalRange.slider("values", 0);
  3577. var end = timeIntervalRange.slider("values", 1);
  3578. // USA ESSE JSON PARA PASSAR AS INFOS DE HORA
  3579. timeJson = {'init': init, 'end': end};
  3580. scriptForPage.automation.setTime('Entre ' + init + " e " + end + " horas.");
  3581.  
  3582. // initialize slider label values
  3583. $.each($(timeIntervalRange.slider("widget")).find('.ui-slider-handle'), function (index, obj) {
  3584. $(obj).attr('data-value', timeIntervalRange.slider("values", index));
  3585. });
  3586.  
  3587. return timeJson;
  3588. },
  3589.  
  3590. populateScheduled: function (automationScheduledJson) {
  3591. if(automationScheduledJson !== '0') {
  3592. $.each(automationScheduledJson, function (index, value) {
  3593. var elementsDays = $("input[name*='day']");
  3594.  
  3595. if (value.sunday == 0)
  3596. $(elementsDays).filter(function () {
  3597. return this.value == 'sun'
  3598. }).attr('checked', false);
  3599.  
  3600. if (value.monday == 0)
  3601. $(elementsDays).filter(function () {
  3602. return this.value == 'mon'
  3603. }).attr('checked', false);
  3604.  
  3605. if (value.tuesday == 0)
  3606. $(elementsDays).filter(function () {
  3607. return this.value == 'tue'
  3608. }).attr('checked', false);
  3609.  
  3610. if (value.wednesday == 0)
  3611. $(elementsDays).filter(function () {
  3612. return this.value == 'wed'
  3613. }).attr('checked', false);
  3614.  
  3615. if (value.thursday == 0)
  3616. $(elementsDays).filter(function () {
  3617. return this.value == 'thu'
  3618. }).attr('checked', false);
  3619.  
  3620. if (value.friday == 0)
  3621. $(elementsDays).filter(function () {
  3622. return this.value == 'fri'
  3623. }).attr('checked', false);
  3624.  
  3625. if (value.saturday == 0)
  3626. $(elementsDays).filter(function () {
  3627. return this.value == 'sat'
  3628. }).attr('checked', false);
  3629.  
  3630. $("#timeIntervalRange").slider('values', 0, value.hour_initial);
  3631. $("#timeIntervalRange").slider('values', 1, value.hour_final);
  3632. scriptForPage.automation.setTime('Entre ' + value.hour_initial + " e " + value.hour_final + " horas.");
  3633. $($(".ui-slider-handle")[0]).attr('data-value', value.hour_initial);
  3634. $($(".ui-slider-handle")[1]).attr('data-value', value.hour_final);
  3635. });
  3636.  
  3637. $('input[name=day]').trigger('change');
  3638. }
  3639. },
  3640.  
  3641. newAutomation: function (automationId, campaignsJson, days, audienceJson, criteriaJson, appId, countSubscribers, allAudiences) {
  3642. transform.highlightSubMenu('#automations');
  3643. behaviors.popUp('#selectCampaign', '#campaignsList');
  3644. var campaignIdSelected = 0;
  3645.  
  3646. $.each(campaignsJson, function (key, obj) {
  3647. $('#camp' + obj.campId).on('click', function () {
  3648. $('#campaignsList').fadeOut('fast');
  3649. $('#campName').html(obj.campName);
  3650. //set title field
  3651. var title;
  3652. if (obj.msgTitle == '') {
  3653. title = '-';
  3654. } else {
  3655. title = obj.msgTitle;
  3656. }
  3657. $('#msgTitle').html(title);
  3658. $('#titlePreview').html(title);
  3659. // set URL field
  3660. var urlPush;
  3661. if (obj.urlPush == null) {
  3662. urlPush = '-';
  3663. $('#pushURL').addClass('orange').removeClass('green').html('Não');
  3664. } else {
  3665. urlPush = obj.urlPush;
  3666. $('#pushURL').addClass('green').removeClass('orange').html('Sim');
  3667. }
  3668. $('#urlPushField').html(urlPush);
  3669. campaignIdSelected = obj.campId;
  3670.  
  3671. transform.colonToEmoji(obj.msgBody, '#msgBody');
  3672. transform.colonToEmoji(obj.msgBody, '#msgPreview');
  3673. $("#campaign").next('.js-error').remove();
  3674. $("#campaign").removeClass("error-outline");
  3675. });
  3676. });
  3677.  
  3678. new Tether({
  3679. element: '#campaignsList',
  3680. target: '#selectCampaign',
  3681. attachment: 'top left',
  3682. targetAttachment: 'bottom left'
  3683. });
  3684.  
  3685. var selectedDays = [];
  3686. var timeJson;
  3687. timeJson = scriptForPage.automation.timeSlider(selectedDays, timeJson, days);
  3688.  
  3689. scriptForPage.newAudience('', audienceJson, criteriaJson, appId, false);
  3690.  
  3691. // transform.emojiPicker();
  3692. scriptForPage.pushScript('newAutomation');
  3693. behaviors.autoTextArea();
  3694.  
  3695. $('#footerSave').on('click', function () {
  3696. if (validate.multiFields([['#componentName', 'Precisamos de um nome para a automação'],
  3697. [validate.fieldCampaignAutomation, campaignIdSelected, automationId],
  3698. [validate.fieldsAdditionalData],
  3699. [validate.fieldsAudienceCampaign, true],
  3700. [validate.fieldsAudienceCriteria, false]])) {
  3701. var audiencesSelected = scriptForPage.getSelectedAudiences();
  3702.  
  3703. var data = {
  3704. 'automationId': automationId,
  3705. 'campaignId': campaignIdSelected,
  3706. 'campaignName': $('#campName').html(),
  3707. 'audiencesSelected': audiencesSelected,
  3708. 'selectedDays': '"' + selectedDays.toString() + '"',
  3709. 'timeInit': $("#timeIntervalRange").slider("values", 0),
  3710. 'timeEnd': $("#timeIntervalRange").slider("values", 1)
  3711. };
  3712. modal.getModal('modal-save-automation.php', false, data);
  3713. }
  3714. });
  3715.  
  3716. scriptForPage.getCampaignRecipients(allAudiences, countSubscribers);
  3717. validate.quantitySubscribers(countSubscribers);
  3718.  
  3719. $('#footerCancel').on('click', function () {
  3720. navigateTo.app.push.automations();
  3721. });
  3722. },
  3723.  
  3724. populateAutomation: function (automationId, automationJson, appId, pushCriteriaJson, automationAudienceJson, additionalJson, automationScheduledJson) {
  3725. if (automationId > 0) {
  3726. var name = automationJson['automation_name'];
  3727. var description = automationJson['automation_description'];
  3728. var campaignId = automationJson['campaign_id'];
  3729.  
  3730. populateAudience(automationAudienceJson);
  3731. populateCriteria(pushCriteriaJson);
  3732. populateAdditionalData(additionalJson);
  3733. scriptForPage.automation.populateScheduled(automationScheduledJson);
  3734.  
  3735. $('#componentName').val(name);
  3736. $('#componentDescription').val(description);
  3737. $('#camp' + campaignId).trigger('click');
  3738.  
  3739. action.findReachAudience(appId);
  3740.  
  3741. $('.page-title').html(name);
  3742. }
  3743.  
  3744. function populateCriteria(pushCriteriaJson) {
  3745. var i = 0;
  3746. $.each(pushCriteriaJson, function (index, value) {
  3747. if ((i > 0) && (value !== null) && (value !== undefined)) {
  3748. $("#addNewCondition").trigger("click");
  3749. }
  3750. var selectField = $("#select" + i + "0").attr('value', value.audience_criteria_id);
  3751. selectField.val(value.audience_field_id);
  3752. selectField.next('a').css({color: 'inherit'});
  3753.  
  3754. var varType = selectField.find('option[value=' + selectField.val() + ']').attr('data-type');
  3755. scriptForPage.showConditionField('#jsConditionRow' + i, varType);
  3756.  
  3757. var objectTypeCondition = $('#jsConditionRow' + i).find('.js-' + varType + '-condition');
  3758.  
  3759. if (varType == 'boolean') {
  3760. objectTypeCondition.find('a[href="#' + value.audience_value + '"]').trigger('click');
  3761. } else {
  3762. objectTypeCondition.find('select[name=operator]').val(value.audience_field_condition_id);
  3763. objectTypeCondition.find('select[name=operator]').attr('value', value.audience_field_condition_id);
  3764. objectTypeCondition.find('select[name=operator]').next('a').css({color: 'inherit'});
  3765.  
  3766. objectTypeCondition.find('input[name=val]').val(value.audience_value);
  3767. }
  3768. i++;
  3769. });
  3770. }
  3771.  
  3772. function populateAudience(automationAudienceJson) {
  3773. if (automationAudienceJson == null || automationAudienceJson == '0') {
  3774. $('#audienceSelected0').attr('checked', true);
  3775. $('#audienceSelected0').trigger('change');
  3776. } else {
  3777. var allRowsAudience = $("input[class*='audience']");
  3778.  
  3779. $.each(automationAudienceJson, function (index, value) {
  3780. var elementAudienceId = $(allRowsAudience).filter(function () {
  3781. return this.value == value.audience_id
  3782. }).attr('id');
  3783.  
  3784. $('#' + elementAudienceId).attr('checked', true);
  3785. $('#' + elementAudienceId).trigger('change');
  3786. });
  3787. }
  3788. }
  3789.  
  3790. function populateAdditionalData(additionalJson) {
  3791. //verify if automation has additional data
  3792. if ((additionalJson !== null) && (additionalJson !== undefined)) {
  3793. var additionalBlock = $('#additionalBlock');
  3794. $.each(additionalJson, function (index, value) {
  3795. if ((value !== null) && (value !== undefined) && (value.key_data !== undefined)) {
  3796. // add row
  3797. additionalBlock.find('.addNewData').trigger('click');
  3798. // insert data
  3799. additionalBlock.find('.js-dataTemplate').prev()
  3800. .find('[name="additional-key"]').attr('value', value.key_data).end()
  3801. .find('[name="additional-value"]').attr('value', value.value_data);
  3802. }
  3803. });
  3804. }
  3805. }
  3806. }
  3807. },
  3808.  
  3809. collaborator: {
  3810. newCollaborator: function (collaboratorJson) {
  3811. scriptForPage.newCollaborator(collaboratorJson);
  3812. },
  3813.  
  3814. populateCollaborator: function () {
  3815.  
  3816. },
  3817.  
  3818. saveCollaborator: function() {
  3819. var elements = $(".js-collaborator-row");
  3820. var valid = [];
  3821.  
  3822. for (var i = 0; i < elements.length; i++) {
  3823. var row = "#" + elements[i].id;
  3824. var selectProfile = $(row.replace('jsCollaboratorRow', 'select') + '0');
  3825. var memberName = $(row).find('input[name=member-name]');
  3826. var memberEmail = $(row).find('input[name=member-email]');
  3827.  
  3828. if ($(selectProfile).val() == '') {
  3829. valid.push(validate.field(selectProfile['selector'], 'Qual o perfil?'),
  3830. $(selectProfile['selector']).nextAll('a'), $(selectProfile['selector']).nextAll('a'));
  3831. }
  3832.  
  3833. if ($(memberName).val() == '') {
  3834. valid.push(validate.field(memberName['selector'], 'Qual o nome?'));
  3835. }
  3836.  
  3837. if ($(memberEmail).val() == '') {
  3838. valid.push(validate.field(memberEmail['selector'], 'Qual o e-mail?'));
  3839. }
  3840. console.log('nada foi encontrado pode salvar');
  3841. //save collaborator and send invitation
  3842. //action.saveCollaborator(customerId, userName);
  3843. }
  3844. }
  3845. },
  3846.  
  3847. generalConfig: {
  3848.  
  3849. /* Register when user copy the element and supports a button to do the copy
  3850. *
  3851. * @param btnId Button ID to copy text
  3852. * @param idToCopy Text ID to copy
  3853. * @param timeOut Timeout time
  3854. * */
  3855. copyContent: function (btnId, idToCopy, timeOut) {
  3856.  
  3857. var copyBtn = $(btnId);
  3858. var copyThis = $(idToCopy);
  3859. timeOut = timeOut || 1000;
  3860.  
  3861. var originalBtnText = copyBtn.html();
  3862. var originalBtnClass = copyBtn.attr('class');
  3863.  
  3864. /* Use clipboard.js plugin
  3865. * Ref: https://github.com/zenorocha/clipboard.js.git
  3866. * */
  3867. copyBtn.attr('data-clipboard-target', idToCopy);
  3868. new Clipboard(btnId);
  3869.  
  3870. copyThis.on('copy', function () {
  3871. copyBtn.html('Copiado!').removeClass('button-clean-gray').addClass('button-blue');
  3872. setTimeout(function () {
  3873. copyBtn.html(originalBtnText);
  3874. if (originalBtnClass.search('button-blue') == -1) {
  3875. copyBtn.switchClass('button-blue', originalBtnClass, 400);
  3876. }
  3877. }, timeOut);
  3878. });
  3879.  
  3880. // DISABLE COPY CUT PASTE
  3881. // copyBtn.on('cut copy paste', function (e) {
  3882. // e.preventDefault(); //disable cut,copy,paste
  3883. // });
  3884. },
  3885.  
  3886.  
  3887. updateField: function (valueField, formData, token) {
  3888. $.ajax({
  3889. type: 'POST',
  3890. url: '/appConfigValidation',
  3891. data: formData,
  3892. dataType: 'json',
  3893. encode: true
  3894. })
  3895.  
  3896. .done(function (data) {
  3897. console.log(data);
  3898.  
  3899. if (!data.success) {
  3900. if (data.errors.password) {
  3901. $('#password-group').addClass('has-error');
  3902. $('#password-group').append('<div class="help-block">' + data.errors.password + '</div>');
  3903. }
  3904. if (data.errors.loginError) {
  3905. //$('#message-login').append('<div class="alert-box">' + data.errors.loginError + '</div>');
  3906. $('#password-group').addClass('has-error');
  3907. $('#password-group').append('<div class="help-block">' + data.errors.loginError + '</div>');
  3908. }
  3909. } else {
  3910. $(valueField).text(formData['appName']);
  3911.  
  3912. var appTitleBtn = $('#appTitleBtn');
  3913. /* update in menu side */
  3914. var nonText = appTitleBtn.html();
  3915. nonText = nonText.substring(nonText.indexOf('<'));
  3916. appTitleBtn.html(formData['appName'] + nonText);
  3917. $('#menuName' + token).text(formData['appName']);
  3918. }
  3919. })
  3920. .fail(function (data) {
  3921. console.log(data);
  3922. });
  3923. },
  3924.  
  3925. updateIcon: function (token) {
  3926.  
  3927. $("#uploadIconForm").on('submit', (function (e) {
  3928. e.preventDefault();
  3929. var uploadMessage = $("#uploadMessage");
  3930. var uploadBtn = $('#uploadIconBtn');
  3931. uploadMessage.empty();
  3932.  
  3933. var formData = new FormData(this);
  3934. formData.append('object', 'appIcon');
  3935.  
  3936. $.ajax({
  3937. url: "/actions/imageUpload.php", // Url to which the request is send
  3938. type: "POST", // Type of request to be send, called as method
  3939. data: formData, // Data sent to server, a set of key/value pairs (i.e. form fields and values)
  3940. contentType: false, // The content type used when sending data to the server.
  3941. cache: false, // To unable request pages to be cached
  3942. processData: false, // To send DOMDocument or non processed data file it is set to false
  3943. success: function (data) { // A function to be called if request succeeds
  3944. var result = $.parseJSON(data);
  3945. console.log('done');
  3946. console.log(data);
  3947. if (result.hasOwnProperty("img")) {
  3948. uploadMessage.css({color: '#3bdb7b', fontWeight: '600'}).text(result.msg);
  3949. uploadBtn.text('Enviado!')
  3950. .removeClass('button-clean-blue')
  3951. .addClass('button-green');
  3952. setTimeout(function () {
  3953. uploadBtn.switchClass('button-green', 'button-clean-blue', 400).text('Upload');
  3954. }, 1500);
  3955. var path = ref.getUploads + '/app_icons/' + result.img;
  3956. $('#appIcon').attr('src', path)
  3957. .attr('data', path);
  3958. /* update in menu side */
  3959. $('#menuImg' + token).attr('src', path);
  3960. } else {
  3961. uploadMessage.attr('style', '""').text(result.msg);
  3962. }
  3963. },
  3964. fail: function (data) {
  3965. console.log('fail');
  3966. console.log(data);
  3967. }
  3968. });
  3969.  
  3970.  
  3971. }));
  3972. }
  3973.  
  3974. },
  3975.  
  3976. getAdditionalData: function () {
  3977. var elements = $('.js-dataRow');
  3978. var dict = [];
  3979.  
  3980. $.each(elements, function (num, obj) {
  3981. var key = $(obj).find('input[name="additional-key"]').val();
  3982. var value = $(obj).find('input[name="additional-value"]').val();
  3983.  
  3984. if ((key !== '') && (value !== '')) {
  3985. dict.push({key: key, value: value});
  3986. }
  3987. });
  3988.  
  3989. return dict;
  3990. },
  3991.  
  3992.  
  3993. // TODO deletar essa função quando o list estiver funcionando
  3994. getCustomFields: function (customFieldsJson) {
  3995. var num = 0; // uniquer number for ids
  3996.  
  3997. $("#addCustomField").hover(function () {
  3998. $(this).css({fontWeight: '400'});
  3999. behaviors.svgChangeTo.hover($(this).children('img'));
  4000. }, function () {
  4001. $(this).attr('style', '');
  4002. behaviors.svgChangeTo.hover($(this).children('img'));
  4003. }).on("click", function () {
  4004. // if ($('.js-customField').length < 5) {
  4005. var $template = $('#templateCustomFields'),
  4006. $clone = $template
  4007. .clone()
  4008. .removeClass('hide template')
  4009. .addClass('js-customField')
  4010. .removeAttr('id')
  4011. .insertBefore($template);
  4012.  
  4013. var amountData = $('.js-customField').length;
  4014. num++;
  4015.  
  4016. // Update the name attributes
  4017. $clone
  4018. .find('#customFieldName').attr('name', 'data[' + num + '].custom_field')
  4019. .attr('id', 'customFieldName' + num).end()
  4020. .find('#customFieldType').attr('id', 'customFieldType' + num).end();
  4021.  
  4022. transform.customSelect('customFieldType' + num);
  4023. //add click atribute
  4024. // remove();
  4025.  
  4026.  
  4027. $.each($('#customFieldForm').find('.numberField'), function (key, obj) {
  4028. $(obj).html('Campo customizável ' + (key + 1));
  4029. });
  4030.  
  4031. if (amountData >= 5) {
  4032. $(".addData").addClass('hide');
  4033. }
  4034. // }
  4035. });
  4036.  
  4037. $("#customFieldsBlock").on('hover', '.js-removeData', function () {
  4038. behaviors.svgChangeTo.hover($(this).children('img'));
  4039. }, function () {
  4040. behaviors.svgChangeTo.hover($(this).children('img'));
  4041. }).on("click", '.js-removeData', function () {
  4042. // Remove element containing the fields
  4043. $(this).parents('.control-panel-row').remove();
  4044.  
  4045. // re-write the titles
  4046. $.each($('#customFieldForm').find('.numberField'), function (key, obj) {
  4047. $(obj).html('Campo customizável ' + (key + 1));
  4048. });
  4049.  
  4050. var amountData = $('.js-customField').length;
  4051. if (amountData <= 5) {
  4052. $(".addData").removeClass('hide');
  4053. } else {
  4054. $(".addData").addClass('hide');
  4055. }
  4056. });
  4057.  
  4058. // function remove() {
  4059. // $(".js-dataRow").on('hover', '.js-removeData', function () {
  4060. // behaviors.svgChangeTo.hover($(this).children('img'));
  4061. // }, function () {
  4062. // behaviors.svgChangeTo.hover($(this).children('img'));
  4063. // }).on("click", '.js-removeData', function () {
  4064. // // Remove element containing the fields
  4065. // $(this).parents('.control-panel-row').remove();
  4066. //
  4067. // // re-write the titles
  4068. // $.each($('#customFieldForm').find('.numberField'), function (key, obj) {
  4069. // $(obj).html('Campo customizável ' + (key + 1));
  4070. // });
  4071. //
  4072. // var amountData = $('.js-customField').length;
  4073. // if (amountData <= 5) {
  4074. // $(".addData").removeClass('hide');
  4075. // } else {
  4076. // $(".addData").addClass('hide');
  4077. // }
  4078. // });
  4079. // }
  4080.  
  4081. var i = 0;
  4082. //verify if app has custom fields
  4083. if ((customFieldsJson !== null) && (customFieldsJson !== undefined)) {
  4084. $.each(customFieldsJson, function (index, value) {
  4085. i++;
  4086. if ((i == 1) && (value !== null) && (value !== undefined) && (value.custom_field_name !== undefined)) {
  4087. $("[name='data[0].custom_field']").attr('value', value.custom_field_name);
  4088. var selectField = $("#customFieldType0").attr('value', value.custom_field_type);
  4089. selectField.val(value.custom_field_type);
  4090. selectField.next('a').css({color: 'inherit'});
  4091. } else if ((value !== null) && (value !== undefined) && (value.custom_field_name !== undefined)) {
  4092. // var $template = $('#templateCustomFields'),
  4093. // $clone = $template
  4094. // .clone()
  4095. // .removeClass('hide')
  4096. // .addClass('.js-customField')
  4097. // .removeAttr('id')
  4098. // .insertBefore($template);
  4099. //
  4100. // var amountData = $('.js-customField').length - 1;
  4101. // num = amountData + 1; // initialize num
  4102.  
  4103. $('#addCustomField').trigger('click');
  4104.  
  4105. // .find('#customFieldName').attr('name', 'data[' + num + '].custom_field')
  4106. $('#customFieldName' + num).attr('value', value.custom_field_name);
  4107. // $('#customFieldType' + num).attr('value', value.custom_field_type);
  4108.  
  4109.  
  4110. // Update the name and value attributes
  4111. // $clone
  4112. // .find('[name="custom_field"]').attr('name', 'data[' + amountData + '].custom_field').attr('value', value.custom_field_name).end()
  4113. // .find('#customFieldType').attr('id', 'customFieldType' + amountData).end()
  4114. // .find('.numberField').html('Campo customizável ' + (amountData + 1)).end();
  4115.  
  4116. var selectField = $("#customFieldType" + num).attr('value', value.custom_field_type);
  4117. selectField.val(value.custom_field_type);
  4118. selectField.next('a').css({color: 'inherit'});
  4119.  
  4120. // $(".js-removeData").trigger("click");
  4121. // transform.customSelect('customFieldType' + amountData);
  4122.  
  4123. // if (amountData == 4)
  4124. // $(".addData").addClass('hide');
  4125. }
  4126. });
  4127.  
  4128. if (i > 1) {
  4129. $('.js-removeData').first().removeClass('hide');
  4130. }
  4131. }
  4132.  
  4133. // remove();
  4134. },
  4135.  
  4136. getSelectedAudiences: function () {
  4137. var elements = $('.list-checkbox');
  4138. var dict = '';
  4139.  
  4140. for (var i = 0; i < elements.length; i++) {
  4141. if ($('#audienceSelected' + i + ':checked').length > 0) {
  4142. var audience = $('#audienceSelected' + i).val();
  4143.  
  4144. if (audience !== '') {
  4145. if (dict == '')
  4146. dict = audience;
  4147. else
  4148. dict += ',' + audience;
  4149. }
  4150. }
  4151. }
  4152.  
  4153. return '"' + dict + '"';
  4154. },
  4155.  
  4156. getAudienceCriteria: function () {
  4157. var elements = $(".js-condition-row");
  4158. var dict = [];
  4159.  
  4160. for (var i = 0; i < elements.length; i++) {
  4161.  
  4162. var row = "#" + elements[i].id;
  4163. var selectCriteria = $(row.replace("jsConditionRow", "select") + '0');
  4164.  
  4165. var nameSelectCriteria = selectCriteria.val();
  4166. if (nameSelectCriteria != '' && nameSelectCriteria != undefined) {
  4167. var nameGroupCriteria = selectCriteria.find(':selected').closest('optgroup').attr('label');
  4168. var nameTypeCriteria = $(selectCriteria).find('option[value=' + nameSelectCriteria + ']').attr('data-type');
  4169.  
  4170. var objectTypeCondition = $(row).find('.js-' + nameTypeCriteria + '-condition');
  4171.  
  4172. var nameInputDeclaration, nameSelectCondition = '';
  4173. if (nameTypeCriteria == 'boolean') {
  4174. nameSelectCondition = objectTypeCondition.find('.ui-state-active').attr('data-value');
  4175. nameInputDeclaration = objectTypeCondition.find('.ui-state-active').find('a').attr("href").replace('#', '');
  4176. } else {
  4177. nameSelectCondition = objectTypeCondition.find('select[name=operator]').val();
  4178. nameInputDeclaration = objectTypeCondition.find('input[name=val]').val();
  4179. }
  4180.  
  4181. var nomeCriteria = $(selectCriteria).find(':selected')[0].innerText;
  4182.  
  4183. if ((nameSelectCriteria !== '') && (nameSelectCondition !== '') && (nameInputDeclaration !== '')) {
  4184. dict.push({
  4185. criteria: nameSelectCriteria,
  4186. nameCriteria: nomeCriteria,
  4187. groupCriteria: nameGroupCriteria,
  4188. typeCriteria: nameTypeCriteria,
  4189. condition: nameSelectCondition,
  4190. value: nameInputDeclaration
  4191. });
  4192. }
  4193. }
  4194. }
  4195. return dict;
  4196. },
  4197.  
  4198. insertRecentAudience: function (recentAudienceId) {
  4199. var $template = $('#templateAudienceRecent'),
  4200. $clone = $template
  4201. .clone()
  4202. .removeClass('hide')
  4203. .removeAttr('id')
  4204. .insertBefore($template);
  4205.  
  4206. var amountData = $('.templateRowAudience').length - 1;
  4207. var date = new Date();
  4208. var month = ("0" + (date.getMonth() + 1)).slice(-2);
  4209. var today = date.getDate() + '/' + month + '/' + date.getFullYear();
  4210.  
  4211. var rangeLocalFormat = parseInt($("#rangeNumber").text()).toLocaleString(locale);
  4212.  
  4213. $clone
  4214. .find('input[type=checkbox]').attr('value', recentAudienceId).attr('checked', true).end()
  4215. .find('input[id=audienceSelected]').attr('id', 'audienceSelected' + amountData).end()
  4216. .find('label[for=audienceSelected]').attr('for', 'audienceSelected' + amountData).end()
  4217. .find('[name="name"]').attr('name', 'nameAudience' + amountData).html($("#componentName").val()).end()
  4218. .find('[name="size"]').attr('name', 'sizeAudience' + amountData).html(rangeLocalFormat).end()
  4219. .find('[name="rank"]').attr('name', 'rankAudience' + amountData).html('-').end()
  4220. .find('[name="dateCreation"]').attr('name', 'dateCreationAudience' + amountData).html(today).end();
  4221.  
  4222. //update the range number
  4223. var rangeFullNumber = parseInt($('.range-full-number').html()) + parseInt($("#rangeNumber").text());
  4224. var rangeFullLocalFormat = rangeFullNumber.toLocaleString(locale);
  4225. $('.range-full-number').html(rangeFullLocalFormat);
  4226. $("#allAudiences").find('[id="sumSize"]').html(rangeFullLocalFormat);
  4227. $('#qtRecipients').html(rangeFullLocalFormat);
  4228. }
  4229.  
  4230. };
  4231.  
  4232. var charts = {
  4233.  
  4234. jsChart: '',
  4235. chartBg: '',
  4236. chartCanvas: '',
  4237.  
  4238. createDonutChart: function (context, value) {
  4239.  
  4240. var chart = value == 0 ? 'doughnut' : 'RoundedDoughnut';
  4241.  
  4242. Chart.defaults.RoundedDoughnut = Chart.helpers.clone(Chart.defaults.doughnut);
  4243. Chart.controllers.RoundedDoughnut = Chart.controllers.doughnut.extend({
  4244. draw: function (ease) {
  4245. var ctx = this.chart.chart.ctx;
  4246.  
  4247. var easingDecimal = ease || 1;
  4248. Chart.helpers.each(this.getDataset().metaData, function (arc, index) {
  4249. arc.transition(easingDecimal).draw();
  4250.  
  4251. var vm = arc._view;
  4252. var radius = (vm.outerRadius + vm.innerRadius) / 2;
  4253. var thickness = (vm.outerRadius - vm.innerRadius) / 2;
  4254. var angle = Math.PI - vm.endAngle - Math.PI / 2;
  4255.  
  4256. ctx.save();
  4257. ctx.fillStyle = vm.backgroundColor;
  4258. ctx.translate(vm.x, vm.y);
  4259. ctx.beginPath();
  4260. ctx.arc(radius * Math.sin(angle), radius * Math.cos(angle), thickness, 0, 2 * Math.PI);
  4261. ctx.arc(radius * Math.sin(Math.PI), radius * Math.cos(Math.PI), thickness, 0, 2 * Math.PI);
  4262. ctx.closePath();
  4263. ctx.fill();
  4264. ctx.restore();
  4265. });
  4266. }
  4267. });
  4268.  
  4269. var deliveredData = {
  4270. labels: [
  4271. "Value"
  4272. ],
  4273. datasets: [
  4274. {
  4275. data: [value, (100 - value)],
  4276. backgroundColor: [
  4277. "#3ec556",
  4278. "rgba(0,0,0,0)"
  4279. ],
  4280. hoverBackgroundColor: [
  4281. "#3ec556",
  4282. "rgba(0,0,0,0)"
  4283. ],
  4284. borderWidth: [
  4285. 0, 0
  4286. ]
  4287. }]
  4288. };
  4289.  
  4290. var deliveredOpt = {
  4291. cutoutPercentage: 88,
  4292. animation: {
  4293. animationRotate: true,
  4294. duration: 1000
  4295. },
  4296. legend: {
  4297. display: false
  4298. },
  4299. tooltips: {
  4300. enabled: false
  4301. }
  4302. };
  4303.  
  4304. this.jsChart = $('.js-chart');
  4305. this.chartBg = $('.chart-background');
  4306. this.chartCanvas = $('.chart-canvas');
  4307.  
  4308. $(window).on('resize', function () {
  4309. charts.resizeChartDiv();
  4310. });
  4311.  
  4312. return new Chart($(context), {
  4313. type: chart,
  4314. data: deliveredData,
  4315. options: deliveredOpt
  4316. });
  4317. },
  4318.  
  4319. resizeChartDiv: function () {
  4320. charts.jsChart.each(function () {
  4321. var width = $(this).width();
  4322. $(this).height(width);
  4323.  
  4324. charts.chartBg.each(function () {
  4325. var width = charts.chartCanvas.width() * 0.065;
  4326. $(this).css({borderWidth: width});
  4327. })
  4328.  
  4329. });
  4330. }
  4331.  
  4332. };
  4333.  
  4334. var validate = {
  4335.  
  4336. /**
  4337. *
  4338. * @param idValue id or OBJECT to be validated (must not be null or '')
  4339. * @param message string message to be shown if there is error
  4340. * @param redBox object [optional] where the red border is to be drawn. if not set will use the idValue
  4341. * @param errorPosition object [optional] the message will be shown after this obj. if not set will use the idValue
  4342. *
  4343. * */
  4344. field: function (idValue, message, redBox, errorPosition, setError) {
  4345.  
  4346. var valid = true;
  4347. var field = $(idValue);
  4348.  
  4349. if (redBox != undefined) {
  4350. var fieldBox = $(redBox);
  4351. } else {
  4352. fieldBox = $(idValue);
  4353. }
  4354. if (errorPosition != undefined) {
  4355. var aboveError = $(errorPosition);
  4356. } else {
  4357. aboveError = $(idValue);
  4358. }
  4359.  
  4360. var errorElement = "<div class='has-error error-pad js-error'>" +
  4361. "<span class='help-block'>" + message + "</span></div>";
  4362.  
  4363. var jsError = aboveError.next('.js-error');
  4364. //jsError.remove();
  4365.  
  4366. fieldBox.off('focus.valid').on('focus.valid', function () {
  4367. if (fieldBox.hasClass('error-outline')) {
  4368. var jsError = aboveError.next('.js-error');
  4369. fieldBox.removeClass('error-outline');
  4370. fieldBox.one('blur', function () {
  4371. if (field.val() == null || field.val() == '') {
  4372. jsError.remove();
  4373. fieldBox.addClass('error-outline');
  4374. aboveError.after(errorElement);
  4375. } else {
  4376. // $('#error-pushContent').slideUp('fast');
  4377. jsError.slideUp('fast', function () {
  4378. this.remove();
  4379. });
  4380. // get rid of the error message at footer bar
  4381. $('#footerError').fadeOut('fast', function () {
  4382. $(this).html('');
  4383. $(this).show();
  4384. });
  4385. }
  4386. });
  4387. }
  4388. });
  4389.  
  4390. if (field.val() == null || field.val() == '' || setError == true) {
  4391. // $('i').after("<div class='has-error js-error' style='line-height: 3em;'><span class='help-block'>" + message + "</span></div>");
  4392. jsError.remove();
  4393. aboveError.after(errorElement);
  4394. fieldBox.addClass('error-outline');
  4395. valid = false;
  4396. }
  4397. return valid;
  4398.  
  4399. },
  4400.  
  4401. /**
  4402. * To validate all fields at once. Pass an Array of arrays.
  4403. * If is to validate using validate.field, then pass an array with the parameters for this function.
  4404. * If it is a validation function, pass an array where the first element is the function name (without ()) and the
  4405. * other elements are parameters (if needed).
  4406. *
  4407. * @param array array = [[idValue, message, redBox, errorPosition], [idValue, message], [function, param1, param2]]
  4408. *
  4409. * */
  4410. multiFields: function (array) {
  4411.  
  4412. var valid = [];
  4413. var validated = true;
  4414.  
  4415. $.each(array, function (index, obj) {
  4416. if (typeof obj[0] === 'function') {
  4417. var params = [];
  4418. for (var i = 1; i < obj.length; i++) {
  4419. params.push(obj[i]);
  4420. }
  4421. valid.push(obj[0].apply(this, params));
  4422. } else {
  4423. valid.push(validate.field(obj[0], obj[1], obj[2], obj[3]));
  4424. }
  4425.  
  4426. });
  4427.  
  4428. $.each(valid, function (key, value) {
  4429. if (!value) {
  4430. validated = false;
  4431. }
  4432. });
  4433. return validated;
  4434. },
  4435.  
  4436. fieldsAdditionalData: function () {
  4437. var elements = $('#additionalBlock').find('.js-dataRow');
  4438. var valid = [];
  4439. var validated = true;
  4440.  
  4441. $.each(elements, function (num, obj) {
  4442. var keyObj = $(obj).find('input[name="additional-key"]');
  4443. var valueObj = $(obj).find('input[name="additional-value"]');
  4444.  
  4445. var key = keyObj.val();
  4446. var value = valueObj.val();
  4447.  
  4448. if (key != '' || value != '') {
  4449. valid.push(validate.field(keyObj, 'Qual a chave?'));
  4450. valid.push(validate.field(valueObj, 'Qual o valor?'));
  4451. }
  4452. });
  4453.  
  4454. $.each(valid, function (key, value) {
  4455. if (!value)
  4456. validated = false;
  4457. });
  4458.  
  4459. return validated;
  4460. },
  4461.  
  4462. fieldsAudienceCriteria: function (mandatoryCriteria) {
  4463. var elements = $(".js-condition-row");
  4464. var valid = [];
  4465. var validated = true;
  4466. var atLeastOne = false;
  4467.  
  4468. for (var i = 0; i < elements.length; i++) {
  4469. var row = "#" + elements[i].id;
  4470. var selectCriteria = $(row.replace("jsConditionRow", "select") + '0');
  4471. //var nameGroupCriteria = selectCriteria.find(':selected').closest('optgroup').attr('label');
  4472.  
  4473. if (selectCriteria.val() !== '' && mandatoryCriteria) {
  4474. atLeastOne = true; // at least 1 criteria has to be set
  4475.  
  4476. var nameTypeCriteria = $(selectCriteria).find('option[value=' + selectCriteria.val() + ']').attr('data-type');
  4477. var objectTypeCondition = $(row).find('.js-' + nameTypeCriteria + '-condition');
  4478. var selectCondition = objectTypeCondition.find('select[name=operator]');
  4479. var inputDeclaration = objectTypeCondition.find('input[name=val]');
  4480.  
  4481. if ($(selectCriteria).val() == '') {
  4482. valid.push(validate.field(selectCriteria['selector'], 'Qual o critério?'),
  4483. $(selectCriteria['selector']).nextAll('a'), $(selectCriteria['selector']).nextAll('a'));
  4484.  
  4485. } else if ($(selectCondition).val() == '') {
  4486. valid.push(validate.field(selectCondition, 'Qual a condição?',
  4487. $(selectCondition).next('a'), $(selectCondition).next('a')));
  4488. if ($(inputDeclaration).val() == '')
  4489. valid.push(validate.field(inputDeclaration['selector'], 'Com o que vamos comparar?'));
  4490.  
  4491. } else if ($(inputDeclaration).val() == '')
  4492. valid.push(validate.field(inputDeclaration['selector'], 'Com o que vamos comparar?'));
  4493. }
  4494. }
  4495.  
  4496. if (!atLeastOne) {
  4497. row = "#" + elements[0].id;
  4498.  
  4499. selectCriteria = $(row.replace("jsConditionRow", "select") + '0');
  4500.  
  4501. if (!validate.field(selectCriteria['selector'], 'Precisamos de pelo menos um critério',
  4502. $(selectCriteria['selector']).next('a'), $('.js-errorPosition').parent('span'))) {
  4503. validated = false;
  4504. }
  4505.  
  4506. } else {
  4507. $.each(valid, function (key, value) {
  4508. if (!value)
  4509. validated = false;
  4510. });
  4511. }
  4512. return validated;
  4513. },
  4514.  
  4515. fieldCampaignAutomation: function (campaignId, automationId) {
  4516. if (automationId == 0 && (campaignId == '' || campaignId == '0')) {
  4517. validate.field('#campaign', 'Por favor, selecione uma campanha para automatizar', '#selectCampaign');
  4518.  
  4519. return false;
  4520. }
  4521.  
  4522. return true;
  4523. },
  4524.  
  4525. /**
  4526. * @param requireUsers boolean If the service needs audience with users (true) or not (false)
  4527. * */
  4528. fieldsAudienceCampaign: function (dontRequireUsers) {
  4529. var elements = $(".list-checkbox");
  4530. var valid = [];
  4531. var validated = true;
  4532. var qtAudiencesSelected = 0;
  4533.  
  4534. for (var i = 0; i < elements.length; i++) {
  4535. if ($('#audienceSelected' + i + ':checked').length > 0)
  4536. qtAudiencesSelected += 1;
  4537. }
  4538.  
  4539. var qtSelected = $('.range-full-number').html();
  4540.  
  4541. $(document).off('ajaxComplete.valid'); // remove ajax so it won't be bound twice if there is another error,
  4542. // like audience with no users
  4543.  
  4544. function showErrorMessage(text) {
  4545. validated = false;
  4546. valid.push(validate.field('label', text, $('none'), $('.table-be-table')));
  4547. $('.js-audienceLabel').css({borderColor: '#EC7E7E'});
  4548. $(document).on('ajaxComplete.valid', function (e, xhr, options) {
  4549. validate.fieldsAudienceCampaign(); //validate again on audience selection
  4550. if (options.url != '/handleSubscribersAudience') { //remove this handler if user change pages
  4551. $(document).off('ajaxComplete.valid');
  4552. }
  4553. });
  4554. }
  4555.  
  4556. if (qtAudiencesSelected == 0) {
  4557. showErrorMessage('Por favor, selecione uma audiência para enviar sua mensagem');
  4558. } else if (qtSelected == 0 && !dontRequireUsers) {
  4559. showErrorMessage('As audiências selecionadas não possuem usuários. Por favor, selecione outra.');
  4560. } else {
  4561. $('#audienceSelectTable').next('.js-error').remove();
  4562. $('.js-audienceLabel').removeClass("error-outline").css({borderColor: ''});
  4563. $('.push-row').find('input[type=checkbox]').off('change.error');
  4564. }
  4565.  
  4566. return validated;
  4567. },
  4568.  
  4569. quantitySubscribers: function (countSubscribers) {
  4570. var valid = [];
  4571. var validated = true;
  4572.  
  4573. if (countSubscribers == 0) {
  4574. // validated = false;
  4575. // valid.push(validate.field('label', 'Não há nenhum usuário cadastrado para esse app'));
  4576. // $('.has-error').css({marginTop: '-31px'});
  4577. $('.list-checkbox').children('label').css({borderColor: '#EC7E7E'});
  4578. $('#footerError').html('Não há nenhum usuário cadastrado.<br>Infelizmente não podemos enviar nenhum push.');
  4579. $('#sendPushBtn').off('click').css({backgroundColor: '#b5b5b5', cursor: 'default'});
  4580. } else {
  4581. // $('.js-error').remove();
  4582. // $('.list-checkbox').children('label').removeClass("error-outline").css({borderColor: ''});
  4583. // $('.has-error').css({marginTop: ''});
  4584. }
  4585.  
  4586. return validated;
  4587. }
  4588. };
  4589. /**
  4590. * Created by Juliano on 04/02/2016.
  4591. */
  4592.  
  4593. var contentContainer = $("#content-container");
  4594. var appHeader = $("#app-header");
  4595. window.locale = 'pt-br';
  4596.  
  4597. (function ($, undefined) {
  4598. $.fn.getCursorPosition = function () {
  4599. var el = $(this).get(0);
  4600. var pos = 0;
  4601. if ('selectionStart' in el) {
  4602. pos = el.selectionStart;
  4603. } else if ('selection' in document) {
  4604. el.focus();
  4605. var Sel = document.selection.createRange();
  4606. var SelLength = document.selection.createRange().text.length;
  4607. Sel.moveStart('character', -el.value.length);
  4608. pos = Sel.text.length - SelLength;
  4609. }
  4610. return pos;
  4611. }
  4612. })(jQuery);
  4613.  
  4614. var access = {
  4615.  
  4616. /* Hover open effect on menu */
  4617. threeDots: function () {
  4618. var optionsBalloon = $("#options-balloon");
  4619. var timer;
  4620. $("#3-dots-menu").on("mouseleave", function () {
  4621. timer = setTimeout(function () {
  4622. optionsBalloon.fadeOut("fast");
  4623. }, 400);
  4624. }).on("click", function () {
  4625. clearTimeout(timer);
  4626. optionsBalloon.fadeToggle("fast");
  4627. event.stopPropagation();
  4628. });
  4629.  
  4630. optionsBalloon.on("mouseenter", function () {
  4631. clearTimeout(timer);
  4632. optionsBalloon.fadeIn();
  4633. event.stopPropagation();
  4634. }).on("mouseleave", function (event) {
  4635. timer = setTimeout(function () {
  4636. optionsBalloon.fadeOut("fast");
  4637. event.stopPropagation();
  4638. }, 400);
  4639. });
  4640.  
  4641. $("#sign-btn-arrow").on("click", function () {
  4642. $("#btn_next").trigger("click");
  4643. });
  4644.  
  4645. $("#forgot-btn-arrow").on("click", function () {
  4646. $("#btn_send").trigger("click");
  4647. });
  4648. },
  4649.  
  4650. /* This is used to personalize the select element of sign up page
  4651. *
  4652. * Have to add this on the page (Theter and Select):
  4653. * <link rel="stylesheet" href="select-theme-default.css" />
  4654. * <script src="tether.min.js"></script>
  4655. * <script src="select.min.js"></script>
  4656. *
  4657. * Then use this code here to use a placeholder and style the element.
  4658. *
  4659. * More info: http://github.hubspot.com/select/docs/welcome/
  4660. */
  4661. customSelect: function () {
  4662. var signSelect;
  4663. var element = document.getElementById('companySize');
  4664. signSelect = new Select({
  4665. el: element,
  4666. className: 'select-theme-inngage'
  4667. });
  4668. signSelect.on('change', function () {
  4669. $(".select-target.select-theme-inngage").css({color: '#444'});
  4670. });
  4671. element.setAttribute('tabindex', '-1');
  4672. },
  4673.  
  4674. doLogout: function () {
  4675. var formData = {
  4676. 'logout': true
  4677. };
  4678. var ajaxSend = $.ajax({
  4679. type: 'POST',
  4680. url: '/handleLogout',
  4681. data: formData,
  4682. dataType: 'json',
  4683. encode: true,
  4684. timeout: 10000
  4685. }).done(function (data) {
  4686. console.log('done');
  4687. //modal.closeModal();
  4688. // modal.getModal('success-saved.php', true, {obj: 'Campanha', justShow: true});
  4689. }).fail(function (data) {
  4690. console.log(data);
  4691. //action.verifyBehavior('fail', afterAction);
  4692. ajaxSend.abort();
  4693. });
  4694. }
  4695. };
  4696.  
  4697. var ref = {
  4698. // INCLUDES
  4699. getIncludes: "/includes",
  4700. // INCLUDES APP-PG
  4701. getAppPg: "/includes/app-pg",
  4702. // INCLUDES MAIN-PG
  4703. getMainPg: "includes/main-pg",
  4704.  
  4705. // PLUGINS PATH
  4706. getPlugins: "/resources/plugins",
  4707. // UPLOADS PATH
  4708. getUploads: "/resources/uploads",
  4709. // VIEW PATH
  4710. getView: "/view"
  4711. };
  4712.  
  4713. var navigation = {
  4714. /* Code to show and hide user pop-up menu in nav bar.
  4715. * The arrow behavior is set here too.
  4716. * */
  4717. userMenu: function () {
  4718.  
  4719. /* show user pop up menu when mouse enters the user bar space */
  4720. var popUpMenu = $("#user-pop");
  4721. var userBar = $(".user-bar");
  4722. var optionsArrow = $("#options-arrow");
  4723. // has to use 2 timers to work when leave popMenu and comes back to userBar
  4724. var timerUser; // timer for when leave userBar
  4725. var timerPop; // timer for when leave userPopMenu
  4726.  
  4727. userBar.on("mouseenter", function (event) {
  4728. clearTimeout(timerUser);
  4729. clearTimeout(timerPop);
  4730. //popUpMenu.fadeIn("fast");
  4731. event.stopPropagation();
  4732. //optionsArrow.addClass('rotate');
  4733. }).on("mouseleave", function () {
  4734. timerUser = setTimeout(function () {
  4735. popUpMenu.fadeOut("fast");
  4736. //event.stopPropagation();
  4737. optionsArrow.removeClass('rotate-180');
  4738. }, 250);
  4739. }).off('click').click(function (event) {
  4740. event.stopPropagation();
  4741. optionsArrow.toggleClass('rotate-180');
  4742. popUpMenu.toggle();
  4743. });
  4744.  
  4745. popUpMenu.on("mouseenter", function () {
  4746. clearTimeout(timerUser);
  4747. clearTimeout(timerPop);
  4748. popUpMenu.fadeIn("fast");
  4749. //event.stopPropagation();
  4750. optionsArrow.addClass('rotate-180');
  4751. }).on("mouseleave", function () {
  4752. timerPop = setTimeout(function () {
  4753. popUpMenu.fadeOut("fast");
  4754. //event.stopPropagation();
  4755. optionsArrow.removeClass('rotate-180');
  4756. }, 250);
  4757. });
  4758.  
  4759. // show the user pop-up menu, and hide it clicking anywhere else in the page
  4760. $(document).on("click", function () {
  4761. popUpMenu.fadeOut("fast");
  4762. optionsArrow.removeClass('rotate-180');
  4763. $("#options-balloon").hide();
  4764. $("#config-balloon").hide();
  4765. });
  4766. },
  4767.  
  4768. /* Menu-side scroll effect */
  4769. navSideScroll: function () {
  4770. var lastScrollPosition = 0;
  4771. var navSide = $("#nav-side");
  4772.  
  4773. var space = "<div style='height: " + navSide.height() + "px;'></div>";
  4774. // var space = "<div style='height: " + navSide.height() + "px;' id='space'></div>";
  4775. // $('#space').remove();
  4776. $('body').prepend(space);
  4777.  
  4778. $(window).scroll(function () {
  4779. var screenWindow = $(window);
  4780. var sp = screenWindow.scrollTop();
  4781.  
  4782. //scrolling down
  4783. if (lastScrollPosition < sp) {
  4784. //if screen passes nav-side bottom
  4785. if (sp + screenWindow.height() >= navSide.height() + navSide.offset().top) {
  4786. navSide.addClass("nav-side-fixed-bot");
  4787. }
  4788. //else if scrolling up
  4789. } else {
  4790. //and is fixed bot
  4791. if (navSide.hasClass("nav-side-fixed-bot")) {
  4792. //set top, pass to absolute
  4793. navSide.removeClass('nav-side-fixed-bot');
  4794. navSide.css({top: sp + screenWindow.height() - navSide.height()});
  4795. }
  4796. //and if scroll is above nav-side top, then set nav-side top to scroll
  4797. if (sp <= navSide.offset().top) {
  4798. navSide.css({top: sp});
  4799. }
  4800. }
  4801. lastScrollPosition = sp;
  4802. });
  4803.  
  4804. $(window).trigger('scroll');
  4805. },
  4806.  
  4807. /* Put shadow on nav-top when user scrolls the screen */
  4808. navTopShadow: function () {
  4809. $(window).scroll(function () {
  4810. var navTop = $(".nav-top");
  4811.  
  4812. if ($(window).scrollTop() > 0) {
  4813. navTop.addClass('nav-top-shadow');
  4814. } else {
  4815. navTop.removeClass('nav-top-shadow');
  4816. }
  4817. });
  4818. },
  4819.  
  4820. navTop: function () {
  4821. this.userMenu();
  4822. this.navTopShadow()
  4823. },
  4824.  
  4825. navSide: function () {
  4826. this.navSideScroll();
  4827. }
  4828. };
  4829.  
  4830. var behaviors = {
  4831. /*
  4832. * This function applyes the menu pop behavior to menu buttons and pop menus.
  4833. * Call this function with the menu trigger button.
  4834. *
  4835. * @param popMenu what is the menu ID to be poped-up (pass #id)
  4836. * @param buttonID what is the menu button ID to open the pop-up (pass #id)
  4837. * @param expandClass class with animation to expand
  4838. * @param shrinkClass class with animation to shrink
  4839. *
  4840. * */
  4841. popUp: function (buttonID, popMenuId, expandClass, shrinkClass) {
  4842. // has to use 2 timers to work when leave popMenu and comes back to userBar
  4843. var timerThis; // timer for when leave 'this'
  4844. var timerPop; // timer for when leave popMenu
  4845. var popMenu = $(popMenuId);
  4846. var button = $(buttonID);
  4847. popMenu.css({visibility: 'visible'}).hide();
  4848.  
  4849. function expand() {
  4850. button.children('img').removeClass(shrinkClass);
  4851. button.children('img').addClass(expandClass);
  4852. }
  4853.  
  4854. function shrink() {
  4855. button.children('img').removeClass(expandClass);
  4856. button.children('img').addClass(shrinkClass);
  4857. }
  4858.  
  4859. button.on('click', function (e) {
  4860. e.stopPropagation();
  4861. popMenu.fadeToggle('fast');
  4862. $(document).one('mouseup.popMenu', function (e) {
  4863. if (!popMenu.is(e.target) // if the target of the click isn't the container...
  4864. && popMenu.has(e.target).length === 0) { // ... nor a descendant of the container
  4865. popMenu.fadeOut("fast");
  4866. shrink();
  4867. }
  4868. });
  4869. }).on("mouseenter", function () {
  4870. clearTimeout(timerThis);
  4871. clearTimeout(timerPop);
  4872. expand();
  4873. }).on("mouseleave", function () {
  4874. timerThis = setTimeout(function () {
  4875. popMenu.fadeOut("fast");
  4876. shrink();
  4877. $(document).off('mouseup.popMenu');
  4878. }, 300);
  4879. });
  4880.  
  4881. popMenu.on("mouseenter", function () {
  4882. clearTimeout(timerThis);
  4883. clearTimeout(timerPop);
  4884. popMenu.fadeIn("fast");
  4885. }).on("mouseleave", function () {
  4886. timerPop = setTimeout(function () {
  4887. popMenu.fadeOut("fast");
  4888. shrink();
  4889. $(document).off('mouseup.popMenu');
  4890. }, 600);
  4891. });
  4892.  
  4893.  
  4894. },
  4895.  
  4896. //no-app change fill color
  4897. plusApp: function () {
  4898. $("#plus-app, #new-app-btn").hover(function () {
  4899. $("#plus-app").addClass("plus-app-hover");
  4900. $("#new-app-btn").addClass("button-blue-hover");
  4901. }, function () {
  4902. $("#plus-app").removeClass("plus-app-hover");
  4903. $("#new-app-btn").removeClass("button-blue-hover");
  4904. });
  4905. },
  4906.  
  4907.  
  4908. /* Insert a local input field to edit content
  4909. *
  4910. * @param clicked element to be clicked and trigger the effect
  4911. * @param toFadeOut element to get rid of
  4912. * @param editCount number of the element to be used in IDs
  4913. * @param wordID the identification text of the ID to be used in selector
  4914. *
  4915. * Update: previous version inserted html to the DOM. This version doesn't
  4916. * */
  4917. editField: {
  4918. // Distinguish between cancel and accept for different fields
  4919. function: function (clicked, toFadeOut, toFadeIn, wordId) {
  4920.  
  4921. //var thisEditCount = editCount;
  4922. var fadeOutThis = $(toFadeOut);
  4923. var fadeInThis = $(toFadeIn);
  4924.  
  4925. //var textValue = $.trim(fadeOutThis.text());
  4926.  
  4927. $(clicked).on('click', function (e) {
  4928. fadeOutThis.fadeOut('fast', function () {
  4929. fadeInThis.fadeIn('fast', function () {
  4930.  
  4931. var inputElem = fadeInThis.find('input');
  4932. // var originalValue = inputElem.val();
  4933.  
  4934. $(document).on('keyup', function (e) {
  4935. if (e.keyCode == 13) {
  4936. $("#accept" + wordId).trigger('click');
  4937. }
  4938. if (e.keyCode == 27) {
  4939. $("#cancel" + wordId).trigger('click');
  4940. }
  4941. });
  4942.  
  4943. $("#accept" + wordId).on('click', function () {
  4944. //var newName = editionInput.val();
  4945.  
  4946. $('#cancel' + wordId).trigger('click');
  4947.  
  4948. });
  4949.  
  4950. $('#cancel' + wordId).on('click', function () {
  4951. fadeInThis.fadeOut('fast', function () {
  4952. fadeOutThis.fadeIn('fast');
  4953. // inputElem.val(originalValue);
  4954. });
  4955. //$('.input-div').css({textAlign: 'right'});
  4956. $(document).off('**');
  4957.  
  4958. });
  4959.  
  4960. $('#input' + wordId).select();
  4961. });
  4962. });
  4963. });
  4964. }
  4965. },
  4966.  
  4967. /* Change SVG color
  4968. * Takes the image source attribute and change the last name to the color to use
  4969. * @param imgTag pass selector of the IMG to switch
  4970. * @param color name of the color */
  4971. svgChangeTo: {
  4972.  
  4973. color: function (imgTag, color) {
  4974. var image = $(imgTag);
  4975.  
  4976. var imgSource = image.attr('src');
  4977.  
  4978. var splited = imgSource.split('-');
  4979. splited[splited.length - 1] = color + '.svg';
  4980. imgSource = splited.join('-');
  4981.  
  4982. image.attr('src', imgSource);
  4983. },
  4984.  
  4985. hover: function (imgTag) {
  4986. var image = $(imgTag);
  4987.  
  4988. var imgSource = image.attr('src');
  4989.  
  4990. var splited = imgSource.split('-');
  4991. var last = splited[splited.length - 1];
  4992. if (last == 'hover.svg') {
  4993. splited[splited.length - 1] = '.svg';
  4994. imgSource = splited.join('-').replace('-.', '.');
  4995. } else {
  4996. splited = imgSource.split('.');
  4997. splited[splited.length - 1] = '-hover.svg';
  4998. imgSource = splited.join('');
  4999. }
  5000.  
  5001. image.attr('src', imgSource);
  5002. },
  5003.  
  5004. white: function (imgTag) {
  5005. this.color(imgTag, 'white');
  5006. },
  5007.  
  5008. blue: function (imgTag) {
  5009. this.color(imgTag, 'blue');
  5010. },
  5011.  
  5012. gray: function (imgTag) {
  5013. this.color(imgTag, 'gray');
  5014. }
  5015.  
  5016. },
  5017.  
  5018. /* auto adjust textarea */
  5019. autoTextArea: function () {
  5020. var textArea = $('.textarea');
  5021. textArea.each(function () {
  5022. $(this).on('keyup', function () {
  5023. $(this).height(0);
  5024. $(this).height(this.scrollHeight);
  5025. });
  5026. $(this).keyup();
  5027. });
  5028. },
  5029.  
  5030. sendPush: function () {
  5031. modal.closeModal();
  5032. navigateTo.app.push.notificationsSent();
  5033. },
  5034.  
  5035. schedulePush: function () {
  5036. modal.closeModal();
  5037. navigateTo.app.push.notificationsScheduled();
  5038. },
  5039.  
  5040. sendPushFail: function (message) {
  5041. modal.closeModal(['modal-fail-push.php', undefined, {message: message}]);
  5042. },
  5043.  
  5044. saveAudienceFail: function () {
  5045. modal.closeModal(['modal-fail-push.php']);
  5046. },
  5047.  
  5048. saveSecurityParameter: function () {
  5049. modal.closeModal(['modal-fail-security-parameter.php']);
  5050. },
  5051.  
  5052. saveAutomationFail: function () {
  5053. modal.closeModal(['modal-fail-automation.php']);
  5054. },
  5055.  
  5056. saveApiTemplateFail: function () {
  5057. modal.closeModal(['modal-fail-api-template.php']);
  5058. },
  5059.  
  5060. saveCamp: function () {
  5061. modal.closeModal(['success-saved.php', true, {
  5062. obj: 'Campanha salva',
  5063. navigate_method: 'navigateTo.app.push.campaigns();'
  5064. }]);
  5065.  
  5066. },
  5067.  
  5068. saveCampFail: function () {
  5069. modal.closeModal(['modal-failed.php', false, {obj: 'Campanha'}]);
  5070. },
  5071.  
  5072. saveSendCamp: function (campId) {
  5073. $.ajax({
  5074. url: '/getCampaign',
  5075. type: "POST",
  5076. data: {'campId': campId, 'action': 'send'},
  5077. success: function (data) {
  5078. contentContainer.html(data);
  5079. modal.closeModal();
  5080. // modal.getModal('success-saved.php', true, {obj: 'Campanha', justShow: true});
  5081. },
  5082. fail: function (data) {
  5083. alert(data);
  5084. }
  5085. });
  5086. },
  5087.  
  5088. sendSaveCampFail: function () {
  5089. this.sendPushFail();
  5090. },
  5091.  
  5092. saveAudience: function () {
  5093. modal.closeModal(['success-saved.php', true, {
  5094. obj: 'Audiência salva',
  5095. navigate_method: 'navigateTo.app.audience.audiences();'
  5096. }]);
  5097. },
  5098.  
  5099. saveAutomation: function () {
  5100. modal.closeModal(['success-saved.php', true, {
  5101. obj: 'Automação salva',
  5102. navigate_method: 'navigateTo.app.push.automations();'
  5103. }]);
  5104. },
  5105.  
  5106. saveApiTemplate: function () {
  5107. modal.closeModal(['success-saved.php', true, {
  5108. obj: 'API Template salva',
  5109. navigate_method: 'navigateTo.app.push.apiTemplate();'
  5110. }]);
  5111. },
  5112.  
  5113. inactivateAudience: function () {
  5114. modal.closeModal();
  5115.  
  5116. // update page values
  5117. // lastRegister
  5118. var lastRegister = $('#lastRegister');
  5119. var lastItemValue = lastRegister.html();
  5120. lastRegister.html(lastItemValue - 1);
  5121. // totalRegsiter
  5122. var totalRegisters = $('#totalRegisters');
  5123. var totalRegistersValue = totalRegisters.html();
  5124. totalRegisters.html(totalRegistersValue - 1);
  5125. },
  5126.  
  5127. tagTemplateSelection: function () {
  5128. function insertText(context, open, close) {
  5129. var aim = context.parent('div').attr('data-box');
  5130. console.log(aim);
  5131. var emojiDiv = $('.emoji-wysiwyg-editor').eq(aim);
  5132.  
  5133. var tag = context.children('span').html();
  5134. emojiDiv.html(emojiDiv.html() + open + tag + close);
  5135. emojiDiv.trigger('keyup');
  5136. $('#tagTemplateMenu').fadeOut('fast');
  5137. }
  5138.  
  5139. $('#tagTemplateMenu').on('click', '.js-customField', function () {
  5140. insertText($(this), '|*', '*|');
  5141. }).on('click', '.js-tagField', function () {
  5142. insertText($(this), '{{', '}}');
  5143. });
  5144. },
  5145.  
  5146. /* Insert new row to add data
  5147. *
  5148. * @param context String selector which is the context of the list (maxRows will be used there)
  5149. * @param maxRows number max number of rows
  5150. * */
  5151. listData: {
  5152. add: function (context, maxRows) {
  5153. if (context == undefined) {
  5154. context = $('body');
  5155. } else {
  5156. context = $(context);
  5157. }
  5158. if (maxRows === undefined) {
  5159. maxRows = Number.POSITIVE_INFINITY;
  5160. }
  5161.  
  5162. context.find('.addNewData').hover(function () {
  5163. $(this).css({fontWeight: '400'});
  5164. behaviors.svgChangeTo.hover($(this).children('img'));
  5165. }, function () {
  5166. $(this).attr('style', '');
  5167. behaviors.svgChangeTo.hover($(this).children('img'));
  5168. }).on("click", function () {
  5169. var context = $(this).parents('.control-panel');
  5170. if (context.find('.js-dataRow').length < maxRows) {
  5171. var $template = context.find('.js-dataTemplate');
  5172.  
  5173. // var $clone = $template
  5174. $template.clone()
  5175. .removeClass('hide')
  5176. .removeClass('js-dataTemplate')
  5177. .addClass('js-dataRow')
  5178. .insertBefore($template);
  5179.  
  5180. // var amountData = $('.template').length - 1;
  5181. var amountData = context.find('.js-dataRow').length;
  5182.  
  5183. // if more than 1, show del to all
  5184. // if (amountData != 1) {
  5185. // context.find(".js-removeData").removeClass('hide');
  5186. // }
  5187.  
  5188. // Update the name attributes
  5189. // $clone
  5190. // .find('[name="' + sectionName + '-key"]').attr('name', 'data[' + amountData + '].' + sectionName + '-key').end()
  5191. // .find('[name="' + sectionName + '-value"]').attr('name', 'data[' + amountData + '].' + sectionName + '-value').end();
  5192.  
  5193. //add click atribute
  5194. // behaviors.listData.remove(maxRows);
  5195. if (amountData == maxRows) {
  5196. context.find(".addData").addClass('hide');
  5197. }
  5198. }
  5199. });
  5200.  
  5201. context.on('hover', '.js-removeData', function () {
  5202. behaviors.svgChangeTo.hover($(this).children('img'));
  5203. }, function () {
  5204. behaviors.svgChangeTo.hover($(this).children('img'));
  5205. }).on("click", '.js-removeData', function () {
  5206. var context = $(this).parents('.control-panel');
  5207. // Remove element containing the fields
  5208. $(this).parents('.control-panel-row').remove();
  5209. // Count lines
  5210. var amountData = context.find('.js-dataRow').length;
  5211.  
  5212. if (amountData < maxRows) {
  5213. $(".addData").removeClass('hide');
  5214. // if (amountData == 1) {
  5215. // context.find(".js-removeData").addClass('hide');
  5216. // }
  5217. } else {
  5218. $(".addData").addClass('hide');
  5219. }
  5220.  
  5221. });
  5222. },
  5223.  
  5224. populate: function (contextId, object) {
  5225. var context = $(contextId);
  5226. var addButton = context.find('.addNewData');
  5227.  
  5228. $.each(object, function (key, obj) {
  5229. addButton.trigger('click');
  5230. var lastRow = context.find('.js-dataRow').last();
  5231.  
  5232. if (obj === Object(obj)) {
  5233. $.each(obj, function (key, value) {
  5234. lastRow.find(key).val(value);
  5235. })
  5236. } else {
  5237. lastRow.find('input').val(obj);
  5238. }
  5239.  
  5240. })
  5241. }
  5242.  
  5243. },
  5244.  
  5245. togglePassword: function (context, id) {
  5246. var elm = document.getElementById(id);
  5247. if (elm.type == "password") {
  5248. elm.type = "text";
  5249. //$(context).removeClass("glyphicon-eye-open");
  5250. $(context).addClass("blue-flat");
  5251. } else if (elm.type == "text") {
  5252. elm.type = "password";
  5253. $(context).removeClass("blue-flat");
  5254. //$(context).toggleClass("glyphicon-eye-close");
  5255. }
  5256. }
  5257. };
  5258.  
  5259. var action = {
  5260.  
  5261. verifyBehavior: function (result, afterAction, message) {
  5262.  
  5263. var behavior;
  5264.  
  5265. if (result == 'success') {
  5266. switch (afterAction) {
  5267. case 'justSend':
  5268. behavior = behaviors.sendPush();
  5269. break;
  5270. case 'scheduleSend':
  5271. behavior = behaviors.schedulePush();
  5272. break;
  5273. case 'saveCamp':
  5274. behavior = behaviors.saveCamp();
  5275. break;
  5276. case 'saveSendCamp':
  5277. behavior = behaviors.saveSendCamp;
  5278. break;
  5279. case 'saveAudience':
  5280. behavior = behaviors.saveAudience();
  5281. break;
  5282. case 'saveAutomation':
  5283. behavior = behaviors.saveAutomation();
  5284. break;
  5285. case 'inactivateAudience':
  5286. behavior = behaviors.inactivateAudience();
  5287. break;
  5288. case 'saveApiTemplate':
  5289. behavior = behaviors.saveApiTemplate();
  5290. break;
  5291. default:
  5292. break;
  5293. }
  5294. } else if (result == 'fail') {
  5295. switch (afterAction) {
  5296. case 'justSend':
  5297. behavior = behaviors.sendPushFail(message);
  5298. break;
  5299. case 'saveCamp':
  5300. behavior = behaviors.saveCampFail();
  5301. break;
  5302. case 'saveSendCamp':
  5303. behavior = behaviors.sendSaveCampFail();
  5304. break;
  5305. case 'saveAudience':
  5306. behavior = behaviors.saveAudienceFail();
  5307. break;
  5308. case 'saveAutomation':
  5309. behavior = behaviors.saveAutomationFail();
  5310. break;
  5311. case 'saveApiTemplate':
  5312. behavior = behaviors.saveApiTemplateFail();
  5313. break;
  5314. case 'saveSecurityParameter':
  5315. behavior = behaviors.saveSecurityParameter();
  5316. break;
  5317. default:
  5318. break;
  5319. }
  5320. }
  5321.  
  5322. return behavior;
  5323. },
  5324.  
  5325. /* AJAX to send push (used in Send Push and Campaign)
  5326. *
  5327. * audiencesSelected array audiences in string ('audience1,audience2,audience3')
  5328. * if private msg, audiencesSelected = 'false,identifier'
  5329. * */
  5330. sendPush: function (appId, appToken, afterAction, campId, audiencesSelected) {
  5331. if (campId == null || campId == '') {
  5332. campId = 0;
  5333. }
  5334.  
  5335. var pushContent = $('#pushContent');
  5336. isScheduler = $('.js-check-showUpSend').is(':checked');
  5337.  
  5338. if (!isScheduler) {
  5339. modal.closeModal(); //don't put modal in closeModal because of undesired async behavior
  5340. modal.getModal('modal-sending-push.php', true);
  5341. } else {
  5342. modal.closeModal();
  5343. modal.getModal('modal-scheduling-push.php', true);
  5344. }
  5345.  
  5346. var pushMsgToPersist = pushContent.val();
  5347. var msgContent = window.emojiPicker.colonToUnicode(pushMsgToPersist);
  5348.  
  5349. var additionalData = scriptForPage.getAdditionalData();
  5350. var flagAdditional = false;
  5351.  
  5352. if (additionalData.length > 0)
  5353. flagAdditional = true;
  5354.  
  5355. var formData = {
  5356. 'msgTitle': $('input[name=msg-title]').val(),
  5357. 'msgContent': msgContent,
  5358. 'appId': appId,
  5359. 'appToken': appToken,
  5360. 'action': 'doSendPush',
  5361. 'flagSchedule': $('.js-check-showUpSend').is(':checked'),
  5362. 'sendDate': $('input[name=sendDate]').val(),
  5363. 'sendHour': $('select[name=sendHour]').val(),
  5364. 'sendMinute': $('select[name=sendMinute]').val(),
  5365. 'persistMsg': pushMsgToPersist,
  5366. 'campId': campId,
  5367. 'flagUrl': $('.js-check-showUpURL').is(':checked'),
  5368. 'urlPush': $('input[name=open-url]').val(),
  5369. 'imgPush': $('input[name=msg-image]').val(),
  5370. 'flagAdditional': flagAdditional,
  5371. 'additionalData': additionalData,
  5372. 'audiences': audiencesSelected
  5373. };
  5374.  
  5375. var ajaxSend = $.ajax({
  5376. type: 'POST',
  5377. url: '/sendPushValidation',
  5378. data: formData,
  5379. dataType: 'json',
  5380. encode: true,
  5381. //timeout: 10000
  5382. //timeout: 120000
  5383. })
  5384. .done(function (data) {
  5385. console.log(data);
  5386. if (data.errors == null) {
  5387. if (campId == 0) {
  5388. action.saveAdditionalData(0, data.message_control_id, 0);
  5389. action.savePushAdresses('NULL', data.message_control_id, audiencesSelected);
  5390. }
  5391. while ($(".modal-container").length == 0) {
  5392. // wait until previous modal is loaded, so it will be correctly closed on afterAction
  5393. }
  5394. action.verifyBehavior('success', afterAction);
  5395. } else {
  5396. action.verifyBehavior('fail', afterAction, data.message);
  5397. }
  5398.  
  5399. })
  5400. .fail(function (data) {
  5401. console.log(data);
  5402. action.verifyBehavior('fail', afterAction);
  5403. ajaxSend.abort();
  5404. });
  5405. },
  5406.  
  5407. saveCampaign: function (appId, appToken, campId, afterAction) {
  5408.  
  5409. var flDraft = 1; //rascunho
  5410.  
  5411. if (afterAction == undefined || afterAction == 'saveSendCamp') { //if there is no afterAction (send Campaign), change to "active" campaign
  5412. flDraft = 0; //enviado
  5413. }
  5414.  
  5415. var formData = {
  5416. 'msgTitle': $('input[name=msg-title]').val(),
  5417. 'msgBody': $('#pushContent').val(),
  5418. 'appId': appId,
  5419. 'campId': campId,
  5420. 'campName': $('#componentName').val(),
  5421. 'campDescription': $('#componentDescription').val(),
  5422. 'campFlDraft': flDraft,
  5423. 'campStatus': 0,
  5424. // 'flagSchedule': $('.js-check-showUpSend').is(':checked'),
  5425. // 'sendDate': $('input[name=sendDate]').val(),
  5426. // 'sendHour': $('select[name=sendHour]').val(),
  5427. // 'sendMinute': $('select[name=sendMinute]').val(),
  5428. 'flagUrl': $('.js-check-showUpURL').is(':checked'),
  5429. 'urlPush': $('input[name=open-url]').val(),
  5430. 'imgPush': $('input[name=msg-image]').val()
  5431. };
  5432.  
  5433. var ajaxSave = $.ajax({
  5434. type: 'POST',
  5435. url: '/handleCampaign',
  5436. data: formData,
  5437. timeout: 10000
  5438. })
  5439. .done(function (data) {
  5440. var campId = data;
  5441. console.log('done');
  5442. action.saveAdditionalData(campId, 0, 0, '');
  5443. var goToSendCamp = action.verifyBehavior('success', afterAction);
  5444. if (afterAction == 'saveSendCamp')
  5445. goToSendCamp(campId);
  5446. })
  5447. .fail(function () {
  5448. console.log('fail');
  5449. action.verifyBehavior('fail', afterAction);
  5450. }).error(function () {
  5451. action.verifyBehavior('fail', afterAction);
  5452. ajaxSave.abort();
  5453. });
  5454.  
  5455. },
  5456.  
  5457. saveAdditionalData: function (campaignId, controlMessageId, automationId, afterAction, apiTemplateId) {
  5458. function getAdditionalData() {
  5459. var elements = $('#additionalBlock').find('.js-dataRow');
  5460. var dict = [];
  5461.  
  5462. $.each(elements, function (num, obj) {
  5463. var key = $(obj).find('input[name="additional-key"]').val();
  5464. var value = $(obj).find('input[name="additional-value"]').val();
  5465.  
  5466. if ((key !== '') && (value !== '')) {
  5467. dict.push({key: key, value: value});
  5468. }
  5469. });
  5470.  
  5471. return dict;
  5472. }
  5473.  
  5474. var additionalData = getAdditionalData();
  5475. var flagAdditional = false;
  5476.  
  5477. if (additionalData.length > 0)
  5478. flagAdditional = true;
  5479.  
  5480. var formData = {
  5481. 'controlMessageId': controlMessageId,
  5482. 'campaignId': campaignId,
  5483. 'automationId': automationId,
  5484. 'flagAdditional': flagAdditional,
  5485. 'additionalData': additionalData,
  5486. 'apiTemplateId': apiTemplateId
  5487. };
  5488.  
  5489. var ajaxSave = $.ajax({
  5490. type: 'POST',
  5491. url: '/handleAdditional',
  5492. data: formData,
  5493. timeout: 10000
  5494. })
  5495. .done(function () {
  5496. if (afterAction != undefined && afterAction != '') {
  5497. action.verifyBehavior('success', afterAction);
  5498. }
  5499. })
  5500. .fail(function (data) {
  5501. console.log('fail');
  5502. console.log(data);
  5503. // action.verifyBehavior('fail', afterAction);
  5504. ajaxSave.abort();
  5505. // }).error(function () {
  5506. // action.verifyBehavior('fail', afterAction);
  5507. // ajaxSave.abort();
  5508. });
  5509. },
  5510.  
  5511. savePushAdresses: function (campId, controlMessageId, audiencesSelected) {
  5512. var formData = {'audiences': audiencesSelected, 'controlMessageId': controlMessageId, 'campaignId': campId};
  5513.  
  5514. var ajaxSave = $.ajax({
  5515. type: 'POST',
  5516. url: '/handlePushAdresses',
  5517. data: formData,
  5518. timeout: 10000
  5519. })
  5520. .done(function (data) {
  5521. console.log(data);
  5522. console.log('done');
  5523. })
  5524. .fail(function (data) {
  5525. console.log('fail');
  5526. console.log(data);
  5527. ajaxSave.abort();
  5528. });
  5529. },
  5530.  
  5531. saveAudience: function (audienceId, appId, showModalSuccess) {
  5532. var criteria = scriptForPage.getAudienceCriteria();
  5533. var recentAudience = 0;
  5534.  
  5535. var formData = {
  5536. 'appId': appId,
  5537. 'audienceId': audienceId,
  5538. 'audienceName': $("#componentName").val(),
  5539. 'audienceDescription': $("#componentDescription").val(),
  5540. 'criteria': criteria
  5541. };
  5542.  
  5543. var ajaxSave = $.ajax({
  5544. type: 'POST',
  5545. url: '/handleAudience',
  5546. data: formData,
  5547. async: false,
  5548. timeout: 10000
  5549. })
  5550. .done(function (data) {
  5551. console.log(data);
  5552. console.log('done');
  5553. if (showModalSuccess) {
  5554. action.verifyBehavior('success', 'saveAudience');
  5555. }
  5556. recentAudience = data;
  5557. })
  5558. .fail(function (data) {
  5559. console.log('fail');
  5560. console.log(data);
  5561. action.verifyBehavior('fail', 'saveAudience');
  5562. ajaxSave.abort();
  5563. });
  5564. return recentAudience;
  5565. },
  5566.  
  5567. saveParameterBlockLogin: function (customerId) {
  5568. var formData = {
  5569. 'customerId': customerId,
  5570. 'maxNumberRetries': $("#openInputQuantity").val(),
  5571. 'action': 'saveParameterBlockLogin'
  5572. };
  5573.  
  5574. var ajaxSave = $.ajax({
  5575. type: 'POST',
  5576. url: '/handleSecurityParameter',
  5577. data: formData,
  5578. async: false,
  5579. timeout: 10000
  5580. })
  5581. .done(function (data) {
  5582. console.log('done');
  5583. })
  5584. .fail(function (data) {
  5585. console.log('fail');
  5586. console.log(data);
  5587. action.verifyBehavior('fail', 'saveSecurityParameter');
  5588. ajaxSave.abort();
  5589. });
  5590. },
  5591.  
  5592. saveParameterChangePassword: function (customerId) {
  5593. var formData = {
  5594. 'customerId': customerId,
  5595. 'changePassword': $('.js-check-showUpChangePassword').is(':checked'),
  5596. 'action': 'saveParameterChangePassword'
  5597. };
  5598.  
  5599. var ajaxSave = $.ajax({
  5600. type: 'POST',
  5601. url: '/handleSecurityParameter',
  5602. data: formData,
  5603. async: false,
  5604. timeout: 10000
  5605. })
  5606. .done(function (data) {
  5607. console.log('done');
  5608. })
  5609. .fail(function (data) {
  5610. console.log('fail');
  5611. console.log(data);
  5612. action.verifyBehavior('fail', 'saveSecurityParameter');
  5613. ajaxSave.abort();
  5614. });
  5615. },
  5616.  
  5617. saveParameterStrengthPassword: function (customerId, strengthId) {
  5618. console.log('saveParameterStrengthPassword');
  5619. var formData = {
  5620. 'customerId': customerId,
  5621. 'passwordStrengthId': strengthId,
  5622. 'action': 'saveParameterStrengthPassword'
  5623. };
  5624.  
  5625. var ajaxSave = $.ajax({
  5626. type: 'POST',
  5627. url: '/handleSecurityParameter',
  5628. data: formData,
  5629. async: false,
  5630. timeout: 10000
  5631. })
  5632. .done(function (data) {
  5633. console.log('done');
  5634. })
  5635. .fail(function (data) {
  5636. console.log('fail');
  5637. console.log(data);
  5638. action.verifyBehavior('fail', 'saveSecurityParameter');
  5639. ajaxSave.abort();
  5640. });
  5641. },
  5642.  
  5643. saveParameterLoginScheduled: function (securityParameterId, selectedDays) {
  5644. var formData = {
  5645. 'securityParameterId': securityParameterId,
  5646. 'selectedDays': '"' + selectedDays.toString() + '"',
  5647. 'timeInit': $("#timeIntervalRange").slider("values", 0),
  5648. 'timeEnd': $("#timeIntervalRange").slider("values", 1),
  5649. 'action': 'saveParameterLoginScheduled'
  5650. };
  5651.  
  5652. var ajaxSave = $.ajax({
  5653. type: 'POST',
  5654. url: '/handleSecurityParameter',
  5655. data: formData,
  5656. async: false,
  5657. timeout: 10000
  5658. })
  5659. .done(function (data) {
  5660. console.log('done');
  5661. })
  5662. .fail(function (data) {
  5663. console.log('fail');
  5664. console.log(data);
  5665. action.verifyBehavior('fail', 'saveSecurityParameter');
  5666. ajaxSave.abort();
  5667. });
  5668. },
  5669.  
  5670. saveCollaborator: function (customerId, userName) {
  5671. if ($('#addNewEmail').val() !== '') {
  5672. var formData = {
  5673. 'customerId': customerId,
  5674. 'email': $('#addNewEmail').val(),
  5675. 'profileId': $('#addNewSelect').val(),
  5676. 'action': 'saveCollaborator'
  5677. };
  5678.  
  5679. var ajaxSave = $.ajax({
  5680. type: 'POST',
  5681. url: '/handleCollaborator',
  5682. data: formData,
  5683. async: false,
  5684. timeout: 10000
  5685. })
  5686. .done(function (data) {
  5687. var json = $.parseJSON(data);
  5688.  
  5689. if (json.success == true) {
  5690. //send invitation
  5691. action.sendInvitationCollaborator(userName);
  5692. } else {
  5693. action.verifyBehavior('fail', 'saveSecurityParameter');
  5694. }
  5695. })
  5696. .fail(function (data) {
  5697. console.log('fail');
  5698. console.log(data);
  5699. action.verifyBehavior('fail', 'saveSecurityParameter');
  5700. ajaxSave.abort();
  5701. });
  5702. }
  5703. },
  5704.  
  5705. sendInvitationCollaborator: function (userName) {
  5706. var formData = {
  5707. 'email': $('#addNewEmail').val(),
  5708. 'userName': userName,
  5709. 'action': 'sendInvite'
  5710. };
  5711.  
  5712. var ajaxSave = $.ajax({
  5713. type: 'POST',
  5714. url: '/handleCollaborator',
  5715. data: formData,
  5716. async: false,
  5717. timeout: 10000
  5718. })
  5719. .done(function (data) {
  5720. //console.log('done');
  5721. })
  5722. .fail(function (data) {
  5723. console.log('fail');
  5724. console.log(data);
  5725. action.verifyBehavior('fail', 'saveSecurityParameter');
  5726. ajaxSave.abort();
  5727. });
  5728. },
  5729.  
  5730. saveApiTemplate: function (apiTemplateId, appId) {
  5731.  
  5732. if ($('.js-check-showUpURL').is(':checked')) {
  5733. var url = $('input[name=open-url]').val();
  5734. } else {
  5735. url = '';
  5736. }
  5737.  
  5738. function getTags() {
  5739. var elements = $('.js-dataRow');
  5740. var tags = [];
  5741.  
  5742. $.each(elements, function (num, obj) {
  5743. var tag = $(obj).find('input[name="tag-value"]').val();
  5744.  
  5745. if (tag !== '') {
  5746. tags.push(tag);
  5747. }
  5748. });
  5749.  
  5750. if (tags != null && tags != '') {
  5751. return tags;
  5752. } else {
  5753. return '';
  5754. }
  5755. }
  5756.  
  5757. // var additionalData = scriptForPage.getAdditionalData();
  5758.  
  5759. var formData = {
  5760. 'apiTemplateId': apiTemplateId,
  5761. 'apiTemplateName': $("#componentName").val(),
  5762. 'apiTemplateDescription': $("#componentDescription").val(),
  5763. 'msgTitle': $('input[name=msg-title]').val(),
  5764. 'msgBody': $('#pushContent').val(),
  5765. 'urlPush': url,
  5766. 'appId': appId,
  5767. 'tags': getTags()
  5768. };
  5769.  
  5770. var ajaxSave = $.ajax({
  5771. type: 'POST',
  5772. url: '/handleApiTemplate',
  5773. data: formData,
  5774. timeout: 10000
  5775. })
  5776. .done(function (data) {
  5777. console.log('done');
  5778. console.log(data);
  5779. var json = $.parseJSON(data);
  5780.  
  5781. if (json.success == true) {
  5782. action.saveAdditionalData('', '', '', 'saveApiTemplate', json.apiId);
  5783. // action.verifyBehavior('success', 'saveApiTemplate');
  5784. } else {
  5785. console.log(data.error);
  5786. // action.verifyBehavior('fail', 'saveApiTemplate');
  5787. }
  5788.  
  5789. })
  5790. .fail(function (data) {
  5791. console.log('fail');
  5792. console.log(data);
  5793. action.verifyBehavior('fail', 'saveApiTemplate');
  5794. ajaxSave.abort();
  5795. });
  5796. },
  5797.  
  5798. findReachAudience: function (appId) {
  5799. var criteria = scriptForPage.getAudienceCriteria();
  5800.  
  5801. if (criteria.length > 0) {
  5802. $.ajax({
  5803. type: 'POST',
  5804. url: '/handleRangeAudience',
  5805. data: {'criteria': criteria, 'appId': appId},
  5806. dataType: 'json',
  5807. encode: true
  5808. })
  5809. .done(function (data) {
  5810. if (data.success) {
  5811. /*console.log('query:');
  5812. console.log(data.query);*/
  5813. console.log(data);
  5814. $("#rangeNumber").text(data.result);
  5815. }
  5816. })
  5817. .fail(function () {
  5818. console.log('fail');
  5819. });
  5820. }
  5821. },
  5822.  
  5823. inactivateAudience: function (audienceId) {
  5824.  
  5825. var formData = {
  5826. 'audienceId': audienceId
  5827. };
  5828.  
  5829. var ajaxSave = $.ajax({
  5830. type: 'POST',
  5831. url: '/handleInactivateAudience',
  5832. data: formData,
  5833. dataType: 'json',
  5834. encode: true,
  5835. timeout: 10000
  5836. })
  5837. .done(function (data) {
  5838. console.log(data);
  5839. console.log('done');
  5840. action.verifyBehavior('success', 'inactivateAudience');
  5841. })
  5842. .fail(function (data) {
  5843. console.log('fail');
  5844. console.log(data);
  5845. action.verifyBehavior('fail', 'saveAudience');
  5846. }).error(function () {
  5847. console.log('error');
  5848. action.verifyBehavior('fail', 'saveAudience');
  5849. ajaxSave.abort();
  5850. });
  5851. },
  5852.  
  5853. getSubscribersAudience: function (audiencesSelected) {
  5854. var data = {'audiencesSelected': audiencesSelected};
  5855.  
  5856. // if(data.findIndex())
  5857.  
  5858. console.log(data);
  5859.  
  5860. var ajaxSend = $.ajax({
  5861. type: 'POST',
  5862. url: '/handleSubscribersAudience',
  5863. data: data,
  5864. dataType: 'json',
  5865. encode: true,
  5866. timeout: 10000
  5867. })
  5868. .done(function (data) {
  5869. var qtyLocalFormat = parseInt(data.quantitySubscribers).toLocaleString(locale);
  5870. $('.range-full-number').html(qtyLocalFormat);
  5871. $('#qtRecipients').html(qtyLocalFormat);
  5872. })
  5873. .fail(function (data) {
  5874. // show any errors
  5875. // best to remove for production
  5876. console.log('fail');
  5877. console.log(data);
  5878. $('.range-full-number').html('-');
  5879. $('#qtRecipients').html('-');
  5880. ajaxSend.abort();
  5881. });
  5882. },
  5883.  
  5884. saveAutomation: function (appId, campId, automationId, audiencesSelected, timeInit, timeEnd, selectedDays) {
  5885. var statusId = 1; //ativo
  5886.  
  5887. var formData = {
  5888. 'automationId': automationId,
  5889. 'campId': campId,
  5890. 'name': $('#componentName').val(),
  5891. 'description': $('#componentDescription').val(),
  5892. 'statusId': statusId,
  5893. 'appId': appId,
  5894. 'action': 'saveAutomation'
  5895. };
  5896. var ajaxSave = $.ajax({
  5897. type: 'POST',
  5898. url: '/handleAutomation',
  5899. data: formData,
  5900. timeout: 10000
  5901. })
  5902. .done(function (data) {
  5903. var objJson = $.parseJSON(data);
  5904. if (objJson.success) {
  5905. action.saveAutomationAudience(objJson.automation_id, audiencesSelected, timeInit, timeEnd, selectedDays);
  5906. } else {
  5907. action.verifyBehavior('fail', 'saveAutomation');
  5908. }
  5909. })
  5910. .fail(function () {
  5911. console.log('fail');
  5912. action.verifyBehavior('fail', 'saveAutomation');
  5913. }).error(function () {
  5914. action.verifyBehavior('fail', 'saveAutomation');
  5915. ajaxSave.abort();
  5916. });
  5917. },
  5918.  
  5919. saveAutomationScheduled: function (automationId, timeInit, timeEnd, selectedDays) {
  5920. var formData = {
  5921. 'automationId': automationId,
  5922. 'selectedDays': selectedDays,
  5923. 'timeInit': timeInit,
  5924. 'timeEnd': timeEnd,
  5925. 'action': 'automationScheduled'
  5926. };
  5927.  
  5928. var ajaxSave = $.ajax({
  5929. type: 'POST',
  5930. url: '/handleAutomation',
  5931. data: formData,
  5932. timeout: 10000
  5933. })
  5934. .done(function (data) {
  5935. var objJson = $.parseJSON(data);
  5936. if (objJson.success) {
  5937. action.saveAdditionalData(0, 0, automationId, 'saveAutomation');
  5938. }
  5939. })
  5940. .fail(function () {
  5941. console.log('fail');
  5942. action.verifyBehavior('fail', 'saveAutomation');
  5943. }).error(function () {
  5944. action.verifyBehavior('fail', 'saveAutomation');
  5945. ajaxSave.abort();
  5946. });
  5947. },
  5948.  
  5949. saveAutomationAudience: function (automationId, audiencesSelected, timeInit, timeEnd, selectedDays) {
  5950. if (parseInt(audiencesSelected) > 0) {
  5951. var formData = {
  5952. 'audiences': audiencesSelected,
  5953. 'automationId': automationId,
  5954. 'action': 'automationAudience'
  5955. };
  5956.  
  5957. var ajaxSave = $.ajax({
  5958. type: 'POST',
  5959. url: '/handleAutomation',
  5960. data: formData,
  5961. timeout: 10000
  5962. })
  5963. .done(function (data) {
  5964. var objJson = $.parseJSON(data);
  5965. if (objJson.success) {
  5966. action.saveAutomationCriteria(automationId, timeInit, timeEnd, selectedDays);
  5967. } else {
  5968. action.verifyBehavior('fail', 'saveAutomation');
  5969. }
  5970. })
  5971. .fail(function (data) {
  5972. console.log('fail');
  5973. console.log(data);
  5974. action.verifyBehavior('fail', 'saveAutomation');
  5975. ajaxSave.abort();
  5976. });
  5977. } else {
  5978. action.saveAutomationCriteria(automationId, timeInit, timeEnd, selectedDays);
  5979. }
  5980. },
  5981.  
  5982. saveAutomationCriteria: function (automationId, timeInit, timeEnd, selectedDays) {
  5983. var criteria = scriptForPage.getAudienceCriteria();
  5984.  
  5985. if (criteria.length > 0) {
  5986. var formData = {
  5987. 'automationId': automationId,
  5988. 'criteria': criteria,
  5989. 'action': 'pushCriteria'
  5990. };
  5991.  
  5992. $.ajax({
  5993. type: 'POST',
  5994. url: '/handleAutomation',
  5995. data: formData,
  5996. timeout: 10000
  5997. })
  5998. .done(function (data) {
  5999. console.log(data);
  6000. var objJson = $.parseJSON(data);
  6001. if (objJson.success) {
  6002. action.saveAutomationScheduled(automationId, timeInit, timeEnd, selectedDays);
  6003. } else {
  6004. action.verifyBehavior('fail', 'saveAutomation');
  6005. }
  6006. })
  6007. .fail(function () {
  6008. console.log('fail');
  6009. action.verifyBehavior('fail', 'saveAutomation');
  6010. });
  6011. } else {
  6012. action.saveAutomationScheduled(automationId, timeInit, timeEnd, selectedDays);
  6013. }
  6014. },
  6015.  
  6016. /*
  6017. * This method paginate the page
  6018. *
  6019. * @param string container Where the retrieved data should be put
  6020. * @param string target What is the target URL
  6021. * @param string rowNumber
  6022. * @param JSON data parameters to send with GET
  6023. *
  6024. * return AJAX fill the container with retrieved data
  6025. *
  6026. * */
  6027. paginate: function (container, target, rowNumber) {
  6028.  
  6029. var viewsPerPage = $("#viewsPerPage").val();
  6030. if (viewsPerPage == undefined || viewsPerPage == '') {
  6031. viewsPerPage = 15;
  6032. }
  6033.  
  6034. var params = 'viewsPerPage=' + viewsPerPage + '&rowNumber=' + rowNumber;
  6035.  
  6036. // look for params in the url, if there is params just insert the page params, else create new params field
  6037. if (target.search('/?') == -1) {
  6038. params = '?' + params;
  6039. } else {
  6040. params = '&' + params;
  6041. }
  6042.  
  6043. var targetURL = '/' + target + params;
  6044. window.scrollTo(0, 0);
  6045. $(container).load(targetURL).hide().fadeIn('300');
  6046. console.log(targetURL);
  6047. console.log(params);
  6048. },
  6049.  
  6050. download: function (text, name, type) {
  6051. var a = document.createElement("a");
  6052. if (type == 'csv') {
  6053. var file = new Blob([text], {type: 'text/plain'});
  6054. a.href = URL.createObjectURL(file);
  6055. } else if (type == 'xls') {
  6056. a.href = text;
  6057. }
  6058. a.download = name;
  6059. a.click();
  6060. a.remove();
  6061. }
  6062. };
  6063.  
  6064. var transform = {
  6065.  
  6066. /* Get all checkbox inputs with class '.js-switch' and put their design like iOS7 */
  6067. iOSswitch: function () {
  6068. var checkboxes = Array.prototype.slice.call(document.querySelectorAll('.js-switch'));
  6069.  
  6070. checkboxes.forEach(function (html) {
  6071. var switchery = new Switchery(html, {size: 'small', secondaryColor: '#DFDFDF'});
  6072. });
  6073. },
  6074.  
  6075. /* Style the select element
  6076. * This is used to personalize the select element of sign up page
  6077. *
  6078. * Have to add this on the page (Theter and Select):
  6079. * <link rel="stylesheet" href="select-theme-default.css" />
  6080. * <script src="tether.min.js"></script>
  6081. * <script src="select.min.js"></script>
  6082. *
  6083. * Then use this code here to use a placeholder and style the element.
  6084. *
  6085. * selectID must be just an ID NAME
  6086. *
  6087. * More info: http://github.hubspot.com/select/docs/welcome/
  6088. */
  6089. customSelect: function (selectID) {
  6090. if (selectID.charAt(0) == '#' || selectID.charAt(0) == '.') {
  6091. selectID = selectID.substr(1);
  6092. }
  6093.  
  6094. var element = document.getElementById(selectID);
  6095. var select = new Select({
  6096. el: element,
  6097. className: 'select-theme-inngage'
  6098. });
  6099.  
  6100. function addOptGroup() {
  6101. var optgroup = $(element).find('optgroup');
  6102.  
  6103. $.each(optgroup, function (index, obj) {
  6104. var optgroupLabel = $(obj).attr('label');
  6105. var addElement = '<div class="custom-optgroup">' + optgroupLabel + '</div>';
  6106.  
  6107. var nextElemValue = ($(obj).children().first()).val();
  6108. var searchOption = 'li[data-value=' + nextElemValue + ']';
  6109.  
  6110. $(select.drop).find(searchOption).before(addElement);
  6111. });
  6112. }
  6113.  
  6114. addOptGroup();
  6115.  
  6116. select.on('change', function () {
  6117. addOptGroup();
  6118. });
  6119.  
  6120. return select;
  6121. },
  6122.  
  6123. emojiPicker: function () {
  6124. // Initializes and creates emoji set from sprite sheet
  6125. window.emojiPicker = new EmojiPicker({
  6126. emojiable_selector: '[data-emojiable=true]',
  6127. assetsPath: ref.getPlugins + '/emoji-area/img/',
  6128. popupButtonClasses: 'fa fa-smile-o',
  6129. iconSize: 19,
  6130. norealTime: false
  6131. });
  6132. // Finds all elements with `emojiable_selector` and converts them to rich emoji input fields
  6133. // You may want to delay this step if you have dynamically created input fields that appear later in the loading process
  6134. // It can be called as many times as necessary; previously converted input fields will not be converted again
  6135. window.emojiPicker.discover();
  6136. },
  6137.  
  6138. counter: function (decimal) {
  6139. $('.js-count').each(function () {
  6140. $(this).stop();
  6141. var value = $(this).text();
  6142.  
  6143. $(this).prop('Counter', 0).animate({
  6144. Counter: $(this).text()
  6145. }, {
  6146. duration: 1000,
  6147. easing: 'easeOutQuart',
  6148. step: function (now) {
  6149. $(this).text(now.toLocaleString(locale, {maximumFractionDigits: decimal}));
  6150. },
  6151. complete: function () {
  6152. $(this).text(value);
  6153. transform.breakThousandsId([$(this)]);
  6154. }
  6155. });
  6156. });
  6157. },
  6158.  
  6159. /* Convert a message with emoji in Unicode format to rich text
  6160. *
  6161. * @param obj Object which has the message, may be json, string...
  6162. * @param selector Where to insert the new message with images
  6163. * @param countIndex boolean True if the obj is a json or array and must use the index to identify the selector
  6164. * */
  6165. unicodeToEmoji: function (obj, selector, countIndex) {
  6166.  
  6167. // transform.emojiPicker();
  6168. window.emojiPicker.discover();
  6169.  
  6170. if (countIndex == true) {
  6171. $.each(obj, function (index, elem) {
  6172. $(selector + index).html(window.emojiPicker.unicodeToImage(elem));
  6173. // console.log(elem);
  6174. });
  6175. } else {
  6176. $(selector).html(window.emojiPicker.unicodeToImage(obj));
  6177. }
  6178. },
  6179.  
  6180. /*
  6181. * @param boolean countIndex If the obj has to be count with an "index" increment
  6182. * */
  6183. colonToEmoji: function (obj, selector, countIndex) {
  6184.  
  6185. transform.emojiPicker();
  6186. window.emojiPicker.discover();
  6187.  
  6188. if (countIndex == true) {
  6189. $.each(obj, function (index, elem) {
  6190. $(selector + index).html(window.emojiPicker.colonToImage(elem));
  6191. });
  6192.  
  6193. } else {
  6194. $(selector).html(window.emojiPicker.colonToImage(obj));
  6195. }
  6196. },
  6197.  
  6198. highlightAppMenu: function () {
  6199. var path = (window.location.pathname).substr(1);
  6200. var dirs = path.split('/');
  6201.  
  6202. $.each(dirs, function (index, val) {
  6203. var name = val.split('-');
  6204. for (var i = 1; i < name.length; i++) {
  6205. var firstLetter = name[i].substring(0, 1);
  6206. name[i] = name[i].replace(firstLetter, firstLetter.toUpperCase());
  6207. }
  6208. dirs[index] = name.join('');
  6209. });
  6210.  
  6211. var pageGroup = '#' + dirs[1];
  6212. var page = '#' + dirs[2];
  6213.  
  6214. $(pageGroup).addClass('nav-side-title-selected');
  6215. if (page) {
  6216. var obj = $(page);
  6217. obj.addClass('nav-side-item-selected');
  6218. }
  6219. },
  6220.  
  6221. highlightSubMenu: function (menuItem) {
  6222. $(menuItem).addClass('nav-side-item-selected');
  6223. },
  6224.  
  6225. /* API to work with tawk.to */
  6226. tawkChat: function () {
  6227. function tawkChatAPI() {
  6228. var Tawk_API = Tawk_API || {}, Tawk_LoadStart = new Date();
  6229. (function () {
  6230. var s1 = document.createElement("script"), s0 = document.getElementsByTagName("script")[0];
  6231. s1.async = true;
  6232. s1.src = 'https://embed.tawk.to/5782b19274888c1b4a85ea3e/default';
  6233. s1.charset = 'UTF-8';
  6234. s1.setAttribute('crossorigin', '*');
  6235. s0.parentNode.insertBefore(s1, s0);
  6236. })();
  6237. }
  6238.  
  6239. tawkChatAPI.call(window);
  6240. },
  6241.  
  6242. /*
  6243. * Separate thousands
  6244. *
  6245. * @param array identificators array of any kind of selector as string
  6246. * @return null
  6247. * */
  6248. breakThousandsId: function (identificators) {
  6249. $.each(identificators, function (key, obj) {
  6250. var number = Number($(obj).html());
  6251. $(obj).html(number.toLocaleString(locale));
  6252. });
  6253. }
  6254.  
  6255. };
  6256.  
  6257. var modal = {
  6258.  
  6259. scrollPosition: 0,
  6260.  
  6261. /* Close block if ESC is pressed */
  6262. typeKeyboardBehavior: function () {
  6263. $(document).on('keyup.keyBlock', function (e) {
  6264. e.stopPropagation();
  6265. if (e.keyCode == 27) {
  6266. modal.closeModal();
  6267. }
  6268. if (e.keyCode == 13) {
  6269. e.preventDefault();
  6270. $('.modal button[type=submit]').first().trigger('click');
  6271. }
  6272. });
  6273. },
  6274.  
  6275. getGrayCover: function () {
  6276. var grayCover = "<div class='gray-cover'></div>";
  6277. $(".modal-container").prepend(grayCover);
  6278. $("body").children("*:not(.gray-cover, .modal-container, .emoji-menu, .tether-element)").addClass("blur");
  6279. $("body,html").css({overflow: "hidden"});
  6280. window.scrollTo(0, 0);
  6281. },
  6282.  
  6283. /**
  6284. * Closes all modals on screen
  6285. * If you need to open another modal after the first is called, pass a object parameter with the data as:
  6286. *
  6287. * @param nextModal array Modal to be opened with options:
  6288. * [file, noClose, data]
  6289. * */
  6290. closeModal: function (nextModal) {
  6291. $('.modal-resource').remove();
  6292. $('.emoji-menu').not(':eq(0)').remove();
  6293. $("*").removeClass("blur");
  6294.  
  6295. function getNextModal() {
  6296. if (nextModal != undefined) {
  6297. var opt = [];
  6298. $.each(nextModal, function (key, value) {
  6299. opt[key] = value;
  6300. });
  6301. modal.getModal(opt[0], opt[1], opt[2]);
  6302. }
  6303. }
  6304.  
  6305. if ($(".modal-container").length != 0) {
  6306.  
  6307. $(".modal-container").fadeOut(300, function () {
  6308. $(window).scrollTop(modal.scrollPosition);
  6309. $('.interferingStyleSheet').prop('disabled', false);
  6310. $(this).remove();
  6311. getNextModal();
  6312. });
  6313.  
  6314. } else {
  6315. getNextModal();
  6316. }
  6317.  
  6318. $("body,html").css({overflow: "visible"});
  6319. $(document).off('keyup.keyBlock');
  6320. getData = window.previousGetData;
  6321. },
  6322.  
  6323. /**
  6324. * Closes all modals on screen and back to previous page
  6325. * */
  6326. backPage: function () {
  6327. modal.closeModal();
  6328. history.back();
  6329. },
  6330.  
  6331. reposition: function () {
  6332. $('.modal-container').css({top: $(window).scrollTop()});
  6333.  
  6334. var block = $('.modal');
  6335. var height = block.height();
  6336. var winHeight = $(window).height();
  6337. if (winHeight < height + 50) {
  6338. var top = 59.5;
  6339. grayHeight = (block.outerHeight(true) + top) + 'px';
  6340. } else {
  6341. top = (winHeight - height) / 2;
  6342. var grayHeight = '100vh';
  6343. }
  6344. var topPixels = top + 'px';
  6345. block.css({top: topPixels});
  6346.  
  6347. $('.gray-cover').css({height: grayHeight});
  6348. document.getElementsByClassName('modal-container')[0].scrollTop = 0;
  6349. },
  6350.  
  6351. modal: function () {
  6352. this.typeKeyboardBehavior();
  6353. this.getGrayCover();
  6354. },
  6355.  
  6356. /*
  6357. * file to be opened
  6358. * noClose boolean is it to be closed on out click or not?
  6359. * data JSON any data to be passed to the block
  6360. * */
  6361. getModal: function (file, noClose, data) {
  6362. console.log('inicio');
  6363. modal.scrollPosition = $(window).scrollTop();
  6364. // console.log(getData);
  6365. if (typeof(getData) != "undefined") {
  6366. window.previousGetData = getData;
  6367. }
  6368.  
  6369. $.post(ref.getIncludes + "/modal/" + file, data, function (code) {
  6370.  
  6371. $(document).ready(function () {
  6372. // code.replace('\<script', '\<script class="modal-resource"');
  6373. // code.replace('<style', '<style class="modal-resource"');
  6374. console.log('ready');
  6375. $("body").prepend(code);
  6376.  
  6377. modal.modal();
  6378. $('.modal').find('button:only-of-type').focus();
  6379. $('.modal').find('input').focus();
  6380.  
  6381. modal.reposition();
  6382. // reposition modal when screen is resized
  6383. $(window).on('resize', function () {
  6384. modal.reposition();
  6385. });
  6386.  
  6387. // the modal is not to be closed by the user (ex: LOADING EVENT)
  6388. if (noClose) {
  6389. $(document).off('keyup.keyBlock');
  6390. } else {
  6391. $('.gray-cover').on('click', function () {
  6392. modal.closeModal();
  6393. });
  6394. }
  6395.  
  6396. /* observe for node manipulation in the modal to resize it if needed */
  6397. var modalObserver = new MutationObserver(function () {
  6398. modal.reposition();
  6399. });
  6400. modalObserver.observe(document.getElementsByClassName('modal')[0], {childList: true, subtree: true});
  6401.  
  6402. // so it don't close when clicked (don't trigger .block-container)
  6403. // $('.modal').on('click', function (e) {
  6404. // console.log(e);
  6405. // e.stopPropagation();
  6406. // });
  6407.  
  6408. });
  6409.  
  6410. });
  6411. }
  6412. };
  6413.  
  6414. var balloon = {
  6415.  
  6416. //close balloon. Pass the balloon ID to close
  6417. closeBalloon: function (id) {
  6418. $(id).hide();
  6419. }
  6420. };
  6421.  
  6422.  
  6423. /* OPEN CONTENTS
  6424. * Procedures to navigate through pages
  6425. * For the window.popstate to work properly, keep the object names the same as the corresponding folders
  6426. * */
  6427. var navigateTo = {
  6428.  
  6429. //MAIN - MY APPS
  6430. myApps: function () {
  6431. window.open('/main-dashboard', '_self');
  6432. },
  6433.  
  6434. // APP PAGE: Run this before opening an item in menu-side
  6435. procedure: function (title, path, item, callback) {
  6436. appHeader.hide();
  6437. $('.select-theme-inngage').remove(); // clean all select DIV created
  6438. $('.modal-resource').remove(); // clean all modal resources (script and style tags)
  6439. $('.js-clean-resource').remove(); // clean all resources not used (script and style tags)
  6440. $('.tether-element').remove(); // clean all resources from TETHER plugin
  6441. $('.select-theme-inngage').remove(); // clean all resources from SELECT plugin
  6442. // $('.emoji-menu').not(':eq(0)').remove(); // clean all emoji menus created
  6443. $('.emoji-menu').remove(); // clean all emoji menus created
  6444. $('.ui-datepicker').remove(); // clean all datepickers
  6445.  
  6446. $('.nav-side-title-selected').removeClass('nav-side-title-selected');
  6447. $('.nav-side-item-selected').removeClass('nav-side-item-selected');
  6448.  
  6449. $(title).addClass('nav-side-title-selected');
  6450. if (item) {
  6451. var obj = $(item);
  6452. obj.addClass('nav-side-item-selected');
  6453. }
  6454.  
  6455. var appToken = window.location.search;
  6456.  
  6457. if (history.state) {
  6458. if (history.state['inn'] != path) {
  6459. history.pushState({'inn': path}, '', '/app' + path + appToken);
  6460. }
  6461. } else {
  6462. history.pushState({'inn': path}, '', '/app' + path + appToken);
  6463. }
  6464.  
  6465. contentContainer.load(ref.getAppPg + path, function () {
  6466. window.scrollTo(0, 0); //if page was scrolled down, then go back to top
  6467. if (callback != undefined && callback != '') {
  6468. callback();
  6469. }
  6470. });
  6471. },
  6472.  
  6473. app: {
  6474. //APP-DASHBOARD
  6475. dashboard: function () {
  6476. navigateTo.procedure('#dashboard', '/dashboard');
  6477. contentContainer.empty();
  6478. appHeader.load(ref.getIncludes + '/app-pg/dashboard/app-header.php').show();
  6479. },
  6480.  
  6481. audience: {
  6482. title: '#audience',
  6483.  
  6484. audiences: function () {
  6485. navigateTo.procedure(this.title, "/audience/audiences", "#audiences");
  6486. },
  6487. newAudience: function () {
  6488. navigateTo.procedure(this.title, "/audience/new-audience", "#audiences");
  6489. },
  6490. subscribers: function () {
  6491. navigateTo.procedure(this.title, "/audience/subscribers", "#subscribers");
  6492. },
  6493. importData: function () {
  6494. navigateTo.procedure(this.title, "/audience/import-data");
  6495. }
  6496. },
  6497.  
  6498. push: {
  6499. title: '#push',
  6500.  
  6501. campaigns: function () {
  6502. navigateTo.procedure(this.title, "/push/campaigns", '#campaigns');
  6503. },
  6504. newCampaign: function () {
  6505. navigateTo.procedure(this.title, "/push/new-campaign", '#campaigns');
  6506. },
  6507. sendPush: function () {
  6508. navigateTo.procedure(this.title, "/push/send-push", '#sendPush');
  6509. },
  6510. notificationsSent: function () {
  6511. navigateTo.procedure(this.title, "/push/notifications-sent", '#sendPush');
  6512. },
  6513. notificationsScheduled: function () {
  6514. navigateTo.procedure(this.title, "/push/notification-scheduled", '#sendPush');
  6515. },
  6516. directMail: function () {
  6517. navigateTo.procedure(this.title, "/push/direct-mail");
  6518. },
  6519. automations: function () {
  6520. navigateTo.procedure(this.title, "/push/automations", '#automations');
  6521. },
  6522. newAutomation: function () {
  6523. navigateTo.procedure(this.title, "/push/new-automation", '#automations');
  6524. },
  6525. apiTemplate: function () {
  6526. navigateTo.procedure(this.title, "/push/api-template", '#apiTemplate');
  6527. },
  6528. newApiTemplate: function () {
  6529. navigateTo.procedure(this.title, "/push/new-api-template", '#apiTemplate');
  6530. },
  6531. },
  6532.  
  6533. status: {
  6534. title: '#status',
  6535.  
  6536. sent: function () {
  6537. navigateTo.procedure(this.title, "/status/sent", '#sent');
  6538. },
  6539. scheduled: function () {
  6540. navigateTo.procedure(this.title, "/status/scheduled", '#scheduled');
  6541. },
  6542. sentApi: function () {
  6543. navigateTo.procedure(this.title, "/status/sent-api");
  6544. },
  6545. autosent: function () {
  6546. navigateTo.procedure(this.title, "/status/autosent", '#autosent');
  6547. }
  6548. },
  6549.  
  6550. configuration: {
  6551. title: '#configuration',
  6552.  
  6553. general: function () {
  6554. navigateTo.procedure(this.title, "/configuration/general", '#general');
  6555.  
  6556. },
  6557. platform: function () {
  6558. navigateTo.procedure(this.title, "/configuration/platform", "#platform");
  6559. },
  6560. fontCode: function () {
  6561. // navigateTo.procedure(this.title, "/configuration/(UNUSED) font-code", '#fontCode');
  6562. window.open('https://inngage.readme.io/');
  6563. },
  6564. team: function () {
  6565. navigateTo.procedure(this.title, "/configuration/team", '#team');
  6566. }
  6567. }
  6568. },
  6569.  
  6570. appPopState: function () {
  6571. var path = (window.location.pathname).substr(1);
  6572. var dirs = path.split('/');
  6573.  
  6574. $.each(dirs, function (index, val) {
  6575. var name = val.split('-');
  6576. for (var i = 1; i < name.length; i++) {
  6577. var firstLetter = name[i].substring(0, 1);
  6578. name[i] = name[i].replace(firstLetter, firstLetter.toUpperCase());
  6579. }
  6580. dirs[index] = name.join('');
  6581. });
  6582.  
  6583. var pageGroup = dirs[1];
  6584. var page = dirs[2];
  6585.  
  6586. if (page) {
  6587. window['navigateTo']['app'][pageGroup][page]();
  6588. } else {
  6589. window['navigateTo']['app'][pageGroup]();
  6590. }
  6591. }
  6592. };
  6593.  
  6594. /* Start immediately */
  6595. $(document).ready(function () {
  6596. behaviors.autoTextArea();
  6597. });
  6598.  
  6599.  
  6600. var scriptForPage = {
  6601.  
  6602. showConditionField: function (rowId, varType) {
  6603. $(rowId).find('.js-condition').hide();
  6604. $(rowId).find('.js-' + varType + '-condition').css({display: 'inline-block'});
  6605. },
  6606.  
  6607. newAudience: function (audienceId, audienceJson, criteriaJson, appId, insertEventsFooter) {
  6608.  
  6609. var num = 0;
  6610. var conditionNumber = 0;
  6611.  
  6612. function insertNewCondition(context) {
  6613. var thisNum = num;
  6614. conditionNumber++;
  6615. num++; //increment the number of conditions
  6616.  
  6617. var clone = $(context.find('#jsNewConditionRow')).clone();
  6618. // PREPARE THE CLONED ELEMENT
  6619. var rowId = 'jsConditionRow' + thisNum;
  6620. clone.attr('id', rowId).removeClass('js-new-condition-row').addClass('js-condition-row');
  6621. clone.find('#removeCondition').attr('id', 'removeCondition' + thisNum);
  6622. $.each($(clone.find('.js-select')), function (index, elem) {
  6623. $(elem).attr('id', 'select' + thisNum + index);
  6624. });
  6625. $.each($(clone.find('input[name=val]')), function (index, elem) {
  6626. $(elem).attr('id', 'val' + thisNum + index);
  6627. });
  6628. clone.find('.element-counter').text(conditionNumber);
  6629. clone.find('.true-false-tab').attr('id', 'trueFalse' + thisNum);
  6630. $.each($(clone.find('.date')), function (index, elem) {
  6631. $(elem).attr('id', 'date' + thisNum + index);
  6632. $(elem).datepicker({
  6633. format: 'dd/mm/yyyy',
  6634. language: locale,
  6635. beforeShow: function (input, obj) {
  6636. // $(input).after($(input).datepicker('widget'));
  6637. // $(input).datepicker("refresh");
  6638. $('.ui-datepicker').removeClass('blur');
  6639. },
  6640. onSelect: function (textData, objDatepicker) {
  6641. action.findReachAudience(appId);
  6642. }
  6643. });
  6644. });
  6645.  
  6646. //INSERT THE PREPARED ELEMENT
  6647. clone.insertBefore(context.find('.js-newCondition')); // use class because of the elements order in modal-new-audience
  6648.  
  6649.  
  6650. //DEFINE BEHAVIORS
  6651. $.each($('#' + rowId).find('.js-select'), function (index, elem) {
  6652. transform.customSelect('select' + thisNum + index);
  6653. $('#select' + thisNum + index).change(function () {
  6654. $(this).next('a').css({color: 'inherit'});
  6655. });
  6656. });
  6657. $('#select' + thisNum + 0).on('change', function () {
  6658. var varType = $(this).find('option[value=' + $(this).val() + ']').attr('data-type');
  6659. scriptForPage.showConditionField('#' + rowId, varType);
  6660. action.findReachAudience(appId);
  6661. });
  6662. var tab = $("#trueFalse" + thisNum).tabs();
  6663.  
  6664. // Set dateInput on change to refresh range
  6665. var dateInput = $('#date' + thisNum + 0);
  6666. dateInput.on('change', function () {
  6667. action.findReachAudience(appId);
  6668. });
  6669. // Date behavior: hide or change the condition input field
  6670. $('#select' + thisNum + 3).on('change', function () {
  6671. var dateType = $(this).val();
  6672. // show Datepicker
  6673. if (dateType <= 13) {
  6674. dateInput.datepicker({
  6675. format: 'dd/mm/yyyy',
  6676. language: locale,
  6677. onSelect: function (textData, objDatepicker) {
  6678. action.findReachAudience(appId);
  6679. }
  6680. });
  6681. dateInput.parent().show(); // show the span with the input
  6682. dateInput.attr('type', 'text').removeClass('days-input');
  6683. $(dateInput.next('span')).css({'display': 'none'});
  6684. // show int and span "Days"
  6685. } else if (dateType <= 16) {
  6686. dateInput.datepicker('destroy');
  6687. dateInput.parent().show();
  6688. dateInput.attr('type', 'number').attr('placeholder', 'Número de dias').addClass('days-input');
  6689. $(dateInput.next('span')).css({'display': 'inline-block'});
  6690. // don't show
  6691. } else if (dateType == 17) {
  6692. $(dateInput.parent()).css({'display': 'none'});
  6693. dateInput.attr('type', 'text').val('today'); // hide the span with the input
  6694. }
  6695. });
  6696.  
  6697. $('#removeCondition' + thisNum).hover(function () {
  6698. behaviors.svgChangeTo.hover($(this).children('img'));
  6699. }, function () {
  6700. behaviors.svgChangeTo.hover($(this).children('img'));
  6701. }).click(function () {
  6702. $(this).parents('.filter-row').remove();
  6703. $.each(context.find('.element-counter'), function (index, elem) {
  6704. $(elem).html(index + 1);
  6705. });
  6706. conditionNumber--;
  6707. if (conditionNumber == 1) {
  6708. $('.remove-icon').fadeOut(200);
  6709. }
  6710. action.findReachAudience(appId);
  6711. });
  6712.  
  6713. // show remove-icon again
  6714. if (conditionNumber > 1) {
  6715. $('.remove-icon').fadeIn(100);
  6716. }
  6717.  
  6718. insertEventToFindReachAudience(appId);
  6719. }
  6720.  
  6721. insertNewCondition($('#addNewCondition').parents('.filter-panel')); // start with a condition row
  6722.  
  6723. $('#addNewCondition').hover(function () {
  6724. $('#plus').addClass('hover-green');
  6725. $(this).css({fontWeight: '400'});
  6726. behaviors.svgChangeTo.hover($(this).children('img'));
  6727. }, function () {
  6728. $('#plus').removeClass('hover-green');
  6729. $(this).attr('style', '');
  6730. behaviors.svgChangeTo.hover($(this).children('img'));
  6731. }).click(function () {
  6732. insertNewCondition($(this).parents('.filter-panel'));
  6733. });
  6734.  
  6735. function insertEventToFindReachAudience(appId) {
  6736. var elements = $(".js-condition-row");
  6737.  
  6738. for (var i = 0; i < elements.length; i++) {
  6739. var row = "#" + elements[i].id;
  6740.  
  6741. $(row).find('select[name=operator]').on('change', function () {
  6742. action.findReachAudience(appId);
  6743. });
  6744.  
  6745. $(row).find('.ui-state-default').on('click', function () {
  6746. action.findReachAudience(appId);
  6747. });
  6748.  
  6749. $(row).find('input[name=val]').on('change', function () {
  6750. action.findReachAudience(appId);
  6751. });
  6752. }
  6753. }
  6754.  
  6755. populateAudience(audienceId, audienceJson, criteriaJson, appId);
  6756.  
  6757. function populateAudience(audienceId, audienceJson, criteriaJson, appId) {
  6758. if (audienceId > 0) {
  6759. var audienceName = audienceJson['audience_name'];
  6760. var audienceDescription = audienceJson['audience_description'];
  6761.  
  6762. populateAudienceCriteria(criteriaJson);
  6763.  
  6764. $('#componentName').val(audienceName);
  6765. $('#componentDescription').val(audienceDescription);
  6766.  
  6767. action.findReachAudience(appId);
  6768.  
  6769. $('.page-title').html(audienceName);
  6770. }
  6771. }
  6772.  
  6773. function populateAudienceCriteria(criteriaJson) {
  6774. if (criteriaJson) {
  6775. var i = 0;
  6776. $.each(criteriaJson, function (index, value) {
  6777. if ((i > 0) && (value !== null) && (value !== undefined)) {
  6778. $("#addNewCondition").trigger("click");
  6779. }
  6780. var selectField = $("#select" + i + "0").attr('value', value.audience_criteria_id);
  6781. selectField.val(value.audience_field_id);
  6782. selectField.next('a').css({color: 'inherit'});
  6783.  
  6784. var varType = selectField.find('option[value=' + selectField.val() + ']').attr('data-type');
  6785. scriptForPage.showConditionField('#jsConditionRow' + i, varType);
  6786.  
  6787. var objectTypeCondition = $('#jsConditionRow' + i).find('.js-' + varType + '-condition');
  6788.  
  6789. if (varType == 'boolean') {
  6790. objectTypeCondition.find('a[href="#' + value.audience_value + '"]').trigger('click');
  6791. } else {
  6792. objectTypeCondition.find('select[name=operator]').val(value.audience_field_condition_id);
  6793. objectTypeCondition.find('select[name=operator]').attr('value', value.audience_field_condition_id);
  6794. objectTypeCondition.find('select[name=operator]').next('a').css({color: 'inherit'});
  6795.  
  6796. objectTypeCondition.find('input[name=val]').val(value.audience_value);
  6797. }
  6798. i++;
  6799. });
  6800. }
  6801. }
  6802.  
  6803. if (insertEventsFooter) {
  6804. $('#footerSave').on('click', function () {
  6805. if ((validate.field('#componentName', 'Qual o nome da sua audiência?')) && (validate.fieldsAudienceCriteria(true))) {
  6806. action.saveAudience(audienceId, appId, true);
  6807. }
  6808. });
  6809.  
  6810. $('#footerCancel').on('click', function () {
  6811. navigateTo.app.audience.audiences();
  6812. });
  6813. }
  6814.  
  6815. },
  6816.  
  6817. dashboard: function () {
  6818.  
  6819. $('#selectAudience').on('change', function () {
  6820. getData();
  6821. });
  6822.  
  6823. function getData() {
  6824. var selectedId = $('#selectAudience').val();
  6825. var audienceId = selectedId.replace('audience', '');
  6826. $.ajax({
  6827. type: 'POST',
  6828. url: '/handleReports',
  6829. data: {audienceId: audienceId}
  6830. }).done(function (data) {
  6831.  
  6832. var json = JSON.parse(data);
  6833. console.log(json);
  6834. updateDataJson(json);
  6835. refreshData();
  6836. }).fail(function (data) {
  6837. console.log(data);
  6838. });
  6839. }
  6840.  
  6841. transform.customSelect('selectAudience');
  6842.  
  6843. window.doughnutChart = charts.createDonutChart('#doughnutChart', 1);
  6844.  
  6845. window.doughnutInfo = 'openedDoughnut'; // initial selected info-bot doughnut
  6846. window.interval = 'week'; // initial selected interval
  6847.  
  6848. function refreshData() {
  6849. $('#' + window.interval).trigger('click');
  6850. $('#' + window.doughnutInfo).trigger('click');
  6851. updateBarChart();
  6852. $(".number-bar-chart").html((window.dataJson.week.sentNum).toLocaleString());
  6853. }
  6854.  
  6855. charts.resizeChartDiv();
  6856. transform.counter(0);
  6857.  
  6858. $("#tabs").tabs();
  6859.  
  6860. /* Render week line chart */
  6861. function renderLineChart() {
  6862.  
  6863. var color = "#2ecc71";
  6864.  
  6865. var data = {
  6866. labels: ['dummy'],
  6867. datasets: [{
  6868. fill: false,
  6869. tension: 0,
  6870. borderCapStyle: 'round',
  6871. pointBackgroundColor: "#fff",
  6872. pointBorderWidth: 3,
  6873. pointHoverRadius: 3,
  6874. pointHoverBorderWidth: 4,
  6875. backgroundColor: color,
  6876. borderColor: color,
  6877. pointHoverBackgroundColor: color,
  6878. pointHoverBorderColor: color,
  6879. pointBorderColor: color,
  6880. data: ["0"]
  6881. }]
  6882. };
  6883.  
  6884. window.lineChart = new Chart($('#lineChart'), {
  6885. type: 'line',
  6886. data: data,
  6887. options: {
  6888. maintainAspectRatio: false,
  6889. legend: {
  6890. display: false
  6891. },
  6892. elements: {
  6893. point: {
  6894. radius: 4
  6895. }
  6896. },
  6897. tooltips: {
  6898. callbacks: {
  6899. title: function (tooltipItem, data) {
  6900.  
  6901. },
  6902. label: function (tooltipItem, data) {
  6903. return tooltipItem.yLabel;
  6904. },
  6905. footer: function (tooltipItem, data) {
  6906.  
  6907. }
  6908. }
  6909. },
  6910. scales: {
  6911. yAxes: [{
  6912. ticks: {
  6913. min: 0,
  6914. suggestedMax: 20
  6915. }
  6916. }]
  6917. }
  6918. }
  6919. });
  6920. }
  6921.  
  6922. renderLineChart();
  6923.  
  6924. function updateDataJson(json) {
  6925. console.log(json);
  6926. window.dataJson = json;
  6927. }
  6928.  
  6929. function updateDoughnutChart() {
  6930.  
  6931. var interval = window.interval;
  6932.  
  6933. var sent = window['dataJson'][interval]['sentNum'];
  6934. var received = window['dataJson'][interval]['received'];
  6935. var opened = window['dataJson'][interval]['openedNum'];
  6936.  
  6937. function update(value) {
  6938. $('#doughnutChartLabel').text(value);
  6939. return [value, (100 - value)];
  6940. }
  6941.  
  6942. if (document.getElementById('doughnutChart').style.display == 'none' &&
  6943. window.doughnutInfo != 'sentDoughnut') {
  6944. $('#doughnutChartLabel').stop();
  6945. $('.cuv-percent').fadeIn();
  6946. $('.chart-background').fadeIn();
  6947. $('#doughnutChart').fadeIn();
  6948. }
  6949.  
  6950. switch (window.doughnutInfo) {
  6951. case 'sentDoughnut':
  6952. $('.cuv-percent').hide();
  6953. $('.chart-background').hide();
  6954. $('#doughnutChart').hide();
  6955.  
  6956. $('#doughnutChartLabel').text(sent);
  6957. transform.counter(0);
  6958.  
  6959. $('#doughnutChartTitle').text('Pushes Enviados');
  6960.  
  6961. return;
  6962.  
  6963. case 'receivedDoughnut':
  6964. window.doughnutChart.data.datasets[0].data = update(received);
  6965. transform.counter(0);
  6966.  
  6967. $('#doughnutChartTitle').text('Pushes Recebidos');
  6968.  
  6969. break;
  6970.  
  6971. case 'openedDoughnut':
  6972. window.doughnutChart.data.datasets[0].data = update(opened);
  6973. transform.counter(0);
  6974.  
  6975. $('#doughnutChartTitle').text('Pushes Abertos');
  6976.  
  6977. break;
  6978.  
  6979. }
  6980.  
  6981. window.doughnutChart.update();
  6982.  
  6983. }
  6984.  
  6985. function updateLineChart() {
  6986.  
  6987. var labels;
  6988. var data;
  6989. var sentNum;
  6990. var received;
  6991. var openedNum;
  6992.  
  6993.  
  6994. function updateDoughnutBotInfo() {
  6995.  
  6996. var interval = window.interval;
  6997.  
  6998. var sent = window['dataJson'][interval]['sentNum'].toLocaleString();
  6999. var received = window['dataJson'][interval]['received'];
  7000. var opened = window['dataJson'][interval]['openedNum'];
  7001.  
  7002. var doughnutBotInfo = $('.doughnut-bot-info');
  7003. doughnutBotInfo.children('#sentDoughnut').children('.number').text(parseInt(sent).toLocaleString(locale));
  7004. doughnutBotInfo.children('#receivedDoughnut').children('.number').text(received + '%');
  7005. doughnutBotInfo.children('#openedDoughnut').children('.number').text(opened + '%');
  7006. }
  7007.  
  7008. function updateInterval(interval) {
  7009.  
  7010. labels = window['dataJson'][interval]['labels'];
  7011. console.log("Labels:");
  7012. console.log(labels);
  7013. data = window['dataJson'][interval]['sent'];
  7014. console.log("Sent:");
  7015. console.log(data);
  7016.  
  7017. window.lineChart.data.labels = labels;
  7018. window.lineChart.data.datasets[0].data = data;
  7019. }
  7020.  
  7021. updateInterval(window.interval);
  7022. updateDoughnutChart();
  7023. updateDoughnutBotInfo();
  7024.  
  7025. // duas linhas no grafico
  7026. /*
  7027. var green = "#2ecc71";
  7028. var blue = "#4ad1ed";
  7029.  
  7030.  
  7031. case 'lineSent':
  7032. // add new line
  7033. if ($('#lineSent').prop('checked')) {
  7034.  
  7035. var interval = $('.line-chart-interval').find('.chart-range-active').attr('id');
  7036.  
  7037. var color = green;
  7038.  
  7039. var dataset = {};
  7040.  
  7041. dataset.fill = false;
  7042. dataset.lineTension = 0.1;
  7043. dataset.borderCapStyle = 'round';
  7044. dataset.pointBackgroundColor = "#fff";
  7045. dataset.pointBorderWidth = 3;
  7046. dataset.pointHoverRadius = 3;
  7047. dataset.pointHoverBorderWidth = 4;
  7048. dataset.backgroundColor = color;
  7049. dataset.borderColor = color;
  7050. dataset.pointHoverBackgroundColor = color;
  7051. dataset.pointHoverBorderColor = color;
  7052. dataset.pointBorderColor = color;
  7053.  
  7054. dataset.data = window['dataJson'][interval]['opened'];
  7055.  
  7056. if (window.lineChart.data.datasets[0] == undefined) {
  7057. window.lineChart.data.datasets[0] = dataset;
  7058. } else {
  7059. window.lineChart.data.datasets[1] = dataset;
  7060. }
  7061.  
  7062. } else {
  7063. window.lineChart.data.datasets.splice(1);
  7064. }
  7065.  
  7066. break;
  7067.  
  7068. case 'lineOpened':
  7069. // add new line
  7070. if ($('#lineOpened').prop('checked')) {
  7071.  
  7072. var interval = $('.line-chart-interval').find('.chart-range-active').attr('id');
  7073.  
  7074. var color = blue;
  7075.  
  7076. var dataset = {};
  7077.  
  7078. dataset.fill = false;
  7079. dataset.lineTension = 0.1;
  7080. dataset.borderCapStyle = 'round';
  7081. dataset.pointBackgroundColor = "#fff";
  7082. dataset.pointBorderWidth = 3;
  7083. dataset.pointHoverRadius = 3;
  7084. dataset.pointHoverBorderWidth = 4;
  7085. dataset.backgroundColor = color;
  7086. dataset.borderColor = color;
  7087. dataset.pointHoverBackgroundColor = color;
  7088. dataset.pointHoverBorderColor = color;
  7089. dataset.pointBorderColor = color;
  7090.  
  7091. dataset.data = window['dataJson'][interval]['opened'];
  7092.  
  7093. if (window.lineChart.data.datasets[0] == undefined) {
  7094. window.lineChart.data.datasets[0] = dataset;
  7095. } else {
  7096. window.lineChart.data.datasets[1] = dataset;
  7097. }
  7098.  
  7099. } else {
  7100. window.lineChart.data.datasets.splice(1);
  7101. }
  7102.  
  7103. break; */
  7104.  
  7105. window.lineChart.update();
  7106. window.doughnutChart.update();
  7107. }
  7108.  
  7109.  
  7110. // select the interval of the chart
  7111. $('.line-chart-interval').on('click', function (e) {
  7112. // only trigger if a button is pressed
  7113. if (e.target.className != 'line-chart-interval') {
  7114. $($(this).children('.chart-range-item')).removeClass('chart-range-active');
  7115. var interval = $(e.target).addClass('chart-range-active').attr('id');
  7116. }
  7117. window.interval = interval;
  7118. updateLineChart(interval);
  7119. });
  7120.  
  7121. // select the filter to see the chart
  7122. $('.js-line-label').on('change', function (e) {
  7123. var intervalElem = $(e.target);
  7124. var interval = intervalElem.attr('id');
  7125.  
  7126. if ($(e.target).prop('checked')) {
  7127. $('#' + interval + 'Label').show();
  7128. } else {
  7129. $('#' + interval + 'Label').hide();
  7130. // keep always one filter selected
  7131. $.each($('.js-line-label'), function (key, elem) {
  7132. var once = false;
  7133. if ($(elem).attr('id') != interval && once == false) {
  7134. $(elem).prop('checked', true);
  7135. $('#' + $(elem).attr('id') + 'Label').show();
  7136. once = true; // loop just for the first matched element
  7137. // interval = $(elem).attr('id'); // change the id so update chart will be right
  7138. }
  7139. });
  7140. }
  7141. });
  7142.  
  7143. // put gray background and green letters when select doughnut chart info
  7144. $('.doughnut-bot-info').on('click', function (e) {
  7145. // only trigger if a button is pressed
  7146. if (e.target.className != 'doughnut-bot-info') {
  7147. $($(this).find('*')).removeClass('darker-bot-info green');
  7148. if (e.target.localName == 'span') {
  7149. var button = $(e.target).parent('button');
  7150. } else {
  7151. var button = $(e.target);
  7152. }
  7153. var doughnutInfo = button.addClass('darker-bot-info').attr('id');
  7154. button.children('.number').addClass('green');
  7155.  
  7156. var older = window.doughnutInfo;
  7157. if (older != doughnutInfo) {
  7158. window.doughnutInfo = doughnutInfo;
  7159. updateDoughnutChart();
  7160. }
  7161. }
  7162. });
  7163.  
  7164. function renderBarChart() {
  7165. var dataBarChart = {
  7166. labels: ['dummy'],
  7167. datasets: [
  7168. {
  7169. backgroundColor: "#d0d0d0",
  7170. borderColor: "#d0d0d0",
  7171. borderWidth: 1,
  7172. hoverBackgroundColor: "#3ec556",
  7173. hoverBorderColor: "#3ec556",
  7174. data: [0]
  7175. }
  7176. ]
  7177. };
  7178.  
  7179. window.barChart = new Chart($('#barChart'), {
  7180. type: 'bar',
  7181. data: dataBarChart,
  7182. options: {
  7183. maintainAspectRatio: false,
  7184. legend: {
  7185. display: false
  7186. },
  7187. scales: {
  7188. xAxes: [{
  7189. gridLines: {
  7190. drawTicks: false,
  7191. zeroLineColor: 'rgba(0, 0, 0, 0.0)',
  7192. color: 'rgba(0, 0, 0, 0.0)'
  7193. }
  7194. }],
  7195. yAxes: [{
  7196. ticks: {
  7197. labelOffset: 0,
  7198. padding: 10,
  7199. min: 0,
  7200. suggestedMax: 20
  7201. }
  7202. }]
  7203. },
  7204. tooltips: {
  7205. titleFontSize: 0,
  7206. titleMarginBottom: 0,
  7207. titleSpacing: 0,
  7208. callbacks: {
  7209. label: function (tooltipItem, data) {
  7210. return tooltipItem.yLabel;
  7211. }
  7212. }
  7213. }
  7214. }
  7215. });
  7216. }
  7217.  
  7218.  
  7219. renderBarChart();
  7220.  
  7221. function updateBarChart() {
  7222. window.barChart.data.datasets[0].data = window.dataJson.week.sent;
  7223. window.barChart.data.labels = window.dataJson.week.labels;
  7224.  
  7225. window.barChart.update();
  7226. }
  7227.  
  7228. refreshData();
  7229. },
  7230.  
  7231. getCampaignRecipients: function (audiencesJson, countSubscribers) {
  7232. if ((audiencesJson !== null) && (audiencesJson !== undefined)) {
  7233. $.each(audiencesJson, function (index, value) {
  7234. if ((value !== null) && (value !== undefined) && (value.audience_id !== undefined)) {
  7235. var $template = $('#templateRowAudience'),
  7236. $clone = $template
  7237. .clone()
  7238. .removeClass('hide')
  7239. .removeAttr('id')
  7240. .insertBefore($template);
  7241.  
  7242. var amountData = $('.templateRowAudience').length - 1;
  7243. var rangeLocalFormat = parseInt(value.range_number).toLocaleString(locale);
  7244.  
  7245. $clone
  7246. .find('input[type=checkbox]').attr('value', value.audience_id).end()
  7247. .find('input[id=audienceSelected]').attr('id', 'audienceSelected' + amountData).end()
  7248. .find('label[for=audienceSelected]').attr('for', 'audienceSelected' + amountData).end()
  7249. .find('[name="name"]').attr('name', 'nameAudience' + amountData).html(value.audience_name).end()
  7250. .find('[name="size"]').attr('name', 'sizeAudience' + amountData).html(rangeLocalFormat).end()
  7251. .find('[name="rank"]').attr('name', 'rankAudience' + amountData).html('-').end()
  7252. .find('[name="dateCreation"]').attr('name', 'dateCreationAudience' + amountData).html(value.audience_creation).end();
  7253. }
  7254.  
  7255. var listAudiencesSelected = [];
  7256.  
  7257. $('#audienceSelected' + amountData).on('change', function () {
  7258. var audiencesSelected = scriptForPage.getSelectedAudiences();
  7259.  
  7260. if (audiencesSelected != listAudiencesSelected) {
  7261. listAudiencesSelected = audiencesSelected;
  7262. action.getSubscribersAudience(audiencesSelected);
  7263. }
  7264. });
  7265. });
  7266. }
  7267.  
  7268. $('.push-row').on('click', function () {
  7269. var checkbox = $(this).find('input[type=checkbox]');
  7270. var check = checkbox.prop('checked');
  7271. checkbox.prop('checked', !check);
  7272. // if all public is checked, then don't need any update
  7273. if (checkbox.attr('id') == 'audienceSelected0' || !$('#audienceSelected0').prop('checked')) {
  7274. checkbox.trigger('change');
  7275. }
  7276. });
  7277.  
  7278. $("#sumSize").html(countSubscribers.toLocaleString(locale));
  7279. },
  7280.  
  7281. getStatusAutomation: function () {
  7282. var filterAutomation = $("#filterAutomation");
  7283. var sendHourIni = $("#sendHourIni");
  7284. var sendHourEnd = $("#sendHourEnd");
  7285. var sendMinuteIni = $("#sendMinuteIni");
  7286. var sendMinuteEnd = $("#sendMinuteEnd");
  7287. var sendDateIni = $("#sendDateIni");
  7288. var sendDateEnd = $("#sendDateEnd");
  7289.  
  7290. var selectAutomation = transform.customSelect('filterAutomation');
  7291. $(selectAutomation.content).css({width: '230px'}); //style the automation selector
  7292. transform.customSelect('sendHourIni');
  7293. transform.customSelect('sendMinuteIni');
  7294. transform.customSelect('sendHourEnd');
  7295. transform.customSelect('sendMinuteEnd');
  7296.  
  7297. // var date = new Date();
  7298. // var dd = date.getDate();
  7299. // var mm = date.getMonth() + 1;
  7300. // var yyyy = date.getFullYear();
  7301. // if (dd < 10) {
  7302. // dd = '0' + dd;
  7303. // }
  7304. // if (mm < 10) {
  7305. // mm = '0' + mm;
  7306. // }
  7307. //
  7308. // var today = dd + '/' + mm + '/' + yyyy;
  7309.  
  7310. window.dateIni = sendDateIni.val();
  7311. window.hourIni = sendHourIni.val();
  7312. window.minuteIni = sendMinuteIni.val();
  7313.  
  7314. window.dateEnd = sendDateEnd.val();
  7315. window.hourEnd = sendHourEnd.val();
  7316. window.minuteEnd = sendMinuteEnd.val();
  7317.  
  7318. window.automation = filterAutomation.val();
  7319.  
  7320. sendDateIni.datepicker({
  7321. format: 'dd/mm/yyyy',
  7322. language: locale,
  7323. beforeShow: function (input, obj) {
  7324. $('.ui-datepicker').removeClass('blur');
  7325. },
  7326. onSelect: function (textData, objDatepicker) {
  7327. dateIni = sendDateIni.val();
  7328. window.scrollTo(0, 0);
  7329. getData(0);
  7330. }
  7331. });
  7332.  
  7333. sendDateEnd.datepicker({
  7334. format: 'dd/mm/yyyy',
  7335. language: locale,
  7336. beforeShow: function (input, obj) {
  7337. $('.ui-datepicker').removeClass('blur');
  7338. },
  7339. onSelect: function (textData, objDatepicker) {
  7340. dateEnd = $(this).val();
  7341. window.scrollTo(0, 0);
  7342. getData(0);
  7343. }
  7344. });
  7345.  
  7346. filterAutomation.change(function () {
  7347. automation = $(this).val();
  7348. window.scrollTo(0, 0);
  7349. getData(0);
  7350. });
  7351.  
  7352. sendHourIni.change(function () {
  7353. hourIni = $(this).val();
  7354. window.scrollTo(0, 0);
  7355. console.log(automation);
  7356. getData(0);
  7357. });
  7358.  
  7359. sendHourEnd.change(function () {
  7360. hourEnd = $(this).val();
  7361. window.scrollTo(0, 0);
  7362. getData(0);
  7363. });
  7364.  
  7365. sendMinuteIni.change(function () {
  7366. minuteIni = $(this).val();
  7367. window.scrollTo(0, 0);
  7368. getData(0);
  7369. });
  7370.  
  7371. sendMinuteEnd.change(function () {
  7372. minuteEnd = $(this).val();
  7373. window.scrollTo(0, 0);
  7374. getData(0);
  7375. });
  7376.  
  7377. },
  7378.  
  7379. // @param calls this variable gets the function which calls the functions inside "pushScript"
  7380. pushScript: function (calls) {
  7381.  
  7382. function resizePreview() {
  7383. var height = $('#preInfo').height();
  7384. $('#preVisualization').css({height: height});
  7385. }
  7386.  
  7387. function showUpSend() {
  7388.  
  7389. var changeCheckbox = $('.js-check-showUpSend');
  7390. var showUp = $('.js-showUpSend');
  7391.  
  7392. changeCheckbox.on('change', function () {
  7393. if ($(this).is(':checked')) {
  7394. showUp.css({visibility: 'visible'}).hide().fadeIn('fast');
  7395. dateTimePreview.changeSendSchedule();
  7396. } else {
  7397. showUp.fadeOut('fast', function () {
  7398. showUp.show().css({visibility: 'hidden'});
  7399. $('#pushSchedule').text('Imediato').removeClass('red');
  7400. });
  7401. }
  7402. });
  7403. }
  7404.  
  7405. function showUpExp() {
  7406.  
  7407. var changeCheckbox = $('.js-check-showUpExp');
  7408. var showUp = $('.js-showUpExp');
  7409.  
  7410. changeCheckbox.on('change', function () {
  7411. if ($(this).is(':checked')) {
  7412. showUp.css({visibility: 'visible'}).hide().fadeIn('fast');
  7413. $('#pushExpiration').text('Informe o tempo').removeClass('orange').addClass('red');
  7414. } else {
  7415. showUp.fadeOut('fast', function () {
  7416. showUp.show().css({visibility: 'hidden'});
  7417. $('#pushExpiration').text('Não').removeClass('red').addClass('orange');
  7418. });
  7419. }
  7420. });
  7421. }
  7422.  
  7423. function showUpURL() {
  7424.  
  7425. var changeCheckbox = $('.js-check-showUpURL');
  7426. var showUp = $('.js-showUpURL');
  7427.  
  7428. changeCheckbox.on('change', function () {
  7429. if ($(this).is(':checked')) {
  7430. showUp.css({visibility: 'visible'}).hide().fadeIn('fast');
  7431. var url = $('input[name=open-url]').val();
  7432.  
  7433. if (url == '') {
  7434. $('.js-pushUrl').text('Informe a URL').removeClass('orange').addClass('red');
  7435. } else {
  7436. $('.js-pushUrl').text(url).removeClass('orange').removeClass('red');
  7437. }
  7438. } else {
  7439. showUp.fadeOut('fast', function () {
  7440. showUp.show().css({visibility: 'hidden'});
  7441. $('.js-pushUrl').text('Não').removeClass('red').addClass('orange');
  7442. });
  7443. }
  7444. });
  7445. }
  7446.  
  7447. function checkYesNo(checkbox, content) {
  7448.  
  7449. var checkbox = $(checkbox);
  7450. var info = $(content);
  7451.  
  7452. checkbox.on('change', function () {
  7453. if ($(this).is(':checked')) {
  7454. info.text('Sim').removeClass('orange').addClass('green');
  7455. } else {
  7456. info.text('Não').removeClass('green').addClass('orange');
  7457. }
  7458. }
  7459. );
  7460. }
  7461.  
  7462. /* Resize emoji for phone preview and DIV (use size param for this) */
  7463. function resizeEmoji(platform, size) {
  7464. var emojis,
  7465. proportion;
  7466.  
  7467. if (platform == 'android') {
  7468. emojis = $('#' + platform + 'Content .img');
  7469. proportion = 0.6;
  7470. } else if (platform == 'iOS') {
  7471. emojis = $('#' + platform + 'Content .img');
  7472. proportion = 0.65;
  7473. } else {
  7474. emojis = $(platform);
  7475. proportion = size;
  7476. }
  7477.  
  7478.  
  7479. emojis.each(function () {
  7480. var width = $(this).width() * proportion;
  7481. var height = $(this).height() * proportion;
  7482.  
  7483. var bgPosition = $(this).css('backgroundPosition');
  7484. var position = bgPosition.replace(/px/g, '').split(' ');
  7485. var posX = position[0] * proportion;
  7486. var posY = position[1] * proportion;
  7487.  
  7488. var bgSize = $(this).css('backgroundSize');
  7489. var size = bgSize.replace(/px/g, '').split(' ');
  7490. var sizeX = size[0] * proportion;
  7491. var sizeY = size[1] * proportion;
  7492.  
  7493. $(this).width(width);
  7494. $(this).height(height);
  7495. $(this).css('backgroundPosition', posX + 'px ' + posY + 'px');
  7496. $(this).css('backgroundSize', sizeX + 'px ' + sizeY + 'px');
  7497. })
  7498. }
  7499.  
  7500. /* @param lastPushMessage Last push returned to preview. Just to be unique, this is 'ççç'
  7501. * @param androidChars Max number of chars in android preview
  7502. * @param iOSChars Max number of chars in iPhone preview
  7503. * @param iOSfirst First time iOS passes sliceMessage, it has to change lastPreview, so it recreates array
  7504. * */
  7505. var lastPushMessage = 'ççç',
  7506. androidChars = 64,
  7507. iOSChars = 120,
  7508. iOSfirst = true;
  7509.  
  7510. /* Slice the message leaving <img> tags and &nbsp; undivided */
  7511. function sliceMessage(typed, size) {
  7512.  
  7513. var lastPreview = typed.substr(0, lastPushMessage.length);
  7514.  
  7515. /* Checks if it is the first iOS preview change, so it has to recreate array and lastPushMessage */
  7516. if (size == iOSChars && iOSfirst) {
  7517. lastPreview = '';
  7518. iOSfirst = false;
  7519. }
  7520.  
  7521. if (lastPreview == lastPushMessage) {
  7522. return lastPushMessage; // if typed piece is the same of the last preview, keep it
  7523. } else {
  7524. var textArray = [],
  7525. wordArray,
  7526. rest = typed,
  7527. pos,
  7528. emojiSpace;
  7529.  
  7530. rest = rest.replace(/&nbsp;/g, ' '); // unseparated &nbsp;
  7531.  
  7532. do {
  7533. pos = rest.search('<img'); // unseparated img
  7534. if (pos != -1) {
  7535. wordArray = rest.substr(0, pos).split('');
  7536. textArray = textArray.concat(wordArray);
  7537.  
  7538. rest = rest.substr(pos);
  7539. pos = rest.search(':">');
  7540. emojiSpace = rest.substr(0, pos + 3);
  7541. textArray.push(emojiSpace, '');
  7542.  
  7543. rest = rest.substr(pos + 3);
  7544. }
  7545. } while (pos != -1 && textArray.length < size);
  7546.  
  7547. textArray = textArray.concat(rest.split(''));
  7548. textArray.map(function (val, index) {
  7549. if (val == ' ') {
  7550. textArray[index] = '&nbsp;'; // bring back &nbsp;
  7551. }
  7552. });
  7553. lastPushMessage = textArray.slice(0, size).join('');
  7554.  
  7555. if (size == androidChars) {
  7556. return lastPushMessage; // return preview TEXT
  7557. }
  7558. return textArray; // return preview ARRAY (for different Android and iOS slices)
  7559. }
  7560. }
  7561.  
  7562. /* Change TITLE while typing */
  7563. function titleMessagePreview() {
  7564. $('#pushTitle').on('keyup', function () {
  7565. var typed = $(this).val();
  7566. $('.js-title').text(typed);
  7567. });
  7568. }
  7569.  
  7570. function doURLPreview(url) {
  7571. if (url == '') {
  7572. $('.js-pushUrl').text('Informe uma URL').removeClass('red').addClass('red');
  7573. } else {
  7574. $('.js-pushUrl').text(url).removeClass('red');
  7575. }
  7576. }
  7577.  
  7578. function URLPreview() {
  7579. $('#openURL').on('keyup', function () {
  7580. var url = $(this).val();
  7581. doURLPreview(url);
  7582. });
  7583. }
  7584.  
  7585. /*
  7586. * @param iOSContent Selector for iOS preview
  7587. * @param androidContent Selector for Android preview
  7588. * @param preMsg selector For message field preview
  7589. * @param observeOnce Boolean to stop Observer at the first time
  7590. * */
  7591. var iOSContent = $('#iOSContent'),
  7592. androidContent = $('#androidContent'),
  7593. preMsg = $('.js-msg'),
  7594. observeOnce = true;
  7595.  
  7596. var target = $('#pushContent').next('div'); // message content DIV
  7597. /* Reset observer boolean */
  7598. $(target).on('keyup', function () {
  7599. observeOnce = true;
  7600. });
  7601. $('.emoji-menu').on('mousedown', function () {
  7602. observeOnce = true;
  7603. });
  7604.  
  7605. function doMessagePreview(typed) {
  7606. /* count how many real chars there is */
  7607. var typedNum = typed.replace(/&nbsp;/g, ' '); // &nbsp; counts 1
  7608.  
  7609. var matches = typed.match(/\<img[^>]*>/g); // <img> counts 2
  7610. if (matches != null) {
  7611. for (var i = 0; i < matches.length; i++) {
  7612. typedNum = typedNum.replace(matches[i], '12');
  7613. }
  7614. var count = typedNum.length;
  7615.  
  7616. } else {
  7617. count = typed.length;
  7618. }
  7619.  
  7620. preMsg.html(typed);
  7621. resizeEmoji();
  7622.  
  7623. /* More than iOS preview space */
  7624. if (count > iOSChars) {
  7625. var textArray = sliceMessage(typed, iOSChars);
  7626.  
  7627. // if textArray isn't array, then the message is the same and don't need to be changed
  7628. if (Array.isArray(textArray)) {
  7629. /* iOS push */
  7630. var textLarge = textArray.slice(0, iOSChars).join('') + '...';
  7631. iOSContent.html(textLarge);
  7632. resizeEmoji('iOS');
  7633. /* Android push */
  7634. var textSmall = textArray.slice(0, androidChars).join('') + '...';
  7635. androidContent.html(textSmall);
  7636. resizeEmoji('android');
  7637. }
  7638.  
  7639. } else if (count > androidChars) {
  7640. iOSContent.html(typed);
  7641. resizeEmoji('iOS');
  7642.  
  7643. /* Change just Android push */
  7644. var text = sliceMessage(typed, androidChars) + '...';
  7645. androidContent.html(text);
  7646. resizeEmoji('android');
  7647. iOSfirst = true;
  7648. } else {
  7649. androidContent.html(typed);
  7650. resizeEmoji('android');
  7651.  
  7652. iOSContent.html(typed);
  7653. resizeEmoji('iOS');
  7654.  
  7655. iOSfirst = true;
  7656. }
  7657. resizePreview(); // if message is to long, resize phone preview DIV
  7658. }
  7659.  
  7660. /* Change MESSAGE while typing */
  7661. function messagePreview() {
  7662. var observer = new MutationObserver(function (mutations) { // create an observer instance
  7663. mutations.forEach(function (mutation) {
  7664. if (observeOnce) {
  7665.  
  7666. // var lastEmoji = target.children('[alt="' + mutation.addedNodes[0].alt + '"]');
  7667. // resizeEmoji(lastEmoji, 0.76);
  7668.  
  7669. var typed = $(mutation.target).html();
  7670.  
  7671. doMessagePreview(typed);
  7672.  
  7673. observeOnce = false;
  7674. }
  7675. });
  7676. });
  7677.  
  7678. observer.observe(target[0], {attributes: true, childList: true});
  7679.  
  7680. }
  7681.  
  7682. function refreshPreview() {
  7683. $('#pushTitle').trigger('keyup');
  7684. }
  7685.  
  7686. var dateTimePreview = {
  7687.  
  7688. /* SEND TIME */
  7689. sendDateTime: {
  7690. proxy: new Proxy(['', '', ''], {
  7691. get: function (target, property) {
  7692. return target[property];
  7693. },
  7694. set: function (target, property, value) {
  7695. target[property] = value;
  7696. dateTimePreview.changeSendSchedule();
  7697. return true;
  7698. }
  7699. })
  7700. },
  7701.  
  7702. setSendDate: function () {
  7703. var nomesMes = [
  7704. "Janeiro", "Fevereiro", "Março",
  7705. "Abril", "Maio", "Junho", "Julho",
  7706. "Agosto", "Setembro", "Outubro",
  7707. "Novembro", "Dezembro"
  7708. ];
  7709.  
  7710. var nomesSemana = [
  7711. "Domingo", "Segunda-feira", "Terça-feira",
  7712. "Quarta-feira", "Quinta-feira",
  7713. "Sexta-feira", "Sábado-feira"
  7714. ];
  7715.  
  7716. var input = $('#sendDate').val().split('/');
  7717. input = input[2] + '-' + input[1] + '-' + input[0];
  7718.  
  7719. var date = new Date(input);
  7720. var fixTime = date.getTimezoneOffset() / 60;
  7721. date.setHours(date.getHours() + fixTime);
  7722.  
  7723. var today = new Date().setHours(0, 0, 0, 0);
  7724. var tomorrow = today + 24 * 60 * 60000;
  7725.  
  7726. var dateString = '';
  7727.  
  7728. if (date.getTime() == today) {
  7729. dateString = 'Hoje, ';
  7730. } else if (date.getTime() == tomorrow) {
  7731. dateString = 'Amanhã, ';
  7732. } else {
  7733. var day = date.getDate();
  7734. var monthIndex = date.getMonth();
  7735. var year = date.getFullYear();
  7736. var weekIndex = date.getDay();
  7737.  
  7738. dateString = nomesSemana[weekIndex] + ', ' + day + ' ' + nomesMes[monthIndex] + ' ' + year + ', ';
  7739. }
  7740.  
  7741. this.sendDateTime.proxy[0] = dateString;
  7742. this.sendDateTime.proxy[4] = date.getTime();
  7743. },
  7744.  
  7745. setSendHour: function () {
  7746. this.sendDateTime.proxy[1] = $('#sendHour').val();
  7747. },
  7748.  
  7749. setSendMinute: function () {
  7750. this.sendDateTime.proxy[2] = $('#sendMinute').val();
  7751. },
  7752.  
  7753. changeSendSchedule: function () {
  7754. var flagSchedule = $('.js-check-showUpSend').is(':checked');
  7755. var date = this.sendDateTime.proxy[0];
  7756. if (flagSchedule && date == '') {
  7757. date = $('#sendDate').val();
  7758. }
  7759.  
  7760. var h = this.sendDateTime.proxy[1];
  7761. if (flagSchedule && h == '') {
  7762. h = $('#sendHour').val();
  7763. }
  7764.  
  7765. var min = this.sendDateTime.proxy[2];
  7766. if (flagSchedule && min == '') {
  7767. min = $('#sendMinute').val();
  7768. }
  7769.  
  7770. var dateMillis = this.sendDateTime.proxy[4] + 60000 * (60 * h) + 60000 * min;
  7771.  
  7772. var today = new Date().getTime();
  7773.  
  7774. window.scheduleValid = false; // if time is valid, set to true and allow push sending
  7775.  
  7776. // if (date == '' || date.search('undefined') != -1) {
  7777. if (date == '' && flagSchedule) {
  7778. $('#pushSchedule').text('Agende o envio').addClass('red bold');
  7779. } else if (dateMillis < today) {
  7780. $('#pushSchedule').text('Escolha uma data futura').addClass('red bold');
  7781. resizePreview();
  7782. } else if (flagSchedule) {
  7783. var dateTime = date + h + ':' + min + 'h';
  7784. $('#pushSchedule').text(dateTime).removeClass('red bold');
  7785. $('#iOS .time').text('Hoje ' + h + ':' + min);
  7786. $('#android .time').text(h + ':' + min);
  7787. window.scheduleValid = true;
  7788. resizePreview();
  7789. }
  7790. }
  7791.  
  7792.  
  7793. };
  7794.  
  7795. function changeExpirationTime() {
  7796. var h = $('#expirationHour').val();
  7797. var min = $('#expirationMinutes').val();
  7798. var hours = '';
  7799. var minutes = '';
  7800.  
  7801. var plural = ['hora', 'horas', 'minuto', 'minutos'];
  7802.  
  7803. if (h != 0) {
  7804. if (h == 1) {
  7805. hours = h + ' ' + plural[0] + ' ';
  7806. } else {
  7807. hours = h + ' ' + plural[1] + ' ';
  7808. }
  7809. }
  7810.  
  7811. if (min != 0) {
  7812. if (min == 1) {
  7813. minutes = min + ' ' + plural[2];
  7814. } else {
  7815. minutes = min + ' ' + plural[3]
  7816. }
  7817. }
  7818.  
  7819. if (min == 0 && h == 0) {
  7820. $('#pushExpiration').text('Informe o tempo').removeClass('red').addClass('red');
  7821. } else if (min != 0 && h != 0) {
  7822. var time = hours + 'e ' + minutes;
  7823. $('#pushExpiration').text(time).removeClass('red');
  7824. } else if (min != 0 ^ h != 0) {
  7825. var time = hours + minutes;
  7826. $('#pushExpiration').text(time).removeClass('red');
  7827. }
  7828. }
  7829.  
  7830. // get the functions to be called here
  7831. if (calls == 'sendPush') {
  7832.  
  7833. // transform.customSelect('expirationMinutes');
  7834. // transform.customSelect('expirationHour');
  7835. transform.customSelect('sendHour');
  7836. transform.customSelect('sendMinute');
  7837.  
  7838. $('#preVisualization').tabs();
  7839.  
  7840. //set time only when checkbox is clicked, so the Proxy isn't triggered in advance
  7841. $('#scheduleSend').one('change', function () {
  7842. dateTimePreview.setSendDate(); // Initializes the date for Send Schedule
  7843. dateTimePreview.setSendHour(); // Initializes the date for Send Schedule
  7844. dateTimePreview.setSendMinute(); // Initializes the date for Send Schedule
  7845. });
  7846.  
  7847. $('#sendDate').datepicker({minDate: 0}).on('change', function () {
  7848. dateTimePreview.setSendDate();
  7849. });
  7850. $('#sendHour').on('change', function () {
  7851. dateTimePreview.setSendHour();
  7852. });
  7853. $('#sendMinute').on('change', function () {
  7854. dateTimePreview.setSendMinute();
  7855. });
  7856.  
  7857. // $('#expirationHour').on('change', function () {
  7858. // changeExpirationTime();
  7859. // });
  7860. // $('#expirationMinutes').on('change', function () {
  7861. // changeExpirationTime();
  7862. // });
  7863.  
  7864. transform.iOSswitch();
  7865.  
  7866. resizePreview();
  7867. showUpSend();
  7868. showUpExp();
  7869. showUpURL();
  7870. // checkYesNo('.js-check-sound', '#pushSound');
  7871. // checkYesNo('.js-check-increment', '#pushIncrement');
  7872. titleMessagePreview();
  7873. URLPreview();
  7874. messagePreview();
  7875. dateTimePreview.changeSendSchedule();
  7876. behaviors.listData.add(undefined, 5);
  7877. // behaviors.listData.remove();
  7878. refreshPreview();
  7879.  
  7880. } else if (calls == 'newCampaign') {
  7881. $('#preVisualization').tabs();
  7882.  
  7883. transform.iOSswitch();
  7884.  
  7885. resizePreview();
  7886. showUpSend();
  7887. showUpExp();
  7888. showUpURL();
  7889. // checkYesNo('.js-check-sound', '#pushSound');
  7890. // checkYesNo('.js-check-increment', '#pushIncrement');
  7891. titleMessagePreview();
  7892. URLPreview();
  7893. messagePreview();
  7894. behaviors.listData.add(undefined, 5);
  7895. // behaviors.listData.remove();
  7896.  
  7897. } else if (calls == 'newAutomation') {
  7898.  
  7899. $('#preVisualization').tabs();
  7900.  
  7901. transform.iOSswitch();
  7902.  
  7903. resizePreview();
  7904. // showUpSend();
  7905. // showUpExp();
  7906. // showUpURL();
  7907. // checkYesNo('.js-check-sound', '#pushSound');
  7908. // checkYesNo('.js-check-increment', '#pushIncrement');
  7909. // titleMessagePreview();
  7910. // URLPreview();
  7911. // messagePreview();
  7912. behaviors.listData.add(undefined, 5);
  7913. // behaviors.listData.remove();
  7914.  
  7915. $('#campaignsList').on('click', 'button', function () {
  7916. $('.js-title').html($('#msgTitle').html());
  7917. doMessagePreview($('#msgBody').html());
  7918. doURLPreview($('#urlPushField').html());
  7919.  
  7920. });
  7921.  
  7922. } else if (calls == 'newApi') {
  7923.  
  7924. $('#preVisualization').tabs();
  7925.  
  7926. transform.iOSswitch();
  7927.  
  7928. resizePreview();
  7929. showUpURL();
  7930. // checkYesNo('.js-check-sound', '#pushSound');
  7931. // checkYesNo('.js-check-increment', '#pushIncrement');
  7932. titleMessagePreview();
  7933. URLPreview();
  7934. messagePreview();
  7935. // dateTimePreview.changeSendSchedule();
  7936. behaviors.listData.add('#tagBlock');
  7937. behaviors.listData.add('#additionalBlock', 5);
  7938. // behaviors.listData.remove();
  7939. refreshPreview();
  7940. }
  7941. },
  7942.  
  7943. automation: {
  7944. setTime: function (text) {
  7945. $("#timeInterval").html(text);
  7946. $("#pushScheduleHour").html(text);
  7947. },
  7948.  
  7949. timeSlider: function (selectedDays, timeJson, days) {
  7950. var daysName = [];
  7951. var pushSchedule = $('#pushSchedule');
  7952. var daysSelectors = $('input[name=day]');
  7953.  
  7954. daysSelectors.on('change', function () {
  7955. $.each($('input[name=day]'), function (key, obj) {
  7956. selectedDays[key] = $(obj).prop('checked');
  7957. });
  7958.  
  7959. daysName.length = 0;
  7960. $.each(selectedDays, function (key, value) {
  7961. if (value == true)
  7962. daysName.push(days[key]);
  7963. });
  7964.  
  7965. if (selectedDays[0] == true) {
  7966. daysName.push(daysName.shift());
  7967. }
  7968.  
  7969. var daysInterval = selectedDays.slice();
  7970. var sunday = daysInterval.shift();
  7971. var saturday = daysInterval.pop();
  7972.  
  7973. if (daysName.length == 7) {
  7974. pushSchedule.html('Todos os dias');
  7975. } else if (daysName.length == 5 && sunday == false && saturday == false) {
  7976. $('#pushSchedule').html('Dias de semana');
  7977. } else if (daysName.length == 2) {
  7978. $('#pushSchedule').html(daysName.join(' e '));
  7979. } else {
  7980. $('#pushSchedule').html(daysName.join(', '));
  7981. }
  7982. });
  7983.  
  7984. daysSelectors.first().trigger('change');
  7985.  
  7986. var timeIntervalRange = $("#timeIntervalRange");
  7987.  
  7988. timeIntervalRange.slider({
  7989. range: true,
  7990. min: 0,
  7991. max: 24,
  7992. values: [0, 24],
  7993. slide: function (event, ui) {
  7994. var text = 'Entre ' + ui.values[0] + " e " + ui.values[1] + " horas.";
  7995. scriptForPage.automation.setTime(text);
  7996. $(ui.handle).attr('data-value', ui.value);
  7997. timeJson = {'init': ui.values[0], 'end': ui.values[1]};
  7998. }
  7999. });
  8000.  
  8001. var init = timeIntervalRange.slider("values", 0);
  8002. var end = timeIntervalRange.slider("values", 1);
  8003. // USA ESSE JSON PARA PASSAR AS INFOS DE HORA
  8004. timeJson = {'init': init, 'end': end};
  8005. scriptForPage.automation.setTime('Entre ' + init + " e " + end + " horas.");
  8006.  
  8007. // initialize slider label values
  8008. $.each($(timeIntervalRange.slider("widget")).find('.ui-slider-handle'), function (index, obj) {
  8009. $(obj).attr('data-value', timeIntervalRange.slider("values", index));
  8010. });
  8011.  
  8012. return timeJson;
  8013. },
  8014.  
  8015. populateScheduled: function (automationScheduledJson) {
  8016. if(automationScheduledJson !== '0') {
  8017. $.each(automationScheduledJson, function (index, value) {
  8018. var elementsDays = $("input[name*='day']");
  8019.  
  8020. if (value.sunday == 0)
  8021. $(elementsDays).filter(function () {
  8022. return this.value == 'sun'
  8023. }).attr('checked', false);
  8024.  
  8025. if (value.monday == 0)
  8026. $(elementsDays).filter(function () {
  8027. return this.value == 'mon'
  8028. }).attr('checked', false);
  8029.  
  8030. if (value.tuesday == 0)
  8031. $(elementsDays).filter(function () {
  8032. return this.value == 'tue'
  8033. }).attr('checked', false);
  8034.  
  8035. if (value.wednesday == 0)
  8036. $(elementsDays).filter(function () {
  8037. return this.value == 'wed'
  8038. }).attr('checked', false);
  8039.  
  8040. if (value.thursday == 0)
  8041. $(elementsDays).filter(function () {
  8042. return this.value == 'thu'
  8043. }).attr('checked', false);
  8044.  
  8045. if (value.friday == 0)
  8046. $(elementsDays).filter(function () {
  8047. return this.value == 'fri'
  8048. }).attr('checked', false);
  8049.  
  8050. if (value.saturday == 0)
  8051. $(elementsDays).filter(function () {
  8052. return this.value == 'sat'
  8053. }).attr('checked', false);
  8054.  
  8055. $("#timeIntervalRange").slider('values', 0, value.hour_initial);
  8056. $("#timeIntervalRange").slider('values', 1, value.hour_final);
  8057. scriptForPage.automation.setTime('Entre ' + value.hour_initial + " e " + value.hour_final + " horas.");
  8058. $($(".ui-slider-handle")[0]).attr('data-value', value.hour_initial);
  8059. $($(".ui-slider-handle")[1]).attr('data-value', value.hour_final);
  8060. });
  8061.  
  8062. $('input[name=day]').trigger('change');
  8063. }
  8064. },
  8065.  
  8066. newAutomation: function (automationId, campaignsJson, days, audienceJson, criteriaJson, appId, countSubscribers, allAudiences) {
  8067. transform.highlightSubMenu('#automations');
  8068. behaviors.popUp('#selectCampaign', '#campaignsList');
  8069. var campaignIdSelected = 0;
  8070.  
  8071. $.each(campaignsJson, function (key, obj) {
  8072. $('#camp' + obj.campId).on('click', function () {
  8073. $('#campaignsList').fadeOut('fast');
  8074. $('#campName').html(obj.campName);
  8075. //set title field
  8076. var title;
  8077. if (obj.msgTitle == '') {
  8078. title = '-';
  8079. } else {
  8080. title = obj.msgTitle;
  8081. }
  8082. $('#msgTitle').html(title);
  8083. $('#titlePreview').html(title);
  8084. // set URL field
  8085. var urlPush;
  8086. if (obj.urlPush == null) {
  8087. urlPush = '-';
  8088. $('#pushURL').addClass('orange').removeClass('green').html('Não');
  8089. } else {
  8090. urlPush = obj.urlPush;
  8091. $('#pushURL').addClass('green').removeClass('orange').html('Sim');
  8092. }
  8093. $('#urlPushField').html(urlPush);
  8094. campaignIdSelected = obj.campId;
  8095.  
  8096. transform.colonToEmoji(obj.msgBody, '#msgBody');
  8097. transform.colonToEmoji(obj.msgBody, '#msgPreview');
  8098. $("#campaign").next('.js-error').remove();
  8099. $("#campaign").removeClass("error-outline");
  8100. });
  8101. });
  8102.  
  8103. new Tether({
  8104. element: '#campaignsList',
  8105. target: '#selectCampaign',
  8106. attachment: 'top left',
  8107. targetAttachment: 'bottom left'
  8108. });
  8109.  
  8110. var selectedDays = [];
  8111. var timeJson;
  8112. timeJson = scriptForPage.automation.timeSlider(selectedDays, timeJson, days);
  8113.  
  8114. scriptForPage.newAudience('', audienceJson, criteriaJson, appId, false);
  8115.  
  8116. // transform.emojiPicker();
  8117. scriptForPage.pushScript('newAutomation');
  8118. behaviors.autoTextArea();
  8119.  
  8120. $('#footerSave').on('click', function () {
  8121. if (validate.multiFields([['#componentName', 'Precisamos de um nome para a automação'],
  8122. [validate.fieldCampaignAutomation, campaignIdSelected, automationId],
  8123. [validate.fieldsAdditionalData],
  8124. [validate.fieldsAudienceCampaign, true],
  8125. [validate.fieldsAudienceCriteria, false]])) {
  8126. var audiencesSelected = scriptForPage.getSelectedAudiences();
  8127.  
  8128. var data = {
  8129. 'automationId': automationId,
  8130. 'campaignId': campaignIdSelected,
  8131. 'campaignName': $('#campName').html(),
  8132. 'audiencesSelected': audiencesSelected,
  8133. 'selectedDays': '"' + selectedDays.toString() + '"',
  8134. 'timeInit': $("#timeIntervalRange").slider("values", 0),
  8135. 'timeEnd': $("#timeIntervalRange").slider("values", 1)
  8136. };
  8137. modal.getModal('modal-save-automation.php', false, data);
  8138. }
  8139. });
  8140.  
  8141. scriptForPage.getCampaignRecipients(allAudiences, countSubscribers);
  8142. validate.quantitySubscribers(countSubscribers);
  8143.  
  8144. $('#footerCancel').on('click', function () {
  8145. navigateTo.app.push.automations();
  8146. });
  8147. },
  8148.  
  8149. populateAutomation: function (automationId, automationJson, appId, pushCriteriaJson, automationAudienceJson, additionalJson, automationScheduledJson) {
  8150. if (automationId > 0) {
  8151. var name = automationJson['automation_name'];
  8152. var description = automationJson['automation_description'];
  8153. var campaignId = automationJson['campaign_id'];
  8154.  
  8155. populateAudience(automationAudienceJson);
  8156. populateCriteria(pushCriteriaJson);
  8157. populateAdditionalData(additionalJson);
  8158. scriptForPage.automation.populateScheduled(automationScheduledJson);
  8159.  
  8160. $('#componentName').val(name);
  8161. $('#componentDescription').val(description);
  8162. $('#camp' + campaignId).trigger('click');
  8163.  
  8164. action.findReachAudience(appId);
  8165.  
  8166. $('.page-title').html(name);
  8167. }
  8168.  
  8169. function populateCriteria(pushCriteriaJson) {
  8170. var i = 0;
  8171. $.each(pushCriteriaJson, function (index, value) {
  8172. if ((i > 0) && (value !== null) && (value !== undefined)) {
  8173. $("#addNewCondition").trigger("click");
  8174. }
  8175. var selectField = $("#select" + i + "0").attr('value', value.audience_criteria_id);
  8176. selectField.val(value.audience_field_id);
  8177. selectField.next('a').css({color: 'inherit'});
  8178.  
  8179. var varType = selectField.find('option[value=' + selectField.val() + ']').attr('data-type');
  8180. scriptForPage.showConditionField('#jsConditionRow' + i, varType);
  8181.  
  8182. var objectTypeCondition = $('#jsConditionRow' + i).find('.js-' + varType + '-condition');
  8183.  
  8184. if (varType == 'boolean') {
  8185. objectTypeCondition.find('a[href="#' + value.audience_value + '"]').trigger('click');
  8186. } else {
  8187. objectTypeCondition.find('select[name=operator]').val(value.audience_field_condition_id);
  8188. objectTypeCondition.find('select[name=operator]').attr('value', value.audience_field_condition_id);
  8189. objectTypeCondition.find('select[name=operator]').next('a').css({color: 'inherit'});
  8190.  
  8191. objectTypeCondition.find('input[name=val]').val(value.audience_value);
  8192. }
  8193. i++;
  8194. });
  8195. }
  8196.  
  8197. function populateAudience(automationAudienceJson) {
  8198. if (automationAudienceJson == null || automationAudienceJson == '0') {
  8199. $('#audienceSelected0').attr('checked', true);
  8200. $('#audienceSelected0').trigger('change');
  8201. } else {
  8202. var allRowsAudience = $("input[class*='audience']");
  8203.  
  8204. $.each(automationAudienceJson, function (index, value) {
  8205. var elementAudienceId = $(allRowsAudience).filter(function () {
  8206. return this.value == value.audience_id
  8207. }).attr('id');
  8208.  
  8209. $('#' + elementAudienceId).attr('checked', true);
  8210. $('#' + elementAudienceId).trigger('change');
  8211. });
  8212. }
  8213. }
  8214.  
  8215. function populateAdditionalData(additionalJson) {
  8216. //verify if automation has additional data
  8217. if ((additionalJson !== null) && (additionalJson !== undefined)) {
  8218. var additionalBlock = $('#additionalBlock');
  8219. $.each(additionalJson, function (index, value) {
  8220. if ((value !== null) && (value !== undefined) && (value.key_data !== undefined)) {
  8221. // add row
  8222. additionalBlock.find('.addNewData').trigger('click');
  8223. // insert data
  8224. additionalBlock.find('.js-dataTemplate').prev()
  8225. .find('[name="additional-key"]').attr('value', value.key_data).end()
  8226. .find('[name="additional-value"]').attr('value', value.value_data);
  8227. }
  8228. });
  8229. }
  8230. }
  8231. }
  8232. },
  8233.  
  8234. generalConfig: {
  8235.  
  8236. /* Register when user copy the element and supports a button to do the copy
  8237. *
  8238. * @param btnId Button ID to copy text
  8239. * @param idToCopy Text ID to copy
  8240. * @param timeOut Timeout time
  8241. * */
  8242. copyContent: function (btnId, idToCopy, timeOut) {
  8243.  
  8244. var copyBtn = $(btnId);
  8245. var copyThis = $(idToCopy);
  8246. timeOut = timeOut || 1000;
  8247.  
  8248. var originalBtnText = copyBtn.html();
  8249. var originalBtnClass = copyBtn.attr('class');
  8250.  
  8251. /* Use clipboard.js plugin
  8252. * Ref: https://github.com/zenorocha/clipboard.js.git
  8253. * */
  8254. copyBtn.attr('data-clipboard-target', idToCopy);
  8255. new Clipboard(btnId);
  8256.  
  8257. copyThis.on('copy', function () {
  8258. copyBtn.html('Copiado!').removeClass('button-clean-gray').addClass('button-blue');
  8259. setTimeout(function () {
  8260. copyBtn.html(originalBtnText);
  8261. if (originalBtnClass.search('button-blue') == -1) {
  8262. copyBtn.switchClass('button-blue', originalBtnClass, 400);
  8263. }
  8264. }, timeOut);
  8265. });
  8266.  
  8267. // DISABLE COPY CUT PASTE
  8268. // copyBtn.on('cut copy paste', function (e) {
  8269. // e.preventDefault(); //disable cut,copy,paste
  8270. // });
  8271. },
  8272.  
  8273.  
  8274. updateField: function (valueField, formData, token) {
  8275. $.ajax({
  8276. type: 'POST',
  8277. url: '/appConfigValidation',
  8278. data: formData,
  8279. dataType: 'json',
  8280. encode: true
  8281. })
  8282.  
  8283. .done(function (data) {
  8284. console.log(data);
  8285.  
  8286. if (!data.success) {
  8287. if (data.errors.password) {
  8288. $('#password-group').addClass('has-error');
  8289. $('#password-group').append('<div class="help-block">' + data.errors.password + '</div>');
  8290. }
  8291. if (data.errors.loginError) {
  8292. //$('#message-login').append('<div class="alert-box">' + data.errors.loginError + '</div>');
  8293. $('#password-group').addClass('has-error');
  8294. $('#password-group').append('<div class="help-block">' + data.errors.loginError + '</div>');
  8295. }
  8296. } else {
  8297. $(valueField).text(formData['appName']);
  8298.  
  8299. var appTitleBtn = $('#appTitleBtn');
  8300. /* update in menu side */
  8301. var nonText = appTitleBtn.html();
  8302. nonText = nonText.substring(nonText.indexOf('<'));
  8303. appTitleBtn.html(formData['appName'] + nonText);
  8304. $('#menuName' + token).text(formData['appName']);
  8305. }
  8306. })
  8307. .fail(function (data) {
  8308. console.log(data);
  8309. });
  8310. },
  8311.  
  8312. updateIcon: function (token) {
  8313.  
  8314. $("#uploadIconForm").on('submit', (function (e) {
  8315. e.preventDefault();
  8316. var uploadMessage = $("#uploadMessage");
  8317. var uploadBtn = $('#uploadIconBtn');
  8318. uploadMessage.empty();
  8319.  
  8320. var formData = new FormData(this);
  8321. formData.append('object', 'appIcon');
  8322.  
  8323. $.ajax({
  8324. url: "/actions/imageUpload.php", // Url to which the request is send
  8325. type: "POST", // Type of request to be send, called as method
  8326. data: formData, // Data sent to server, a set of key/value pairs (i.e. form fields and values)
  8327. contentType: false, // The content type used when sending data to the server.
  8328. cache: false, // To unable request pages to be cached
  8329. processData: false, // To send DOMDocument or non processed data file it is set to false
  8330. success: function (data) { // A function to be called if request succeeds
  8331. var result = $.parseJSON(data);
  8332. console.log('done');
  8333. console.log(data);
  8334. if (result.hasOwnProperty("img")) {
  8335. uploadMessage.css({color: '#3bdb7b', fontWeight: '600'}).text(result.msg);
  8336. uploadBtn.text('Enviado!')
  8337. .removeClass('button-clean-blue')
  8338. .addClass('button-green');
  8339. setTimeout(function () {
  8340. uploadBtn.switchClass('button-green', 'button-clean-blue', 400).text('Upload');
  8341. }, 1500);
  8342. var path = ref.getUploads + '/app_icons/' + result.img;
  8343. $('#appIcon').attr('src', path)
  8344. .attr('data', path);
  8345. /* update in menu side */
  8346. $('#menuImg' + token).attr('src', path);
  8347. } else {
  8348. uploadMessage.attr('style', '""').text(result.msg);
  8349. }
  8350. },
  8351. fail: function (data) {
  8352. console.log('fail');
  8353. console.log(data);
  8354. }
  8355. });
  8356.  
  8357.  
  8358. }));
  8359. }
  8360.  
  8361. },
  8362.  
  8363. getAdditionalData: function () {
  8364. var elements = $('.js-dataRow');
  8365. var dict = [];
  8366.  
  8367. $.each(elements, function (num, obj) {
  8368. var key = $(obj).find('input[name="additional-key"]').val();
  8369. var value = $(obj).find('input[name="additional-value"]').val();
  8370.  
  8371. if ((key !== '') && (value !== '')) {
  8372. dict.push({key: key, value: value});
  8373. }
  8374. });
  8375.  
  8376. return dict;
  8377. },
  8378.  
  8379.  
  8380. // TODO deletar essa função quando o list estiver funcionando
  8381. getCustomFields: function (customFieldsJson) {
  8382. var num = 0; // uniquer number for ids
  8383.  
  8384. $("#addCustomField").hover(function () {
  8385. $(this).css({fontWeight: '400'});
  8386. behaviors.svgChangeTo.hover($(this).children('img'));
  8387. }, function () {
  8388. $(this).attr('style', '');
  8389. behaviors.svgChangeTo.hover($(this).children('img'));
  8390. }).on("click", function () {
  8391. // if ($('.js-customField').length < 5) {
  8392. var $template = $('#templateCustomFields'),
  8393. $clone = $template
  8394. .clone()
  8395. .removeClass('hide template')
  8396. .addClass('js-customField')
  8397. .removeAttr('id')
  8398. .insertBefore($template);
  8399.  
  8400. var amountData = $('.js-customField').length;
  8401. num++;
  8402.  
  8403. // Update the name attributes
  8404. $clone
  8405. .find('#customFieldName').attr('name', 'data[' + num + '].custom_field')
  8406. .attr('id', 'customFieldName' + num).end()
  8407. .find('#customFieldType').attr('id', 'customFieldType' + num).end();
  8408.  
  8409. transform.customSelect('customFieldType' + num);
  8410. //add click atribute
  8411. // remove();
  8412.  
  8413.  
  8414. $.each($('#customFieldForm').find('.numberField'), function (key, obj) {
  8415. $(obj).html('Campo customizável ' + (key + 1));
  8416. });
  8417.  
  8418. if (amountData >= 5) {
  8419. $(".addData").addClass('hide');
  8420. }
  8421. // }
  8422. });
  8423.  
  8424. $("#customFieldsBlock").on('hover', '.js-removeData', function () {
  8425. behaviors.svgChangeTo.hover($(this).children('img'));
  8426. }, function () {
  8427. behaviors.svgChangeTo.hover($(this).children('img'));
  8428. }).on("click", '.js-removeData', function () {
  8429. // Remove element containing the fields
  8430. $(this).parents('.control-panel-row').remove();
  8431.  
  8432. // re-write the titles
  8433. $.each($('#customFieldForm').find('.numberField'), function (key, obj) {
  8434. $(obj).html('Campo customizável ' + (key + 1));
  8435. });
  8436.  
  8437. var amountData = $('.js-customField').length;
  8438. if (amountData <= 5) {
  8439. $(".addData").removeClass('hide');
  8440. } else {
  8441. $(".addData").addClass('hide');
  8442. }
  8443. });
  8444.  
  8445. // function remove() {
  8446. // $(".js-dataRow").on('hover', '.js-removeData', function () {
  8447. // behaviors.svgChangeTo.hover($(this).children('img'));
  8448. // }, function () {
  8449. // behaviors.svgChangeTo.hover($(this).children('img'));
  8450. // }).on("click", '.js-removeData', function () {
  8451. // // Remove element containing the fields
  8452. // $(this).parents('.control-panel-row').remove();
  8453. //
  8454. // // re-write the titles
  8455. // $.each($('#customFieldForm').find('.numberField'), function (key, obj) {
  8456. // $(obj).html('Campo customizável ' + (key + 1));
  8457. // });
  8458. //
  8459. // var amountData = $('.js-customField').length;
  8460. // if (amountData <= 5) {
  8461. // $(".addData").removeClass('hide');
  8462. // } else {
  8463. // $(".addData").addClass('hide');
  8464. // }
  8465. // });
  8466. // }
  8467.  
  8468. var i = 0;
  8469. //verify if app has custom fields
  8470. if ((customFieldsJson !== null) && (customFieldsJson !== undefined)) {
  8471. $.each(customFieldsJson, function (index, value) {
  8472. i++;
  8473. if ((i == 1) && (value !== null) && (value !== undefined) && (value.custom_field_name !== undefined)) {
  8474. $("[name='data[0].custom_field']").attr('value', value.custom_field_name);
  8475. var selectField = $("#customFieldType0").attr('value', value.custom_field_type);
  8476. selectField.val(value.custom_field_type);
  8477. selectField.next('a').css({color: 'inherit'});
  8478. } else if ((value !== null) && (value !== undefined) && (value.custom_field_name !== undefined)) {
  8479. // var $template = $('#templateCustomFields'),
  8480. // $clone = $template
  8481. // .clone()
  8482. // .removeClass('hide')
  8483. // .addClass('.js-customField')
  8484. // .removeAttr('id')
  8485. // .insertBefore($template);
  8486. //
  8487. // var amountData = $('.js-customField').length - 1;
  8488. // num = amountData + 1; // initialize num
  8489.  
  8490. $('#addCustomField').trigger('click');
  8491.  
  8492. // .find('#customFieldName').attr('name', 'data[' + num + '].custom_field')
  8493. $('#customFieldName' + num).attr('value', value.custom_field_name);
  8494. // $('#customFieldType' + num).attr('value', value.custom_field_type);
  8495.  
  8496.  
  8497. // Update the name and value attributes
  8498. // $clone
  8499. // .find('[name="custom_field"]').attr('name', 'data[' + amountData + '].custom_field').attr('value', value.custom_field_name).end()
  8500. // .find('#customFieldType').attr('id', 'customFieldType' + amountData).end()
  8501. // .find('.numberField').html('Campo customizável ' + (amountData + 1)).end();
  8502.  
  8503. var selectField = $("#customFieldType" + num).attr('value', value.custom_field_type);
  8504. selectField.val(value.custom_field_type);
  8505. selectField.next('a').css({color: 'inherit'});
  8506.  
  8507. // $(".js-removeData").trigger("click");
  8508. // transform.customSelect('customFieldType' + amountData);
  8509.  
  8510. // if (amountData == 4)
  8511. // $(".addData").addClass('hide');
  8512. }
  8513. });
  8514.  
  8515. if (i > 1) {
  8516. $('.js-removeData').first().removeClass('hide');
  8517. }
  8518. }
  8519.  
  8520. // remove();
  8521. },
  8522.  
  8523. getSelectedAudiences: function () {
  8524. var elements = $('.list-checkbox');
  8525. var dict = '';
  8526.  
  8527. for (var i = 0; i < elements.length; i++) {
  8528. if ($('#audienceSelected' + i + ':checked').length > 0) {
  8529. var audience = $('#audienceSelected' + i).val();
  8530.  
  8531. if (audience !== '') {
  8532. if (dict == '')
  8533. dict = audience;
  8534. else
  8535. dict += ',' + audience;
  8536. }
  8537. }
  8538. }
  8539.  
  8540. return '"' + dict + '"';
  8541. },
  8542.  
  8543. getAudienceCriteria: function () {
  8544. var elements = $(".js-condition-row");
  8545. var dict = [];
  8546.  
  8547. for (var i = 0; i < elements.length; i++) {
  8548.  
  8549. var row = "#" + elements[i].id;
  8550. var selectCriteria = $(row.replace("jsConditionRow", "select") + '0');
  8551.  
  8552. var nameSelectCriteria = selectCriteria.val();
  8553. if (nameSelectCriteria != '' && nameSelectCriteria != undefined) {
  8554. var nameGroupCriteria = selectCriteria.find(':selected').closest('optgroup').attr('label');
  8555. var nameTypeCriteria = $(selectCriteria).find('option[value=' + nameSelectCriteria + ']').attr('data-type');
  8556.  
  8557. var objectTypeCondition = $(row).find('.js-' + nameTypeCriteria + '-condition');
  8558.  
  8559. var nameInputDeclaration, nameSelectCondition = '';
  8560. if (nameTypeCriteria == 'boolean') {
  8561. nameSelectCondition = objectTypeCondition.find('.ui-state-active').attr('data-value');
  8562. nameInputDeclaration = objectTypeCondition.find('.ui-state-active').find('a').attr("href").replace('#', '');
  8563. } else {
  8564. nameSelectCondition = objectTypeCondition.find('select[name=operator]').val();
  8565. nameInputDeclaration = objectTypeCondition.find('input[name=val]').val();
  8566. }
  8567.  
  8568. var nomeCriteria = $(selectCriteria).find(':selected')[0].innerText;
  8569.  
  8570. if ((nameSelectCriteria !== '') && (nameSelectCondition !== '') && (nameInputDeclaration !== '')) {
  8571. dict.push({
  8572. criteria: nameSelectCriteria,
  8573. nameCriteria: nomeCriteria,
  8574. groupCriteria: nameGroupCriteria,
  8575. typeCriteria: nameTypeCriteria,
  8576. condition: nameSelectCondition,
  8577. value: nameInputDeclaration
  8578. });
  8579. }
  8580. }
  8581. }
  8582. return dict;
  8583. },
  8584.  
  8585. insertRecentAudience: function (recentAudienceId) {
  8586. var $template = $('#templateAudienceRecent'),
  8587. $clone = $template
  8588. .clone()
  8589. .removeClass('hide')
  8590. .removeAttr('id')
  8591. .insertBefore($template);
  8592.  
  8593. var amountData = $('.templateRowAudience').length - 1;
  8594. var date = new Date();
  8595. var month = ("0" + (date.getMonth() + 1)).slice(-2);
  8596. var today = date.getDate() + '/' + month + '/' + date.getFullYear();
  8597.  
  8598. var rangeLocalFormat = parseInt($("#rangeNumber").text()).toLocaleString(locale);
  8599.  
  8600. $clone
  8601. .find('input[type=checkbox]').attr('value', recentAudienceId).attr('checked', true).end()
  8602. .find('input[id=audienceSelected]').attr('id', 'audienceSelected' + amountData).end()
  8603. .find('label[for=audienceSelected]').attr('for', 'audienceSelected' + amountData).end()
  8604. .find('[name="name"]').attr('name', 'nameAudience' + amountData).html($("#componentName").val()).end()
  8605. .find('[name="size"]').attr('name', 'sizeAudience' + amountData).html(rangeLocalFormat).end()
  8606. .find('[name="rank"]').attr('name', 'rankAudience' + amountData).html('-').end()
  8607. .find('[name="dateCreation"]').attr('name', 'dateCreationAudience' + amountData).html(today).end();
  8608.  
  8609. //update the range number
  8610. var rangeFullNumber = parseInt($('.range-full-number').html()) + parseInt($("#rangeNumber").text());
  8611. var rangeFullLocalFormat = rangeFullNumber.toLocaleString(locale);
  8612. $('.range-full-number').html(rangeFullLocalFormat);
  8613. $("#allAudiences").find('[id="sumSize"]').html(rangeFullLocalFormat);
  8614. $('#qtRecipients').html(rangeFullLocalFormat);
  8615. }
  8616.  
  8617. };
  8618.  
  8619. var charts = {
  8620.  
  8621. jsChart: '',
  8622. chartBg: '',
  8623. chartCanvas: '',
  8624.  
  8625. createDonutChart: function (context, value) {
  8626.  
  8627. var chart = value == 0 ? 'doughnut' : 'RoundedDoughnut';
  8628.  
  8629. Chart.defaults.RoundedDoughnut = Chart.helpers.clone(Chart.defaults.doughnut);
  8630. Chart.controllers.RoundedDoughnut = Chart.controllers.doughnut.extend({
  8631. draw: function (ease) {
  8632. var ctx = this.chart.chart.ctx;
  8633.  
  8634. var easingDecimal = ease || 1;
  8635. Chart.helpers.each(this.getDataset().metaData, function (arc, index) {
  8636. arc.transition(easingDecimal).draw();
  8637.  
  8638. var vm = arc._view;
  8639. var radius = (vm.outerRadius + vm.innerRadius) / 2;
  8640. var thickness = (vm.outerRadius - vm.innerRadius) / 2;
  8641. var angle = Math.PI - vm.endAngle - Math.PI / 2;
  8642.  
  8643. ctx.save();
  8644. ctx.fillStyle = vm.backgroundColor;
  8645. ctx.translate(vm.x, vm.y);
  8646. ctx.beginPath();
  8647. ctx.arc(radius * Math.sin(angle), radius * Math.cos(angle), thickness, 0, 2 * Math.PI);
  8648. ctx.arc(radius * Math.sin(Math.PI), radius * Math.cos(Math.PI), thickness, 0, 2 * Math.PI);
  8649. ctx.closePath();
  8650. ctx.fill();
  8651. ctx.restore();
  8652. });
  8653. }
  8654. });
  8655.  
  8656. var deliveredData = {
  8657. labels: [
  8658. "Value"
  8659. ],
  8660. datasets: [
  8661. {
  8662. data: [value, (100 - value)],
  8663. backgroundColor: [
  8664. "#3ec556",
  8665. "rgba(0,0,0,0)"
  8666. ],
  8667. hoverBackgroundColor: [
  8668. "#3ec556",
  8669. "rgba(0,0,0,0)"
  8670. ],
  8671. borderWidth: [
  8672. 0, 0
  8673. ]
  8674. }]
  8675. };
  8676.  
  8677. var deliveredOpt = {
  8678. cutoutPercentage: 88,
  8679. animation: {
  8680. animationRotate: true,
  8681. duration: 1000
  8682. },
  8683. legend: {
  8684. display: false
  8685. },
  8686. tooltips: {
  8687. enabled: false
  8688. }
  8689. };
  8690.  
  8691. this.jsChart = $('.js-chart');
  8692. this.chartBg = $('.chart-background');
  8693. this.chartCanvas = $('.chart-canvas');
  8694.  
  8695. $(window).on('resize', function () {
  8696. charts.resizeChartDiv();
  8697. });
  8698.  
  8699. return new Chart($(context), {
  8700. type: chart,
  8701. data: deliveredData,
  8702. options: deliveredOpt
  8703. });
  8704. },
  8705.  
  8706. resizeChartDiv: function () {
  8707. charts.jsChart.each(function () {
  8708. var width = $(this).width();
  8709. $(this).height(width);
  8710.  
  8711. charts.chartBg.each(function () {
  8712. var width = charts.chartCanvas.width() * 0.065;
  8713. $(this).css({borderWidth: width});
  8714. })
  8715.  
  8716. });
  8717. }
  8718.  
  8719. };
  8720.  
  8721. var validate = {
  8722.  
  8723. /**
  8724. *
  8725. * @param idValue id or OBJECT to be validated (must not be null or '')
  8726. * @param message string message to be shown if there is error
  8727. * @param redBox object [optional] where the red border is to be drawn. if not set will use the idValue
  8728. * @param errorPosition object [optional] the message will be shown after this obj. if not set will use the idValue
  8729. *
  8730. * */
  8731. field: function (idValue, message, redBox, errorPosition, setError) {
  8732.  
  8733. var valid = true;
  8734. var field = $(idValue);
  8735.  
  8736. if (redBox != undefined) {
  8737. var fieldBox = $(redBox);
  8738. } else {
  8739. fieldBox = $(idValue);
  8740. }
  8741. if (errorPosition != undefined) {
  8742. var aboveError = $(errorPosition);
  8743. } else {
  8744. aboveError = $(idValue);
  8745. }
  8746.  
  8747. var errorElement = "<div class='has-error error-pad js-error'>" +
  8748. "<span class='help-block'>" + message + "</span></div>";
  8749.  
  8750. var jsError = aboveError.next('.js-error');
  8751. //jsError.remove();
  8752.  
  8753. fieldBox.off('focus.valid').on('focus.valid', function () {
  8754. if (fieldBox.hasClass('error-outline')) {
  8755. var jsError = aboveError.next('.js-error');
  8756. fieldBox.removeClass('error-outline');
  8757. fieldBox.one('blur', function () {
  8758. if (field.val() == null || field.val() == '') {
  8759. jsError.remove();
  8760. fieldBox.addClass('error-outline');
  8761. aboveError.after(errorElement);
  8762. } else {
  8763. // $('#error-pushContent').slideUp('fast');
  8764. jsError.slideUp('fast', function () {
  8765. this.remove();
  8766. });
  8767. // get rid of the error message at footer bar
  8768. $('#footerError').fadeOut('fast', function () {
  8769. $(this).html('');
  8770. $(this).show();
  8771. });
  8772. }
  8773. });
  8774. }
  8775. });
  8776.  
  8777. if (field.val() == null || field.val() == '' || setError == true) {
  8778. // $('i').after("<div class='has-error js-error' style='line-height: 3em;'><span class='help-block'>" + message + "</span></div>");
  8779. jsError.remove();
  8780. aboveError.after(errorElement);
  8781. fieldBox.addClass('error-outline');
  8782. valid = false;
  8783. }
  8784. return valid;
  8785.  
  8786. },
  8787.  
  8788. /**
  8789. * To validate all fields at once. Pass an Array of arrays.
  8790. * If is to validate using validate.field, then pass an array with the parameters for this function.
  8791. * If it is a validation function, pass an array where the first element is the function name (without ()) and the
  8792. * other elements are parameters (if needed).
  8793. *
  8794. * @param array array = [[idValue, message, redBox, errorPosition], [idValue, message], [function, param1, param2]]
  8795. *
  8796. * */
  8797. multiFields: function (array) {
  8798.  
  8799. var valid = [];
  8800. var validated = true;
  8801.  
  8802. $.each(array, function (index, obj) {
  8803. if (typeof obj[0] === 'function') {
  8804. var params = [];
  8805. for (var i = 1; i < obj.length; i++) {
  8806. params.push(obj[i]);
  8807. }
  8808. valid.push(obj[0].apply(this, params));
  8809. } else {
  8810. valid.push(validate.field(obj[0], obj[1], obj[2], obj[3]));
  8811. }
  8812.  
  8813. });
  8814.  
  8815. $.each(valid, function (key, value) {
  8816. if (!value) {
  8817. validated = false;
  8818. }
  8819. });
  8820. return validated;
  8821. },
  8822.  
  8823. fieldsAdditionalData: function () {
  8824. var elements = $('#additionalBlock').find('.js-dataRow');
  8825. var valid = [];
  8826. var validated = true;
  8827.  
  8828. $.each(elements, function (num, obj) {
  8829. var keyObj = $(obj).find('input[name="additional-key"]');
  8830. var valueObj = $(obj).find('input[name="additional-value"]');
  8831.  
  8832. var key = keyObj.val();
  8833. var value = valueObj.val();
  8834.  
  8835. if (key != '' || value != '') {
  8836. valid.push(validate.field(keyObj, 'Qual a chave?'));
  8837. valid.push(validate.field(valueObj, 'Qual o valor?'));
  8838. }
  8839. });
  8840.  
  8841. $.each(valid, function (key, value) {
  8842. if (!value)
  8843. validated = false;
  8844. });
  8845.  
  8846. return validated;
  8847. },
  8848.  
  8849. fieldsAudienceCriteria: function (mandatoryCriteria) {
  8850. var elements = $(".js-condition-row");
  8851. var valid = [];
  8852. var validated = true;
  8853. var atLeastOne = false;
  8854.  
  8855. for (var i = 0; i < elements.length; i++) {
  8856. var row = "#" + elements[i].id;
  8857. var selectCriteria = $(row.replace("jsConditionRow", "select") + '0');
  8858. //var nameGroupCriteria = selectCriteria.find(':selected').closest('optgroup').attr('label');
  8859.  
  8860. if (selectCriteria.val() !== '' && mandatoryCriteria) {
  8861. atLeastOne = true; // at least 1 criteria has to be set
  8862.  
  8863. var nameTypeCriteria = $(selectCriteria).find('option[value=' + selectCriteria.val() + ']').attr('data-type');
  8864. var objectTypeCondition = $(row).find('.js-' + nameTypeCriteria + '-condition');
  8865. var selectCondition = objectTypeCondition.find('select[name=operator]');
  8866. var inputDeclaration = objectTypeCondition.find('input[name=val]');
  8867.  
  8868. if ($(selectCriteria).val() == '') {
  8869. valid.push(validate.field(selectCriteria['selector'], 'Qual o critério?'),
  8870. $(selectCriteria['selector']).nextAll('a'), $(selectCriteria['selector']).nextAll('a'));
  8871.  
  8872. } else if ($(selectCondition).val() == '') {
  8873. valid.push(validate.field(selectCondition, 'Qual a condição?',
  8874. $(selectCondition).next('a'), $(selectCondition).next('a')));
  8875. if ($(inputDeclaration).val() == '')
  8876. valid.push(validate.field(inputDeclaration['selector'], 'Com o que vamos comparar?'));
  8877.  
  8878. } else if ($(inputDeclaration).val() == '')
  8879. valid.push(validate.field(inputDeclaration['selector'], 'Com o que vamos comparar?'));
  8880. }
  8881. }
  8882.  
  8883. if (!atLeastOne) {
  8884. row = "#" + elements[0].id;
  8885.  
  8886. selectCriteria = $(row.replace("jsConditionRow", "select") + '0');
  8887.  
  8888. if (!validate.field(selectCriteria['selector'], 'Precisamos de pelo menos um critério',
  8889. $(selectCriteria['selector']).next('a'), $('.js-errorPosition').parent('span'))) {
  8890. validated = false;
  8891. }
  8892.  
  8893. } else {
  8894. $.each(valid, function (key, value) {
  8895. if (!value)
  8896. validated = false;
  8897. });
  8898. }
  8899. return validated;
  8900. },
  8901.  
  8902. fieldCampaignAutomation: function (campaignId, automationId) {
  8903. if (automationId == 0 && (campaignId == '' || campaignId == '0')) {
  8904. validate.field('#campaign', 'Por favor, selecione uma campanha para automatizar', '#selectCampaign');
  8905.  
  8906. return false;
  8907. }
  8908.  
  8909. return true;
  8910. },
  8911.  
  8912. /**
  8913. * @param requireUsers boolean If the service needs audience with users (true) or not (false)
  8914. * */
  8915. fieldsAudienceCampaign: function (dontRequireUsers) {
  8916. var elements = $(".list-checkbox");
  8917. var valid = [];
  8918. var validated = true;
  8919. var qtAudiencesSelected = 0;
  8920.  
  8921. for (var i = 0; i < elements.length; i++) {
  8922. if ($('#audienceSelected' + i + ':checked').length > 0)
  8923. qtAudiencesSelected += 1;
  8924. }
  8925.  
  8926. var qtSelected = $('.range-full-number').html();
  8927.  
  8928. $(document).off('ajaxComplete.valid'); // remove ajax so it won't be bound twice if there is another error,
  8929. // like audience with no users
  8930.  
  8931. function showErrorMessage(text) {
  8932. validated = false;
  8933. valid.push(validate.field('label', text, $('none'), $('.table-be-table')));
  8934. $('.js-audienceLabel').css({borderColor: '#EC7E7E'});
  8935. $(document).on('ajaxComplete.valid', function (e, xhr, options) {
  8936. validate.fieldsAudienceCampaign(); //validate again on audience selection
  8937. if (options.url != '/handleSubscribersAudience') { //remove this handler if user change pages
  8938. $(document).off('ajaxComplete.valid');
  8939. }
  8940. });
  8941. }
  8942.  
  8943. if (qtAudiencesSelected == 0) {
  8944. showErrorMessage('Por favor, selecione uma audiência para enviar sua mensagem');
  8945. } else if (qtSelected == 0 && !dontRequireUsers) {
  8946. showErrorMessage('As audiências selecionadas não possuem usuários. Por favor, selecione outra.');
  8947. } else {
  8948. $('#audienceSelectTable').next('.js-error').remove();
  8949. $('.js-audienceLabel').removeClass("error-outline").css({borderColor: ''});
  8950. $('.push-row').find('input[type=checkbox]').off('change.error');
  8951. }
  8952.  
  8953. return validated;
  8954. },
  8955.  
  8956. quantitySubscribers: function (countSubscribers) {
  8957. var valid = [];
  8958. var validated = true;
  8959.  
  8960. if (countSubscribers == 0) {
  8961. // validated = false;
  8962. // valid.push(validate.field('label', 'Não há nenhum usuário cadastrado para esse app'));
  8963. // $('.has-error').css({marginTop: '-31px'});
  8964. $('.list-checkbox').children('label').css({borderColor: '#EC7E7E'});
  8965. $('#footerError').html('Não há nenhum usuário cadastrado.<br>Infelizmente não podemos enviar nenhum push.');
  8966. $('#sendPushBtn').off('click').css({backgroundColor: '#b5b5b5', cursor: 'default'});
  8967. } else {
  8968. // $('.js-error').remove();
  8969. // $('.list-checkbox').children('label').removeClass("error-outline").css({borderColor: ''});
  8970. // $('.has-error').css({marginTop: ''});
  8971. }
  8972.  
  8973. return validated;
  8974. }
  8975. };
Add Comment
Please, Sign In to add comment