Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /**
- * Created by Juliano on 04/02/2016.
- */
- var contentContainer = $("#content-container");
- var appHeader = $("#app-header");
- window.locale = 'pt-br';
- (function ($, undefined) {
- $.fn.getCursorPosition = function () {
- var el = $(this).get(0);
- var pos = 0;
- if ('selectionStart' in el) {
- pos = el.selectionStart;
- } else if ('selection' in document) {
- el.focus();
- var Sel = document.selection.createRange();
- var SelLength = document.selection.createRange().text.length;
- Sel.moveStart('character', -el.value.length);
- pos = Sel.text.length - SelLength;
- }
- return pos;
- }
- })(jQuery);
- var access = {
- /* Hover open effect on menu */
- threeDots: function () {
- var optionsBalloon = $("#options-balloon");
- var timer;
- $("#3-dots-menu").on("mouseleave", function () {
- timer = setTimeout(function () {
- optionsBalloon.fadeOut("fast");
- }, 400);
- }).on("click", function () {
- clearTimeout(timer);
- optionsBalloon.fadeToggle("fast");
- event.stopPropagation();
- });
- optionsBalloon.on("mouseenter", function () {
- clearTimeout(timer);
- optionsBalloon.fadeIn();
- event.stopPropagation();
- }).on("mouseleave", function (event) {
- timer = setTimeout(function () {
- optionsBalloon.fadeOut("fast");
- event.stopPropagation();
- }, 400);
- });
- $("#sign-btn-arrow").on("click", function () {
- $("#btn_next").trigger("click");
- });
- $("#forgot-btn-arrow").on("click", function () {
- $("#btn_send").trigger("click");
- });
- },
- /* This is used to personalize the select element of sign up page
- *
- * Have to add this on the page (Theter and Select):
- * <link rel="stylesheet" href="select-theme-default.css" />
- * <script src="tether.min.js"></script>
- * <script src="select.min.js"></script>
- *
- * Then use this code here to use a placeholder and style the element.
- *
- * More info: http://github.hubspot.com/select/docs/welcome/
- */
- customSelect: function () {
- var signSelect;
- var element = document.getElementById('companySize');
- signSelect = new Select({
- el: element,
- className: 'select-theme-inngage'
- });
- signSelect.on('change', function () {
- $(".select-target.select-theme-inngage").css({color: '#444'});
- });
- element.setAttribute('tabindex', '-1');
- },
- doLogout: function () {
- var formData = {
- 'logout': true
- };
- var ajaxSend = $.ajax({
- type: 'POST',
- url: '/handleLogout',
- data: formData,
- dataType: 'json',
- encode: true,
- timeout: 10000
- }).done(function (data) {
- console.log('done');
- //modal.closeModal();
- // modal.getModal('success-saved.php', true, {obj: 'Campanha', justShow: true});
- }).fail(function (data) {
- console.log(data);
- //action.verifyBehavior('fail', afterAction);
- ajaxSend.abort();
- });
- }
- };
- var ref = {
- // INCLUDES
- getIncludes: "/includes",
- // INCLUDES APP-PG
- getAppPg: "/includes/app-pg",
- // INCLUDES MAIN-PG
- getMainPg: "includes/main-pg",
- // PLUGINS PATH
- getPlugins: "/resources/plugins",
- // UPLOADS PATH
- getUploads: "/resources/uploads",
- // VIEW PATH
- getView: "/view"
- };
- var navigation = {
- /* Code to show and hide user pop-up menu in nav bar.
- * The arrow behavior is set here too.
- * */
- userMenu: function () {
- /* show user pop up menu when mouse enters the user bar space */
- var popUpMenu = $("#user-pop");
- var userBar = $(".user-bar");
- var optionsArrow = $("#options-arrow");
- // has to use 2 timers to work when leave popMenu and comes back to userBar
- var timerUser; // timer for when leave userBar
- var timerPop; // timer for when leave userPopMenu
- userBar.on("mouseenter", function (event) {
- clearTimeout(timerUser);
- clearTimeout(timerPop);
- //popUpMenu.fadeIn("fast");
- event.stopPropagation();
- //optionsArrow.addClass('rotate');
- }).on("mouseleave", function () {
- timerUser = setTimeout(function () {
- popUpMenu.fadeOut("fast");
- //event.stopPropagation();
- optionsArrow.removeClass('rotate-180');
- }, 250);
- }).off('click').click(function (event) {
- event.stopPropagation();
- optionsArrow.toggleClass('rotate-180');
- popUpMenu.toggle();
- });
- popUpMenu.on("mouseenter", function () {
- clearTimeout(timerUser);
- clearTimeout(timerPop);
- popUpMenu.fadeIn("fast");
- //event.stopPropagation();
- optionsArrow.addClass('rotate-180');
- }).on("mouseleave", function () {
- timerPop = setTimeout(function () {
- popUpMenu.fadeOut("fast");
- //event.stopPropagation();
- optionsArrow.removeClass('rotate-180');
- }, 250);
- });
- // show the user pop-up menu, and hide it clicking anywhere else in the page
- $(document).on("click", function () {
- popUpMenu.fadeOut("fast");
- optionsArrow.removeClass('rotate-180');
- $("#options-balloon").hide();
- $("#config-balloon").hide();
- });
- },
- /* Menu-side scroll effect */
- navSideScroll: function () {
- var lastScrollPosition = 0;
- var navSide = $("#nav-side");
- var space = "<div style='height: " + navSide.height() + "px;'></div>";
- // var space = "<div style='height: " + navSide.height() + "px;' id='space'></div>";
- // $('#space').remove();
- $('body').prepend(space);
- $(window).scroll(function () {
- var screenWindow = $(window);
- var sp = screenWindow.scrollTop();
- //scrolling down
- if (lastScrollPosition < sp) {
- //if screen passes nav-side bottom
- if (sp + screenWindow.height() >= navSide.height() + navSide.offset().top) {
- navSide.addClass("nav-side-fixed-bot");
- }
- //else if scrolling up
- } else {
- //and is fixed bot
- if (navSide.hasClass("nav-side-fixed-bot")) {
- //set top, pass to absolute
- navSide.removeClass('nav-side-fixed-bot');
- navSide.css({top: sp + screenWindow.height() - navSide.height()});
- }
- //and if scroll is above nav-side top, then set nav-side top to scroll
- if (sp <= navSide.offset().top) {
- navSide.css({top: sp});
- }
- }
- lastScrollPosition = sp;
- });
- $(window).trigger('scroll');
- },
- /* Put shadow on nav-top when user scrolls the screen */
- navTopShadow: function () {
- $(window).scroll(function () {
- var navTop = $(".nav-top");
- if ($(window).scrollTop() > 0) {
- navTop.addClass('nav-top-shadow');
- } else {
- navTop.removeClass('nav-top-shadow');
- }
- });
- },
- navTop: function () {
- this.userMenu();
- this.navTopShadow()
- },
- navSide: function () {
- this.navSideScroll();
- }
- };
- var behaviors = {
- /*
- * This function applyes the menu pop behavior to menu buttons and pop menus.
- * Call this function with the menu trigger button.
- *
- * @param popMenu what is the menu ID to be poped-up (pass #id)
- * @param buttonID what is the menu button ID to open the pop-up (pass #id)
- * @param expandClass class with animation to expand
- * @param shrinkClass class with animation to shrink
- *
- * */
- popUp: function (buttonID, popMenuId, expandClass, shrinkClass) {
- // has to use 2 timers to work when leave popMenu and comes back to userBar
- var timerThis; // timer for when leave 'this'
- var timerPop; // timer for when leave popMenu
- var popMenu = $(popMenuId);
- var button = $(buttonID);
- popMenu.css({visibility: 'visible'}).hide();
- function expand() {
- button.children('img').removeClass(shrinkClass);
- button.children('img').addClass(expandClass);
- }
- function shrink() {
- button.children('img').removeClass(expandClass);
- button.children('img').addClass(shrinkClass);
- }
- button.on('click', function (e) {
- e.stopPropagation();
- popMenu.fadeToggle('fast');
- $(document).one('mouseup.popMenu', function (e) {
- if (!popMenu.is(e.target) // if the target of the click isn't the container...
- && popMenu.has(e.target).length === 0) { // ... nor a descendant of the container
- popMenu.fadeOut("fast");
- shrink();
- }
- });
- }).on("mouseenter", function () {
- clearTimeout(timerThis);
- clearTimeout(timerPop);
- expand();
- }).on("mouseleave", function () {
- timerThis = setTimeout(function () {
- popMenu.fadeOut("fast");
- shrink();
- $(document).off('mouseup.popMenu');
- }, 300);
- });
- popMenu.on("mouseenter", function () {
- clearTimeout(timerThis);
- clearTimeout(timerPop);
- popMenu.fadeIn("fast");
- }).on("mouseleave", function () {
- timerPop = setTimeout(function () {
- popMenu.fadeOut("fast");
- shrink();
- $(document).off('mouseup.popMenu');
- }, 600);
- });
- },
- //no-app change fill color
- plusApp: function () {
- $("#plus-app, #new-app-btn").hover(function () {
- $("#plus-app").addClass("plus-app-hover");
- $("#new-app-btn").addClass("button-blue-hover");
- }, function () {
- $("#plus-app").removeClass("plus-app-hover");
- $("#new-app-btn").removeClass("button-blue-hover");
- });
- },
- /* Insert a local input field to edit content
- *
- * @param clicked element to be clicked and trigger the effect
- * @param toFadeOut element to get rid of
- * @param editCount number of the element to be used in IDs
- * @param wordID the identification text of the ID to be used in selector
- *
- * Update: previous version inserted html to the DOM. This version doesn't
- * */
- editField: {
- // Distinguish between cancel and accept for different fields
- function: function (clicked, toFadeOut, toFadeIn, wordId) {
- //var thisEditCount = editCount;
- var fadeOutThis = $(toFadeOut);
- var fadeInThis = $(toFadeIn);
- //var textValue = $.trim(fadeOutThis.text());
- $(clicked).on('click', function (e) {
- fadeOutThis.fadeOut('fast', function () {
- fadeInThis.fadeIn('fast', function () {
- var inputElem = fadeInThis.find('input');
- // var originalValue = inputElem.val();
- $(document).on('keyup', function (e) {
- if (e.keyCode == 13) {
- $("#accept" + wordId).trigger('click');
- }
- if (e.keyCode == 27) {
- $("#cancel" + wordId).trigger('click');
- }
- });
- $("#accept" + wordId).on('click', function () {
- //var newName = editionInput.val();
- $('#cancel' + wordId).trigger('click');
- });
- $('#cancel' + wordId).on('click', function () {
- fadeInThis.fadeOut('fast', function () {
- fadeOutThis.fadeIn('fast');
- // inputElem.val(originalValue);
- });
- //$('.input-div').css({textAlign: 'right'});
- $(document).off('**');
- });
- $('#input' + wordId).select();
- });
- });
- });
- }
- },
- /* Change SVG color
- * Takes the image source attribute and change the last name to the color to use
- * @param imgTag pass selector of the IMG to switch
- * @param color name of the color */
- svgChangeTo: {
- color: function (imgTag, color) {
- var image = $(imgTag);
- var imgSource = image.attr('src');
- var splited = imgSource.split('-');
- splited[splited.length - 1] = color + '.svg';
- imgSource = splited.join('-');
- image.attr('src', imgSource);
- },
- hover: function (imgTag) {
- var image = $(imgTag);
- var imgSource = image.attr('src');
- var splited = imgSource.split('-');
- var last = splited[splited.length - 1];
- if (last == 'hover.svg') {
- splited[splited.length - 1] = '.svg';
- imgSource = splited.join('-').replace('-.', '.');
- } else {
- splited = imgSource.split('.');
- splited[splited.length - 1] = '-hover.svg';
- imgSource = splited.join('');
- }
- image.attr('src', imgSource);
- },
- white: function (imgTag) {
- this.color(imgTag, 'white');
- },
- blue: function (imgTag) {
- this.color(imgTag, 'blue');
- },
- gray: function (imgTag) {
- this.color(imgTag, 'gray');
- }
- },
- /* auto adjust textarea */
- autoTextArea: function () {
- var textArea = $('.textarea');
- textArea.each(function () {
- $(this).on('keyup', function () {
- $(this).height(0);
- $(this).height(this.scrollHeight);
- });
- $(this).keyup();
- });
- },
- sendPush: function () {
- modal.closeModal();
- navigateTo.app.push.notificationsSent();
- },
- schedulePush: function () {
- modal.closeModal();
- navigateTo.app.push.notificationsScheduled();
- },
- sendPushFail: function (message) {
- modal.closeModal(['modal-fail-push.php', undefined, {message: message}]);
- },
- saveAudienceFail: function () {
- modal.closeModal(['modal-fail-push.php']);
- },
- saveSecurityParameter: function () {
- modal.closeModal(['modal-fail-security-parameter.php']);
- },
- saveAutomationFail: function () {
- modal.closeModal(['modal-fail-automation.php']);
- },
- saveApiTemplateFail: function () {
- modal.closeModal(['modal-fail-api-template.php']);
- },
- saveCamp: function () {
- modal.closeModal(['success-saved.php', true, {
- obj: 'Campanha salva',
- navigate_method: 'navigateTo.app.push.campaigns();'
- }]);
- },
- saveCampFail: function () {
- modal.closeModal(['modal-failed.php', false, {obj: 'Campanha'}]);
- },
- saveSendCamp: function (campId) {
- $.ajax({
- url: '/getCampaign',
- type: "POST",
- data: {'campId': campId, 'action': 'send'},
- success: function (data) {
- contentContainer.html(data);
- modal.closeModal();
- // modal.getModal('success-saved.php', true, {obj: 'Campanha', justShow: true});
- },
- fail: function (data) {
- alert(data);
- }
- });
- },
- sendSaveCampFail: function () {
- this.sendPushFail();
- },
- saveAudience: function () {
- modal.closeModal(['success-saved.php', true, {
- obj: 'Audiência salva',
- navigate_method: 'navigateTo.app.audience.audiences();'
- }]);
- },
- saveAutomation: function () {
- modal.closeModal(['success-saved.php', true, {
- obj: 'Automação salva',
- navigate_method: 'navigateTo.app.push.automations();'
- }]);
- },
- saveApiTemplate: function () {
- modal.closeModal(['success-saved.php', true, {
- obj: 'API Template salva',
- navigate_method: 'navigateTo.app.push.apiTemplate();'
- }]);
- },
- inactivateAudience: function () {
- modal.closeModal();
- // update page values
- // lastRegister
- var lastRegister = $('#lastRegister');
- var lastItemValue = lastRegister.html();
- lastRegister.html(lastItemValue - 1);
- // totalRegsiter
- var totalRegisters = $('#totalRegisters');
- var totalRegistersValue = totalRegisters.html();
- totalRegisters.html(totalRegistersValue - 1);
- },
- tagTemplateSelection: function () {
- function insertText(context, open, close) {
- var aim = context.parent('div').attr('data-box');
- console.log(aim);
- var emojiDiv = $('.emoji-wysiwyg-editor').eq(aim);
- var tag = context.children('span').html();
- emojiDiv.html(emojiDiv.html() + open + tag + close);
- emojiDiv.trigger('keyup');
- $('#tagTemplateMenu').fadeOut('fast');
- }
- $('#tagTemplateMenu').on('click', '.js-customField', function () {
- insertText($(this), '|*', '*|');
- }).on('click', '.js-tagField', function () {
- insertText($(this), '{{', '}}');
- });
- },
- /* Insert new row to add data
- *
- * @param context String selector which is the context of the list (maxRows will be used there)
- * @param maxRows number max number of rows
- * */
- listData: {
- add: function (context, maxRows) {
- if (context == undefined) {
- context = $('body');
- } else {
- context = $(context);
- }
- if (maxRows === undefined) {
- maxRows = Number.POSITIVE_INFINITY;
- }
- context.find('.addNewData').hover(function () {
- $(this).css({fontWeight: '400'});
- behaviors.svgChangeTo.hover($(this).children('img'));
- }, function () {
- $(this).attr('style', '');
- behaviors.svgChangeTo.hover($(this).children('img'));
- }).on("click", function () {
- var context = $(this).parents('.control-panel');
- if (context.find('.js-dataRow').length < maxRows) {
- var $template = context.find('.js-dataTemplate');
- // var $clone = $template
- $template.clone()
- .removeClass('hide')
- .removeClass('js-dataTemplate')
- .addClass('js-dataRow')
- .insertBefore($template);
- // var amountData = $('.template').length - 1;
- var amountData = context.find('.js-dataRow').length;
- // if more than 1, show del to all
- // if (amountData != 1) {
- // context.find(".js-removeData").removeClass('hide');
- // }
- // Update the name attributes
- // $clone
- // .find('[name="' + sectionName + '-key"]').attr('name', 'data[' + amountData + '].' + sectionName + '-key').end()
- // .find('[name="' + sectionName + '-value"]').attr('name', 'data[' + amountData + '].' + sectionName + '-value').end();
- //add click atribute
- // behaviors.listData.remove(maxRows);
- if (amountData == maxRows) {
- context.find(".addData").addClass('hide');
- }
- }
- });
- context.on('hover', '.js-removeData', function () {
- behaviors.svgChangeTo.hover($(this).children('img'));
- }, function () {
- behaviors.svgChangeTo.hover($(this).children('img'));
- }).on("click", '.js-removeData', function () {
- var context = $(this).parents('.control-panel');
- // Remove element containing the fields
- $(this).parents('.control-panel-row').remove();
- // Count lines
- var amountData = context.find('.js-dataRow').length;
- if (amountData < maxRows) {
- $(".addData").removeClass('hide');
- // if (amountData == 1) {
- // context.find(".js-removeData").addClass('hide');
- // }
- } else {
- $(".addData").addClass('hide');
- }
- });
- },
- populate: function (contextId, object) {
- var context = $(contextId);
- var addButton = context.find('.addNewData');
- $.each(object, function (key, obj) {
- addButton.trigger('click');
- var lastRow = context.find('.js-dataRow').last();
- if (obj === Object(obj)) {
- $.each(obj, function (key, value) {
- lastRow.find(key).val(value);
- })
- } else {
- lastRow.find('input').val(obj);
- }
- })
- }
- },
- togglePassword: function (context, id) {
- var elm = document.getElementById(id);
- if (elm.type == "password") {
- elm.type = "text";
- //$(context).removeClass("glyphicon-eye-open");
- $(context).addClass("blue-flat");
- } else if (elm.type == "text") {
- elm.type = "password";
- $(context).removeClass("blue-flat");
- //$(context).toggleClass("glyphicon-eye-close");
- }
- }
- };
- var action = {
- verifyBehavior: function (result, afterAction, message) {
- var behavior;
- if (result == 'success') {
- switch (afterAction) {
- case 'justSend':
- behavior = behaviors.sendPush();
- break;
- case 'scheduleSend':
- behavior = behaviors.schedulePush();
- break;
- case 'saveCamp':
- behavior = behaviors.saveCamp();
- break;
- case 'saveSendCamp':
- behavior = behaviors.saveSendCamp;
- break;
- case 'saveAudience':
- behavior = behaviors.saveAudience();
- break;
- case 'saveAutomation':
- behavior = behaviors.saveAutomation();
- break;
- case 'inactivateAudience':
- behavior = behaviors.inactivateAudience();
- break;
- case 'saveApiTemplate':
- behavior = behaviors.saveApiTemplate();
- break;
- default:
- break;
- }
- } else if (result == 'fail') {
- switch (afterAction) {
- case 'justSend':
- behavior = behaviors.sendPushFail(message);
- break;
- case 'saveCamp':
- behavior = behaviors.saveCampFail();
- break;
- case 'saveSendCamp':
- behavior = behaviors.sendSaveCampFail();
- break;
- case 'saveAudience':
- behavior = behaviors.saveAudienceFail();
- break;
- case 'saveAutomation':
- behavior = behaviors.saveAutomationFail();
- break;
- case 'saveApiTemplate':
- behavior = behaviors.saveApiTemplateFail();
- break;
- case 'saveSecurityParameter':
- behavior = behaviors.saveSecurityParameter();
- break;
- default:
- break;
- }
- }
- return behavior;
- },
- /* AJAX to send push (used in Send Push and Campaign)
- *
- * audiencesSelected array audiences in string ('audience1,audience2,audience3')
- * if private msg, audiencesSelected = 'false,identifier'
- * */
- sendPush: function (appId, appToken, afterAction, campId, audiencesSelected) {
- if (campId == null || campId == '') {
- campId = 0;
- }
- var pushContent = $('#pushContent');
- isScheduler = $('.js-check-showUpSend').is(':checked');
- if (!isScheduler) {
- modal.closeModal(); //don't put modal in closeModal because of undesired async behavior
- modal.getModal('modal-sending-push.php', true);
- } else {
- modal.closeModal();
- modal.getModal('modal-scheduling-push.php', true);
- }
- var pushMsgToPersist = pushContent.val();
- var msgContent = window.emojiPicker.colonToUnicode(pushMsgToPersist);
- var additionalData = scriptForPage.getAdditionalData();
- var flagAdditional = false;
- if (additionalData.length > 0)
- flagAdditional = true;
- var formData = {
- 'msgTitle': $('input[name=msg-title]').val(),
- 'msgContent': msgContent,
- 'appId': appId,
- 'appToken': appToken,
- 'action': 'doSendPush',
- 'flagSchedule': $('.js-check-showUpSend').is(':checked'),
- 'sendDate': $('input[name=sendDate]').val(),
- 'sendHour': $('select[name=sendHour]').val(),
- 'sendMinute': $('select[name=sendMinute]').val(),
- 'persistMsg': pushMsgToPersist,
- 'campId': campId,
- 'flagUrl': $('.js-check-showUpURL').is(':checked'),
- 'urlPush': $('input[name=open-url]').val(),
- 'imgPush': $('input[name=msg-image]').val(),
- 'flagAdditional': flagAdditional,
- 'additionalData': additionalData,
- 'audiences': audiencesSelected
- };
- var ajaxSend = $.ajax({
- type: 'POST',
- url: '/sendPushValidation',
- data: formData,
- dataType: 'json',
- encode: true,
- //timeout: 10000
- //timeout: 120000
- })
- .done(function (data) {
- console.log(data);
- if (data.errors == null) {
- if (campId == 0) {
- action.saveAdditionalData(0, data.message_control_id, 0);
- action.savePushAdresses('NULL', data.message_control_id, audiencesSelected);
- }
- while ($(".modal-container").length == 0) {
- // wait until previous modal is loaded, so it will be correctly closed on afterAction
- }
- action.verifyBehavior('success', afterAction);
- } else {
- action.verifyBehavior('fail', afterAction, data.message);
- }
- })
- .fail(function (data) {
- console.log(data);
- action.verifyBehavior('fail', afterAction);
- ajaxSend.abort();
- });
- },
- saveCampaign: function (appId, appToken, campId, afterAction) {
- var flDraft = 1; //rascunho
- if (afterAction == undefined || afterAction == 'saveSendCamp') { //if there is no afterAction (send Campaign), change to "active" campaign
- flDraft = 0; //enviado
- }
- var formData = {
- 'msgTitle': $('input[name=msg-title]').val(),
- 'msgBody': $('#pushContent').val(),
- 'appId': appId,
- 'campId': campId,
- 'campName': $('#componentName').val(),
- 'campDescription': $('#componentDescription').val(),
- 'campFlDraft': flDraft,
- 'campStatus': 0,
- // 'flagSchedule': $('.js-check-showUpSend').is(':checked'),
- // 'sendDate': $('input[name=sendDate]').val(),
- // 'sendHour': $('select[name=sendHour]').val(),
- // 'sendMinute': $('select[name=sendMinute]').val(),
- 'flagUrl': $('.js-check-showUpURL').is(':checked'),
- 'urlPush': $('input[name=open-url]').val(),
- 'imgPush': $('input[name=msg-image]').val()
- };
- var ajaxSave = $.ajax({
- type: 'POST',
- url: '/handleCampaign',
- data: formData,
- timeout: 10000
- })
- .done(function (data) {
- var campId = data;
- console.log('done');
- action.saveAdditionalData(campId, 0, 0, '');
- var goToSendCamp = action.verifyBehavior('success', afterAction);
- if (afterAction == 'saveSendCamp')
- goToSendCamp(campId);
- })
- .fail(function () {
- console.log('fail');
- action.verifyBehavior('fail', afterAction);
- }).error(function () {
- action.verifyBehavior('fail', afterAction);
- ajaxSave.abort();
- });
- },
- saveAdditionalData: function (campaignId, controlMessageId, automationId, afterAction, apiTemplateId) {
- function getAdditionalData() {
- var elements = $('#additionalBlock').find('.js-dataRow');
- var dict = [];
- $.each(elements, function (num, obj) {
- var key = $(obj).find('input[name="additional-key"]').val();
- var value = $(obj).find('input[name="additional-value"]').val();
- if ((key !== '') && (value !== '')) {
- dict.push({key: key, value: value});
- }
- });
- return dict;
- }
- var additionalData = getAdditionalData();
- var flagAdditional = false;
- if (additionalData.length > 0)
- flagAdditional = true;
- var formData = {
- 'controlMessageId': controlMessageId,
- 'campaignId': campaignId,
- 'automationId': automationId,
- 'flagAdditional': flagAdditional,
- 'additionalData': additionalData,
- 'apiTemplateId': apiTemplateId
- };
- var ajaxSave = $.ajax({
- type: 'POST',
- url: '/handleAdditional',
- data: formData,
- timeout: 10000
- })
- .done(function () {
- if (afterAction != undefined && afterAction != '') {
- action.verifyBehavior('success', afterAction);
- }
- })
- .fail(function (data) {
- console.log('fail');
- console.log(data);
- // action.verifyBehavior('fail', afterAction);
- ajaxSave.abort();
- // }).error(function () {
- // action.verifyBehavior('fail', afterAction);
- // ajaxSave.abort();
- });
- },
- savePushAdresses: function (campId, controlMessageId, audiencesSelected) {
- var formData = {'audiences': audiencesSelected, 'controlMessageId': controlMessageId, 'campaignId': campId};
- var ajaxSave = $.ajax({
- type: 'POST',
- url: '/handlePushAdresses',
- data: formData,
- timeout: 10000
- })
- .done(function (data) {
- console.log(data);
- console.log('done');
- })
- .fail(function (data) {
- console.log('fail');
- console.log(data);
- ajaxSave.abort();
- });
- },
- saveAudience: function (audienceId, appId, showModalSuccess) {
- var criteria = scriptForPage.getAudienceCriteria();
- var recentAudience = 0;
- var formData = {
- 'appId': appId,
- 'audienceId': audienceId,
- 'audienceName': $("#componentName").val(),
- 'audienceDescription': $("#componentDescription").val(),
- 'criteria': criteria
- };
- var ajaxSave = $.ajax({
- type: 'POST',
- url: '/handleAudience',
- data: formData,
- async: false,
- timeout: 10000
- })
- .done(function (data) {
- console.log(data);
- console.log('done');
- if (showModalSuccess) {
- action.verifyBehavior('success', 'saveAudience');
- }
- recentAudience = data;
- })
- .fail(function (data) {
- console.log('fail');
- console.log(data);
- action.verifyBehavior('fail', 'saveAudience');
- ajaxSave.abort();
- });
- return recentAudience;
- },
- saveParameterBlockLogin: function (customerId) {
- var formData = {
- 'customerId': customerId,
- 'maxNumberRetries': $("#openInputQuantity").val(),
- 'action': 'saveParameterBlockLogin'
- };
- var ajaxSave = $.ajax({
- type: 'POST',
- url: '/handleSecurityParameter',
- data: formData,
- async: false,
- timeout: 10000
- })
- .done(function (data) {
- console.log('done');
- })
- .fail(function (data) {
- console.log('fail');
- console.log(data);
- action.verifyBehavior('fail', 'saveSecurityParameter');
- ajaxSave.abort();
- });
- },
- saveParameterChangePassword: function (customerId) {
- var formData = {
- 'customerId': customerId,
- 'changePassword': $('.js-check-showUpChangePassword').is(':checked'),
- 'action': 'saveParameterChangePassword'
- };
- var ajaxSave = $.ajax({
- type: 'POST',
- url: '/handleSecurityParameter',
- data: formData,
- async: false,
- timeout: 10000
- })
- .done(function (data) {
- console.log('done');
- })
- .fail(function (data) {
- console.log('fail');
- console.log(data);
- action.verifyBehavior('fail', 'saveSecurityParameter');
- ajaxSave.abort();
- });
- },
- saveParameterStrengthPassword: function (customerId, strengthId) {
- console.log('saveParameterStrengthPassword');
- var formData = {
- 'customerId': customerId,
- 'passwordStrengthId': strengthId,
- 'action': 'saveParameterStrengthPassword'
- };
- var ajaxSave = $.ajax({
- type: 'POST',
- url: '/handleSecurityParameter',
- data: formData,
- async: false,
- timeout: 10000
- })
- .done(function (data) {
- console.log('done');
- })
- .fail(function (data) {
- console.log('fail');
- console.log(data);
- action.verifyBehavior('fail', 'saveSecurityParameter');
- ajaxSave.abort();
- });
- },
- saveParameterLoginScheduled: function (securityParameterId, selectedDays) {
- var formData = {
- 'securityParameterId': securityParameterId,
- 'selectedDays': '"' + selectedDays.toString() + '"',
- 'timeInit': $("#timeIntervalRange").slider("values", 0),
- 'timeEnd': $("#timeIntervalRange").slider("values", 1),
- 'action': 'saveParameterLoginScheduled'
- };
- var ajaxSave = $.ajax({
- type: 'POST',
- url: '/handleSecurityParameter',
- data: formData,
- async: false,
- timeout: 10000
- })
- .done(function (data) {
- console.log('done');
- })
- .fail(function (data) {
- console.log('fail');
- console.log(data);
- action.verifyBehavior('fail', 'saveSecurityParameter');
- ajaxSave.abort();
- });
- },
- saveCollaborator: function (customerId, userName) {
- var formData = {
- 'customerId': customerId,
- 'email': $('#addEmail').val(),
- 'profileId': $('#addNewSelect').val(),
- 'action': 'saveCollaborator'
- };
- var ajaxSave = $.ajax({
- type: 'POST',
- url: '/handleCollaborator',
- data: formData,
- async: false,
- timeout: 10000
- })
- .done(function (data) {
- var json = $.parseJSON(data);
- if (json.success == true) {
- //send invitation
- action.sendInvitationCollaborator(userName);
- } else {
- action.verifyBehavior('fail', 'saveSecurityParameter');
- }
- })
- .fail(function (data) {
- console.log('fail');
- console.log(data);
- action.verifyBehavior('fail', 'saveSecurityParameter');
- ajaxSave.abort();
- });
- },
- deleteCollaborator: function (email, buttonDelete, context, collaboratorNumber) {
- console.log('deleteCollaborator');
- var formData = {
- 'email': email,
- 'action': 'deleteCollaborator'
- };
- console.log(formData);
- var ajaxSave = $.ajax({
- type: 'POST',
- url: '/handleCollaborator',
- data: formData,
- async: false,
- timeout: 10000
- })
- .done(function (data) {
- console.log('success');
- var json = $.parseJSON(data);
- if (json.success == true) {
- console.log('json success');
- $(buttonDelete).parents('.styleNewCollaborator').remove();
- $.each(context.find('.element-counter'), function (index, elem) {
- $(elem).html(index + 1);
- });
- collaboratorNumber--;
- }
- })
- .fail(function (data) {
- console.log('fail');
- console.log(data);
- action.verifyBehavior('fail', 'saveSecurityParameter');
- ajaxSave.abort();
- });
- },
- sendInvitationCollaborator: function (userName) {
- var formData = {
- 'email': $('#addEmail').val(),
- 'userName': userName,
- 'action': 'sendInvite'
- };
- var ajaxSave = $.ajax({
- type: 'POST',
- url: '/handleCollaborator',
- data: formData,
- async: false,
- timeout: 10000
- })
- .done(function (data) {
- //console.log('done');
- })
- .fail(function (data) {
- console.log('fail');
- console.log(data);
- action.verifyBehavior('fail', 'saveSecurityParameter');
- ajaxSave.abort();
- });
- },
- saveApiTemplate: function (apiTemplateId, appId) {
- if ($('.js-check-showUpURL').is(':checked')) {
- var url = $('input[name=open-url]').val();
- } else {
- url = '';
- }
- function getTags() {
- var elements = $('.js-dataRow');
- var tags = [];
- $.each(elements, function (num, obj) {
- var tag = $(obj).find('input[name="tag-value"]').val();
- if (tag !== '') {
- tags.push(tag);
- }
- });
- if (tags != null && tags != '') {
- return tags;
- } else {
- return '';
- }
- }
- // var additionalData = scriptForPage.getAdditionalData();
- var formData = {
- 'apiTemplateId': apiTemplateId,
- 'apiTemplateName': $("#componentName").val(),
- 'apiTemplateDescription': $("#componentDescription").val(),
- 'msgTitle': $('input[name=msg-title]').val(),
- 'msgBody': $('#pushContent').val(),
- 'urlPush': url,
- 'appId': appId,
- 'tags': getTags()
- };
- var ajaxSave = $.ajax({
- type: 'POST',
- url: '/handleApiTemplate',
- data: formData,
- timeout: 10000
- })
- .done(function (data) {
- console.log('done');
- console.log(data);
- var json = $.parseJSON(data);
- if (json.success == true) {
- action.saveAdditionalData('', '', '', 'saveApiTemplate', json.apiId);
- // action.verifyBehavior('success', 'saveApiTemplate');
- } else {
- console.log(data.error);
- // action.verifyBehavior('fail', 'saveApiTemplate');
- }
- })
- .fail(function (data) {
- console.log('fail');
- console.log(data);
- action.verifyBehavior('fail', 'saveApiTemplate');
- ajaxSave.abort();
- });
- },
- findReachAudience: function (appId) {
- var criteria = scriptForPage.getAudienceCriteria();
- if (criteria.length > 0) {
- $.ajax({
- type: 'POST',
- url: '/handleRangeAudience',
- data: {'criteria': criteria, 'appId': appId},
- dataType: 'json',
- encode: true
- })
- .done(function (data) {
- if (data.success) {
- /*console.log('query:');
- console.log(data.query);*/
- console.log(data);
- $("#rangeNumber").text(data.result);
- }
- })
- .fail(function () {
- console.log('fail');
- });
- }
- },
- inactivateAudience: function (audienceId) {
- var formData = {
- 'audienceId': audienceId
- };
- var ajaxSave = $.ajax({
- type: 'POST',
- url: '/handleInactivateAudience',
- data: formData,
- dataType: 'json',
- encode: true,
- timeout: 10000
- })
- .done(function (data) {
- console.log(data);
- console.log('done');
- action.verifyBehavior('success', 'inactivateAudience');
- })
- .fail(function (data) {
- console.log('fail');
- console.log(data);
- action.verifyBehavior('fail', 'saveAudience');
- }).error(function () {
- console.log('error');
- action.verifyBehavior('fail', 'saveAudience');
- ajaxSave.abort();
- });
- },
- getSubscribersAudience: function (audiencesSelected) {
- var data = {'audiencesSelected': audiencesSelected};
- // if(data.findIndex())
- console.log(data);
- var ajaxSend = $.ajax({
- type: 'POST',
- url: '/handleSubscribersAudience',
- data: data,
- dataType: 'json',
- encode: true,
- timeout: 10000
- })
- .done(function (data) {
- var qtyLocalFormat = parseInt(data.quantitySubscribers).toLocaleString(locale);
- $('.range-full-number').html(qtyLocalFormat);
- $('#qtRecipients').html(qtyLocalFormat);
- })
- .fail(function (data) {
- // show any errors
- // best to remove for production
- console.log('fail');
- console.log(data);
- $('.range-full-number').html('-');
- $('#qtRecipients').html('-');
- ajaxSend.abort();
- });
- },
- saveAutomation: function (appId, campId, automationId, audiencesSelected, timeInit, timeEnd, selectedDays) {
- var statusId = 1; //ativo
- var formData = {
- 'automationId': automationId,
- 'campId': campId,
- 'name': $('#componentName').val(),
- 'description': $('#componentDescription').val(),
- 'statusId': statusId,
- 'appId': appId,
- 'action': 'saveAutomation'
- };
- var ajaxSave = $.ajax({
- type: 'POST',
- url: '/handleAutomation',
- data: formData,
- timeout: 10000
- })
- .done(function (data) {
- var objJson = $.parseJSON(data);
- if (objJson.success) {
- action.saveAutomationAudience(objJson.automation_id, audiencesSelected, timeInit, timeEnd, selectedDays);
- } else {
- action.verifyBehavior('fail', 'saveAutomation');
- }
- })
- .fail(function () {
- console.log('fail');
- action.verifyBehavior('fail', 'saveAutomation');
- }).error(function () {
- action.verifyBehavior('fail', 'saveAutomation');
- ajaxSave.abort();
- });
- },
- saveAutomationScheduled: function (automationId, timeInit, timeEnd, selectedDays) {
- var formData = {
- 'automationId': automationId,
- 'selectedDays': selectedDays,
- 'timeInit': timeInit,
- 'timeEnd': timeEnd,
- 'action': 'automationScheduled'
- };
- var ajaxSave = $.ajax({
- type: 'POST',
- url: '/handleAutomation',
- data: formData,
- timeout: 10000
- })
- .done(function (data) {
- var objJson = $.parseJSON(data);
- if (objJson.success) {
- action.saveAdditionalData(0, 0, automationId, 'saveAutomation');
- }
- })
- .fail(function () {
- console.log('fail');
- action.verifyBehavior('fail', 'saveAutomation');
- }).error(function () {
- action.verifyBehavior('fail', 'saveAutomation');
- ajaxSave.abort();
- });
- },
- saveAutomationAudience: function (automationId, audiencesSelected, timeInit, timeEnd, selectedDays) {
- if (parseInt(audiencesSelected) > 0) {
- var formData = {
- 'audiences': audiencesSelected,
- 'automationId': automationId,
- 'action': 'automationAudience'
- };
- var ajaxSave = $.ajax({
- type: 'POST',
- url: '/handleAutomation',
- data: formData,
- timeout: 10000
- })
- .done(function (data) {
- var objJson = $.parseJSON(data);
- if (objJson.success) {
- action.saveAutomationCriteria(automationId, timeInit, timeEnd, selectedDays);
- } else {
- action.verifyBehavior('fail', 'saveAutomation');
- }
- })
- .fail(function (data) {
- console.log('fail');
- console.log(data);
- action.verifyBehavior('fail', 'saveAutomation');
- ajaxSave.abort();
- });
- } else {
- action.saveAutomationCriteria(automationId, timeInit, timeEnd, selectedDays);
- }
- },
- saveAutomationCriteria: function (automationId, timeInit, timeEnd, selectedDays) {
- var criteria = scriptForPage.getAudienceCriteria();
- if (criteria.length > 0) {
- var formData = {
- 'automationId': automationId,
- 'criteria': criteria,
- 'action': 'pushCriteria'
- };
- $.ajax({
- type: 'POST',
- url: '/handleAutomation',
- data: formData,
- timeout: 10000
- })
- .done(function (data) {
- console.log(data);
- var objJson = $.parseJSON(data);
- if (objJson.success) {
- action.saveAutomationScheduled(automationId, timeInit, timeEnd, selectedDays);
- } else {
- action.verifyBehavior('fail', 'saveAutomation');
- }
- })
- .fail(function () {
- console.log('fail');
- action.verifyBehavior('fail', 'saveAutomation');
- });
- } else {
- action.saveAutomationScheduled(automationId, timeInit, timeEnd, selectedDays);
- }
- },
- /*
- * This method paginate the page
- *
- * @param string container Where the retrieved data should be put
- * @param string target What is the target URL
- * @param string rowNumber
- * @param JSON data parameters to send with GET
- *
- * return AJAX fill the container with retrieved data
- *
- * */
- paginate: function (container, target, rowNumber) {
- var viewsPerPage = $("#viewsPerPage").val();
- if (viewsPerPage == undefined || viewsPerPage == '') {
- viewsPerPage = 15;
- }
- var params = 'viewsPerPage=' + viewsPerPage + '&rowNumber=' + rowNumber;
- // look for params in the url, if there is params just insert the page params, else create new params field
- if (target.search('/?') == -1) {
- params = '?' + params;
- } else {
- params = '&' + params;
- }
- var targetURL = '/' + target + params;
- window.scrollTo(0, 0);
- $(container).load(targetURL).hide().fadeIn('300');
- console.log(targetURL);
- console.log(params);
- },
- download: function (text, name, type) {
- var a = document.createElement("a");
- if (type == 'csv') {
- var file = new Blob([text], {type: 'text/plain'});
- a.href = URL.createObjectURL(file);
- } else if (type == 'xls') {
- a.href = text;
- }
- a.download = name;
- a.click();
- a.remove();
- }
- };
- var transform = {
- /* Get all checkbox inputs with class '.js-switch' and put their design like iOS7 */
- iOSswitch: function () {
- var checkboxes = Array.prototype.slice.call(document.querySelectorAll('.js-switch'));
- checkboxes.forEach(function (html) {
- var switchery = new Switchery(html, {size: 'small', secondaryColor: '#DFDFDF'});
- });
- },
- /* Style the select element
- * This is used to personalize the select element of sign up page
- *
- * Have to add this on the page (Theter and Select):
- * <link rel="stylesheet" href="select-theme-default.css" />
- * <script src="tether.min.js"></script>
- * <script src="select.min.js"></script>
- *
- * Then use this code here to use a placeholder and style the element.
- *
- * selectID must be just an ID NAME
- *
- * More info: http://github.hubspot.com/select/docs/welcome/
- */
- customSelect: function (selectID) {
- if (selectID.charAt(0) == '#' || selectID.charAt(0) == '.') {
- selectID = selectID.substr(1);
- }
- var element = document.getElementById(selectID);
- var select = new Select({
- el: element,
- className: 'select-theme-inngage'
- });
- function addOptGroup() {
- var optgroup = $(element).find('optgroup');
- $.each(optgroup, function (index, obj) {
- var optgroupLabel = $(obj).attr('label');
- var addElement = '<div class="custom-optgroup">' + optgroupLabel + '</div>';
- var nextElemValue = ($(obj).children().first()).val();
- var searchOption = 'li[data-value=' + nextElemValue + ']';
- $(select.drop).find(searchOption).before(addElement);
- });
- }
- addOptGroup();
- select.on('change', function () {
- addOptGroup();
- });
- return select;
- },
- emojiPicker: function () {
- // Initializes and creates emoji set from sprite sheet
- window.emojiPicker = new EmojiPicker({
- emojiable_selector: '[data-emojiable=true]',
- assetsPath: ref.getPlugins + '/emoji-area/img/',
- popupButtonClasses: 'fa fa-smile-o',
- iconSize: 19,
- norealTime: false
- });
- // Finds all elements with `emojiable_selector` and converts them to rich emoji input fields
- // You may want to delay this step if you have dynamically created input fields that appear later in the loading process
- // It can be called as many times as necessary; previously converted input fields will not be converted again
- window.emojiPicker.discover();
- },
- counter: function (decimal) {
- $('.js-count').each(function () {
- $(this).stop();
- var value = $(this).text();
- $(this).prop('Counter', 0).animate({
- Counter: $(this).text()
- }, {
- duration: 1000,
- easing: 'easeOutQuart',
- step: function (now) {
- $(this).text(now.toLocaleString(locale, {maximumFractionDigits: decimal}));
- },
- complete: function () {
- $(this).text(value);
- transform.breakThousandsId([$(this)]);
- }
- });
- });
- },
- /* Convert a message with emoji in Unicode format to rich text
- *
- * @param obj Object which has the message, may be json, string...
- * @param selector Where to insert the new message with images
- * @param countIndex boolean True if the obj is a json or array and must use the index to identify the selector
- * */
- unicodeToEmoji: function (obj, selector, countIndex) {
- // transform.emojiPicker();
- window.emojiPicker.discover();
- if (countIndex == true) {
- $.each(obj, function (index, elem) {
- $(selector + index).html(window.emojiPicker.unicodeToImage(elem));
- // console.log(elem);
- });
- } else {
- $(selector).html(window.emojiPicker.unicodeToImage(obj));
- }
- },
- /*
- * @param boolean countIndex If the obj has to be count with an "index" increment
- * */
- colonToEmoji: function (obj, selector, countIndex) {
- transform.emojiPicker();
- window.emojiPicker.discover();
- if (countIndex == true) {
- $.each(obj, function (index, elem) {
- $(selector + index).html(window.emojiPicker.colonToImage(elem));
- });
- } else {
- $(selector).html(window.emojiPicker.colonToImage(obj));
- }
- },
- highlightAppMenu: function () {
- var path = (window.location.pathname).substr(1);
- var dirs = path.split('/');
- $.each(dirs, function (index, val) {
- var name = val.split('-');
- for (var i = 1; i < name.length; i++) {
- var firstLetter = name[i].substring(0, 1);
- name[i] = name[i].replace(firstLetter, firstLetter.toUpperCase());
- }
- dirs[index] = name.join('');
- });
- var pageGroup = '#' + dirs[1];
- var page = '#' + dirs[2];
- $(pageGroup).addClass('nav-side-title-selected');
- if (page) {
- var obj = $(page);
- obj.addClass('nav-side-item-selected');
- }
- },
- highlightSubMenu: function (menuItem) {
- $(menuItem).addClass('nav-side-item-selected');
- },
- /* API to work with tawk.to */
- tawkChat: function () {
- function tawkChatAPI() {
- var Tawk_API = Tawk_API || {}, Tawk_LoadStart = new Date();
- (function () {
- var s1 = document.createElement("script"), s0 = document.getElementsByTagName("script")[0];
- s1.async = true;
- s1.src = 'https://embed.tawk.to/5782b19274888c1b4a85ea3e/default';
- s1.charset = 'UTF-8';
- s1.setAttribute('crossorigin', '*');
- s0.parentNode.insertBefore(s1, s0);
- })();
- }
- tawkChatAPI.call(window);
- },
- /*
- * Separate thousands
- *
- * @param array identificators array of any kind of selector as string
- * @return null
- * */
- breakThousandsId: function (identificators) {
- $.each(identificators, function (key, obj) {
- var number = Number($(obj).html());
- $(obj).html(number.toLocaleString(locale));
- });
- }
- };
- var modal = {
- scrollPosition: 0,
- /* Close block if ESC is pressed */
- typeKeyboardBehavior: function () {
- $(document).on('keyup.keyBlock', function (e) {
- e.stopPropagation();
- if (e.keyCode == 27) {
- modal.closeModal();
- }
- if (e.keyCode == 13) {
- e.preventDefault();
- $('.modal button[type=submit]').first().trigger('click');
- }
- });
- },
- getGrayCover: function () {
- var grayCover = "<div class='gray-cover'></div>";
- $(".modal-container").prepend(grayCover);
- $("body").children("*:not(.gray-cover, .modal-container, .emoji-menu, .tether-element)").addClass("blur");
- $("body,html").css({overflow: "hidden"});
- window.scrollTo(0, 0);
- },
- /**
- * Closes all modals on screen
- * If you need to open another modal after the first is called, pass a object parameter with the data as:
- *
- * @param nextModal array Modal to be opened with options:
- * [file, noClose, data]
- * */
- closeModal: function (nextModal) {
- $('.modal-resource').remove();
- $('.emoji-menu').not(':eq(0)').remove();
- $("*").removeClass("blur");
- function getNextModal() {
- if (nextModal != undefined) {
- var opt = [];
- $.each(nextModal, function (key, value) {
- opt[key] = value;
- });
- modal.getModal(opt[0], opt[1], opt[2]);
- }
- }
- if ($(".modal-container").length != 0) {
- $(".modal-container").fadeOut(300, function () {
- $(window).scrollTop(modal.scrollPosition);
- $('.interferingStyleSheet').prop('disabled', false);
- $(this).remove();
- getNextModal();
- });
- } else {
- getNextModal();
- }
- $("body,html").css({overflow: "visible"});
- $(document).off('keyup.keyBlock');
- getData = window.previousGetData;
- },
- /**
- * Closes all modals on screen and back to previous page
- * */
- backPage: function () {
- modal.closeModal();
- history.back();
- },
- reposition: function () {
- $('.modal-container').css({top: $(window).scrollTop()});
- var block = $('.modal');
- var height = block.height();
- var winHeight = $(window).height();
- if (winHeight < height + 50) {
- var top = 59.5;
- grayHeight = (block.outerHeight(true) + top) + 'px';
- } else {
- top = (winHeight - height) / 2;
- var grayHeight = '100vh';
- }
- var topPixels = top + 'px';
- block.css({top: topPixels});
- $('.gray-cover').css({height: grayHeight});
- document.getElementsByClassName('modal-container')[0].scrollTop = 0;
- },
- modal: function () {
- this.typeKeyboardBehavior();
- this.getGrayCover();
- },
- /*
- * file to be opened
- * noClose boolean is it to be closed on out click or not?
- * data JSON any data to be passed to the block
- * */
- getModal: function (file, noClose, data) {
- console.log('inicio');
- modal.scrollPosition = $(window).scrollTop();
- // console.log(getData);
- if (typeof(getData) != "undefined") {
- window.previousGetData = getData;
- }
- $.post(ref.getIncludes + "/modal/" + file, data, function (code) {
- $(document).ready(function () {
- // code.replace('\<script', '\<script class="modal-resource"');
- // code.replace('<style', '<style class="modal-resource"');
- console.log('ready');
- $("body").prepend(code);
- modal.modal();
- $('.modal').find('button:only-of-type').focus();
- $('.modal').find('input').focus();
- modal.reposition();
- // reposition modal when screen is resized
- $(window).on('resize', function () {
- modal.reposition();
- });
- // the modal is not to be closed by the user (ex: LOADING EVENT)
- if (noClose) {
- $(document).off('keyup.keyBlock');
- } else {
- $('.gray-cover').on('click', function () {
- modal.closeModal();
- });
- }
- /* observe for node manipulation in the modal to resize it if needed */
- var modalObserver = new MutationObserver(function () {
- modal.reposition();
- });
- modalObserver.observe(document.getElementsByClassName('modal')[0], {childList: true, subtree: true});
- // so it don't close when clicked (don't trigger .block-container)
- // $('.modal').on('click', function (e) {
- // console.log(e);
- // e.stopPropagation();
- // });
- });
- });
- }
- };
- var balloon = {
- //close balloon. Pass the balloon ID to close
- closeBalloon: function (id) {
- $(id).hide();
- }
- };
- /* OPEN CONTENTS
- * Procedures to navigate through pages
- * For the window.popstate to work properly, keep the object names the same as the corresponding folders
- * */
- var navigateTo = {
- //MAIN - MY APPS
- myApps: function () {
- window.open('/main-dashboard', '_self');
- },
- // APP PAGE: Run this before opening an item in menu-side
- procedure: function (title, path, item, callback) {
- appHeader.hide();
- $('.select-theme-inngage').remove(); // clean all select DIV created
- $('.modal-resource').remove(); // clean all modal resources (script and style tags)
- $('.js-clean-resource').remove(); // clean all resources not used (script and style tags)
- $('.tether-element').remove(); // clean all resources from TETHER plugin
- $('.select-theme-inngage').remove(); // clean all resources from SELECT plugin
- // $('.emoji-menu').not(':eq(0)').remove(); // clean all emoji menus created
- $('.emoji-menu').remove(); // clean all emoji menus created
- $('.ui-datepicker').remove(); // clean all datepickers
- $('.nav-side-title-selected').removeClass('nav-side-title-selected');
- $('.nav-side-item-selected').removeClass('nav-side-item-selected');
- $(title).addClass('nav-side-title-selected');
- if (item) {
- var obj = $(item);
- obj.addClass('nav-side-item-selected');
- }
- var appToken = window.location.search;
- if (history.state) {
- if (history.state['inn'] != path) {
- history.pushState({'inn': path}, '', '/app' + path + appToken);
- }
- } else {
- history.pushState({'inn': path}, '', '/app' + path + appToken);
- }
- contentContainer.load(ref.getAppPg + path, function () {
- window.scrollTo(0, 0); //if page was scrolled down, then go back to top
- if (callback != undefined && callback != '') {
- callback();
- }
- });
- },
- app: {
- //APP-DASHBOARD
- dashboard: function () {
- navigateTo.procedure('#dashboard', '/dashboard');
- contentContainer.empty();
- appHeader.load(ref.getIncludes + '/app-pg/dashboard/app-header.php').show();
- },
- audience: {
- title: '#audience',
- audiences: function () {
- navigateTo.procedure(this.title, "/audience/audiences", "#audiences");
- },
- newAudience: function () {
- navigateTo.procedure(this.title, "/audience/new-audience", "#audiences");
- },
- subscribers: function () {
- navigateTo.procedure(this.title, "/audience/subscribers", "#subscribers");
- },
- importData: function () {
- navigateTo.procedure(this.title, "/audience/import-data");
- }
- },
- push: {
- title: '#push',
- campaigns: function () {
- navigateTo.procedure(this.title, "/push/campaigns", '#campaigns');
- },
- newCampaign: function () {
- navigateTo.procedure(this.title, "/push/new-campaign", '#campaigns');
- },
- sendPush: function () {
- navigateTo.procedure(this.title, "/push/send-push", '#sendPush');
- },
- notificationsSent: function () {
- navigateTo.procedure(this.title, "/push/notifications-sent", '#sendPush');
- },
- notificationsScheduled: function () {
- navigateTo.procedure(this.title, "/push/notification-scheduled", '#sendPush');
- },
- directMail: function () {
- navigateTo.procedure(this.title, "/push/direct-mail");
- },
- automations: function () {
- navigateTo.procedure(this.title, "/push/automations", '#automations');
- },
- newAutomation: function () {
- navigateTo.procedure(this.title, "/push/new-automation", '#automations');
- },
- apiTemplate: function () {
- navigateTo.procedure(this.title, "/push/api-template", '#apiTemplate');
- },
- newApiTemplate: function () {
- navigateTo.procedure(this.title, "/push/new-api-template", '#apiTemplate');
- },
- massUpload: function () {
- navigateTo.procedure(this.title, "/push/mass-upload", '#massUpload');
- },
- massMatch: function () {
- navigateTo.procedure(this.title, "/push/mass-match", '#massMatch');
- },
- massPush: function () {
- navigateTo.procedure(this.title, "/push/mass-push", '#massPush');
- },
- },
- status: {
- title: '#status',
- sent: function () {
- navigateTo.procedure(this.title, "/status/sent", '#sent');
- },
- scheduled: function () {
- navigateTo.procedure(this.title, "/status/scheduled", '#scheduled');
- },
- sentApi: function () {
- navigateTo.procedure(this.title, "/status/sent-api");
- },
- autosent: function () {
- navigateTo.procedure(this.title, "/status/autosent", '#autosent');
- }
- },
- configuration: {
- title: '#configuration',
- general: function () {
- navigateTo.procedure(this.title, "/configuration/general", '#general');
- },
- platform: function () {
- navigateTo.procedure(this.title, "/configuration/platform", "#platform");
- },
- fontCode: function () {
- // navigateTo.procedure(this.title, "/configuration/(UNUSED) font-code", '#fontCode');
- window.open('https://inngage.readme.io/');
- },
- teamNew: function () {
- navigateTo.procedure(this.title, "/configuration/teamNew", '#team');
- },
- team: function () {
- navigateTo.procedure(this.title, "/configuration/team", '#team');
- }
- }
- },
- appPopState: function () {
- var path = (window.location.pathname).substr(1);
- var dirs = path.split('/');
- $.each(dirs, function (index, val) {
- var name = val.split('-');
- for (var i = 1; i < name.length; i++) {
- var firstLetter = name[i].substring(0, 1);
- name[i] = name[i].replace(firstLetter, firstLetter.toUpperCase());
- }
- dirs[index] = name.join('');
- });
- var pageGroup = dirs[1];
- var page = dirs[2];
- if (page) {
- window['navigateTo']['app'][pageGroup][page]();
- } else {
- window['navigateTo']['app'][pageGroup]();
- }
- }
- };
- /* Start immediately */
- $(document).ready(function () {
- behaviors.autoTextArea();
- });
- var scriptForPage = {
- showConditionField: function (rowId, varType) {
- $(rowId).find('.js-condition').hide();
- $(rowId).find('.js-' + varType + '-condition').css({display: 'inline-block'});
- },
- newAudience: function (audienceId, audienceJson, criteriaJson, appId, insertEventsFooter) {
- var num = 0;
- var conditionNumber = 0;
- function insertNewCondition(context) {
- var thisNum = num;
- conditionNumber++;
- num++; //increment the number of conditions
- var clone = $(context.find('#jsNewConditionRow')).clone();
- // PREPARE THE CLONED ELEMENT
- var rowId = 'jsConditionRow' + thisNum;
- clone.attr('id', rowId).removeClass('js-new-condition-row').addClass('js-condition-row');
- clone.find('#removeCondition').attr('id', 'removeCondition' + thisNum);
- $.each($(clone.find('.js-select')), function (index, elem) {
- $(elem).attr('id', 'select' + thisNum + index);
- });
- $.each($(clone.find('input[name=val]')), function (index, elem) {
- $(elem).attr('id', 'val' + thisNum + index);
- });
- clone.find('.element-counter').text(conditionNumber);
- clone.find('.true-false-tab').attr('id', 'trueFalse' + thisNum);
- $.each($(clone.find('.date')), function (index, elem) {
- $(elem).attr('id', 'date' + thisNum + index);
- $(elem).datepicker({
- format: 'dd/mm/yyyy',
- language: locale,
- beforeShow: function (input, obj) {
- // $(input).after($(input).datepicker('widget'));
- // $(input).datepicker("refresh");
- $('.ui-datepicker').removeClass('blur');
- },
- onSelect: function (textData, objDatepicker) {
- action.findReachAudience(appId);
- }
- });
- });
- //INSERT THE PREPARED ELEMENT
- clone.insertBefore(context.find('.js-newCondition')); // use class because of the elements order in modal-new-audience
- //DEFINE BEHAVIORS
- $.each($('#' + rowId).find('.js-select'), function (index, elem) {
- transform.customSelect('select' + thisNum + index);
- $('#select' + thisNum + index).change(function () {
- $(this).next('a').css({color: 'inherit'});
- });
- });
- $('#select' + thisNum + 0).on('change', function () {
- var varType = $(this).find('option[value=' + $(this).val() + ']').attr('data-type');
- scriptForPage.showConditionField('#' + rowId, varType);
- action.findReachAudience(appId);
- });
- var tab = $("#trueFalse" + thisNum).tabs();
- // Set dateInput on change to refresh range
- var dateInput = $('#date' + thisNum + 0);
- dateInput.on('change', function () {
- action.findReachAudience(appId);
- });
- // Date behavior: hide or change the condition input field
- $('#select' + thisNum + 3).on('change', function () {
- var dateType = $(this).val();
- // show Datepicker
- if (dateType <= 13) {
- dateInput.datepicker({
- format: 'dd/mm/yyyy',
- language: locale,
- onSelect: function (textData, objDatepicker) {
- action.findReachAudience(appId);
- }
- });
- dateInput.parent().show(); // show the span with the input
- dateInput.attr('type', 'text').removeClass('days-input');
- $(dateInput.next('span')).css({'display': 'none'});
- // show int and span "Days"
- } else if (dateType <= 16) {
- dateInput.datepicker('destroy');
- dateInput.parent().show();
- dateInput.attr('type', 'number').attr('placeholder', 'Número de dias').addClass('days-input');
- $(dateInput.next('span')).css({'display': 'inline-block'});
- // don't show
- } else if (dateType == 17) {
- $(dateInput.parent()).css({'display': 'none'});
- dateInput.attr('type', 'text').val('today'); // hide the span with the input
- }
- });
- $('#removeCondition' + thisNum).hover(function () {
- behaviors.svgChangeTo.hover($(this).children('img'));
- }, function () {
- behaviors.svgChangeTo.hover($(this).children('img'));
- }).click(function () {
- $(this).parents('.filter-row').remove();
- $.each(context.find('.element-counter'), function (index, elem) {
- $(elem).html(index + 1);
- });
- conditionNumber--;
- if (conditionNumber == 1) {
- $('.remove-icon').fadeOut(200);
- }
- action.findReachAudience(appId);
- });
- // show remove-icon again
- if (conditionNumber > 1) {
- $('.remove-icon').fadeIn(100);
- }
- insertEventToFindReachAudience(appId);
- }
- insertNewCondition($('#addNewCondition').parents('.filter-panel')); // starts with a condition row
- $('#addNewCondition').hover(function () {
- $('#plus').addClass('hover-green');
- $(this).css({fontWeight: '400'});
- behaviors.svgChangeTo.hover($(this).children('img'));
- }, function () {
- $('#plus').removeClass('hover-green');
- $(this).attr('style', '');
- behaviors.svgChangeTo.hover($(this).children('img'));
- }).click(function () {
- insertNewCondition($(this).parents('.filter-panel'));
- });
- function insertEventToFindReachAudience(appId) {
- var elements = $(".js-condition-row");
- for (var i = 0; i < elements.length; i++) {
- var row = "#" + elements[i].id;
- $(row).find('select[name=operator]').on('change', function () {
- action.findReachAudience(appId);
- });
- $(row).find('.ui-state-default').on('click', function () {
- action.findReachAudience(appId);
- });
- $(row).find('input[name=val]').on('change', function () {
- action.findReachAudience(appId);
- });
- }
- }
- populateAudience(audienceId, audienceJson, criteriaJson, appId);
- function populateAudience(audienceId, audienceJson, criteriaJson, appId) {
- if (audienceId > 0) {
- var audienceName = audienceJson['audience_name'];
- var audienceDescription = audienceJson['audience_description'];
- populateAudienceCriteria(criteriaJson);
- $('#componentName').val(audienceName);
- $('#componentDescription').val(audienceDescription);
- action.findReachAudience(appId);
- $('.page-title').html(audienceName);
- }
- }
- function populateAudienceCriteria(criteriaJson) {
- if (criteriaJson) {
- var i = 0;
- $.each(criteriaJson, function (index, value) {
- if ((i > 0) && (value !== null) && (value !== undefined)) {
- $("#addNewCondition").trigger("click");
- }
- var selectField = $("#select" + i + "0").attr('value', value.audience_criteria_id);
- selectField.val(value.audience_field_id);
- selectField.next('a').css({color: 'inherit'});
- var varType = selectField.find('option[value=' + selectField.val() + ']').attr('data-type');
- scriptForPage.showConditionField('#jsConditionRow' + i, varType);
- var objectTypeCondition = $('#jsConditionRow' + i).find('.js-' + varType + '-condition');
- if (varType == 'boolean') {
- objectTypeCondition.find('a[href="#' + value.audience_value + '"]').trigger('click');
- } else {
- objectTypeCondition.find('select[name=operator]').val(value.audience_field_condition_id);
- objectTypeCondition.find('select[name=operator]').attr('value', value.audience_field_condition_id);
- objectTypeCondition.find('select[name=operator]').next('a').css({color: 'inherit'});
- objectTypeCondition.find('input[name=val]').val(value.audience_value);
- }
- i++;
- });
- }
- }
- if (insertEventsFooter) {
- $('#footerSave').on('click', function () {
- if ((validate.field('#componentName', 'Qual o nome da sua audiência?')) && (validate.fieldsAudienceCriteria(true))) {
- action.saveAudience(audienceId, appId, true);
- }
- });
- $('#footerCancel').on('click', function () {
- navigateTo.app.audience.audiences();
- });
- }
- },
- newCollaborator: function (collaboratorJson) {
- var num = 0;
- var collaboratorNumber = 0;
- function insertNewCollaborator(context) {
- var thisNum = num;
- collaboratorNumber++;
- num++; //increment the number of conditions
- var clone = $(context.find('#jsNewCollaboratorRow')).clone();
- // PREPARE THE CLONED ELEMENT
- var rowId = 'jsCollaboratorRow' + thisNum;
- clone.attr('id', rowId).removeClass('js-new-row').addClass('js-collaborator-row');
- clone.find('#removeMember').attr('id', 'removeMember' + thisNum);
- $.each($(clone.find('.js-select')), function (index, elem) {
- $(elem).attr('id', 'select' + thisNum + index);
- });
- $.each($(clone.find('input[name=member-name]')), function (index, elem) {
- $(elem).attr('id', 'member-name' + thisNum + index);
- });
- $.each($(clone.find('input[name=member-email]')), function (index, elem) {
- $(elem).attr('id', 'member-email' + thisNum + index);
- });
- clone.find('.element-counter').text(collaboratorNumber);
- //INSERT THE PREPARED ELEMENT
- clone.insertBefore(context.find('.js-newCollaborator'));
- //DEFINE BEHAVIORS
- $.each($('#' + rowId).find('.js-select'), function (index, elem) {
- transform.customSelect('select' + thisNum + index);
- $('#select' + thisNum + index).change(function () {
- $(this).next('a').css({color: 'inherit'});
- });
- });
- $('#removeMember' + thisNum).hover(function () {
- behaviors.svgChangeTo.hover($(this).children('img'));
- }, function () {
- behaviors.svgChangeTo.hover($(this).children('img'));
- }).click(function () {
- //updates user indicating that he has been deleted
- var idFieldName = '#' + $(this)[0].id.replace('removeMember', 'member-email') + '0';
- action.deleteCollaborator($(idFieldName).val(), this, context, collaboratorNumber);
- /*-------
- *TODO: implementar uma verificação se o usuário excluído é o usuário logado, se for deslogar o usuário
- -------*/
- });
- insertEventToSaveCollaborator();
- }
- insertNewCollaborator($('#addNewCollaborator').parents('.control-panel')); // starts with a condition row
- $('#addNewCollaborator').hover(function () {
- $('#plus').addClass('hover-green');
- $(this).css({fontWeight: '400'});
- behaviors.svgChangeTo.hover($(this).children('img'));
- }, function () {
- $('#plus').removeClass('hover-green');
- $(this).attr('style', '');
- behaviors.svgChangeTo.hover($(this).children('img'));
- }).click(function () {
- insertNewCollaborator($(this).parents('.control-panel'));
- });
- function insertEventToSaveCollaborator() {
- var elements = $(".js-collaborator-row");
- for (var i = 0; i < elements.length; i++) {
- var row = "#" + elements[i].id;
- $(row).find('select[name=profile]').on('change', function () {
- scriptForPage.collaborator.saveCollaborator();
- });
- $(row).find('input[name=member-name]').on('change', function () {
- scriptForPage.collaborator.saveCollaborator();
- });
- $(row).find('input[name=member-email]').on('change', function () {
- scriptForPage.collaborator.saveCollaborator();
- });
- }
- }
- populateCollaborator(collaboratorJson);
- function populateCollaborator(collaboratorJson) {
- var i = 0;
- $.each(collaboratorJson, function (index, value) {
- if ((i > 0) && (value !== null) && (value !== undefined)) {
- $("#addNewCollaborator").trigger("click");
- }
- var selectProfile = $("#select" + i + "0").attr('value', value.profile_id);
- selectProfile.val(value.profile_id);
- selectProfile.next('a').css({color: 'inherit'});
- $("#member-name" + i + "0").val(value.name);
- $("#member-email" + i + "0").val(value.email);
- //objectTypeCondition.find('select[name=operator]').next('a').css({color: 'inherit'});
- //objectTypeCondition.find('input[name=val]').val(value.audience_value);
- i++;
- });
- }
- /*if (insertEventsFooter) {
- $('#footerSave').on('click', function () {
- if ((validate.field('#componentName', 'Qual o nome da sua audiência?')) && (validate.fieldsAudienceCriteria(true))) {
- action.saveAudience(audienceId, appId, true);
- }
- });
- }*/
- },
- dashboard: function () {
- $('#selectAudience').on('change', function () {
- getData();
- });
- function getData() {
- var selectedId = $('#selectAudience').val();
- var audienceId = selectedId.replace('audience', '');
- $.ajax({
- type: 'POST',
- url: '/handleReports',
- data: {audienceId: audienceId}
- }).done(function (data) {
- var json = JSON.parse(data);
- console.log(json);
- updateDataJson(json);
- refreshData();
- }).fail(function (data) {
- console.log(data);
- });
- }
- transform.customSelect('selectAudience');
- window.doughnutChart = charts.createDonutChart('#doughnutChart', 1);
- window.doughnutInfo = 'openedDoughnut'; // initial selected info-bot doughnut
- window.interval = 'week'; // initial selected interval
- function refreshData() {
- $('#' + window.interval).trigger('click');
- $('#' + window.doughnutInfo).trigger('click');
- updateBarChart();
- $(".number-bar-chart").html((window.dataJson.week.sentNum).toLocaleString());
- }
- charts.resizeChartDiv();
- transform.counter(0);
- $("#tabs").tabs();
- /* Render week line chart */
- function renderLineChart() {
- var color = "#2ecc71";
- var data = {
- labels: ['dummy'],
- datasets: [{
- fill: false,
- tension: 0,
- borderCapStyle: 'round',
- pointBackgroundColor: "#fff",
- pointBorderWidth: 3,
- pointHoverRadius: 3,
- pointHoverBorderWidth: 4,
- backgroundColor: color,
- borderColor: color,
- pointHoverBackgroundColor: color,
- pointHoverBorderColor: color,
- pointBorderColor: color,
- data: ["0"]
- }]
- };
- window.lineChart = new Chart($('#lineChart'), {
- type: 'line',
- data: data,
- options: {
- maintainAspectRatio: false,
- legend: {
- display: false
- },
- elements: {
- point: {
- radius: 4
- }
- },
- tooltips: {
- callbacks: {
- title: function (tooltipItem, data) {
- },
- label: function (tooltipItem, data) {
- return tooltipItem.yLabel;
- },
- footer: function (tooltipItem, data) {
- }
- }
- },
- scales: {
- yAxes: [{
- ticks: {
- min: 0,
- suggestedMax: 20
- }
- }]
- }
- }
- });
- }
- renderLineChart();
- function updateDataJson(json) {
- console.log(json);
- window.dataJson = json;
- }
- function updateDoughnutChart() {
- var interval = window.interval;
- var sent = window['dataJson'][interval]['sentNum'];
- var received = window['dataJson'][interval]['received'];
- var opened = window['dataJson'][interval]['openedNum'];
- function update(value) {
- $('#doughnutChartLabel').text(value);
- return [value, (100 - value)];
- }
- if (document.getElementById('doughnutChart').style.display == 'none' &&
- window.doughnutInfo != 'sentDoughnut') {
- $('#doughnutChartLabel').stop();
- $('.cuv-percent').fadeIn();
- $('.chart-background').fadeIn();
- $('#doughnutChart').fadeIn();
- }
- switch (window.doughnutInfo) {
- case 'sentDoughnut':
- $('.cuv-percent').hide();
- $('.chart-background').hide();
- $('#doughnutChart').hide();
- $('#doughnutChartLabel').text(sent);
- transform.counter(0);
- $('#doughnutChartTitle').text('Pushes Enviados');
- return;
- case 'receivedDoughnut':
- window.doughnutChart.data.datasets[0].data = update(received);
- transform.counter(0);
- $('#doughnutChartTitle').text('Pushes Recebidos');
- break;
- case 'openedDoughnut':
- window.doughnutChart.data.datasets[0].data = update(opened);
- transform.counter(0);
- $('#doughnutChartTitle').text('Pushes Abertos');
- break;
- }
- window.doughnutChart.update();
- }
- function updateLineChart() {
- var labels;
- var data;
- var sentNum;
- var received;
- var openedNum;
- function updateDoughnutBotInfo() {
- var interval = window.interval;
- var sent = window['dataJson'][interval]['sentNum'].toLocaleString();
- var received = window['dataJson'][interval]['received'];
- var opened = window['dataJson'][interval]['openedNum'];
- var doughnutBotInfo = $('.doughnut-bot-info');
- doughnutBotInfo.children('#sentDoughnut').children('.number').text(parseInt(sent).toLocaleString(locale));
- doughnutBotInfo.children('#receivedDoughnut').children('.number').text(received + '%');
- doughnutBotInfo.children('#openedDoughnut').children('.number').text(opened + '%');
- }
- function updateInterval(interval) {
- labels = window['dataJson'][interval]['labels'];
- console.log("Labels:");
- console.log(labels);
- data = window['dataJson'][interval]['sent'];
- console.log("Sent:");
- console.log(data);
- window.lineChart.data.labels = labels;
- window.lineChart.data.datasets[0].data = data;
- }
- updateInterval(window.interval);
- updateDoughnutChart();
- updateDoughnutBotInfo();
- // duas linhas no grafico
- /*
- var green = "#2ecc71";
- var blue = "#4ad1ed";
- case 'lineSent':
- // add new line
- if ($('#lineSent').prop('checked')) {
- var interval = $('.line-chart-interval').find('.chart-range-active').attr('id');
- var color = green;
- var dataset = {};
- dataset.fill = false;
- dataset.lineTension = 0.1;
- dataset.borderCapStyle = 'round';
- dataset.pointBackgroundColor = "#fff";
- dataset.pointBorderWidth = 3;
- dataset.pointHoverRadius = 3;
- dataset.pointHoverBorderWidth = 4;
- dataset.backgroundColor = color;
- dataset.borderColor = color;
- dataset.pointHoverBackgroundColor = color;
- dataset.pointHoverBorderColor = color;
- dataset.pointBorderColor = color;
- dataset.data = window['dataJson'][interval]['opened'];
- if (window.lineChart.data.datasets[0] == undefined) {
- window.lineChart.data.datasets[0] = dataset;
- } else {
- window.lineChart.data.datasets[1] = dataset;
- }
- } else {
- window.lineChart.data.datasets.splice(1);
- }
- break;
- case 'lineOpened':
- // add new line
- if ($('#lineOpened').prop('checked')) {
- var interval = $('.line-chart-interval').find('.chart-range-active').attr('id');
- var color = blue;
- var dataset = {};
- dataset.fill = false;
- dataset.lineTension = 0.1;
- dataset.borderCapStyle = 'round';
- dataset.pointBackgroundColor = "#fff";
- dataset.pointBorderWidth = 3;
- dataset.pointHoverRadius = 3;
- dataset.pointHoverBorderWidth = 4;
- dataset.backgroundColor = color;
- dataset.borderColor = color;
- dataset.pointHoverBackgroundColor = color;
- dataset.pointHoverBorderColor = color;
- dataset.pointBorderColor = color;
- dataset.data = window['dataJson'][interval]['opened'];
- if (window.lineChart.data.datasets[0] == undefined) {
- window.lineChart.data.datasets[0] = dataset;
- } else {
- window.lineChart.data.datasets[1] = dataset;
- }
- } else {
- window.lineChart.data.datasets.splice(1);
- }
- break; */
- window.lineChart.update();
- window.doughnutChart.update();
- }
- // select the interval of the chart
- $('.line-chart-interval').on('click', function (e) {
- // only trigger if a button is pressed
- if (e.target.className != 'line-chart-interval') {
- $($(this).children('.chart-range-item')).removeClass('chart-range-active');
- var interval = $(e.target).addClass('chart-range-active').attr('id');
- }
- window.interval = interval;
- updateLineChart(interval);
- });
- // select the filter to see the chart
- $('.js-line-label').on('change', function (e) {
- var intervalElem = $(e.target);
- var interval = intervalElem.attr('id');
- if ($(e.target).prop('checked')) {
- $('#' + interval + 'Label').show();
- } else {
- $('#' + interval + 'Label').hide();
- // keep always one filter selected
- $.each($('.js-line-label'), function (key, elem) {
- var once = false;
- if ($(elem).attr('id') != interval && once == false) {
- $(elem).prop('checked', true);
- $('#' + $(elem).attr('id') + 'Label').show();
- once = true; // loop just for the first matched element
- // interval = $(elem).attr('id'); // change the id so update chart will be right
- }
- });
- }
- });
- // put gray background and green letters when select doughnut chart info
- $('.doughnut-bot-info').on('click', function (e) {
- // only trigger if a button is pressed
- if (e.target.className != 'doughnut-bot-info') {
- $($(this).find('*')).removeClass('darker-bot-info green');
- if (e.target.localName == 'span') {
- var button = $(e.target).parent('button');
- } else {
- var button = $(e.target);
- }
- var doughnutInfo = button.addClass('darker-bot-info').attr('id');
- button.children('.number').addClass('green');
- var older = window.doughnutInfo;
- if (older != doughnutInfo) {
- window.doughnutInfo = doughnutInfo;
- updateDoughnutChart();
- }
- }
- });
- function renderBarChart() {
- var dataBarChart = {
- labels: ['dummy'],
- datasets: [
- {
- backgroundColor: "#d0d0d0",
- borderColor: "#d0d0d0",
- borderWidth: 1,
- hoverBackgroundColor: "#3ec556",
- hoverBorderColor: "#3ec556",
- data: [0]
- }
- ]
- };
- window.barChart = new Chart($('#barChart'), {
- type: 'bar',
- data: dataBarChart,
- options: {
- maintainAspectRatio: false,
- legend: {
- display: false
- },
- scales: {
- xAxes: [{
- gridLines: {
- drawTicks: false,
- zeroLineColor: 'rgba(0, 0, 0, 0.0)',
- color: 'rgba(0, 0, 0, 0.0)'
- }
- }],
- yAxes: [{
- ticks: {
- labelOffset: 0,
- padding: 10,
- min: 0,
- suggestedMax: 20
- }
- }]
- },
- tooltips: {
- titleFontSize: 0,
- titleMarginBottom: 0,
- titleSpacing: 0,
- callbacks: {
- label: function (tooltipItem, data) {
- return tooltipItem.yLabel;
- }
- }
- }
- }
- });
- }
- renderBarChart();
- function updateBarChart() {
- window.barChart.data.datasets[0].data = window.dataJson.week.sent;
- window.barChart.data.labels = window.dataJson.week.labels;
- window.barChart.update();
- }
- refreshData();
- },
- getCampaignRecipients: function (audiencesJson, countSubscribers) {
- if ((audiencesJson !== null) && (audiencesJson !== undefined)) {
- $.each(audiencesJson, function (index, value) {
- if ((value !== null) && (value !== undefined) && (value.audience_id !== undefined)) {
- var $template = $('#templateRowAudience'),
- $clone = $template
- .clone()
- .removeClass('hide')
- .removeAttr('id')
- .insertBefore($template);
- var amountData = $('.templateRowAudience').length - 1;
- var rangeLocalFormat = parseInt(value.range_number).toLocaleString(locale);
- $clone
- .find('input[type=checkbox]').attr('value', value.audience_id).end()
- .find('input[id=audienceSelected]').attr('id', 'audienceSelected' + amountData).end()
- .find('label[for=audienceSelected]').attr('for', 'audienceSelected' + amountData).end()
- .find('[name="name"]').attr('name', 'nameAudience' + amountData).html(value.audience_name).end()
- .find('[name="size"]').attr('name', 'sizeAudience' + amountData).html(rangeLocalFormat).end()
- .find('[name="rank"]').attr('name', 'rankAudience' + amountData).html('-').end()
- .find('[name="dateCreation"]').attr('name', 'dateCreationAudience' + amountData).html(value.audience_creation).end();
- }
- var listAudiencesSelected = [];
- $('#audienceSelected' + amountData).on('change', function () {
- var audiencesSelected = scriptForPage.getSelectedAudiences();
- if (audiencesSelected != listAudiencesSelected) {
- listAudiencesSelected = audiencesSelected;
- action.getSubscribersAudience(audiencesSelected);
- }
- });
- });
- }
- $('.push-row').on('click', function () {
- var checkbox = $(this).find('input[type=checkbox]');
- var check = checkbox.prop('checked');
- checkbox.prop('checked', !check);
- // if all public is checked, then don't need any update
- if (checkbox.attr('id') == 'audienceSelected0' || !$('#audienceSelected0').prop('checked')) {
- checkbox.trigger('change');
- }
- });
- $("#sumSize").html(countSubscribers.toLocaleString(locale));
- },
- getStatusAutomation: function () {
- var filterAutomation = $("#filterAutomation");
- var sendHourIni = $("#sendHourIni");
- var sendHourEnd = $("#sendHourEnd");
- var sendMinuteIni = $("#sendMinuteIni");
- var sendMinuteEnd = $("#sendMinuteEnd");
- var sendDateIni = $("#sendDateIni");
- var sendDateEnd = $("#sendDateEnd");
- var selectAutomation = transform.customSelect('filterAutomation');
- $(selectAutomation.content).css({width: '230px'}); //style the automation selector
- transform.customSelect('sendHourIni');
- transform.customSelect('sendMinuteIni');
- transform.customSelect('sendHourEnd');
- transform.customSelect('sendMinuteEnd');
- // var date = new Date();
- // var dd = date.getDate();
- // var mm = date.getMonth() + 1;
- // var yyyy = date.getFullYear();
- // if (dd < 10) {
- // dd = '0' + dd;
- // }
- // if (mm < 10) {
- // mm = '0' + mm;
- // }
- //
- // var today = dd + '/' + mm + '/' + yyyy;
- window.dateIni = sendDateIni.val();
- window.hourIni = sendHourIni.val();
- window.minuteIni = sendMinuteIni.val();
- window.dateEnd = sendDateEnd.val();
- window.hourEnd = sendHourEnd.val();
- window.minuteEnd = sendMinuteEnd.val();
- window.automation = filterAutomation.val();
- sendDateIni.datepicker({
- format: 'dd/mm/yyyy',
- language: locale,
- beforeShow: function (input, obj) {
- $('.ui-datepicker').removeClass('blur');
- },
- onSelect: function (textData, objDatepicker) {
- dateIni = sendDateIni.val();
- window.scrollTo(0, 0);
- getData(0);
- }
- });
- sendDateEnd.datepicker({
- format: 'dd/mm/yyyy',
- language: locale,
- beforeShow: function (input, obj) {
- $('.ui-datepicker').removeClass('blur');
- },
- onSelect: function (textData, objDatepicker) {
- dateEnd = $(this).val();
- window.scrollTo(0, 0);
- getData(0);
- }
- });
- filterAutomation.change(function () {
- automation = $(this).val();
- window.scrollTo(0, 0);
- getData(0);
- });
- sendHourIni.change(function () {
- hourIni = $(this).val();
- window.scrollTo(0, 0);
- console.log(automation);
- getData(0);
- });
- sendHourEnd.change(function () {
- hourEnd = $(this).val();
- window.scrollTo(0, 0);
- getData(0);
- });
- sendMinuteIni.change(function () {
- minuteIni = $(this).val();
- window.scrollTo(0, 0);
- getData(0);
- });
- sendMinuteEnd.change(function () {
- minuteEnd = $(this).val();
- window.scrollTo(0, 0);
- getData(0);
- });
- },
- // @param calls this variable gets the function which calls the functions inside "pushScript"
- pushScript: function (calls) {
- function resizePreview() {
- var height = $('#preInfo').height();
- $('#preVisualization').css({height: height});
- }
- function showUpSend() {
- var changeCheckbox = $('.js-check-showUpSend');
- var showUp = $('.js-showUpSend');
- changeCheckbox.on('change', function () {
- if ($(this).is(':checked')) {
- showUp.css({visibility: 'visible'}).hide().fadeIn('fast');
- dateTimePreview.changeSendSchedule();
- } else {
- showUp.fadeOut('fast', function () {
- showUp.show().css({visibility: 'hidden'});
- $('#pushSchedule').text('Imediato').removeClass('red');
- });
- }
- });
- }
- function showUpExp() {
- var changeCheckbox = $('.js-check-showUpExp');
- var showUp = $('.js-showUpExp');
- changeCheckbox.on('change', function () {
- if ($(this).is(':checked')) {
- showUp.css({visibility: 'visible'}).hide().fadeIn('fast');
- $('#pushExpiration').text('Informe o tempo').removeClass('orange').addClass('red');
- } else {
- showUp.fadeOut('fast', function () {
- showUp.show().css({visibility: 'hidden'});
- $('#pushExpiration').text('Não').removeClass('red').addClass('orange');
- });
- }
- });
- }
- function showUpURL() {
- var changeCheckbox = $('.js-check-showUpURL');
- var showUp = $('.js-showUpURL');
- changeCheckbox.on('change', function () {
- if ($(this).is(':checked')) {
- showUp.css({visibility: 'visible'}).hide().fadeIn('fast');
- var url = $('input[name=open-url]').val();
- if (url == '') {
- $('.js-pushUrl').text('Informe a URL').removeClass('orange').addClass('red');
- } else {
- $('.js-pushUrl').text(url).removeClass('orange').removeClass('red');
- }
- } else {
- showUp.fadeOut('fast', function () {
- showUp.show().css({visibility: 'hidden'});
- $('.js-pushUrl').text('Não').removeClass('red').addClass('orange');
- });
- }
- });
- }
- function checkYesNo(checkbox, content) {
- var checkbox = $(checkbox);
- var info = $(content);
- checkbox.on('change', function () {
- if ($(this).is(':checked')) {
- info.text('Sim').removeClass('orange').addClass('green');
- } else {
- info.text('Não').removeClass('green').addClass('orange');
- }
- }
- );
- }
- /* Resize emoji for phone preview and DIV (use size param for this) */
- function resizeEmoji(platform, size) {
- var emojis,
- proportion;
- if (platform == 'android') {
- emojis = $('#' + platform + 'Content .img');
- proportion = 0.6;
- } else if (platform == 'iOS') {
- emojis = $('#' + platform + 'Content .img');
- proportion = 0.65;
- } else {
- emojis = $(platform);
- proportion = size;
- }
- emojis.each(function () {
- var width = $(this).width() * proportion;
- var height = $(this).height() * proportion;
- var bgPosition = $(this).css('backgroundPosition');
- var position = bgPosition.replace(/px/g, '').split(' ');
- var posX = position[0] * proportion;
- var posY = position[1] * proportion;
- var bgSize = $(this).css('backgroundSize');
- var size = bgSize.replace(/px/g, '').split(' ');
- var sizeX = size[0] * proportion;
- var sizeY = size[1] * proportion;
- $(this).width(width);
- $(this).height(height);
- $(this).css('backgroundPosition', posX + 'px ' + posY + 'px');
- $(this).css('backgroundSize', sizeX + 'px ' + sizeY + 'px');
- })
- }
- /* @param lastPushMessage Last push returned to preview. Just to be unique, this is 'ççç'
- * @param androidChars Max number of chars in android preview
- * @param iOSChars Max number of chars in iPhone preview
- * @param iOSfirst First time iOS passes sliceMessage, it has to change lastPreview, so it recreates array
- * */
- var lastPushMessage = 'ççç',
- androidChars = 64,
- iOSChars = 120,
- iOSfirst = true;
- /* Slice the message leaving <img> tags and undivided */
- function sliceMessage(typed, size) {
- var lastPreview = typed.substr(0, lastPushMessage.length);
- /* Checks if it is the first iOS preview change, so it has to recreate array and lastPushMessage */
- if (size == iOSChars && iOSfirst) {
- lastPreview = '';
- iOSfirst = false;
- }
- if (lastPreview == lastPushMessage) {
- return lastPushMessage; // if typed piece is the same of the last preview, keep it
- } else {
- var textArray = [],
- wordArray,
- rest = typed,
- pos,
- emojiSpace;
- rest = rest.replace(/ /g, ' '); // unseparated
- do {
- pos = rest.search('<img'); // unseparated img
- if (pos != -1) {
- wordArray = rest.substr(0, pos).split('');
- textArray = textArray.concat(wordArray);
- rest = rest.substr(pos);
- pos = rest.search(':">');
- emojiSpace = rest.substr(0, pos + 3);
- textArray.push(emojiSpace, '');
- rest = rest.substr(pos + 3);
- }
- } while (pos != -1 && textArray.length < size);
- textArray = textArray.concat(rest.split(''));
- textArray.map(function (val, index) {
- if (val == ' ') {
- textArray[index] = ' '; // bring back
- }
- });
- lastPushMessage = textArray.slice(0, size).join('');
- if (size == androidChars) {
- return lastPushMessage; // return preview TEXT
- }
- return textArray; // return preview ARRAY (for different Android and iOS slices)
- }
- }
- /* Change TITLE while typing */
- function titleMessagePreview() {
- $('#pushTitle').on('keyup', function () {
- var typed = $(this).val();
- $('.js-title').text(typed);
- });
- }
- function doURLPreview(url) {
- if (url == '') {
- $('.js-pushUrl').text('Informe uma URL').removeClass('red').addClass('red');
- } else {
- $('.js-pushUrl').text(url).removeClass('red');
- }
- }
- function URLPreview() {
- $('#openURL').on('keyup', function () {
- var url = $(this).val();
- doURLPreview(url);
- });
- }
- /*
- * @param iOSContent Selector for iOS preview
- * @param androidContent Selector for Android preview
- * @param preMsg selector For message field preview
- * @param observeOnce Boolean to stop Observer at the first time
- * */
- var iOSContent = $('#iOSContent'),
- androidContent = $('#androidContent'),
- preMsg = $('.js-msg'),
- observeOnce = true;
- var target = $('#pushContent').next('div'); // message content DIV
- /* Reset observer boolean */
- $(target).on('keyup', function () {
- observeOnce = true;
- });
- $('.emoji-menu').on('mousedown', function () {
- observeOnce = true;
- });
- function doMessagePreview(typed) {
- /* count how many real chars there is */
- var typedNum = typed.replace(/ /g, ' '); // counts 1
- var matches = typed.match(/\<img[^>]*>/g); // <img> counts 2
- if (matches != null) {
- for (var i = 0; i < matches.length; i++) {
- typedNum = typedNum.replace(matches[i], '12');
- }
- var count = typedNum.length;
- } else {
- count = typed.length;
- }
- preMsg.html(typed);
- resizeEmoji();
- /* More than iOS preview space */
- if (count > iOSChars) {
- var textArray = sliceMessage(typed, iOSChars);
- // if textArray isn't array, then the message is the same and don't need to be changed
- if (Array.isArray(textArray)) {
- /* iOS push */
- var textLarge = textArray.slice(0, iOSChars).join('') + '...';
- iOSContent.html(textLarge);
- resizeEmoji('iOS');
- /* Android push */
- var textSmall = textArray.slice(0, androidChars).join('') + '...';
- androidContent.html(textSmall);
- resizeEmoji('android');
- }
- } else if (count > androidChars) {
- iOSContent.html(typed);
- resizeEmoji('iOS');
- /* Change just Android push */
- var text = sliceMessage(typed, androidChars) + '...';
- androidContent.html(text);
- resizeEmoji('android');
- iOSfirst = true;
- } else {
- androidContent.html(typed);
- resizeEmoji('android');
- iOSContent.html(typed);
- resizeEmoji('iOS');
- iOSfirst = true;
- }
- resizePreview(); // if message is to long, resize phone preview DIV
- }
- /* Change MESSAGE while typing */
- function messagePreview() {
- var observer = new MutationObserver(function (mutations) { // create an observer instance
- mutations.forEach(function (mutation) {
- if (observeOnce) {
- // var lastEmoji = target.children('[alt="' + mutation.addedNodes[0].alt + '"]');
- // resizeEmoji(lastEmoji, 0.76);
- var typed = $(mutation.target).html();
- doMessagePreview(typed);
- observeOnce = false;
- }
- });
- });
- observer.observe(target[0], {attributes: true, childList: true});
- }
- function refreshPreview() {
- $('#pushTitle').trigger('keyup');
- }
- var dateTimePreview = {
- /* SEND TIME */
- sendDateTime: {
- proxy: new Proxy(['', '', ''], {
- get: function (target, property) {
- return target[property];
- },
- set: function (target, property, value) {
- target[property] = value;
- dateTimePreview.changeSendSchedule();
- return true;
- }
- })
- },
- setSendDate: function () {
- var nomesMes = [
- "Janeiro", "Fevereiro", "Março",
- "Abril", "Maio", "Junho", "Julho",
- "Agosto", "Setembro", "Outubro",
- "Novembro", "Dezembro"
- ];
- var nomesSemana = [
- "Domingo", "Segunda-feira", "Terça-feira",
- "Quarta-feira", "Quinta-feira",
- "Sexta-feira", "Sábado-feira"
- ];
- var input = $('#sendDate').val().split('/');
- input = input[2] + '-' + input[1] + '-' + input[0];
- var date = new Date(input);
- var fixTime = date.getTimezoneOffset() / 60;
- date.setHours(date.getHours() + fixTime);
- var today = new Date().setHours(0, 0, 0, 0);
- var tomorrow = today + 24 * 60 * 60000;
- var dateString = '';
- if (date.getTime() == today) {
- dateString = 'Hoje, ';
- } else if (date.getTime() == tomorrow) {
- dateString = 'Amanhã, ';
- } else {
- var day = date.getDate();
- var monthIndex = date.getMonth();
- var year = date.getFullYear();
- var weekIndex = date.getDay();
- dateString = nomesSemana[weekIndex] + ', ' + day + ' ' + nomesMes[monthIndex] + ' ' + year + ', ';
- }
- this.sendDateTime.proxy[0] = dateString;
- this.sendDateTime.proxy[4] = date.getTime();
- },
- setSendHour: function () {
- this.sendDateTime.proxy[1] = $('#sendHour').val();
- },
- setSendMinute: function () {
- this.sendDateTime.proxy[2] = $('#sendMinute').val();
- },
- changeSendSchedule: function () {
- var flagSchedule = $('.js-check-showUpSend').is(':checked');
- var date = this.sendDateTime.proxy[0];
- if (flagSchedule && date == '') {
- date = $('#sendDate').val();
- }
- var h = this.sendDateTime.proxy[1];
- if (flagSchedule && h == '') {
- h = $('#sendHour').val();
- }
- var min = this.sendDateTime.proxy[2];
- if (flagSchedule && min == '') {
- min = $('#sendMinute').val();
- }
- var dateMillis = this.sendDateTime.proxy[4] + 60000 * (60 * h) + 60000 * min;
- var today = new Date().getTime();
- window.scheduleValid = false; // if time is valid, set to true and allow push sending
- // if (date == '' || date.search('undefined') != -1) {
- if (date == '' && flagSchedule) {
- $('#pushSchedule').text('Agende o envio').addClass('red bold');
- } else if (dateMillis < today) {
- $('#pushSchedule').text('Escolha uma data futura').addClass('red bold');
- resizePreview();
- } else if (flagSchedule) {
- var dateTime = date + h + ':' + min + 'h';
- $('#pushSchedule').text(dateTime).removeClass('red bold');
- $('#iOS .time').text('Hoje ' + h + ':' + min);
- $('#android .time').text(h + ':' + min);
- window.scheduleValid = true;
- resizePreview();
- }
- }
- };
- function changeExpirationTime() {
- var h = $('#expirationHour').val();
- var min = $('#expirationMinutes').val();
- var hours = '';
- var minutes = '';
- var plural = ['hora', 'horas', 'minuto', 'minutos'];
- if (h != 0) {
- if (h == 1) {
- hours = h + ' ' + plural[0] + ' ';
- } else {
- hours = h + ' ' + plural[1] + ' ';
- }
- }
- if (min != 0) {
- if (min == 1) {
- minutes = min + ' ' + plural[2];
- } else {
- minutes = min + ' ' + plural[3]
- }
- }
- if (min == 0 && h == 0) {
- $('#pushExpiration').text('Informe o tempo').removeClass('red').addClass('red');
- } else if (min != 0 && h != 0) {
- var time = hours + 'e ' + minutes;
- $('#pushExpiration').text(time).removeClass('red');
- } else if (min != 0 ^ h != 0) {
- var time = hours + minutes;
- $('#pushExpiration').text(time).removeClass('red');
- }
- }
- // get the functions to be called here
- if (calls == 'sendPush') {
- // transform.customSelect('expirationMinutes');
- // transform.customSelect('expirationHour');
- transform.customSelect('sendHour');
- transform.customSelect('sendMinute');
- $('#preVisualization').tabs();
- //set time only when checkbox is clicked, so the Proxy isn't triggered in advance
- $('#scheduleSend').one('change', function () {
- dateTimePreview.setSendDate(); // Initializes the date for Send Schedule
- dateTimePreview.setSendHour(); // Initializes the date for Send Schedule
- dateTimePreview.setSendMinute(); // Initializes the date for Send Schedule
- });
- $('#sendDate').datepicker({minDate: 0}).on('change', function () {
- dateTimePreview.setSendDate();
- });
- $('#sendHour').on('change', function () {
- dateTimePreview.setSendHour();
- });
- $('#sendMinute').on('change', function () {
- dateTimePreview.setSendMinute();
- });
- // $('#expirationHour').on('change', function () {
- // changeExpirationTime();
- // });
- // $('#expirationMinutes').on('change', function () {
- // changeExpirationTime();
- // });
- transform.iOSswitch();
- resizePreview();
- showUpSend();
- showUpExp();
- showUpURL();
- // checkYesNo('.js-check-sound', '#pushSound');
- // checkYesNo('.js-check-increment', '#pushIncrement');
- titleMessagePreview();
- URLPreview();
- messagePreview();
- dateTimePreview.changeSendSchedule();
- behaviors.listData.add(undefined, 5);
- // behaviors.listData.remove();
- refreshPreview();
- } else if (calls == 'newCampaign') {
- $('#preVisualization').tabs();
- transform.iOSswitch();
- resizePreview();
- showUpSend();
- showUpExp();
- showUpURL();
- // checkYesNo('.js-check-sound', '#pushSound');
- // checkYesNo('.js-check-increment', '#pushIncrement');
- titleMessagePreview();
- URLPreview();
- messagePreview();
- behaviors.listData.add(undefined, 5);
- // behaviors.listData.remove();
- } else if (calls == 'newAutomation') {
- $('#preVisualization').tabs();
- transform.iOSswitch();
- resizePreview();
- // showUpSend();
- // showUpExp();
- // showUpURL();
- // checkYesNo('.js-check-sound', '#pushSound');
- // checkYesNo('.js-check-increment', '#pushIncrement');
- // titleMessagePreview();
- // URLPreview();
- // messagePreview();
- behaviors.listData.add(undefined, 5);
- // behaviors.listData.remove();
- $('#campaignsList').on('click', 'button', function () {
- $('.js-title').html($('#msgTitle').html());
- doMessagePreview($('#msgBody').html());
- doURLPreview($('#urlPushField').html());
- });
- } else if (calls == 'newApi') {
- $('#preVisualization').tabs();
- transform.iOSswitch();
- resizePreview();
- showUpURL();
- // checkYesNo('.js-check-sound', '#pushSound');
- // checkYesNo('.js-check-increment', '#pushIncrement');
- titleMessagePreview();
- URLPreview();
- messagePreview();
- // dateTimePreview.changeSendSchedule();
- behaviors.listData.add('#tagBlock');
- behaviors.listData.add('#additionalBlock', 5);
- // behaviors.listData.remove();
- refreshPreview();
- }
- },
- automation: {
- setTime: function (text) {
- $("#timeInterval").html(text);
- $("#pushScheduleHour").html(text);
- },
- timeSlider: function (selectedDays, timeJson, days) {
- var daysName = [];
- var pushSchedule = $('#pushSchedule');
- var daysSelectors = $('input[name=day]');
- daysSelectors.on('change', function () {
- $.each($('input[name=day]'), function (key, obj) {
- selectedDays[key] = $(obj).prop('checked');
- });
- daysName.length = 0;
- $.each(selectedDays, function (key, value) {
- if (value == true)
- daysName.push(days[key]);
- });
- if (selectedDays[0] == true) {
- daysName.push(daysName.shift());
- }
- var daysInterval = selectedDays.slice();
- var sunday = daysInterval.shift();
- var saturday = daysInterval.pop();
- if (daysName.length == 7) {
- pushSchedule.html('Todos os dias');
- } else if (daysName.length == 5 && sunday == false && saturday == false) {
- $('#pushSchedule').html('Dias de semana');
- } else if (daysName.length == 2) {
- $('#pushSchedule').html(daysName.join(' e '));
- } else {
- $('#pushSchedule').html(daysName.join(', '));
- }
- });
- daysSelectors.first().trigger('change');
- var timeIntervalRange = $("#timeIntervalRange");
- timeIntervalRange.slider({
- range: true,
- min: 0,
- max: 24,
- values: [0, 24],
- slide: function (event, ui) {
- var text = 'Entre ' + ui.values[0] + " e " + ui.values[1] + " horas.";
- scriptForPage.automation.setTime(text);
- $(ui.handle).attr('data-value', ui.value);
- timeJson = {'init': ui.values[0], 'end': ui.values[1]};
- }
- });
- var init = timeIntervalRange.slider("values", 0);
- var end = timeIntervalRange.slider("values", 1);
- // USA ESSE JSON PARA PASSAR AS INFOS DE HORA
- timeJson = {'init': init, 'end': end};
- scriptForPage.automation.setTime('Entre ' + init + " e " + end + " horas.");
- // initialize slider label values
- $.each($(timeIntervalRange.slider("widget")).find('.ui-slider-handle'), function (index, obj) {
- $(obj).attr('data-value', timeIntervalRange.slider("values", index));
- });
- return timeJson;
- },
- populateScheduled: function (automationScheduledJson) {
- if(automationScheduledJson !== '0') {
- $.each(automationScheduledJson, function (index, value) {
- var elementsDays = $("input[name*='day']");
- if (value.sunday == 0)
- $(elementsDays).filter(function () {
- return this.value == 'sun'
- }).attr('checked', false);
- if (value.monday == 0)
- $(elementsDays).filter(function () {
- return this.value == 'mon'
- }).attr('checked', false);
- if (value.tuesday == 0)
- $(elementsDays).filter(function () {
- return this.value == 'tue'
- }).attr('checked', false);
- if (value.wednesday == 0)
- $(elementsDays).filter(function () {
- return this.value == 'wed'
- }).attr('checked', false);
- if (value.thursday == 0)
- $(elementsDays).filter(function () {
- return this.value == 'thu'
- }).attr('checked', false);
- if (value.friday == 0)
- $(elementsDays).filter(function () {
- return this.value == 'fri'
- }).attr('checked', false);
- if (value.saturday == 0)
- $(elementsDays).filter(function () {
- return this.value == 'sat'
- }).attr('checked', false);
- $("#timeIntervalRange").slider('values', 0, value.hour_initial);
- $("#timeIntervalRange").slider('values', 1, value.hour_final);
- scriptForPage.automation.setTime('Entre ' + value.hour_initial + " e " + value.hour_final + " horas.");
- $($(".ui-slider-handle")[0]).attr('data-value', value.hour_initial);
- $($(".ui-slider-handle")[1]).attr('data-value', value.hour_final);
- });
- $('input[name=day]').trigger('change');
- }
- },
- newAutomation: function (automationId, campaignsJson, days, audienceJson, criteriaJson, appId, countSubscribers, allAudiences) {
- transform.highlightSubMenu('#automations');
- behaviors.popUp('#selectCampaign', '#campaignsList');
- var campaignIdSelected = 0;
- $.each(campaignsJson, function (key, obj) {
- $('#camp' + obj.campId).on('click', function () {
- $('#campaignsList').fadeOut('fast');
- $('#campName').html(obj.campName);
- //set title field
- var title;
- if (obj.msgTitle == '') {
- title = '-';
- } else {
- title = obj.msgTitle;
- }
- $('#msgTitle').html(title);
- $('#titlePreview').html(title);
- // set URL field
- var urlPush;
- if (obj.urlPush == null) {
- urlPush = '-';
- $('#pushURL').addClass('orange').removeClass('green').html('Não');
- } else {
- urlPush = obj.urlPush;
- $('#pushURL').addClass('green').removeClass('orange').html('Sim');
- }
- $('#urlPushField').html(urlPush);
- campaignIdSelected = obj.campId;
- transform.colonToEmoji(obj.msgBody, '#msgBody');
- transform.colonToEmoji(obj.msgBody, '#msgPreview');
- $("#campaign").next('.js-error').remove();
- $("#campaign").removeClass("error-outline");
- });
- });
- new Tether({
- element: '#campaignsList',
- target: '#selectCampaign',
- attachment: 'top left',
- targetAttachment: 'bottom left'
- });
- var selectedDays = [];
- var timeJson;
- timeJson = scriptForPage.automation.timeSlider(selectedDays, timeJson, days);
- scriptForPage.newAudience('', audienceJson, criteriaJson, appId, false);
- // transform.emojiPicker();
- scriptForPage.pushScript('newAutomation');
- behaviors.autoTextArea();
- $('#footerSave').on('click', function () {
- if (validate.multiFields([['#componentName', 'Precisamos de um nome para a automação'],
- [validate.fieldCampaignAutomation, campaignIdSelected, automationId],
- [validate.fieldsAdditionalData],
- [validate.fieldsAudienceCampaign, true],
- [validate.fieldsAudienceCriteria, false]])) {
- var audiencesSelected = scriptForPage.getSelectedAudiences();
- var data = {
- 'automationId': automationId,
- 'campaignId': campaignIdSelected,
- 'campaignName': $('#campName').html(),
- 'audiencesSelected': audiencesSelected,
- 'selectedDays': '"' + selectedDays.toString() + '"',
- 'timeInit': $("#timeIntervalRange").slider("values", 0),
- 'timeEnd': $("#timeIntervalRange").slider("values", 1)
- };
- modal.getModal('modal-save-automation.php', false, data);
- }
- });
- scriptForPage.getCampaignRecipients(allAudiences, countSubscribers);
- validate.quantitySubscribers(countSubscribers);
- $('#footerCancel').on('click', function () {
- navigateTo.app.push.automations();
- });
- },
- populateAutomation: function (automationId, automationJson, appId, pushCriteriaJson, automationAudienceJson, additionalJson, automationScheduledJson) {
- if (automationId > 0) {
- var name = automationJson['automation_name'];
- var description = automationJson['automation_description'];
- var campaignId = automationJson['campaign_id'];
- populateAudience(automationAudienceJson);
- populateCriteria(pushCriteriaJson);
- populateAdditionalData(additionalJson);
- scriptForPage.automation.populateScheduled(automationScheduledJson);
- $('#componentName').val(name);
- $('#componentDescription').val(description);
- $('#camp' + campaignId).trigger('click');
- action.findReachAudience(appId);
- $('.page-title').html(name);
- }
- function populateCriteria(pushCriteriaJson) {
- var i = 0;
- $.each(pushCriteriaJson, function (index, value) {
- if ((i > 0) && (value !== null) && (value !== undefined)) {
- $("#addNewCondition").trigger("click");
- }
- var selectField = $("#select" + i + "0").attr('value', value.audience_criteria_id);
- selectField.val(value.audience_field_id);
- selectField.next('a').css({color: 'inherit'});
- var varType = selectField.find('option[value=' + selectField.val() + ']').attr('data-type');
- scriptForPage.showConditionField('#jsConditionRow' + i, varType);
- var objectTypeCondition = $('#jsConditionRow' + i).find('.js-' + varType + '-condition');
- if (varType == 'boolean') {
- objectTypeCondition.find('a[href="#' + value.audience_value + '"]').trigger('click');
- } else {
- objectTypeCondition.find('select[name=operator]').val(value.audience_field_condition_id);
- objectTypeCondition.find('select[name=operator]').attr('value', value.audience_field_condition_id);
- objectTypeCondition.find('select[name=operator]').next('a').css({color: 'inherit'});
- objectTypeCondition.find('input[name=val]').val(value.audience_value);
- }
- i++;
- });
- }
- function populateAudience(automationAudienceJson) {
- if (automationAudienceJson == null || automationAudienceJson == '0') {
- $('#audienceSelected0').attr('checked', true);
- $('#audienceSelected0').trigger('change');
- } else {
- var allRowsAudience = $("input[class*='audience']");
- $.each(automationAudienceJson, function (index, value) {
- var elementAudienceId = $(allRowsAudience).filter(function () {
- return this.value == value.audience_id
- }).attr('id');
- $('#' + elementAudienceId).attr('checked', true);
- $('#' + elementAudienceId).trigger('change');
- });
- }
- }
- function populateAdditionalData(additionalJson) {
- //verify if automation has additional data
- if ((additionalJson !== null) && (additionalJson !== undefined)) {
- var additionalBlock = $('#additionalBlock');
- $.each(additionalJson, function (index, value) {
- if ((value !== null) && (value !== undefined) && (value.key_data !== undefined)) {
- // add row
- additionalBlock.find('.addNewData').trigger('click');
- // insert data
- additionalBlock.find('.js-dataTemplate').prev()
- .find('[name="additional-key"]').attr('value', value.key_data).end()
- .find('[name="additional-value"]').attr('value', value.value_data);
- }
- });
- }
- }
- }
- },
- collaborator: {
- newCollaborator: function (collaboratorJson) {
- scriptForPage.newCollaborator(collaboratorJson);
- },
- populateCollaborator: function () {
- },
- saveCollaborator: function() {
- var elements = $(".js-collaborator-row");
- var valid = [];
- for (var i = 0; i < elements.length; i++) {
- var row = "#" + elements[i].id;
- var selectProfile = $(row.replace('jsCollaboratorRow', 'select') + '0');
- var memberName = $(row).find('input[name=member-name]');
- var memberEmail = $(row).find('input[name=member-email]');
- if ($(selectProfile).val() == '') {
- valid.push(validate.field(selectProfile['selector'], 'Qual o perfil?'),
- $(selectProfile['selector']).nextAll('a'), $(selectProfile['selector']).nextAll('a'));
- }
- if ($(memberName).val() == '') {
- valid.push(validate.field(memberName['selector'], 'Qual o nome?'));
- }
- if ($(memberEmail).val() == '') {
- valid.push(validate.field(memberEmail['selector'], 'Qual o e-mail?'));
- }
- console.log('nada foi encontrado pode salvar');
- //save collaborator and send invitation
- //action.saveCollaborator(customerId, userName);
- }
- }
- },
- generalConfig: {
- /* Register when user copy the element and supports a button to do the copy
- *
- * @param btnId Button ID to copy text
- * @param idToCopy Text ID to copy
- * @param timeOut Timeout time
- * */
- copyContent: function (btnId, idToCopy, timeOut) {
- var copyBtn = $(btnId);
- var copyThis = $(idToCopy);
- timeOut = timeOut || 1000;
- var originalBtnText = copyBtn.html();
- var originalBtnClass = copyBtn.attr('class');
- /* Use clipboard.js plugin
- * Ref: https://github.com/zenorocha/clipboard.js.git
- * */
- copyBtn.attr('data-clipboard-target', idToCopy);
- new Clipboard(btnId);
- copyThis.on('copy', function () {
- copyBtn.html('Copiado!').removeClass('button-clean-gray').addClass('button-blue');
- setTimeout(function () {
- copyBtn.html(originalBtnText);
- if (originalBtnClass.search('button-blue') == -1) {
- copyBtn.switchClass('button-blue', originalBtnClass, 400);
- }
- }, timeOut);
- });
- // DISABLE COPY CUT PASTE
- // copyBtn.on('cut copy paste', function (e) {
- // e.preventDefault(); //disable cut,copy,paste
- // });
- },
- updateField: function (valueField, formData, token) {
- $.ajax({
- type: 'POST',
- url: '/appConfigValidation',
- data: formData,
- dataType: 'json',
- encode: true
- })
- .done(function (data) {
- console.log(data);
- if (!data.success) {
- if (data.errors.password) {
- $('#password-group').addClass('has-error');
- $('#password-group').append('<div class="help-block">' + data.errors.password + '</div>');
- }
- if (data.errors.loginError) {
- //$('#message-login').append('<div class="alert-box">' + data.errors.loginError + '</div>');
- $('#password-group').addClass('has-error');
- $('#password-group').append('<div class="help-block">' + data.errors.loginError + '</div>');
- }
- } else {
- $(valueField).text(formData['appName']);
- var appTitleBtn = $('#appTitleBtn');
- /* update in menu side */
- var nonText = appTitleBtn.html();
- nonText = nonText.substring(nonText.indexOf('<'));
- appTitleBtn.html(formData['appName'] + nonText);
- $('#menuName' + token).text(formData['appName']);
- }
- })
- .fail(function (data) {
- console.log(data);
- });
- },
- updateIcon: function (token) {
- $("#uploadIconForm").on('submit', (function (e) {
- e.preventDefault();
- var uploadMessage = $("#uploadMessage");
- var uploadBtn = $('#uploadIconBtn');
- uploadMessage.empty();
- var formData = new FormData(this);
- formData.append('object', 'appIcon');
- $.ajax({
- url: "/actions/imageUpload.php", // Url to which the request is send
- type: "POST", // Type of request to be send, called as method
- data: formData, // Data sent to server, a set of key/value pairs (i.e. form fields and values)
- contentType: false, // The content type used when sending data to the server.
- cache: false, // To unable request pages to be cached
- processData: false, // To send DOMDocument or non processed data file it is set to false
- success: function (data) { // A function to be called if request succeeds
- var result = $.parseJSON(data);
- console.log('done');
- console.log(data);
- if (result.hasOwnProperty("img")) {
- uploadMessage.css({color: '#3bdb7b', fontWeight: '600'}).text(result.msg);
- uploadBtn.text('Enviado!')
- .removeClass('button-clean-blue')
- .addClass('button-green');
- setTimeout(function () {
- uploadBtn.switchClass('button-green', 'button-clean-blue', 400).text('Upload');
- }, 1500);
- var path = ref.getUploads + '/app_icons/' + result.img;
- $('#appIcon').attr('src', path)
- .attr('data', path);
- /* update in menu side */
- $('#menuImg' + token).attr('src', path);
- } else {
- uploadMessage.attr('style', '""').text(result.msg);
- }
- },
- fail: function (data) {
- console.log('fail');
- console.log(data);
- }
- });
- }));
- }
- },
- getAdditionalData: function () {
- var elements = $('.js-dataRow');
- var dict = [];
- $.each(elements, function (num, obj) {
- var key = $(obj).find('input[name="additional-key"]').val();
- var value = $(obj).find('input[name="additional-value"]').val();
- if ((key !== '') && (value !== '')) {
- dict.push({key: key, value: value});
- }
- });
- return dict;
- },
- // TODO deletar essa função quando o list estiver funcionando
- getCustomFields: function (customFieldsJson) {
- var num = 0; // uniquer number for ids
- $("#addCustomField").hover(function () {
- $(this).css({fontWeight: '400'});
- behaviors.svgChangeTo.hover($(this).children('img'));
- }, function () {
- $(this).attr('style', '');
- behaviors.svgChangeTo.hover($(this).children('img'));
- }).on("click", function () {
- // if ($('.js-customField').length < 5) {
- var $template = $('#templateCustomFields'),
- $clone = $template
- .clone()
- .removeClass('hide template')
- .addClass('js-customField')
- .removeAttr('id')
- .insertBefore($template);
- var amountData = $('.js-customField').length;
- num++;
- // Update the name attributes
- $clone
- .find('#customFieldName').attr('name', 'data[' + num + '].custom_field')
- .attr('id', 'customFieldName' + num).end()
- .find('#customFieldType').attr('id', 'customFieldType' + num).end();
- transform.customSelect('customFieldType' + num);
- //add click atribute
- // remove();
- $.each($('#customFieldForm').find('.numberField'), function (key, obj) {
- $(obj).html('Campo customizável ' + (key + 1));
- });
- if (amountData >= 5) {
- $(".addData").addClass('hide');
- }
- // }
- });
- $("#customFieldsBlock").on('hover', '.js-removeData', function () {
- behaviors.svgChangeTo.hover($(this).children('img'));
- }, function () {
- behaviors.svgChangeTo.hover($(this).children('img'));
- }).on("click", '.js-removeData', function () {
- // Remove element containing the fields
- $(this).parents('.control-panel-row').remove();
- // re-write the titles
- $.each($('#customFieldForm').find('.numberField'), function (key, obj) {
- $(obj).html('Campo customizável ' + (key + 1));
- });
- var amountData = $('.js-customField').length;
- if (amountData <= 5) {
- $(".addData").removeClass('hide');
- } else {
- $(".addData").addClass('hide');
- }
- });
- // function remove() {
- // $(".js-dataRow").on('hover', '.js-removeData', function () {
- // behaviors.svgChangeTo.hover($(this).children('img'));
- // }, function () {
- // behaviors.svgChangeTo.hover($(this).children('img'));
- // }).on("click", '.js-removeData', function () {
- // // Remove element containing the fields
- // $(this).parents('.control-panel-row').remove();
- //
- // // re-write the titles
- // $.each($('#customFieldForm').find('.numberField'), function (key, obj) {
- // $(obj).html('Campo customizável ' + (key + 1));
- // });
- //
- // var amountData = $('.js-customField').length;
- // if (amountData <= 5) {
- // $(".addData").removeClass('hide');
- // } else {
- // $(".addData").addClass('hide');
- // }
- // });
- // }
- var i = 0;
- //verify if app has custom fields
- if ((customFieldsJson !== null) && (customFieldsJson !== undefined)) {
- $.each(customFieldsJson, function (index, value) {
- i++;
- if ((i == 1) && (value !== null) && (value !== undefined) && (value.custom_field_name !== undefined)) {
- $("[name='data[0].custom_field']").attr('value', value.custom_field_name);
- var selectField = $("#customFieldType0").attr('value', value.custom_field_type);
- selectField.val(value.custom_field_type);
- selectField.next('a').css({color: 'inherit'});
- } else if ((value !== null) && (value !== undefined) && (value.custom_field_name !== undefined)) {
- // var $template = $('#templateCustomFields'),
- // $clone = $template
- // .clone()
- // .removeClass('hide')
- // .addClass('.js-customField')
- // .removeAttr('id')
- // .insertBefore($template);
- //
- // var amountData = $('.js-customField').length - 1;
- // num = amountData + 1; // initialize num
- $('#addCustomField').trigger('click');
- // .find('#customFieldName').attr('name', 'data[' + num + '].custom_field')
- $('#customFieldName' + num).attr('value', value.custom_field_name);
- // $('#customFieldType' + num).attr('value', value.custom_field_type);
- // Update the name and value attributes
- // $clone
- // .find('[name="custom_field"]').attr('name', 'data[' + amountData + '].custom_field').attr('value', value.custom_field_name).end()
- // .find('#customFieldType').attr('id', 'customFieldType' + amountData).end()
- // .find('.numberField').html('Campo customizável ' + (amountData + 1)).end();
- var selectField = $("#customFieldType" + num).attr('value', value.custom_field_type);
- selectField.val(value.custom_field_type);
- selectField.next('a').css({color: 'inherit'});
- // $(".js-removeData").trigger("click");
- // transform.customSelect('customFieldType' + amountData);
- // if (amountData == 4)
- // $(".addData").addClass('hide');
- }
- });
- if (i > 1) {
- $('.js-removeData').first().removeClass('hide');
- }
- }
- // remove();
- },
- getSelectedAudiences: function () {
- var elements = $('.list-checkbox');
- var dict = '';
- for (var i = 0; i < elements.length; i++) {
- if ($('#audienceSelected' + i + ':checked').length > 0) {
- var audience = $('#audienceSelected' + i).val();
- if (audience !== '') {
- if (dict == '')
- dict = audience;
- else
- dict += ',' + audience;
- }
- }
- }
- return '"' + dict + '"';
- },
- getAudienceCriteria: function () {
- var elements = $(".js-condition-row");
- var dict = [];
- for (var i = 0; i < elements.length; i++) {
- var row = "#" + elements[i].id;
- var selectCriteria = $(row.replace("jsConditionRow", "select") + '0');
- var nameSelectCriteria = selectCriteria.val();
- if (nameSelectCriteria != '' && nameSelectCriteria != undefined) {
- var nameGroupCriteria = selectCriteria.find(':selected').closest('optgroup').attr('label');
- var nameTypeCriteria = $(selectCriteria).find('option[value=' + nameSelectCriteria + ']').attr('data-type');
- var objectTypeCondition = $(row).find('.js-' + nameTypeCriteria + '-condition');
- var nameInputDeclaration, nameSelectCondition = '';
- if (nameTypeCriteria == 'boolean') {
- nameSelectCondition = objectTypeCondition.find('.ui-state-active').attr('data-value');
- nameInputDeclaration = objectTypeCondition.find('.ui-state-active').find('a').attr("href").replace('#', '');
- } else {
- nameSelectCondition = objectTypeCondition.find('select[name=operator]').val();
- nameInputDeclaration = objectTypeCondition.find('input[name=val]').val();
- }
- var nomeCriteria = $(selectCriteria).find(':selected')[0].innerText;
- if ((nameSelectCriteria !== '') && (nameSelectCondition !== '') && (nameInputDeclaration !== '')) {
- dict.push({
- criteria: nameSelectCriteria,
- nameCriteria: nomeCriteria,
- groupCriteria: nameGroupCriteria,
- typeCriteria: nameTypeCriteria,
- condition: nameSelectCondition,
- value: nameInputDeclaration
- });
- }
- }
- }
- return dict;
- },
- insertRecentAudience: function (recentAudienceId) {
- var $template = $('#templateAudienceRecent'),
- $clone = $template
- .clone()
- .removeClass('hide')
- .removeAttr('id')
- .insertBefore($template);
- var amountData = $('.templateRowAudience').length - 1;
- var date = new Date();
- var month = ("0" + (date.getMonth() + 1)).slice(-2);
- var today = date.getDate() + '/' + month + '/' + date.getFullYear();
- var rangeLocalFormat = parseInt($("#rangeNumber").text()).toLocaleString(locale);
- $clone
- .find('input[type=checkbox]').attr('value', recentAudienceId).attr('checked', true).end()
- .find('input[id=audienceSelected]').attr('id', 'audienceSelected' + amountData).end()
- .find('label[for=audienceSelected]').attr('for', 'audienceSelected' + amountData).end()
- .find('[name="name"]').attr('name', 'nameAudience' + amountData).html($("#componentName").val()).end()
- .find('[name="size"]').attr('name', 'sizeAudience' + amountData).html(rangeLocalFormat).end()
- .find('[name="rank"]').attr('name', 'rankAudience' + amountData).html('-').end()
- .find('[name="dateCreation"]').attr('name', 'dateCreationAudience' + amountData).html(today).end();
- //update the range number
- var rangeFullNumber = parseInt($('.range-full-number').html()) + parseInt($("#rangeNumber").text());
- var rangeFullLocalFormat = rangeFullNumber.toLocaleString(locale);
- $('.range-full-number').html(rangeFullLocalFormat);
- $("#allAudiences").find('[id="sumSize"]').html(rangeFullLocalFormat);
- $('#qtRecipients').html(rangeFullLocalFormat);
- }
- };
- var charts = {
- jsChart: '',
- chartBg: '',
- chartCanvas: '',
- createDonutChart: function (context, value) {
- var chart = value == 0 ? 'doughnut' : 'RoundedDoughnut';
- Chart.defaults.RoundedDoughnut = Chart.helpers.clone(Chart.defaults.doughnut);
- Chart.controllers.RoundedDoughnut = Chart.controllers.doughnut.extend({
- draw: function (ease) {
- var ctx = this.chart.chart.ctx;
- var easingDecimal = ease || 1;
- Chart.helpers.each(this.getDataset().metaData, function (arc, index) {
- arc.transition(easingDecimal).draw();
- var vm = arc._view;
- var radius = (vm.outerRadius + vm.innerRadius) / 2;
- var thickness = (vm.outerRadius - vm.innerRadius) / 2;
- var angle = Math.PI - vm.endAngle - Math.PI / 2;
- ctx.save();
- ctx.fillStyle = vm.backgroundColor;
- ctx.translate(vm.x, vm.y);
- ctx.beginPath();
- ctx.arc(radius * Math.sin(angle), radius * Math.cos(angle), thickness, 0, 2 * Math.PI);
- ctx.arc(radius * Math.sin(Math.PI), radius * Math.cos(Math.PI), thickness, 0, 2 * Math.PI);
- ctx.closePath();
- ctx.fill();
- ctx.restore();
- });
- }
- });
- var deliveredData = {
- labels: [
- "Value"
- ],
- datasets: [
- {
- data: [value, (100 - value)],
- backgroundColor: [
- "#3ec556",
- "rgba(0,0,0,0)"
- ],
- hoverBackgroundColor: [
- "#3ec556",
- "rgba(0,0,0,0)"
- ],
- borderWidth: [
- 0, 0
- ]
- }]
- };
- var deliveredOpt = {
- cutoutPercentage: 88,
- animation: {
- animationRotate: true,
- duration: 1000
- },
- legend: {
- display: false
- },
- tooltips: {
- enabled: false
- }
- };
- this.jsChart = $('.js-chart');
- this.chartBg = $('.chart-background');
- this.chartCanvas = $('.chart-canvas');
- $(window).on('resize', function () {
- charts.resizeChartDiv();
- });
- return new Chart($(context), {
- type: chart,
- data: deliveredData,
- options: deliveredOpt
- });
- },
- resizeChartDiv: function () {
- charts.jsChart.each(function () {
- var width = $(this).width();
- $(this).height(width);
- charts.chartBg.each(function () {
- var width = charts.chartCanvas.width() * 0.065;
- $(this).css({borderWidth: width});
- })
- });
- }
- };
- var validate = {
- /**
- *
- * @param idValue id or OBJECT to be validated (must not be null or '')
- * @param message string message to be shown if there is error
- * @param redBox object [optional] where the red border is to be drawn. if not set will use the idValue
- * @param errorPosition object [optional] the message will be shown after this obj. if not set will use the idValue
- *
- * */
- field: function (idValue, message, redBox, errorPosition, setError) {
- var valid = true;
- var field = $(idValue);
- if (redBox != undefined) {
- var fieldBox = $(redBox);
- } else {
- fieldBox = $(idValue);
- }
- if (errorPosition != undefined) {
- var aboveError = $(errorPosition);
- } else {
- aboveError = $(idValue);
- }
- var errorElement = "<div class='has-error error-pad js-error'>" +
- "<span class='help-block'>" + message + "</span></div>";
- var jsError = aboveError.next('.js-error');
- //jsError.remove();
- fieldBox.off('focus.valid').on('focus.valid', function () {
- if (fieldBox.hasClass('error-outline')) {
- var jsError = aboveError.next('.js-error');
- fieldBox.removeClass('error-outline');
- fieldBox.one('blur', function () {
- if (field.val() == null || field.val() == '') {
- jsError.remove();
- fieldBox.addClass('error-outline');
- aboveError.after(errorElement);
- } else {
- // $('#error-pushContent').slideUp('fast');
- jsError.slideUp('fast', function () {
- this.remove();
- });
- // get rid of the error message at footer bar
- $('#footerError').fadeOut('fast', function () {
- $(this).html('');
- $(this).show();
- });
- }
- });
- }
- });
- if (field.val() == null || field.val() == '' || setError == true) {
- // $('i').after("<div class='has-error js-error' style='line-height: 3em;'><span class='help-block'>" + message + "</span></div>");
- jsError.remove();
- aboveError.after(errorElement);
- fieldBox.addClass('error-outline');
- valid = false;
- }
- return valid;
- },
- /**
- * To validate all fields at once. Pass an Array of arrays.
- * If is to validate using validate.field, then pass an array with the parameters for this function.
- * If it is a validation function, pass an array where the first element is the function name (without ()) and the
- * other elements are parameters (if needed).
- *
- * @param array array = [[idValue, message, redBox, errorPosition], [idValue, message], [function, param1, param2]]
- *
- * */
- multiFields: function (array) {
- var valid = [];
- var validated = true;
- $.each(array, function (index, obj) {
- if (typeof obj[0] === 'function') {
- var params = [];
- for (var i = 1; i < obj.length; i++) {
- params.push(obj[i]);
- }
- valid.push(obj[0].apply(this, params));
- } else {
- valid.push(validate.field(obj[0], obj[1], obj[2], obj[3]));
- }
- });
- $.each(valid, function (key, value) {
- if (!value) {
- validated = false;
- }
- });
- return validated;
- },
- fieldsAdditionalData: function () {
- var elements = $('#additionalBlock').find('.js-dataRow');
- var valid = [];
- var validated = true;
- $.each(elements, function (num, obj) {
- var keyObj = $(obj).find('input[name="additional-key"]');
- var valueObj = $(obj).find('input[name="additional-value"]');
- var key = keyObj.val();
- var value = valueObj.val();
- if (key != '' || value != '') {
- valid.push(validate.field(keyObj, 'Qual a chave?'));
- valid.push(validate.field(valueObj, 'Qual o valor?'));
- }
- });
- $.each(valid, function (key, value) {
- if (!value)
- validated = false;
- });
- return validated;
- },
- fieldsAudienceCriteria: function (mandatoryCriteria) {
- var elements = $(".js-condition-row");
- var valid = [];
- var validated = true;
- var atLeastOne = false;
- for (var i = 0; i < elements.length; i++) {
- var row = "#" + elements[i].id;
- var selectCriteria = $(row.replace("jsConditionRow", "select") + '0');
- //var nameGroupCriteria = selectCriteria.find(':selected').closest('optgroup').attr('label');
- if (selectCriteria.val() !== '' && mandatoryCriteria) {
- atLeastOne = true; // at least 1 criteria has to be set
- var nameTypeCriteria = $(selectCriteria).find('option[value=' + selectCriteria.val() + ']').attr('data-type');
- var objectTypeCondition = $(row).find('.js-' + nameTypeCriteria + '-condition');
- var selectCondition = objectTypeCondition.find('select[name=operator]');
- var inputDeclaration = objectTypeCondition.find('input[name=val]');
- if ($(selectCriteria).val() == '') {
- valid.push(validate.field(selectCriteria['selector'], 'Qual o critério?'),
- $(selectCriteria['selector']).nextAll('a'), $(selectCriteria['selector']).nextAll('a'));
- } else if ($(selectCondition).val() == '') {
- valid.push(validate.field(selectCondition, 'Qual a condição?',
- $(selectCondition).next('a'), $(selectCondition).next('a')));
- if ($(inputDeclaration).val() == '')
- valid.push(validate.field(inputDeclaration['selector'], 'Com o que vamos comparar?'));
- } else if ($(inputDeclaration).val() == '')
- valid.push(validate.field(inputDeclaration['selector'], 'Com o que vamos comparar?'));
- }
- }
- if (!atLeastOne) {
- row = "#" + elements[0].id;
- selectCriteria = $(row.replace("jsConditionRow", "select") + '0');
- if (!validate.field(selectCriteria['selector'], 'Precisamos de pelo menos um critério',
- $(selectCriteria['selector']).next('a'), $('.js-errorPosition').parent('span'))) {
- validated = false;
- }
- } else {
- $.each(valid, function (key, value) {
- if (!value)
- validated = false;
- });
- }
- return validated;
- },
- fieldCampaignAutomation: function (campaignId, automationId) {
- if (automationId == 0 && (campaignId == '' || campaignId == '0')) {
- validate.field('#campaign', 'Por favor, selecione uma campanha para automatizar', '#selectCampaign');
- return false;
- }
- return true;
- },
- /**
- * @param requireUsers boolean If the service needs audience with users (true) or not (false)
- * */
- fieldsAudienceCampaign: function (dontRequireUsers) {
- var elements = $(".list-checkbox");
- var valid = [];
- var validated = true;
- var qtAudiencesSelected = 0;
- for (var i = 0; i < elements.length; i++) {
- if ($('#audienceSelected' + i + ':checked').length > 0)
- qtAudiencesSelected += 1;
- }
- var qtSelected = $('.range-full-number').html();
- $(document).off('ajaxComplete.valid'); // remove ajax so it won't be bound twice if there is another error,
- // like audience with no users
- function showErrorMessage(text) {
- validated = false;
- valid.push(validate.field('label', text, $('none'), $('.table-be-table')));
- $('.js-audienceLabel').css({borderColor: '#EC7E7E'});
- $(document).on('ajaxComplete.valid', function (e, xhr, options) {
- validate.fieldsAudienceCampaign(); //validate again on audience selection
- if (options.url != '/handleSubscribersAudience') { //remove this handler if user change pages
- $(document).off('ajaxComplete.valid');
- }
- });
- }
- if (qtAudiencesSelected == 0) {
- showErrorMessage('Por favor, selecione uma audiência para enviar sua mensagem');
- } else if (qtSelected == 0 && !dontRequireUsers) {
- showErrorMessage('As audiências selecionadas não possuem usuários. Por favor, selecione outra.');
- } else {
- $('#audienceSelectTable').next('.js-error').remove();
- $('.js-audienceLabel').removeClass("error-outline").css({borderColor: ''});
- $('.push-row').find('input[type=checkbox]').off('change.error');
- }
- return validated;
- },
- quantitySubscribers: function (countSubscribers) {
- var valid = [];
- var validated = true;
- if (countSubscribers == 0) {
- // validated = false;
- // valid.push(validate.field('label', 'Não há nenhum usuário cadastrado para esse app'));
- // $('.has-error').css({marginTop: '-31px'});
- $('.list-checkbox').children('label').css({borderColor: '#EC7E7E'});
- $('#footerError').html('Não há nenhum usuário cadastrado.<br>Infelizmente não podemos enviar nenhum push.');
- $('#sendPushBtn').off('click').css({backgroundColor: '#b5b5b5', cursor: 'default'});
- } else {
- // $('.js-error').remove();
- // $('.list-checkbox').children('label').removeClass("error-outline").css({borderColor: ''});
- // $('.has-error').css({marginTop: ''});
- }
- return validated;
- }
- };
- /**
- * Created by Juliano on 04/02/2016.
- */
- var contentContainer = $("#content-container");
- var appHeader = $("#app-header");
- window.locale = 'pt-br';
- (function ($, undefined) {
- $.fn.getCursorPosition = function () {
- var el = $(this).get(0);
- var pos = 0;
- if ('selectionStart' in el) {
- pos = el.selectionStart;
- } else if ('selection' in document) {
- el.focus();
- var Sel = document.selection.createRange();
- var SelLength = document.selection.createRange().text.length;
- Sel.moveStart('character', -el.value.length);
- pos = Sel.text.length - SelLength;
- }
- return pos;
- }
- })(jQuery);
- var access = {
- /* Hover open effect on menu */
- threeDots: function () {
- var optionsBalloon = $("#options-balloon");
- var timer;
- $("#3-dots-menu").on("mouseleave", function () {
- timer = setTimeout(function () {
- optionsBalloon.fadeOut("fast");
- }, 400);
- }).on("click", function () {
- clearTimeout(timer);
- optionsBalloon.fadeToggle("fast");
- event.stopPropagation();
- });
- optionsBalloon.on("mouseenter", function () {
- clearTimeout(timer);
- optionsBalloon.fadeIn();
- event.stopPropagation();
- }).on("mouseleave", function (event) {
- timer = setTimeout(function () {
- optionsBalloon.fadeOut("fast");
- event.stopPropagation();
- }, 400);
- });
- $("#sign-btn-arrow").on("click", function () {
- $("#btn_next").trigger("click");
- });
- $("#forgot-btn-arrow").on("click", function () {
- $("#btn_send").trigger("click");
- });
- },
- /* This is used to personalize the select element of sign up page
- *
- * Have to add this on the page (Theter and Select):
- * <link rel="stylesheet" href="select-theme-default.css" />
- * <script src="tether.min.js"></script>
- * <script src="select.min.js"></script>
- *
- * Then use this code here to use a placeholder and style the element.
- *
- * More info: http://github.hubspot.com/select/docs/welcome/
- */
- customSelect: function () {
- var signSelect;
- var element = document.getElementById('companySize');
- signSelect = new Select({
- el: element,
- className: 'select-theme-inngage'
- });
- signSelect.on('change', function () {
- $(".select-target.select-theme-inngage").css({color: '#444'});
- });
- element.setAttribute('tabindex', '-1');
- },
- doLogout: function () {
- var formData = {
- 'logout': true
- };
- var ajaxSend = $.ajax({
- type: 'POST',
- url: '/handleLogout',
- data: formData,
- dataType: 'json',
- encode: true,
- timeout: 10000
- }).done(function (data) {
- console.log('done');
- //modal.closeModal();
- // modal.getModal('success-saved.php', true, {obj: 'Campanha', justShow: true});
- }).fail(function (data) {
- console.log(data);
- //action.verifyBehavior('fail', afterAction);
- ajaxSend.abort();
- });
- }
- };
- var ref = {
- // INCLUDES
- getIncludes: "/includes",
- // INCLUDES APP-PG
- getAppPg: "/includes/app-pg",
- // INCLUDES MAIN-PG
- getMainPg: "includes/main-pg",
- // PLUGINS PATH
- getPlugins: "/resources/plugins",
- // UPLOADS PATH
- getUploads: "/resources/uploads",
- // VIEW PATH
- getView: "/view"
- };
- var navigation = {
- /* Code to show and hide user pop-up menu in nav bar.
- * The arrow behavior is set here too.
- * */
- userMenu: function () {
- /* show user pop up menu when mouse enters the user bar space */
- var popUpMenu = $("#user-pop");
- var userBar = $(".user-bar");
- var optionsArrow = $("#options-arrow");
- // has to use 2 timers to work when leave popMenu and comes back to userBar
- var timerUser; // timer for when leave userBar
- var timerPop; // timer for when leave userPopMenu
- userBar.on("mouseenter", function (event) {
- clearTimeout(timerUser);
- clearTimeout(timerPop);
- //popUpMenu.fadeIn("fast");
- event.stopPropagation();
- //optionsArrow.addClass('rotate');
- }).on("mouseleave", function () {
- timerUser = setTimeout(function () {
- popUpMenu.fadeOut("fast");
- //event.stopPropagation();
- optionsArrow.removeClass('rotate-180');
- }, 250);
- }).off('click').click(function (event) {
- event.stopPropagation();
- optionsArrow.toggleClass('rotate-180');
- popUpMenu.toggle();
- });
- popUpMenu.on("mouseenter", function () {
- clearTimeout(timerUser);
- clearTimeout(timerPop);
- popUpMenu.fadeIn("fast");
- //event.stopPropagation();
- optionsArrow.addClass('rotate-180');
- }).on("mouseleave", function () {
- timerPop = setTimeout(function () {
- popUpMenu.fadeOut("fast");
- //event.stopPropagation();
- optionsArrow.removeClass('rotate-180');
- }, 250);
- });
- // show the user pop-up menu, and hide it clicking anywhere else in the page
- $(document).on("click", function () {
- popUpMenu.fadeOut("fast");
- optionsArrow.removeClass('rotate-180');
- $("#options-balloon").hide();
- $("#config-balloon").hide();
- });
- },
- /* Menu-side scroll effect */
- navSideScroll: function () {
- var lastScrollPosition = 0;
- var navSide = $("#nav-side");
- var space = "<div style='height: " + navSide.height() + "px;'></div>";
- // var space = "<div style='height: " + navSide.height() + "px;' id='space'></div>";
- // $('#space').remove();
- $('body').prepend(space);
- $(window).scroll(function () {
- var screenWindow = $(window);
- var sp = screenWindow.scrollTop();
- //scrolling down
- if (lastScrollPosition < sp) {
- //if screen passes nav-side bottom
- if (sp + screenWindow.height() >= navSide.height() + navSide.offset().top) {
- navSide.addClass("nav-side-fixed-bot");
- }
- //else if scrolling up
- } else {
- //and is fixed bot
- if (navSide.hasClass("nav-side-fixed-bot")) {
- //set top, pass to absolute
- navSide.removeClass('nav-side-fixed-bot');
- navSide.css({top: sp + screenWindow.height() - navSide.height()});
- }
- //and if scroll is above nav-side top, then set nav-side top to scroll
- if (sp <= navSide.offset().top) {
- navSide.css({top: sp});
- }
- }
- lastScrollPosition = sp;
- });
- $(window).trigger('scroll');
- },
- /* Put shadow on nav-top when user scrolls the screen */
- navTopShadow: function () {
- $(window).scroll(function () {
- var navTop = $(".nav-top");
- if ($(window).scrollTop() > 0) {
- navTop.addClass('nav-top-shadow');
- } else {
- navTop.removeClass('nav-top-shadow');
- }
- });
- },
- navTop: function () {
- this.userMenu();
- this.navTopShadow()
- },
- navSide: function () {
- this.navSideScroll();
- }
- };
- var behaviors = {
- /*
- * This function applyes the menu pop behavior to menu buttons and pop menus.
- * Call this function with the menu trigger button.
- *
- * @param popMenu what is the menu ID to be poped-up (pass #id)
- * @param buttonID what is the menu button ID to open the pop-up (pass #id)
- * @param expandClass class with animation to expand
- * @param shrinkClass class with animation to shrink
- *
- * */
- popUp: function (buttonID, popMenuId, expandClass, shrinkClass) {
- // has to use 2 timers to work when leave popMenu and comes back to userBar
- var timerThis; // timer for when leave 'this'
- var timerPop; // timer for when leave popMenu
- var popMenu = $(popMenuId);
- var button = $(buttonID);
- popMenu.css({visibility: 'visible'}).hide();
- function expand() {
- button.children('img').removeClass(shrinkClass);
- button.children('img').addClass(expandClass);
- }
- function shrink() {
- button.children('img').removeClass(expandClass);
- button.children('img').addClass(shrinkClass);
- }
- button.on('click', function (e) {
- e.stopPropagation();
- popMenu.fadeToggle('fast');
- $(document).one('mouseup.popMenu', function (e) {
- if (!popMenu.is(e.target) // if the target of the click isn't the container...
- && popMenu.has(e.target).length === 0) { // ... nor a descendant of the container
- popMenu.fadeOut("fast");
- shrink();
- }
- });
- }).on("mouseenter", function () {
- clearTimeout(timerThis);
- clearTimeout(timerPop);
- expand();
- }).on("mouseleave", function () {
- timerThis = setTimeout(function () {
- popMenu.fadeOut("fast");
- shrink();
- $(document).off('mouseup.popMenu');
- }, 300);
- });
- popMenu.on("mouseenter", function () {
- clearTimeout(timerThis);
- clearTimeout(timerPop);
- popMenu.fadeIn("fast");
- }).on("mouseleave", function () {
- timerPop = setTimeout(function () {
- popMenu.fadeOut("fast");
- shrink();
- $(document).off('mouseup.popMenu');
- }, 600);
- });
- },
- //no-app change fill color
- plusApp: function () {
- $("#plus-app, #new-app-btn").hover(function () {
- $("#plus-app").addClass("plus-app-hover");
- $("#new-app-btn").addClass("button-blue-hover");
- }, function () {
- $("#plus-app").removeClass("plus-app-hover");
- $("#new-app-btn").removeClass("button-blue-hover");
- });
- },
- /* Insert a local input field to edit content
- *
- * @param clicked element to be clicked and trigger the effect
- * @param toFadeOut element to get rid of
- * @param editCount number of the element to be used in IDs
- * @param wordID the identification text of the ID to be used in selector
- *
- * Update: previous version inserted html to the DOM. This version doesn't
- * */
- editField: {
- // Distinguish between cancel and accept for different fields
- function: function (clicked, toFadeOut, toFadeIn, wordId) {
- //var thisEditCount = editCount;
- var fadeOutThis = $(toFadeOut);
- var fadeInThis = $(toFadeIn);
- //var textValue = $.trim(fadeOutThis.text());
- $(clicked).on('click', function (e) {
- fadeOutThis.fadeOut('fast', function () {
- fadeInThis.fadeIn('fast', function () {
- var inputElem = fadeInThis.find('input');
- // var originalValue = inputElem.val();
- $(document).on('keyup', function (e) {
- if (e.keyCode == 13) {
- $("#accept" + wordId).trigger('click');
- }
- if (e.keyCode == 27) {
- $("#cancel" + wordId).trigger('click');
- }
- });
- $("#accept" + wordId).on('click', function () {
- //var newName = editionInput.val();
- $('#cancel' + wordId).trigger('click');
- });
- $('#cancel' + wordId).on('click', function () {
- fadeInThis.fadeOut('fast', function () {
- fadeOutThis.fadeIn('fast');
- // inputElem.val(originalValue);
- });
- //$('.input-div').css({textAlign: 'right'});
- $(document).off('**');
- });
- $('#input' + wordId).select();
- });
- });
- });
- }
- },
- /* Change SVG color
- * Takes the image source attribute and change the last name to the color to use
- * @param imgTag pass selector of the IMG to switch
- * @param color name of the color */
- svgChangeTo: {
- color: function (imgTag, color) {
- var image = $(imgTag);
- var imgSource = image.attr('src');
- var splited = imgSource.split('-');
- splited[splited.length - 1] = color + '.svg';
- imgSource = splited.join('-');
- image.attr('src', imgSource);
- },
- hover: function (imgTag) {
- var image = $(imgTag);
- var imgSource = image.attr('src');
- var splited = imgSource.split('-');
- var last = splited[splited.length - 1];
- if (last == 'hover.svg') {
- splited[splited.length - 1] = '.svg';
- imgSource = splited.join('-').replace('-.', '.');
- } else {
- splited = imgSource.split('.');
- splited[splited.length - 1] = '-hover.svg';
- imgSource = splited.join('');
- }
- image.attr('src', imgSource);
- },
- white: function (imgTag) {
- this.color(imgTag, 'white');
- },
- blue: function (imgTag) {
- this.color(imgTag, 'blue');
- },
- gray: function (imgTag) {
- this.color(imgTag, 'gray');
- }
- },
- /* auto adjust textarea */
- autoTextArea: function () {
- var textArea = $('.textarea');
- textArea.each(function () {
- $(this).on('keyup', function () {
- $(this).height(0);
- $(this).height(this.scrollHeight);
- });
- $(this).keyup();
- });
- },
- sendPush: function () {
- modal.closeModal();
- navigateTo.app.push.notificationsSent();
- },
- schedulePush: function () {
- modal.closeModal();
- navigateTo.app.push.notificationsScheduled();
- },
- sendPushFail: function (message) {
- modal.closeModal(['modal-fail-push.php', undefined, {message: message}]);
- },
- saveAudienceFail: function () {
- modal.closeModal(['modal-fail-push.php']);
- },
- saveSecurityParameter: function () {
- modal.closeModal(['modal-fail-security-parameter.php']);
- },
- saveAutomationFail: function () {
- modal.closeModal(['modal-fail-automation.php']);
- },
- saveApiTemplateFail: function () {
- modal.closeModal(['modal-fail-api-template.php']);
- },
- saveCamp: function () {
- modal.closeModal(['success-saved.php', true, {
- obj: 'Campanha salva',
- navigate_method: 'navigateTo.app.push.campaigns();'
- }]);
- },
- saveCampFail: function () {
- modal.closeModal(['modal-failed.php', false, {obj: 'Campanha'}]);
- },
- saveSendCamp: function (campId) {
- $.ajax({
- url: '/getCampaign',
- type: "POST",
- data: {'campId': campId, 'action': 'send'},
- success: function (data) {
- contentContainer.html(data);
- modal.closeModal();
- // modal.getModal('success-saved.php', true, {obj: 'Campanha', justShow: true});
- },
- fail: function (data) {
- alert(data);
- }
- });
- },
- sendSaveCampFail: function () {
- this.sendPushFail();
- },
- saveAudience: function () {
- modal.closeModal(['success-saved.php', true, {
- obj: 'Audiência salva',
- navigate_method: 'navigateTo.app.audience.audiences();'
- }]);
- },
- saveAutomation: function () {
- modal.closeModal(['success-saved.php', true, {
- obj: 'Automação salva',
- navigate_method: 'navigateTo.app.push.automations();'
- }]);
- },
- saveApiTemplate: function () {
- modal.closeModal(['success-saved.php', true, {
- obj: 'API Template salva',
- navigate_method: 'navigateTo.app.push.apiTemplate();'
- }]);
- },
- inactivateAudience: function () {
- modal.closeModal();
- // update page values
- // lastRegister
- var lastRegister = $('#lastRegister');
- var lastItemValue = lastRegister.html();
- lastRegister.html(lastItemValue - 1);
- // totalRegsiter
- var totalRegisters = $('#totalRegisters');
- var totalRegistersValue = totalRegisters.html();
- totalRegisters.html(totalRegistersValue - 1);
- },
- tagTemplateSelection: function () {
- function insertText(context, open, close) {
- var aim = context.parent('div').attr('data-box');
- console.log(aim);
- var emojiDiv = $('.emoji-wysiwyg-editor').eq(aim);
- var tag = context.children('span').html();
- emojiDiv.html(emojiDiv.html() + open + tag + close);
- emojiDiv.trigger('keyup');
- $('#tagTemplateMenu').fadeOut('fast');
- }
- $('#tagTemplateMenu').on('click', '.js-customField', function () {
- insertText($(this), '|*', '*|');
- }).on('click', '.js-tagField', function () {
- insertText($(this), '{{', '}}');
- });
- },
- /* Insert new row to add data
- *
- * @param context String selector which is the context of the list (maxRows will be used there)
- * @param maxRows number max number of rows
- * */
- listData: {
- add: function (context, maxRows) {
- if (context == undefined) {
- context = $('body');
- } else {
- context = $(context);
- }
- if (maxRows === undefined) {
- maxRows = Number.POSITIVE_INFINITY;
- }
- context.find('.addNewData').hover(function () {
- $(this).css({fontWeight: '400'});
- behaviors.svgChangeTo.hover($(this).children('img'));
- }, function () {
- $(this).attr('style', '');
- behaviors.svgChangeTo.hover($(this).children('img'));
- }).on("click", function () {
- var context = $(this).parents('.control-panel');
- if (context.find('.js-dataRow').length < maxRows) {
- var $template = context.find('.js-dataTemplate');
- // var $clone = $template
- $template.clone()
- .removeClass('hide')
- .removeClass('js-dataTemplate')
- .addClass('js-dataRow')
- .insertBefore($template);
- // var amountData = $('.template').length - 1;
- var amountData = context.find('.js-dataRow').length;
- // if more than 1, show del to all
- // if (amountData != 1) {
- // context.find(".js-removeData").removeClass('hide');
- // }
- // Update the name attributes
- // $clone
- // .find('[name="' + sectionName + '-key"]').attr('name', 'data[' + amountData + '].' + sectionName + '-key').end()
- // .find('[name="' + sectionName + '-value"]').attr('name', 'data[' + amountData + '].' + sectionName + '-value').end();
- //add click atribute
- // behaviors.listData.remove(maxRows);
- if (amountData == maxRows) {
- context.find(".addData").addClass('hide');
- }
- }
- });
- context.on('hover', '.js-removeData', function () {
- behaviors.svgChangeTo.hover($(this).children('img'));
- }, function () {
- behaviors.svgChangeTo.hover($(this).children('img'));
- }).on("click", '.js-removeData', function () {
- var context = $(this).parents('.control-panel');
- // Remove element containing the fields
- $(this).parents('.control-panel-row').remove();
- // Count lines
- var amountData = context.find('.js-dataRow').length;
- if (amountData < maxRows) {
- $(".addData").removeClass('hide');
- // if (amountData == 1) {
- // context.find(".js-removeData").addClass('hide');
- // }
- } else {
- $(".addData").addClass('hide');
- }
- });
- },
- populate: function (contextId, object) {
- var context = $(contextId);
- var addButton = context.find('.addNewData');
- $.each(object, function (key, obj) {
- addButton.trigger('click');
- var lastRow = context.find('.js-dataRow').last();
- if (obj === Object(obj)) {
- $.each(obj, function (key, value) {
- lastRow.find(key).val(value);
- })
- } else {
- lastRow.find('input').val(obj);
- }
- })
- }
- },
- togglePassword: function (context, id) {
- var elm = document.getElementById(id);
- if (elm.type == "password") {
- elm.type = "text";
- //$(context).removeClass("glyphicon-eye-open");
- $(context).addClass("blue-flat");
- } else if (elm.type == "text") {
- elm.type = "password";
- $(context).removeClass("blue-flat");
- //$(context).toggleClass("glyphicon-eye-close");
- }
- }
- };
- var action = {
- verifyBehavior: function (result, afterAction, message) {
- var behavior;
- if (result == 'success') {
- switch (afterAction) {
- case 'justSend':
- behavior = behaviors.sendPush();
- break;
- case 'scheduleSend':
- behavior = behaviors.schedulePush();
- break;
- case 'saveCamp':
- behavior = behaviors.saveCamp();
- break;
- case 'saveSendCamp':
- behavior = behaviors.saveSendCamp;
- break;
- case 'saveAudience':
- behavior = behaviors.saveAudience();
- break;
- case 'saveAutomation':
- behavior = behaviors.saveAutomation();
- break;
- case 'inactivateAudience':
- behavior = behaviors.inactivateAudience();
- break;
- case 'saveApiTemplate':
- behavior = behaviors.saveApiTemplate();
- break;
- default:
- break;
- }
- } else if (result == 'fail') {
- switch (afterAction) {
- case 'justSend':
- behavior = behaviors.sendPushFail(message);
- break;
- case 'saveCamp':
- behavior = behaviors.saveCampFail();
- break;
- case 'saveSendCamp':
- behavior = behaviors.sendSaveCampFail();
- break;
- case 'saveAudience':
- behavior = behaviors.saveAudienceFail();
- break;
- case 'saveAutomation':
- behavior = behaviors.saveAutomationFail();
- break;
- case 'saveApiTemplate':
- behavior = behaviors.saveApiTemplateFail();
- break;
- case 'saveSecurityParameter':
- behavior = behaviors.saveSecurityParameter();
- break;
- default:
- break;
- }
- }
- return behavior;
- },
- /* AJAX to send push (used in Send Push and Campaign)
- *
- * audiencesSelected array audiences in string ('audience1,audience2,audience3')
- * if private msg, audiencesSelected = 'false,identifier'
- * */
- sendPush: function (appId, appToken, afterAction, campId, audiencesSelected) {
- if (campId == null || campId == '') {
- campId = 0;
- }
- var pushContent = $('#pushContent');
- isScheduler = $('.js-check-showUpSend').is(':checked');
- if (!isScheduler) {
- modal.closeModal(); //don't put modal in closeModal because of undesired async behavior
- modal.getModal('modal-sending-push.php', true);
- } else {
- modal.closeModal();
- modal.getModal('modal-scheduling-push.php', true);
- }
- var pushMsgToPersist = pushContent.val();
- var msgContent = window.emojiPicker.colonToUnicode(pushMsgToPersist);
- var additionalData = scriptForPage.getAdditionalData();
- var flagAdditional = false;
- if (additionalData.length > 0)
- flagAdditional = true;
- var formData = {
- 'msgTitle': $('input[name=msg-title]').val(),
- 'msgContent': msgContent,
- 'appId': appId,
- 'appToken': appToken,
- 'action': 'doSendPush',
- 'flagSchedule': $('.js-check-showUpSend').is(':checked'),
- 'sendDate': $('input[name=sendDate]').val(),
- 'sendHour': $('select[name=sendHour]').val(),
- 'sendMinute': $('select[name=sendMinute]').val(),
- 'persistMsg': pushMsgToPersist,
- 'campId': campId,
- 'flagUrl': $('.js-check-showUpURL').is(':checked'),
- 'urlPush': $('input[name=open-url]').val(),
- 'imgPush': $('input[name=msg-image]').val(),
- 'flagAdditional': flagAdditional,
- 'additionalData': additionalData,
- 'audiences': audiencesSelected
- };
- var ajaxSend = $.ajax({
- type: 'POST',
- url: '/sendPushValidation',
- data: formData,
- dataType: 'json',
- encode: true,
- //timeout: 10000
- //timeout: 120000
- })
- .done(function (data) {
- console.log(data);
- if (data.errors == null) {
- if (campId == 0) {
- action.saveAdditionalData(0, data.message_control_id, 0);
- action.savePushAdresses('NULL', data.message_control_id, audiencesSelected);
- }
- while ($(".modal-container").length == 0) {
- // wait until previous modal is loaded, so it will be correctly closed on afterAction
- }
- action.verifyBehavior('success', afterAction);
- } else {
- action.verifyBehavior('fail', afterAction, data.message);
- }
- })
- .fail(function (data) {
- console.log(data);
- action.verifyBehavior('fail', afterAction);
- ajaxSend.abort();
- });
- },
- saveCampaign: function (appId, appToken, campId, afterAction) {
- var flDraft = 1; //rascunho
- if (afterAction == undefined || afterAction == 'saveSendCamp') { //if there is no afterAction (send Campaign), change to "active" campaign
- flDraft = 0; //enviado
- }
- var formData = {
- 'msgTitle': $('input[name=msg-title]').val(),
- 'msgBody': $('#pushContent').val(),
- 'appId': appId,
- 'campId': campId,
- 'campName': $('#componentName').val(),
- 'campDescription': $('#componentDescription').val(),
- 'campFlDraft': flDraft,
- 'campStatus': 0,
- // 'flagSchedule': $('.js-check-showUpSend').is(':checked'),
- // 'sendDate': $('input[name=sendDate]').val(),
- // 'sendHour': $('select[name=sendHour]').val(),
- // 'sendMinute': $('select[name=sendMinute]').val(),
- 'flagUrl': $('.js-check-showUpURL').is(':checked'),
- 'urlPush': $('input[name=open-url]').val(),
- 'imgPush': $('input[name=msg-image]').val()
- };
- var ajaxSave = $.ajax({
- type: 'POST',
- url: '/handleCampaign',
- data: formData,
- timeout: 10000
- })
- .done(function (data) {
- var campId = data;
- console.log('done');
- action.saveAdditionalData(campId, 0, 0, '');
- var goToSendCamp = action.verifyBehavior('success', afterAction);
- if (afterAction == 'saveSendCamp')
- goToSendCamp(campId);
- })
- .fail(function () {
- console.log('fail');
- action.verifyBehavior('fail', afterAction);
- }).error(function () {
- action.verifyBehavior('fail', afterAction);
- ajaxSave.abort();
- });
- },
- saveAdditionalData: function (campaignId, controlMessageId, automationId, afterAction, apiTemplateId) {
- function getAdditionalData() {
- var elements = $('#additionalBlock').find('.js-dataRow');
- var dict = [];
- $.each(elements, function (num, obj) {
- var key = $(obj).find('input[name="additional-key"]').val();
- var value = $(obj).find('input[name="additional-value"]').val();
- if ((key !== '') && (value !== '')) {
- dict.push({key: key, value: value});
- }
- });
- return dict;
- }
- var additionalData = getAdditionalData();
- var flagAdditional = false;
- if (additionalData.length > 0)
- flagAdditional = true;
- var formData = {
- 'controlMessageId': controlMessageId,
- 'campaignId': campaignId,
- 'automationId': automationId,
- 'flagAdditional': flagAdditional,
- 'additionalData': additionalData,
- 'apiTemplateId': apiTemplateId
- };
- var ajaxSave = $.ajax({
- type: 'POST',
- url: '/handleAdditional',
- data: formData,
- timeout: 10000
- })
- .done(function () {
- if (afterAction != undefined && afterAction != '') {
- action.verifyBehavior('success', afterAction);
- }
- })
- .fail(function (data) {
- console.log('fail');
- console.log(data);
- // action.verifyBehavior('fail', afterAction);
- ajaxSave.abort();
- // }).error(function () {
- // action.verifyBehavior('fail', afterAction);
- // ajaxSave.abort();
- });
- },
- savePushAdresses: function (campId, controlMessageId, audiencesSelected) {
- var formData = {'audiences': audiencesSelected, 'controlMessageId': controlMessageId, 'campaignId': campId};
- var ajaxSave = $.ajax({
- type: 'POST',
- url: '/handlePushAdresses',
- data: formData,
- timeout: 10000
- })
- .done(function (data) {
- console.log(data);
- console.log('done');
- })
- .fail(function (data) {
- console.log('fail');
- console.log(data);
- ajaxSave.abort();
- });
- },
- saveAudience: function (audienceId, appId, showModalSuccess) {
- var criteria = scriptForPage.getAudienceCriteria();
- var recentAudience = 0;
- var formData = {
- 'appId': appId,
- 'audienceId': audienceId,
- 'audienceName': $("#componentName").val(),
- 'audienceDescription': $("#componentDescription").val(),
- 'criteria': criteria
- };
- var ajaxSave = $.ajax({
- type: 'POST',
- url: '/handleAudience',
- data: formData,
- async: false,
- timeout: 10000
- })
- .done(function (data) {
- console.log(data);
- console.log('done');
- if (showModalSuccess) {
- action.verifyBehavior('success', 'saveAudience');
- }
- recentAudience = data;
- })
- .fail(function (data) {
- console.log('fail');
- console.log(data);
- action.verifyBehavior('fail', 'saveAudience');
- ajaxSave.abort();
- });
- return recentAudience;
- },
- saveParameterBlockLogin: function (customerId) {
- var formData = {
- 'customerId': customerId,
- 'maxNumberRetries': $("#openInputQuantity").val(),
- 'action': 'saveParameterBlockLogin'
- };
- var ajaxSave = $.ajax({
- type: 'POST',
- url: '/handleSecurityParameter',
- data: formData,
- async: false,
- timeout: 10000
- })
- .done(function (data) {
- console.log('done');
- })
- .fail(function (data) {
- console.log('fail');
- console.log(data);
- action.verifyBehavior('fail', 'saveSecurityParameter');
- ajaxSave.abort();
- });
- },
- saveParameterChangePassword: function (customerId) {
- var formData = {
- 'customerId': customerId,
- 'changePassword': $('.js-check-showUpChangePassword').is(':checked'),
- 'action': 'saveParameterChangePassword'
- };
- var ajaxSave = $.ajax({
- type: 'POST',
- url: '/handleSecurityParameter',
- data: formData,
- async: false,
- timeout: 10000
- })
- .done(function (data) {
- console.log('done');
- })
- .fail(function (data) {
- console.log('fail');
- console.log(data);
- action.verifyBehavior('fail', 'saveSecurityParameter');
- ajaxSave.abort();
- });
- },
- saveParameterStrengthPassword: function (customerId, strengthId) {
- console.log('saveParameterStrengthPassword');
- var formData = {
- 'customerId': customerId,
- 'passwordStrengthId': strengthId,
- 'action': 'saveParameterStrengthPassword'
- };
- var ajaxSave = $.ajax({
- type: 'POST',
- url: '/handleSecurityParameter',
- data: formData,
- async: false,
- timeout: 10000
- })
- .done(function (data) {
- console.log('done');
- })
- .fail(function (data) {
- console.log('fail');
- console.log(data);
- action.verifyBehavior('fail', 'saveSecurityParameter');
- ajaxSave.abort();
- });
- },
- saveParameterLoginScheduled: function (securityParameterId, selectedDays) {
- var formData = {
- 'securityParameterId': securityParameterId,
- 'selectedDays': '"' + selectedDays.toString() + '"',
- 'timeInit': $("#timeIntervalRange").slider("values", 0),
- 'timeEnd': $("#timeIntervalRange").slider("values", 1),
- 'action': 'saveParameterLoginScheduled'
- };
- var ajaxSave = $.ajax({
- type: 'POST',
- url: '/handleSecurityParameter',
- data: formData,
- async: false,
- timeout: 10000
- })
- .done(function (data) {
- console.log('done');
- })
- .fail(function (data) {
- console.log('fail');
- console.log(data);
- action.verifyBehavior('fail', 'saveSecurityParameter');
- ajaxSave.abort();
- });
- },
- saveCollaborator: function (customerId, userName) {
- if ($('#addNewEmail').val() !== '') {
- var formData = {
- 'customerId': customerId,
- 'email': $('#addNewEmail').val(),
- 'profileId': $('#addNewSelect').val(),
- 'action': 'saveCollaborator'
- };
- var ajaxSave = $.ajax({
- type: 'POST',
- url: '/handleCollaborator',
- data: formData,
- async: false,
- timeout: 10000
- })
- .done(function (data) {
- var json = $.parseJSON(data);
- if (json.success == true) {
- //send invitation
- action.sendInvitationCollaborator(userName);
- } else {
- action.verifyBehavior('fail', 'saveSecurityParameter');
- }
- })
- .fail(function (data) {
- console.log('fail');
- console.log(data);
- action.verifyBehavior('fail', 'saveSecurityParameter');
- ajaxSave.abort();
- });
- }
- },
- sendInvitationCollaborator: function (userName) {
- var formData = {
- 'email': $('#addNewEmail').val(),
- 'userName': userName,
- 'action': 'sendInvite'
- };
- var ajaxSave = $.ajax({
- type: 'POST',
- url: '/handleCollaborator',
- data: formData,
- async: false,
- timeout: 10000
- })
- .done(function (data) {
- //console.log('done');
- })
- .fail(function (data) {
- console.log('fail');
- console.log(data);
- action.verifyBehavior('fail', 'saveSecurityParameter');
- ajaxSave.abort();
- });
- },
- saveApiTemplate: function (apiTemplateId, appId) {
- if ($('.js-check-showUpURL').is(':checked')) {
- var url = $('input[name=open-url]').val();
- } else {
- url = '';
- }
- function getTags() {
- var elements = $('.js-dataRow');
- var tags = [];
- $.each(elements, function (num, obj) {
- var tag = $(obj).find('input[name="tag-value"]').val();
- if (tag !== '') {
- tags.push(tag);
- }
- });
- if (tags != null && tags != '') {
- return tags;
- } else {
- return '';
- }
- }
- // var additionalData = scriptForPage.getAdditionalData();
- var formData = {
- 'apiTemplateId': apiTemplateId,
- 'apiTemplateName': $("#componentName").val(),
- 'apiTemplateDescription': $("#componentDescription").val(),
- 'msgTitle': $('input[name=msg-title]').val(),
- 'msgBody': $('#pushContent').val(),
- 'urlPush': url,
- 'appId': appId,
- 'tags': getTags()
- };
- var ajaxSave = $.ajax({
- type: 'POST',
- url: '/handleApiTemplate',
- data: formData,
- timeout: 10000
- })
- .done(function (data) {
- console.log('done');
- console.log(data);
- var json = $.parseJSON(data);
- if (json.success == true) {
- action.saveAdditionalData('', '', '', 'saveApiTemplate', json.apiId);
- // action.verifyBehavior('success', 'saveApiTemplate');
- } else {
- console.log(data.error);
- // action.verifyBehavior('fail', 'saveApiTemplate');
- }
- })
- .fail(function (data) {
- console.log('fail');
- console.log(data);
- action.verifyBehavior('fail', 'saveApiTemplate');
- ajaxSave.abort();
- });
- },
- findReachAudience: function (appId) {
- var criteria = scriptForPage.getAudienceCriteria();
- if (criteria.length > 0) {
- $.ajax({
- type: 'POST',
- url: '/handleRangeAudience',
- data: {'criteria': criteria, 'appId': appId},
- dataType: 'json',
- encode: true
- })
- .done(function (data) {
- if (data.success) {
- /*console.log('query:');
- console.log(data.query);*/
- console.log(data);
- $("#rangeNumber").text(data.result);
- }
- })
- .fail(function () {
- console.log('fail');
- });
- }
- },
- inactivateAudience: function (audienceId) {
- var formData = {
- 'audienceId': audienceId
- };
- var ajaxSave = $.ajax({
- type: 'POST',
- url: '/handleInactivateAudience',
- data: formData,
- dataType: 'json',
- encode: true,
- timeout: 10000
- })
- .done(function (data) {
- console.log(data);
- console.log('done');
- action.verifyBehavior('success', 'inactivateAudience');
- })
- .fail(function (data) {
- console.log('fail');
- console.log(data);
- action.verifyBehavior('fail', 'saveAudience');
- }).error(function () {
- console.log('error');
- action.verifyBehavior('fail', 'saveAudience');
- ajaxSave.abort();
- });
- },
- getSubscribersAudience: function (audiencesSelected) {
- var data = {'audiencesSelected': audiencesSelected};
- // if(data.findIndex())
- console.log(data);
- var ajaxSend = $.ajax({
- type: 'POST',
- url: '/handleSubscribersAudience',
- data: data,
- dataType: 'json',
- encode: true,
- timeout: 10000
- })
- .done(function (data) {
- var qtyLocalFormat = parseInt(data.quantitySubscribers).toLocaleString(locale);
- $('.range-full-number').html(qtyLocalFormat);
- $('#qtRecipients').html(qtyLocalFormat);
- })
- .fail(function (data) {
- // show any errors
- // best to remove for production
- console.log('fail');
- console.log(data);
- $('.range-full-number').html('-');
- $('#qtRecipients').html('-');
- ajaxSend.abort();
- });
- },
- saveAutomation: function (appId, campId, automationId, audiencesSelected, timeInit, timeEnd, selectedDays) {
- var statusId = 1; //ativo
- var formData = {
- 'automationId': automationId,
- 'campId': campId,
- 'name': $('#componentName').val(),
- 'description': $('#componentDescription').val(),
- 'statusId': statusId,
- 'appId': appId,
- 'action': 'saveAutomation'
- };
- var ajaxSave = $.ajax({
- type: 'POST',
- url: '/handleAutomation',
- data: formData,
- timeout: 10000
- })
- .done(function (data) {
- var objJson = $.parseJSON(data);
- if (objJson.success) {
- action.saveAutomationAudience(objJson.automation_id, audiencesSelected, timeInit, timeEnd, selectedDays);
- } else {
- action.verifyBehavior('fail', 'saveAutomation');
- }
- })
- .fail(function () {
- console.log('fail');
- action.verifyBehavior('fail', 'saveAutomation');
- }).error(function () {
- action.verifyBehavior('fail', 'saveAutomation');
- ajaxSave.abort();
- });
- },
- saveAutomationScheduled: function (automationId, timeInit, timeEnd, selectedDays) {
- var formData = {
- 'automationId': automationId,
- 'selectedDays': selectedDays,
- 'timeInit': timeInit,
- 'timeEnd': timeEnd,
- 'action': 'automationScheduled'
- };
- var ajaxSave = $.ajax({
- type: 'POST',
- url: '/handleAutomation',
- data: formData,
- timeout: 10000
- })
- .done(function (data) {
- var objJson = $.parseJSON(data);
- if (objJson.success) {
- action.saveAdditionalData(0, 0, automationId, 'saveAutomation');
- }
- })
- .fail(function () {
- console.log('fail');
- action.verifyBehavior('fail', 'saveAutomation');
- }).error(function () {
- action.verifyBehavior('fail', 'saveAutomation');
- ajaxSave.abort();
- });
- },
- saveAutomationAudience: function (automationId, audiencesSelected, timeInit, timeEnd, selectedDays) {
- if (parseInt(audiencesSelected) > 0) {
- var formData = {
- 'audiences': audiencesSelected,
- 'automationId': automationId,
- 'action': 'automationAudience'
- };
- var ajaxSave = $.ajax({
- type: 'POST',
- url: '/handleAutomation',
- data: formData,
- timeout: 10000
- })
- .done(function (data) {
- var objJson = $.parseJSON(data);
- if (objJson.success) {
- action.saveAutomationCriteria(automationId, timeInit, timeEnd, selectedDays);
- } else {
- action.verifyBehavior('fail', 'saveAutomation');
- }
- })
- .fail(function (data) {
- console.log('fail');
- console.log(data);
- action.verifyBehavior('fail', 'saveAutomation');
- ajaxSave.abort();
- });
- } else {
- action.saveAutomationCriteria(automationId, timeInit, timeEnd, selectedDays);
- }
- },
- saveAutomationCriteria: function (automationId, timeInit, timeEnd, selectedDays) {
- var criteria = scriptForPage.getAudienceCriteria();
- if (criteria.length > 0) {
- var formData = {
- 'automationId': automationId,
- 'criteria': criteria,
- 'action': 'pushCriteria'
- };
- $.ajax({
- type: 'POST',
- url: '/handleAutomation',
- data: formData,
- timeout: 10000
- })
- .done(function (data) {
- console.log(data);
- var objJson = $.parseJSON(data);
- if (objJson.success) {
- action.saveAutomationScheduled(automationId, timeInit, timeEnd, selectedDays);
- } else {
- action.verifyBehavior('fail', 'saveAutomation');
- }
- })
- .fail(function () {
- console.log('fail');
- action.verifyBehavior('fail', 'saveAutomation');
- });
- } else {
- action.saveAutomationScheduled(automationId, timeInit, timeEnd, selectedDays);
- }
- },
- /*
- * This method paginate the page
- *
- * @param string container Where the retrieved data should be put
- * @param string target What is the target URL
- * @param string rowNumber
- * @param JSON data parameters to send with GET
- *
- * return AJAX fill the container with retrieved data
- *
- * */
- paginate: function (container, target, rowNumber) {
- var viewsPerPage = $("#viewsPerPage").val();
- if (viewsPerPage == undefined || viewsPerPage == '') {
- viewsPerPage = 15;
- }
- var params = 'viewsPerPage=' + viewsPerPage + '&rowNumber=' + rowNumber;
- // look for params in the url, if there is params just insert the page params, else create new params field
- if (target.search('/?') == -1) {
- params = '?' + params;
- } else {
- params = '&' + params;
- }
- var targetURL = '/' + target + params;
- window.scrollTo(0, 0);
- $(container).load(targetURL).hide().fadeIn('300');
- console.log(targetURL);
- console.log(params);
- },
- download: function (text, name, type) {
- var a = document.createElement("a");
- if (type == 'csv') {
- var file = new Blob([text], {type: 'text/plain'});
- a.href = URL.createObjectURL(file);
- } else if (type == 'xls') {
- a.href = text;
- }
- a.download = name;
- a.click();
- a.remove();
- }
- };
- var transform = {
- /* Get all checkbox inputs with class '.js-switch' and put their design like iOS7 */
- iOSswitch: function () {
- var checkboxes = Array.prototype.slice.call(document.querySelectorAll('.js-switch'));
- checkboxes.forEach(function (html) {
- var switchery = new Switchery(html, {size: 'small', secondaryColor: '#DFDFDF'});
- });
- },
- /* Style the select element
- * This is used to personalize the select element of sign up page
- *
- * Have to add this on the page (Theter and Select):
- * <link rel="stylesheet" href="select-theme-default.css" />
- * <script src="tether.min.js"></script>
- * <script src="select.min.js"></script>
- *
- * Then use this code here to use a placeholder and style the element.
- *
- * selectID must be just an ID NAME
- *
- * More info: http://github.hubspot.com/select/docs/welcome/
- */
- customSelect: function (selectID) {
- if (selectID.charAt(0) == '#' || selectID.charAt(0) == '.') {
- selectID = selectID.substr(1);
- }
- var element = document.getElementById(selectID);
- var select = new Select({
- el: element,
- className: 'select-theme-inngage'
- });
- function addOptGroup() {
- var optgroup = $(element).find('optgroup');
- $.each(optgroup, function (index, obj) {
- var optgroupLabel = $(obj).attr('label');
- var addElement = '<div class="custom-optgroup">' + optgroupLabel + '</div>';
- var nextElemValue = ($(obj).children().first()).val();
- var searchOption = 'li[data-value=' + nextElemValue + ']';
- $(select.drop).find(searchOption).before(addElement);
- });
- }
- addOptGroup();
- select.on('change', function () {
- addOptGroup();
- });
- return select;
- },
- emojiPicker: function () {
- // Initializes and creates emoji set from sprite sheet
- window.emojiPicker = new EmojiPicker({
- emojiable_selector: '[data-emojiable=true]',
- assetsPath: ref.getPlugins + '/emoji-area/img/',
- popupButtonClasses: 'fa fa-smile-o',
- iconSize: 19,
- norealTime: false
- });
- // Finds all elements with `emojiable_selector` and converts them to rich emoji input fields
- // You may want to delay this step if you have dynamically created input fields that appear later in the loading process
- // It can be called as many times as necessary; previously converted input fields will not be converted again
- window.emojiPicker.discover();
- },
- counter: function (decimal) {
- $('.js-count').each(function () {
- $(this).stop();
- var value = $(this).text();
- $(this).prop('Counter', 0).animate({
- Counter: $(this).text()
- }, {
- duration: 1000,
- easing: 'easeOutQuart',
- step: function (now) {
- $(this).text(now.toLocaleString(locale, {maximumFractionDigits: decimal}));
- },
- complete: function () {
- $(this).text(value);
- transform.breakThousandsId([$(this)]);
- }
- });
- });
- },
- /* Convert a message with emoji in Unicode format to rich text
- *
- * @param obj Object which has the message, may be json, string...
- * @param selector Where to insert the new message with images
- * @param countIndex boolean True if the obj is a json or array and must use the index to identify the selector
- * */
- unicodeToEmoji: function (obj, selector, countIndex) {
- // transform.emojiPicker();
- window.emojiPicker.discover();
- if (countIndex == true) {
- $.each(obj, function (index, elem) {
- $(selector + index).html(window.emojiPicker.unicodeToImage(elem));
- // console.log(elem);
- });
- } else {
- $(selector).html(window.emojiPicker.unicodeToImage(obj));
- }
- },
- /*
- * @param boolean countIndex If the obj has to be count with an "index" increment
- * */
- colonToEmoji: function (obj, selector, countIndex) {
- transform.emojiPicker();
- window.emojiPicker.discover();
- if (countIndex == true) {
- $.each(obj, function (index, elem) {
- $(selector + index).html(window.emojiPicker.colonToImage(elem));
- });
- } else {
- $(selector).html(window.emojiPicker.colonToImage(obj));
- }
- },
- highlightAppMenu: function () {
- var path = (window.location.pathname).substr(1);
- var dirs = path.split('/');
- $.each(dirs, function (index, val) {
- var name = val.split('-');
- for (var i = 1; i < name.length; i++) {
- var firstLetter = name[i].substring(0, 1);
- name[i] = name[i].replace(firstLetter, firstLetter.toUpperCase());
- }
- dirs[index] = name.join('');
- });
- var pageGroup = '#' + dirs[1];
- var page = '#' + dirs[2];
- $(pageGroup).addClass('nav-side-title-selected');
- if (page) {
- var obj = $(page);
- obj.addClass('nav-side-item-selected');
- }
- },
- highlightSubMenu: function (menuItem) {
- $(menuItem).addClass('nav-side-item-selected');
- },
- /* API to work with tawk.to */
- tawkChat: function () {
- function tawkChatAPI() {
- var Tawk_API = Tawk_API || {}, Tawk_LoadStart = new Date();
- (function () {
- var s1 = document.createElement("script"), s0 = document.getElementsByTagName("script")[0];
- s1.async = true;
- s1.src = 'https://embed.tawk.to/5782b19274888c1b4a85ea3e/default';
- s1.charset = 'UTF-8';
- s1.setAttribute('crossorigin', '*');
- s0.parentNode.insertBefore(s1, s0);
- })();
- }
- tawkChatAPI.call(window);
- },
- /*
- * Separate thousands
- *
- * @param array identificators array of any kind of selector as string
- * @return null
- * */
- breakThousandsId: function (identificators) {
- $.each(identificators, function (key, obj) {
- var number = Number($(obj).html());
- $(obj).html(number.toLocaleString(locale));
- });
- }
- };
- var modal = {
- scrollPosition: 0,
- /* Close block if ESC is pressed */
- typeKeyboardBehavior: function () {
- $(document).on('keyup.keyBlock', function (e) {
- e.stopPropagation();
- if (e.keyCode == 27) {
- modal.closeModal();
- }
- if (e.keyCode == 13) {
- e.preventDefault();
- $('.modal button[type=submit]').first().trigger('click');
- }
- });
- },
- getGrayCover: function () {
- var grayCover = "<div class='gray-cover'></div>";
- $(".modal-container").prepend(grayCover);
- $("body").children("*:not(.gray-cover, .modal-container, .emoji-menu, .tether-element)").addClass("blur");
- $("body,html").css({overflow: "hidden"});
- window.scrollTo(0, 0);
- },
- /**
- * Closes all modals on screen
- * If you need to open another modal after the first is called, pass a object parameter with the data as:
- *
- * @param nextModal array Modal to be opened with options:
- * [file, noClose, data]
- * */
- closeModal: function (nextModal) {
- $('.modal-resource').remove();
- $('.emoji-menu').not(':eq(0)').remove();
- $("*").removeClass("blur");
- function getNextModal() {
- if (nextModal != undefined) {
- var opt = [];
- $.each(nextModal, function (key, value) {
- opt[key] = value;
- });
- modal.getModal(opt[0], opt[1], opt[2]);
- }
- }
- if ($(".modal-container").length != 0) {
- $(".modal-container").fadeOut(300, function () {
- $(window).scrollTop(modal.scrollPosition);
- $('.interferingStyleSheet').prop('disabled', false);
- $(this).remove();
- getNextModal();
- });
- } else {
- getNextModal();
- }
- $("body,html").css({overflow: "visible"});
- $(document).off('keyup.keyBlock');
- getData = window.previousGetData;
- },
- /**
- * Closes all modals on screen and back to previous page
- * */
- backPage: function () {
- modal.closeModal();
- history.back();
- },
- reposition: function () {
- $('.modal-container').css({top: $(window).scrollTop()});
- var block = $('.modal');
- var height = block.height();
- var winHeight = $(window).height();
- if (winHeight < height + 50) {
- var top = 59.5;
- grayHeight = (block.outerHeight(true) + top) + 'px';
- } else {
- top = (winHeight - height) / 2;
- var grayHeight = '100vh';
- }
- var topPixels = top + 'px';
- block.css({top: topPixels});
- $('.gray-cover').css({height: grayHeight});
- document.getElementsByClassName('modal-container')[0].scrollTop = 0;
- },
- modal: function () {
- this.typeKeyboardBehavior();
- this.getGrayCover();
- },
- /*
- * file to be opened
- * noClose boolean is it to be closed on out click or not?
- * data JSON any data to be passed to the block
- * */
- getModal: function (file, noClose, data) {
- console.log('inicio');
- modal.scrollPosition = $(window).scrollTop();
- // console.log(getData);
- if (typeof(getData) != "undefined") {
- window.previousGetData = getData;
- }
- $.post(ref.getIncludes + "/modal/" + file, data, function (code) {
- $(document).ready(function () {
- // code.replace('\<script', '\<script class="modal-resource"');
- // code.replace('<style', '<style class="modal-resource"');
- console.log('ready');
- $("body").prepend(code);
- modal.modal();
- $('.modal').find('button:only-of-type').focus();
- $('.modal').find('input').focus();
- modal.reposition();
- // reposition modal when screen is resized
- $(window).on('resize', function () {
- modal.reposition();
- });
- // the modal is not to be closed by the user (ex: LOADING EVENT)
- if (noClose) {
- $(document).off('keyup.keyBlock');
- } else {
- $('.gray-cover').on('click', function () {
- modal.closeModal();
- });
- }
- /* observe for node manipulation in the modal to resize it if needed */
- var modalObserver = new MutationObserver(function () {
- modal.reposition();
- });
- modalObserver.observe(document.getElementsByClassName('modal')[0], {childList: true, subtree: true});
- // so it don't close when clicked (don't trigger .block-container)
- // $('.modal').on('click', function (e) {
- // console.log(e);
- // e.stopPropagation();
- // });
- });
- });
- }
- };
- var balloon = {
- //close balloon. Pass the balloon ID to close
- closeBalloon: function (id) {
- $(id).hide();
- }
- };
- /* OPEN CONTENTS
- * Procedures to navigate through pages
- * For the window.popstate to work properly, keep the object names the same as the corresponding folders
- * */
- var navigateTo = {
- //MAIN - MY APPS
- myApps: function () {
- window.open('/main-dashboard', '_self');
- },
- // APP PAGE: Run this before opening an item in menu-side
- procedure: function (title, path, item, callback) {
- appHeader.hide();
- $('.select-theme-inngage').remove(); // clean all select DIV created
- $('.modal-resource').remove(); // clean all modal resources (script and style tags)
- $('.js-clean-resource').remove(); // clean all resources not used (script and style tags)
- $('.tether-element').remove(); // clean all resources from TETHER plugin
- $('.select-theme-inngage').remove(); // clean all resources from SELECT plugin
- // $('.emoji-menu').not(':eq(0)').remove(); // clean all emoji menus created
- $('.emoji-menu').remove(); // clean all emoji menus created
- $('.ui-datepicker').remove(); // clean all datepickers
- $('.nav-side-title-selected').removeClass('nav-side-title-selected');
- $('.nav-side-item-selected').removeClass('nav-side-item-selected');
- $(title).addClass('nav-side-title-selected');
- if (item) {
- var obj = $(item);
- obj.addClass('nav-side-item-selected');
- }
- var appToken = window.location.search;
- if (history.state) {
- if (history.state['inn'] != path) {
- history.pushState({'inn': path}, '', '/app' + path + appToken);
- }
- } else {
- history.pushState({'inn': path}, '', '/app' + path + appToken);
- }
- contentContainer.load(ref.getAppPg + path, function () {
- window.scrollTo(0, 0); //if page was scrolled down, then go back to top
- if (callback != undefined && callback != '') {
- callback();
- }
- });
- },
- app: {
- //APP-DASHBOARD
- dashboard: function () {
- navigateTo.procedure('#dashboard', '/dashboard');
- contentContainer.empty();
- appHeader.load(ref.getIncludes + '/app-pg/dashboard/app-header.php').show();
- },
- audience: {
- title: '#audience',
- audiences: function () {
- navigateTo.procedure(this.title, "/audience/audiences", "#audiences");
- },
- newAudience: function () {
- navigateTo.procedure(this.title, "/audience/new-audience", "#audiences");
- },
- subscribers: function () {
- navigateTo.procedure(this.title, "/audience/subscribers", "#subscribers");
- },
- importData: function () {
- navigateTo.procedure(this.title, "/audience/import-data");
- }
- },
- push: {
- title: '#push',
- campaigns: function () {
- navigateTo.procedure(this.title, "/push/campaigns", '#campaigns');
- },
- newCampaign: function () {
- navigateTo.procedure(this.title, "/push/new-campaign", '#campaigns');
- },
- sendPush: function () {
- navigateTo.procedure(this.title, "/push/send-push", '#sendPush');
- },
- notificationsSent: function () {
- navigateTo.procedure(this.title, "/push/notifications-sent", '#sendPush');
- },
- notificationsScheduled: function () {
- navigateTo.procedure(this.title, "/push/notification-scheduled", '#sendPush');
- },
- directMail: function () {
- navigateTo.procedure(this.title, "/push/direct-mail");
- },
- automations: function () {
- navigateTo.procedure(this.title, "/push/automations", '#automations');
- },
- newAutomation: function () {
- navigateTo.procedure(this.title, "/push/new-automation", '#automations');
- },
- apiTemplate: function () {
- navigateTo.procedure(this.title, "/push/api-template", '#apiTemplate');
- },
- newApiTemplate: function () {
- navigateTo.procedure(this.title, "/push/new-api-template", '#apiTemplate');
- },
- },
- status: {
- title: '#status',
- sent: function () {
- navigateTo.procedure(this.title, "/status/sent", '#sent');
- },
- scheduled: function () {
- navigateTo.procedure(this.title, "/status/scheduled", '#scheduled');
- },
- sentApi: function () {
- navigateTo.procedure(this.title, "/status/sent-api");
- },
- autosent: function () {
- navigateTo.procedure(this.title, "/status/autosent", '#autosent');
- }
- },
- configuration: {
- title: '#configuration',
- general: function () {
- navigateTo.procedure(this.title, "/configuration/general", '#general');
- },
- platform: function () {
- navigateTo.procedure(this.title, "/configuration/platform", "#platform");
- },
- fontCode: function () {
- // navigateTo.procedure(this.title, "/configuration/(UNUSED) font-code", '#fontCode');
- window.open('https://inngage.readme.io/');
- },
- team: function () {
- navigateTo.procedure(this.title, "/configuration/team", '#team');
- }
- }
- },
- appPopState: function () {
- var path = (window.location.pathname).substr(1);
- var dirs = path.split('/');
- $.each(dirs, function (index, val) {
- var name = val.split('-');
- for (var i = 1; i < name.length; i++) {
- var firstLetter = name[i].substring(0, 1);
- name[i] = name[i].replace(firstLetter, firstLetter.toUpperCase());
- }
- dirs[index] = name.join('');
- });
- var pageGroup = dirs[1];
- var page = dirs[2];
- if (page) {
- window['navigateTo']['app'][pageGroup][page]();
- } else {
- window['navigateTo']['app'][pageGroup]();
- }
- }
- };
- /* Start immediately */
- $(document).ready(function () {
- behaviors.autoTextArea();
- });
- var scriptForPage = {
- showConditionField: function (rowId, varType) {
- $(rowId).find('.js-condition').hide();
- $(rowId).find('.js-' + varType + '-condition').css({display: 'inline-block'});
- },
- newAudience: function (audienceId, audienceJson, criteriaJson, appId, insertEventsFooter) {
- var num = 0;
- var conditionNumber = 0;
- function insertNewCondition(context) {
- var thisNum = num;
- conditionNumber++;
- num++; //increment the number of conditions
- var clone = $(context.find('#jsNewConditionRow')).clone();
- // PREPARE THE CLONED ELEMENT
- var rowId = 'jsConditionRow' + thisNum;
- clone.attr('id', rowId).removeClass('js-new-condition-row').addClass('js-condition-row');
- clone.find('#removeCondition').attr('id', 'removeCondition' + thisNum);
- $.each($(clone.find('.js-select')), function (index, elem) {
- $(elem).attr('id', 'select' + thisNum + index);
- });
- $.each($(clone.find('input[name=val]')), function (index, elem) {
- $(elem).attr('id', 'val' + thisNum + index);
- });
- clone.find('.element-counter').text(conditionNumber);
- clone.find('.true-false-tab').attr('id', 'trueFalse' + thisNum);
- $.each($(clone.find('.date')), function (index, elem) {
- $(elem).attr('id', 'date' + thisNum + index);
- $(elem).datepicker({
- format: 'dd/mm/yyyy',
- language: locale,
- beforeShow: function (input, obj) {
- // $(input).after($(input).datepicker('widget'));
- // $(input).datepicker("refresh");
- $('.ui-datepicker').removeClass('blur');
- },
- onSelect: function (textData, objDatepicker) {
- action.findReachAudience(appId);
- }
- });
- });
- //INSERT THE PREPARED ELEMENT
- clone.insertBefore(context.find('.js-newCondition')); // use class because of the elements order in modal-new-audience
- //DEFINE BEHAVIORS
- $.each($('#' + rowId).find('.js-select'), function (index, elem) {
- transform.customSelect('select' + thisNum + index);
- $('#select' + thisNum + index).change(function () {
- $(this).next('a').css({color: 'inherit'});
- });
- });
- $('#select' + thisNum + 0).on('change', function () {
- var varType = $(this).find('option[value=' + $(this).val() + ']').attr('data-type');
- scriptForPage.showConditionField('#' + rowId, varType);
- action.findReachAudience(appId);
- });
- var tab = $("#trueFalse" + thisNum).tabs();
- // Set dateInput on change to refresh range
- var dateInput = $('#date' + thisNum + 0);
- dateInput.on('change', function () {
- action.findReachAudience(appId);
- });
- // Date behavior: hide or change the condition input field
- $('#select' + thisNum + 3).on('change', function () {
- var dateType = $(this).val();
- // show Datepicker
- if (dateType <= 13) {
- dateInput.datepicker({
- format: 'dd/mm/yyyy',
- language: locale,
- onSelect: function (textData, objDatepicker) {
- action.findReachAudience(appId);
- }
- });
- dateInput.parent().show(); // show the span with the input
- dateInput.attr('type', 'text').removeClass('days-input');
- $(dateInput.next('span')).css({'display': 'none'});
- // show int and span "Days"
- } else if (dateType <= 16) {
- dateInput.datepicker('destroy');
- dateInput.parent().show();
- dateInput.attr('type', 'number').attr('placeholder', 'Número de dias').addClass('days-input');
- $(dateInput.next('span')).css({'display': 'inline-block'});
- // don't show
- } else if (dateType == 17) {
- $(dateInput.parent()).css({'display': 'none'});
- dateInput.attr('type', 'text').val('today'); // hide the span with the input
- }
- });
- $('#removeCondition' + thisNum).hover(function () {
- behaviors.svgChangeTo.hover($(this).children('img'));
- }, function () {
- behaviors.svgChangeTo.hover($(this).children('img'));
- }).click(function () {
- $(this).parents('.filter-row').remove();
- $.each(context.find('.element-counter'), function (index, elem) {
- $(elem).html(index + 1);
- });
- conditionNumber--;
- if (conditionNumber == 1) {
- $('.remove-icon').fadeOut(200);
- }
- action.findReachAudience(appId);
- });
- // show remove-icon again
- if (conditionNumber > 1) {
- $('.remove-icon').fadeIn(100);
- }
- insertEventToFindReachAudience(appId);
- }
- insertNewCondition($('#addNewCondition').parents('.filter-panel')); // start with a condition row
- $('#addNewCondition').hover(function () {
- $('#plus').addClass('hover-green');
- $(this).css({fontWeight: '400'});
- behaviors.svgChangeTo.hover($(this).children('img'));
- }, function () {
- $('#plus').removeClass('hover-green');
- $(this).attr('style', '');
- behaviors.svgChangeTo.hover($(this).children('img'));
- }).click(function () {
- insertNewCondition($(this).parents('.filter-panel'));
- });
- function insertEventToFindReachAudience(appId) {
- var elements = $(".js-condition-row");
- for (var i = 0; i < elements.length; i++) {
- var row = "#" + elements[i].id;
- $(row).find('select[name=operator]').on('change', function () {
- action.findReachAudience(appId);
- });
- $(row).find('.ui-state-default').on('click', function () {
- action.findReachAudience(appId);
- });
- $(row).find('input[name=val]').on('change', function () {
- action.findReachAudience(appId);
- });
- }
- }
- populateAudience(audienceId, audienceJson, criteriaJson, appId);
- function populateAudience(audienceId, audienceJson, criteriaJson, appId) {
- if (audienceId > 0) {
- var audienceName = audienceJson['audience_name'];
- var audienceDescription = audienceJson['audience_description'];
- populateAudienceCriteria(criteriaJson);
- $('#componentName').val(audienceName);
- $('#componentDescription').val(audienceDescription);
- action.findReachAudience(appId);
- $('.page-title').html(audienceName);
- }
- }
- function populateAudienceCriteria(criteriaJson) {
- if (criteriaJson) {
- var i = 0;
- $.each(criteriaJson, function (index, value) {
- if ((i > 0) && (value !== null) && (value !== undefined)) {
- $("#addNewCondition").trigger("click");
- }
- var selectField = $("#select" + i + "0").attr('value', value.audience_criteria_id);
- selectField.val(value.audience_field_id);
- selectField.next('a').css({color: 'inherit'});
- var varType = selectField.find('option[value=' + selectField.val() + ']').attr('data-type');
- scriptForPage.showConditionField('#jsConditionRow' + i, varType);
- var objectTypeCondition = $('#jsConditionRow' + i).find('.js-' + varType + '-condition');
- if (varType == 'boolean') {
- objectTypeCondition.find('a[href="#' + value.audience_value + '"]').trigger('click');
- } else {
- objectTypeCondition.find('select[name=operator]').val(value.audience_field_condition_id);
- objectTypeCondition.find('select[name=operator]').attr('value', value.audience_field_condition_id);
- objectTypeCondition.find('select[name=operator]').next('a').css({color: 'inherit'});
- objectTypeCondition.find('input[name=val]').val(value.audience_value);
- }
- i++;
- });
- }
- }
- if (insertEventsFooter) {
- $('#footerSave').on('click', function () {
- if ((validate.field('#componentName', 'Qual o nome da sua audiência?')) && (validate.fieldsAudienceCriteria(true))) {
- action.saveAudience(audienceId, appId, true);
- }
- });
- $('#footerCancel').on('click', function () {
- navigateTo.app.audience.audiences();
- });
- }
- },
- dashboard: function () {
- $('#selectAudience').on('change', function () {
- getData();
- });
- function getData() {
- var selectedId = $('#selectAudience').val();
- var audienceId = selectedId.replace('audience', '');
- $.ajax({
- type: 'POST',
- url: '/handleReports',
- data: {audienceId: audienceId}
- }).done(function (data) {
- var json = JSON.parse(data);
- console.log(json);
- updateDataJson(json);
- refreshData();
- }).fail(function (data) {
- console.log(data);
- });
- }
- transform.customSelect('selectAudience');
- window.doughnutChart = charts.createDonutChart('#doughnutChart', 1);
- window.doughnutInfo = 'openedDoughnut'; // initial selected info-bot doughnut
- window.interval = 'week'; // initial selected interval
- function refreshData() {
- $('#' + window.interval).trigger('click');
- $('#' + window.doughnutInfo).trigger('click');
- updateBarChart();
- $(".number-bar-chart").html((window.dataJson.week.sentNum).toLocaleString());
- }
- charts.resizeChartDiv();
- transform.counter(0);
- $("#tabs").tabs();
- /* Render week line chart */
- function renderLineChart() {
- var color = "#2ecc71";
- var data = {
- labels: ['dummy'],
- datasets: [{
- fill: false,
- tension: 0,
- borderCapStyle: 'round',
- pointBackgroundColor: "#fff",
- pointBorderWidth: 3,
- pointHoverRadius: 3,
- pointHoverBorderWidth: 4,
- backgroundColor: color,
- borderColor: color,
- pointHoverBackgroundColor: color,
- pointHoverBorderColor: color,
- pointBorderColor: color,
- data: ["0"]
- }]
- };
- window.lineChart = new Chart($('#lineChart'), {
- type: 'line',
- data: data,
- options: {
- maintainAspectRatio: false,
- legend: {
- display: false
- },
- elements: {
- point: {
- radius: 4
- }
- },
- tooltips: {
- callbacks: {
- title: function (tooltipItem, data) {
- },
- label: function (tooltipItem, data) {
- return tooltipItem.yLabel;
- },
- footer: function (tooltipItem, data) {
- }
- }
- },
- scales: {
- yAxes: [{
- ticks: {
- min: 0,
- suggestedMax: 20
- }
- }]
- }
- }
- });
- }
- renderLineChart();
- function updateDataJson(json) {
- console.log(json);
- window.dataJson = json;
- }
- function updateDoughnutChart() {
- var interval = window.interval;
- var sent = window['dataJson'][interval]['sentNum'];
- var received = window['dataJson'][interval]['received'];
- var opened = window['dataJson'][interval]['openedNum'];
- function update(value) {
- $('#doughnutChartLabel').text(value);
- return [value, (100 - value)];
- }
- if (document.getElementById('doughnutChart').style.display == 'none' &&
- window.doughnutInfo != 'sentDoughnut') {
- $('#doughnutChartLabel').stop();
- $('.cuv-percent').fadeIn();
- $('.chart-background').fadeIn();
- $('#doughnutChart').fadeIn();
- }
- switch (window.doughnutInfo) {
- case 'sentDoughnut':
- $('.cuv-percent').hide();
- $('.chart-background').hide();
- $('#doughnutChart').hide();
- $('#doughnutChartLabel').text(sent);
- transform.counter(0);
- $('#doughnutChartTitle').text('Pushes Enviados');
- return;
- case 'receivedDoughnut':
- window.doughnutChart.data.datasets[0].data = update(received);
- transform.counter(0);
- $('#doughnutChartTitle').text('Pushes Recebidos');
- break;
- case 'openedDoughnut':
- window.doughnutChart.data.datasets[0].data = update(opened);
- transform.counter(0);
- $('#doughnutChartTitle').text('Pushes Abertos');
- break;
- }
- window.doughnutChart.update();
- }
- function updateLineChart() {
- var labels;
- var data;
- var sentNum;
- var received;
- var openedNum;
- function updateDoughnutBotInfo() {
- var interval = window.interval;
- var sent = window['dataJson'][interval]['sentNum'].toLocaleString();
- var received = window['dataJson'][interval]['received'];
- var opened = window['dataJson'][interval]['openedNum'];
- var doughnutBotInfo = $('.doughnut-bot-info');
- doughnutBotInfo.children('#sentDoughnut').children('.number').text(parseInt(sent).toLocaleString(locale));
- doughnutBotInfo.children('#receivedDoughnut').children('.number').text(received + '%');
- doughnutBotInfo.children('#openedDoughnut').children('.number').text(opened + '%');
- }
- function updateInterval(interval) {
- labels = window['dataJson'][interval]['labels'];
- console.log("Labels:");
- console.log(labels);
- data = window['dataJson'][interval]['sent'];
- console.log("Sent:");
- console.log(data);
- window.lineChart.data.labels = labels;
- window.lineChart.data.datasets[0].data = data;
- }
- updateInterval(window.interval);
- updateDoughnutChart();
- updateDoughnutBotInfo();
- // duas linhas no grafico
- /*
- var green = "#2ecc71";
- var blue = "#4ad1ed";
- case 'lineSent':
- // add new line
- if ($('#lineSent').prop('checked')) {
- var interval = $('.line-chart-interval').find('.chart-range-active').attr('id');
- var color = green;
- var dataset = {};
- dataset.fill = false;
- dataset.lineTension = 0.1;
- dataset.borderCapStyle = 'round';
- dataset.pointBackgroundColor = "#fff";
- dataset.pointBorderWidth = 3;
- dataset.pointHoverRadius = 3;
- dataset.pointHoverBorderWidth = 4;
- dataset.backgroundColor = color;
- dataset.borderColor = color;
- dataset.pointHoverBackgroundColor = color;
- dataset.pointHoverBorderColor = color;
- dataset.pointBorderColor = color;
- dataset.data = window['dataJson'][interval]['opened'];
- if (window.lineChart.data.datasets[0] == undefined) {
- window.lineChart.data.datasets[0] = dataset;
- } else {
- window.lineChart.data.datasets[1] = dataset;
- }
- } else {
- window.lineChart.data.datasets.splice(1);
- }
- break;
- case 'lineOpened':
- // add new line
- if ($('#lineOpened').prop('checked')) {
- var interval = $('.line-chart-interval').find('.chart-range-active').attr('id');
- var color = blue;
- var dataset = {};
- dataset.fill = false;
- dataset.lineTension = 0.1;
- dataset.borderCapStyle = 'round';
- dataset.pointBackgroundColor = "#fff";
- dataset.pointBorderWidth = 3;
- dataset.pointHoverRadius = 3;
- dataset.pointHoverBorderWidth = 4;
- dataset.backgroundColor = color;
- dataset.borderColor = color;
- dataset.pointHoverBackgroundColor = color;
- dataset.pointHoverBorderColor = color;
- dataset.pointBorderColor = color;
- dataset.data = window['dataJson'][interval]['opened'];
- if (window.lineChart.data.datasets[0] == undefined) {
- window.lineChart.data.datasets[0] = dataset;
- } else {
- window.lineChart.data.datasets[1] = dataset;
- }
- } else {
- window.lineChart.data.datasets.splice(1);
- }
- break; */
- window.lineChart.update();
- window.doughnutChart.update();
- }
- // select the interval of the chart
- $('.line-chart-interval').on('click', function (e) {
- // only trigger if a button is pressed
- if (e.target.className != 'line-chart-interval') {
- $($(this).children('.chart-range-item')).removeClass('chart-range-active');
- var interval = $(e.target).addClass('chart-range-active').attr('id');
- }
- window.interval = interval;
- updateLineChart(interval);
- });
- // select the filter to see the chart
- $('.js-line-label').on('change', function (e) {
- var intervalElem = $(e.target);
- var interval = intervalElem.attr('id');
- if ($(e.target).prop('checked')) {
- $('#' + interval + 'Label').show();
- } else {
- $('#' + interval + 'Label').hide();
- // keep always one filter selected
- $.each($('.js-line-label'), function (key, elem) {
- var once = false;
- if ($(elem).attr('id') != interval && once == false) {
- $(elem).prop('checked', true);
- $('#' + $(elem).attr('id') + 'Label').show();
- once = true; // loop just for the first matched element
- // interval = $(elem).attr('id'); // change the id so update chart will be right
- }
- });
- }
- });
- // put gray background and green letters when select doughnut chart info
- $('.doughnut-bot-info').on('click', function (e) {
- // only trigger if a button is pressed
- if (e.target.className != 'doughnut-bot-info') {
- $($(this).find('*')).removeClass('darker-bot-info green');
- if (e.target.localName == 'span') {
- var button = $(e.target).parent('button');
- } else {
- var button = $(e.target);
- }
- var doughnutInfo = button.addClass('darker-bot-info').attr('id');
- button.children('.number').addClass('green');
- var older = window.doughnutInfo;
- if (older != doughnutInfo) {
- window.doughnutInfo = doughnutInfo;
- updateDoughnutChart();
- }
- }
- });
- function renderBarChart() {
- var dataBarChart = {
- labels: ['dummy'],
- datasets: [
- {
- backgroundColor: "#d0d0d0",
- borderColor: "#d0d0d0",
- borderWidth: 1,
- hoverBackgroundColor: "#3ec556",
- hoverBorderColor: "#3ec556",
- data: [0]
- }
- ]
- };
- window.barChart = new Chart($('#barChart'), {
- type: 'bar',
- data: dataBarChart,
- options: {
- maintainAspectRatio: false,
- legend: {
- display: false
- },
- scales: {
- xAxes: [{
- gridLines: {
- drawTicks: false,
- zeroLineColor: 'rgba(0, 0, 0, 0.0)',
- color: 'rgba(0, 0, 0, 0.0)'
- }
- }],
- yAxes: [{
- ticks: {
- labelOffset: 0,
- padding: 10,
- min: 0,
- suggestedMax: 20
- }
- }]
- },
- tooltips: {
- titleFontSize: 0,
- titleMarginBottom: 0,
- titleSpacing: 0,
- callbacks: {
- label: function (tooltipItem, data) {
- return tooltipItem.yLabel;
- }
- }
- }
- }
- });
- }
- renderBarChart();
- function updateBarChart() {
- window.barChart.data.datasets[0].data = window.dataJson.week.sent;
- window.barChart.data.labels = window.dataJson.week.labels;
- window.barChart.update();
- }
- refreshData();
- },
- getCampaignRecipients: function (audiencesJson, countSubscribers) {
- if ((audiencesJson !== null) && (audiencesJson !== undefined)) {
- $.each(audiencesJson, function (index, value) {
- if ((value !== null) && (value !== undefined) && (value.audience_id !== undefined)) {
- var $template = $('#templateRowAudience'),
- $clone = $template
- .clone()
- .removeClass('hide')
- .removeAttr('id')
- .insertBefore($template);
- var amountData = $('.templateRowAudience').length - 1;
- var rangeLocalFormat = parseInt(value.range_number).toLocaleString(locale);
- $clone
- .find('input[type=checkbox]').attr('value', value.audience_id).end()
- .find('input[id=audienceSelected]').attr('id', 'audienceSelected' + amountData).end()
- .find('label[for=audienceSelected]').attr('for', 'audienceSelected' + amountData).end()
- .find('[name="name"]').attr('name', 'nameAudience' + amountData).html(value.audience_name).end()
- .find('[name="size"]').attr('name', 'sizeAudience' + amountData).html(rangeLocalFormat).end()
- .find('[name="rank"]').attr('name', 'rankAudience' + amountData).html('-').end()
- .find('[name="dateCreation"]').attr('name', 'dateCreationAudience' + amountData).html(value.audience_creation).end();
- }
- var listAudiencesSelected = [];
- $('#audienceSelected' + amountData).on('change', function () {
- var audiencesSelected = scriptForPage.getSelectedAudiences();
- if (audiencesSelected != listAudiencesSelected) {
- listAudiencesSelected = audiencesSelected;
- action.getSubscribersAudience(audiencesSelected);
- }
- });
- });
- }
- $('.push-row').on('click', function () {
- var checkbox = $(this).find('input[type=checkbox]');
- var check = checkbox.prop('checked');
- checkbox.prop('checked', !check);
- // if all public is checked, then don't need any update
- if (checkbox.attr('id') == 'audienceSelected0' || !$('#audienceSelected0').prop('checked')) {
- checkbox.trigger('change');
- }
- });
- $("#sumSize").html(countSubscribers.toLocaleString(locale));
- },
- getStatusAutomation: function () {
- var filterAutomation = $("#filterAutomation");
- var sendHourIni = $("#sendHourIni");
- var sendHourEnd = $("#sendHourEnd");
- var sendMinuteIni = $("#sendMinuteIni");
- var sendMinuteEnd = $("#sendMinuteEnd");
- var sendDateIni = $("#sendDateIni");
- var sendDateEnd = $("#sendDateEnd");
- var selectAutomation = transform.customSelect('filterAutomation');
- $(selectAutomation.content).css({width: '230px'}); //style the automation selector
- transform.customSelect('sendHourIni');
- transform.customSelect('sendMinuteIni');
- transform.customSelect('sendHourEnd');
- transform.customSelect('sendMinuteEnd');
- // var date = new Date();
- // var dd = date.getDate();
- // var mm = date.getMonth() + 1;
- // var yyyy = date.getFullYear();
- // if (dd < 10) {
- // dd = '0' + dd;
- // }
- // if (mm < 10) {
- // mm = '0' + mm;
- // }
- //
- // var today = dd + '/' + mm + '/' + yyyy;
- window.dateIni = sendDateIni.val();
- window.hourIni = sendHourIni.val();
- window.minuteIni = sendMinuteIni.val();
- window.dateEnd = sendDateEnd.val();
- window.hourEnd = sendHourEnd.val();
- window.minuteEnd = sendMinuteEnd.val();
- window.automation = filterAutomation.val();
- sendDateIni.datepicker({
- format: 'dd/mm/yyyy',
- language: locale,
- beforeShow: function (input, obj) {
- $('.ui-datepicker').removeClass('blur');
- },
- onSelect: function (textData, objDatepicker) {
- dateIni = sendDateIni.val();
- window.scrollTo(0, 0);
- getData(0);
- }
- });
- sendDateEnd.datepicker({
- format: 'dd/mm/yyyy',
- language: locale,
- beforeShow: function (input, obj) {
- $('.ui-datepicker').removeClass('blur');
- },
- onSelect: function (textData, objDatepicker) {
- dateEnd = $(this).val();
- window.scrollTo(0, 0);
- getData(0);
- }
- });
- filterAutomation.change(function () {
- automation = $(this).val();
- window.scrollTo(0, 0);
- getData(0);
- });
- sendHourIni.change(function () {
- hourIni = $(this).val();
- window.scrollTo(0, 0);
- console.log(automation);
- getData(0);
- });
- sendHourEnd.change(function () {
- hourEnd = $(this).val();
- window.scrollTo(0, 0);
- getData(0);
- });
- sendMinuteIni.change(function () {
- minuteIni = $(this).val();
- window.scrollTo(0, 0);
- getData(0);
- });
- sendMinuteEnd.change(function () {
- minuteEnd = $(this).val();
- window.scrollTo(0, 0);
- getData(0);
- });
- },
- // @param calls this variable gets the function which calls the functions inside "pushScript"
- pushScript: function (calls) {
- function resizePreview() {
- var height = $('#preInfo').height();
- $('#preVisualization').css({height: height});
- }
- function showUpSend() {
- var changeCheckbox = $('.js-check-showUpSend');
- var showUp = $('.js-showUpSend');
- changeCheckbox.on('change', function () {
- if ($(this).is(':checked')) {
- showUp.css({visibility: 'visible'}).hide().fadeIn('fast');
- dateTimePreview.changeSendSchedule();
- } else {
- showUp.fadeOut('fast', function () {
- showUp.show().css({visibility: 'hidden'});
- $('#pushSchedule').text('Imediato').removeClass('red');
- });
- }
- });
- }
- function showUpExp() {
- var changeCheckbox = $('.js-check-showUpExp');
- var showUp = $('.js-showUpExp');
- changeCheckbox.on('change', function () {
- if ($(this).is(':checked')) {
- showUp.css({visibility: 'visible'}).hide().fadeIn('fast');
- $('#pushExpiration').text('Informe o tempo').removeClass('orange').addClass('red');
- } else {
- showUp.fadeOut('fast', function () {
- showUp.show().css({visibility: 'hidden'});
- $('#pushExpiration').text('Não').removeClass('red').addClass('orange');
- });
- }
- });
- }
- function showUpURL() {
- var changeCheckbox = $('.js-check-showUpURL');
- var showUp = $('.js-showUpURL');
- changeCheckbox.on('change', function () {
- if ($(this).is(':checked')) {
- showUp.css({visibility: 'visible'}).hide().fadeIn('fast');
- var url = $('input[name=open-url]').val();
- if (url == '') {
- $('.js-pushUrl').text('Informe a URL').removeClass('orange').addClass('red');
- } else {
- $('.js-pushUrl').text(url).removeClass('orange').removeClass('red');
- }
- } else {
- showUp.fadeOut('fast', function () {
- showUp.show().css({visibility: 'hidden'});
- $('.js-pushUrl').text('Não').removeClass('red').addClass('orange');
- });
- }
- });
- }
- function checkYesNo(checkbox, content) {
- var checkbox = $(checkbox);
- var info = $(content);
- checkbox.on('change', function () {
- if ($(this).is(':checked')) {
- info.text('Sim').removeClass('orange').addClass('green');
- } else {
- info.text('Não').removeClass('green').addClass('orange');
- }
- }
- );
- }
- /* Resize emoji for phone preview and DIV (use size param for this) */
- function resizeEmoji(platform, size) {
- var emojis,
- proportion;
- if (platform == 'android') {
- emojis = $('#' + platform + 'Content .img');
- proportion = 0.6;
- } else if (platform == 'iOS') {
- emojis = $('#' + platform + 'Content .img');
- proportion = 0.65;
- } else {
- emojis = $(platform);
- proportion = size;
- }
- emojis.each(function () {
- var width = $(this).width() * proportion;
- var height = $(this).height() * proportion;
- var bgPosition = $(this).css('backgroundPosition');
- var position = bgPosition.replace(/px/g, '').split(' ');
- var posX = position[0] * proportion;
- var posY = position[1] * proportion;
- var bgSize = $(this).css('backgroundSize');
- var size = bgSize.replace(/px/g, '').split(' ');
- var sizeX = size[0] * proportion;
- var sizeY = size[1] * proportion;
- $(this).width(width);
- $(this).height(height);
- $(this).css('backgroundPosition', posX + 'px ' + posY + 'px');
- $(this).css('backgroundSize', sizeX + 'px ' + sizeY + 'px');
- })
- }
- /* @param lastPushMessage Last push returned to preview. Just to be unique, this is 'ççç'
- * @param androidChars Max number of chars in android preview
- * @param iOSChars Max number of chars in iPhone preview
- * @param iOSfirst First time iOS passes sliceMessage, it has to change lastPreview, so it recreates array
- * */
- var lastPushMessage = 'ççç',
- androidChars = 64,
- iOSChars = 120,
- iOSfirst = true;
- /* Slice the message leaving <img> tags and undivided */
- function sliceMessage(typed, size) {
- var lastPreview = typed.substr(0, lastPushMessage.length);
- /* Checks if it is the first iOS preview change, so it has to recreate array and lastPushMessage */
- if (size == iOSChars && iOSfirst) {
- lastPreview = '';
- iOSfirst = false;
- }
- if (lastPreview == lastPushMessage) {
- return lastPushMessage; // if typed piece is the same of the last preview, keep it
- } else {
- var textArray = [],
- wordArray,
- rest = typed,
- pos,
- emojiSpace;
- rest = rest.replace(/ /g, ' '); // unseparated
- do {
- pos = rest.search('<img'); // unseparated img
- if (pos != -1) {
- wordArray = rest.substr(0, pos).split('');
- textArray = textArray.concat(wordArray);
- rest = rest.substr(pos);
- pos = rest.search(':">');
- emojiSpace = rest.substr(0, pos + 3);
- textArray.push(emojiSpace, '');
- rest = rest.substr(pos + 3);
- }
- } while (pos != -1 && textArray.length < size);
- textArray = textArray.concat(rest.split(''));
- textArray.map(function (val, index) {
- if (val == ' ') {
- textArray[index] = ' '; // bring back
- }
- });
- lastPushMessage = textArray.slice(0, size).join('');
- if (size == androidChars) {
- return lastPushMessage; // return preview TEXT
- }
- return textArray; // return preview ARRAY (for different Android and iOS slices)
- }
- }
- /* Change TITLE while typing */
- function titleMessagePreview() {
- $('#pushTitle').on('keyup', function () {
- var typed = $(this).val();
- $('.js-title').text(typed);
- });
- }
- function doURLPreview(url) {
- if (url == '') {
- $('.js-pushUrl').text('Informe uma URL').removeClass('red').addClass('red');
- } else {
- $('.js-pushUrl').text(url).removeClass('red');
- }
- }
- function URLPreview() {
- $('#openURL').on('keyup', function () {
- var url = $(this).val();
- doURLPreview(url);
- });
- }
- /*
- * @param iOSContent Selector for iOS preview
- * @param androidContent Selector for Android preview
- * @param preMsg selector For message field preview
- * @param observeOnce Boolean to stop Observer at the first time
- * */
- var iOSContent = $('#iOSContent'),
- androidContent = $('#androidContent'),
- preMsg = $('.js-msg'),
- observeOnce = true;
- var target = $('#pushContent').next('div'); // message content DIV
- /* Reset observer boolean */
- $(target).on('keyup', function () {
- observeOnce = true;
- });
- $('.emoji-menu').on('mousedown', function () {
- observeOnce = true;
- });
- function doMessagePreview(typed) {
- /* count how many real chars there is */
- var typedNum = typed.replace(/ /g, ' '); // counts 1
- var matches = typed.match(/\<img[^>]*>/g); // <img> counts 2
- if (matches != null) {
- for (var i = 0; i < matches.length; i++) {
- typedNum = typedNum.replace(matches[i], '12');
- }
- var count = typedNum.length;
- } else {
- count = typed.length;
- }
- preMsg.html(typed);
- resizeEmoji();
- /* More than iOS preview space */
- if (count > iOSChars) {
- var textArray = sliceMessage(typed, iOSChars);
- // if textArray isn't array, then the message is the same and don't need to be changed
- if (Array.isArray(textArray)) {
- /* iOS push */
- var textLarge = textArray.slice(0, iOSChars).join('') + '...';
- iOSContent.html(textLarge);
- resizeEmoji('iOS');
- /* Android push */
- var textSmall = textArray.slice(0, androidChars).join('') + '...';
- androidContent.html(textSmall);
- resizeEmoji('android');
- }
- } else if (count > androidChars) {
- iOSContent.html(typed);
- resizeEmoji('iOS');
- /* Change just Android push */
- var text = sliceMessage(typed, androidChars) + '...';
- androidContent.html(text);
- resizeEmoji('android');
- iOSfirst = true;
- } else {
- androidContent.html(typed);
- resizeEmoji('android');
- iOSContent.html(typed);
- resizeEmoji('iOS');
- iOSfirst = true;
- }
- resizePreview(); // if message is to long, resize phone preview DIV
- }
- /* Change MESSAGE while typing */
- function messagePreview() {
- var observer = new MutationObserver(function (mutations) { // create an observer instance
- mutations.forEach(function (mutation) {
- if (observeOnce) {
- // var lastEmoji = target.children('[alt="' + mutation.addedNodes[0].alt + '"]');
- // resizeEmoji(lastEmoji, 0.76);
- var typed = $(mutation.target).html();
- doMessagePreview(typed);
- observeOnce = false;
- }
- });
- });
- observer.observe(target[0], {attributes: true, childList: true});
- }
- function refreshPreview() {
- $('#pushTitle').trigger('keyup');
- }
- var dateTimePreview = {
- /* SEND TIME */
- sendDateTime: {
- proxy: new Proxy(['', '', ''], {
- get: function (target, property) {
- return target[property];
- },
- set: function (target, property, value) {
- target[property] = value;
- dateTimePreview.changeSendSchedule();
- return true;
- }
- })
- },
- setSendDate: function () {
- var nomesMes = [
- "Janeiro", "Fevereiro", "Março",
- "Abril", "Maio", "Junho", "Julho",
- "Agosto", "Setembro", "Outubro",
- "Novembro", "Dezembro"
- ];
- var nomesSemana = [
- "Domingo", "Segunda-feira", "Terça-feira",
- "Quarta-feira", "Quinta-feira",
- "Sexta-feira", "Sábado-feira"
- ];
- var input = $('#sendDate').val().split('/');
- input = input[2] + '-' + input[1] + '-' + input[0];
- var date = new Date(input);
- var fixTime = date.getTimezoneOffset() / 60;
- date.setHours(date.getHours() + fixTime);
- var today = new Date().setHours(0, 0, 0, 0);
- var tomorrow = today + 24 * 60 * 60000;
- var dateString = '';
- if (date.getTime() == today) {
- dateString = 'Hoje, ';
- } else if (date.getTime() == tomorrow) {
- dateString = 'Amanhã, ';
- } else {
- var day = date.getDate();
- var monthIndex = date.getMonth();
- var year = date.getFullYear();
- var weekIndex = date.getDay();
- dateString = nomesSemana[weekIndex] + ', ' + day + ' ' + nomesMes[monthIndex] + ' ' + year + ', ';
- }
- this.sendDateTime.proxy[0] = dateString;
- this.sendDateTime.proxy[4] = date.getTime();
- },
- setSendHour: function () {
- this.sendDateTime.proxy[1] = $('#sendHour').val();
- },
- setSendMinute: function () {
- this.sendDateTime.proxy[2] = $('#sendMinute').val();
- },
- changeSendSchedule: function () {
- var flagSchedule = $('.js-check-showUpSend').is(':checked');
- var date = this.sendDateTime.proxy[0];
- if (flagSchedule && date == '') {
- date = $('#sendDate').val();
- }
- var h = this.sendDateTime.proxy[1];
- if (flagSchedule && h == '') {
- h = $('#sendHour').val();
- }
- var min = this.sendDateTime.proxy[2];
- if (flagSchedule && min == '') {
- min = $('#sendMinute').val();
- }
- var dateMillis = this.sendDateTime.proxy[4] + 60000 * (60 * h) + 60000 * min;
- var today = new Date().getTime();
- window.scheduleValid = false; // if time is valid, set to true and allow push sending
- // if (date == '' || date.search('undefined') != -1) {
- if (date == '' && flagSchedule) {
- $('#pushSchedule').text('Agende o envio').addClass('red bold');
- } else if (dateMillis < today) {
- $('#pushSchedule').text('Escolha uma data futura').addClass('red bold');
- resizePreview();
- } else if (flagSchedule) {
- var dateTime = date + h + ':' + min + 'h';
- $('#pushSchedule').text(dateTime).removeClass('red bold');
- $('#iOS .time').text('Hoje ' + h + ':' + min);
- $('#android .time').text(h + ':' + min);
- window.scheduleValid = true;
- resizePreview();
- }
- }
- };
- function changeExpirationTime() {
- var h = $('#expirationHour').val();
- var min = $('#expirationMinutes').val();
- var hours = '';
- var minutes = '';
- var plural = ['hora', 'horas', 'minuto', 'minutos'];
- if (h != 0) {
- if (h == 1) {
- hours = h + ' ' + plural[0] + ' ';
- } else {
- hours = h + ' ' + plural[1] + ' ';
- }
- }
- if (min != 0) {
- if (min == 1) {
- minutes = min + ' ' + plural[2];
- } else {
- minutes = min + ' ' + plural[3]
- }
- }
- if (min == 0 && h == 0) {
- $('#pushExpiration').text('Informe o tempo').removeClass('red').addClass('red');
- } else if (min != 0 && h != 0) {
- var time = hours + 'e ' + minutes;
- $('#pushExpiration').text(time).removeClass('red');
- } else if (min != 0 ^ h != 0) {
- var time = hours + minutes;
- $('#pushExpiration').text(time).removeClass('red');
- }
- }
- // get the functions to be called here
- if (calls == 'sendPush') {
- // transform.customSelect('expirationMinutes');
- // transform.customSelect('expirationHour');
- transform.customSelect('sendHour');
- transform.customSelect('sendMinute');
- $('#preVisualization').tabs();
- //set time only when checkbox is clicked, so the Proxy isn't triggered in advance
- $('#scheduleSend').one('change', function () {
- dateTimePreview.setSendDate(); // Initializes the date for Send Schedule
- dateTimePreview.setSendHour(); // Initializes the date for Send Schedule
- dateTimePreview.setSendMinute(); // Initializes the date for Send Schedule
- });
- $('#sendDate').datepicker({minDate: 0}).on('change', function () {
- dateTimePreview.setSendDate();
- });
- $('#sendHour').on('change', function () {
- dateTimePreview.setSendHour();
- });
- $('#sendMinute').on('change', function () {
- dateTimePreview.setSendMinute();
- });
- // $('#expirationHour').on('change', function () {
- // changeExpirationTime();
- // });
- // $('#expirationMinutes').on('change', function () {
- // changeExpirationTime();
- // });
- transform.iOSswitch();
- resizePreview();
- showUpSend();
- showUpExp();
- showUpURL();
- // checkYesNo('.js-check-sound', '#pushSound');
- // checkYesNo('.js-check-increment', '#pushIncrement');
- titleMessagePreview();
- URLPreview();
- messagePreview();
- dateTimePreview.changeSendSchedule();
- behaviors.listData.add(undefined, 5);
- // behaviors.listData.remove();
- refreshPreview();
- } else if (calls == 'newCampaign') {
- $('#preVisualization').tabs();
- transform.iOSswitch();
- resizePreview();
- showUpSend();
- showUpExp();
- showUpURL();
- // checkYesNo('.js-check-sound', '#pushSound');
- // checkYesNo('.js-check-increment', '#pushIncrement');
- titleMessagePreview();
- URLPreview();
- messagePreview();
- behaviors.listData.add(undefined, 5);
- // behaviors.listData.remove();
- } else if (calls == 'newAutomation') {
- $('#preVisualization').tabs();
- transform.iOSswitch();
- resizePreview();
- // showUpSend();
- // showUpExp();
- // showUpURL();
- // checkYesNo('.js-check-sound', '#pushSound');
- // checkYesNo('.js-check-increment', '#pushIncrement');
- // titleMessagePreview();
- // URLPreview();
- // messagePreview();
- behaviors.listData.add(undefined, 5);
- // behaviors.listData.remove();
- $('#campaignsList').on('click', 'button', function () {
- $('.js-title').html($('#msgTitle').html());
- doMessagePreview($('#msgBody').html());
- doURLPreview($('#urlPushField').html());
- });
- } else if (calls == 'newApi') {
- $('#preVisualization').tabs();
- transform.iOSswitch();
- resizePreview();
- showUpURL();
- // checkYesNo('.js-check-sound', '#pushSound');
- // checkYesNo('.js-check-increment', '#pushIncrement');
- titleMessagePreview();
- URLPreview();
- messagePreview();
- // dateTimePreview.changeSendSchedule();
- behaviors.listData.add('#tagBlock');
- behaviors.listData.add('#additionalBlock', 5);
- // behaviors.listData.remove();
- refreshPreview();
- }
- },
- automation: {
- setTime: function (text) {
- $("#timeInterval").html(text);
- $("#pushScheduleHour").html(text);
- },
- timeSlider: function (selectedDays, timeJson, days) {
- var daysName = [];
- var pushSchedule = $('#pushSchedule');
- var daysSelectors = $('input[name=day]');
- daysSelectors.on('change', function () {
- $.each($('input[name=day]'), function (key, obj) {
- selectedDays[key] = $(obj).prop('checked');
- });
- daysName.length = 0;
- $.each(selectedDays, function (key, value) {
- if (value == true)
- daysName.push(days[key]);
- });
- if (selectedDays[0] == true) {
- daysName.push(daysName.shift());
- }
- var daysInterval = selectedDays.slice();
- var sunday = daysInterval.shift();
- var saturday = daysInterval.pop();
- if (daysName.length == 7) {
- pushSchedule.html('Todos os dias');
- } else if (daysName.length == 5 && sunday == false && saturday == false) {
- $('#pushSchedule').html('Dias de semana');
- } else if (daysName.length == 2) {
- $('#pushSchedule').html(daysName.join(' e '));
- } else {
- $('#pushSchedule').html(daysName.join(', '));
- }
- });
- daysSelectors.first().trigger('change');
- var timeIntervalRange = $("#timeIntervalRange");
- timeIntervalRange.slider({
- range: true,
- min: 0,
- max: 24,
- values: [0, 24],
- slide: function (event, ui) {
- var text = 'Entre ' + ui.values[0] + " e " + ui.values[1] + " horas.";
- scriptForPage.automation.setTime(text);
- $(ui.handle).attr('data-value', ui.value);
- timeJson = {'init': ui.values[0], 'end': ui.values[1]};
- }
- });
- var init = timeIntervalRange.slider("values", 0);
- var end = timeIntervalRange.slider("values", 1);
- // USA ESSE JSON PARA PASSAR AS INFOS DE HORA
- timeJson = {'init': init, 'end': end};
- scriptForPage.automation.setTime('Entre ' + init + " e " + end + " horas.");
- // initialize slider label values
- $.each($(timeIntervalRange.slider("widget")).find('.ui-slider-handle'), function (index, obj) {
- $(obj).attr('data-value', timeIntervalRange.slider("values", index));
- });
- return timeJson;
- },
- populateScheduled: function (automationScheduledJson) {
- if(automationScheduledJson !== '0') {
- $.each(automationScheduledJson, function (index, value) {
- var elementsDays = $("input[name*='day']");
- if (value.sunday == 0)
- $(elementsDays).filter(function () {
- return this.value == 'sun'
- }).attr('checked', false);
- if (value.monday == 0)
- $(elementsDays).filter(function () {
- return this.value == 'mon'
- }).attr('checked', false);
- if (value.tuesday == 0)
- $(elementsDays).filter(function () {
- return this.value == 'tue'
- }).attr('checked', false);
- if (value.wednesday == 0)
- $(elementsDays).filter(function () {
- return this.value == 'wed'
- }).attr('checked', false);
- if (value.thursday == 0)
- $(elementsDays).filter(function () {
- return this.value == 'thu'
- }).attr('checked', false);
- if (value.friday == 0)
- $(elementsDays).filter(function () {
- return this.value == 'fri'
- }).attr('checked', false);
- if (value.saturday == 0)
- $(elementsDays).filter(function () {
- return this.value == 'sat'
- }).attr('checked', false);
- $("#timeIntervalRange").slider('values', 0, value.hour_initial);
- $("#timeIntervalRange").slider('values', 1, value.hour_final);
- scriptForPage.automation.setTime('Entre ' + value.hour_initial + " e " + value.hour_final + " horas.");
- $($(".ui-slider-handle")[0]).attr('data-value', value.hour_initial);
- $($(".ui-slider-handle")[1]).attr('data-value', value.hour_final);
- });
- $('input[name=day]').trigger('change');
- }
- },
- newAutomation: function (automationId, campaignsJson, days, audienceJson, criteriaJson, appId, countSubscribers, allAudiences) {
- transform.highlightSubMenu('#automations');
- behaviors.popUp('#selectCampaign', '#campaignsList');
- var campaignIdSelected = 0;
- $.each(campaignsJson, function (key, obj) {
- $('#camp' + obj.campId).on('click', function () {
- $('#campaignsList').fadeOut('fast');
- $('#campName').html(obj.campName);
- //set title field
- var title;
- if (obj.msgTitle == '') {
- title = '-';
- } else {
- title = obj.msgTitle;
- }
- $('#msgTitle').html(title);
- $('#titlePreview').html(title);
- // set URL field
- var urlPush;
- if (obj.urlPush == null) {
- urlPush = '-';
- $('#pushURL').addClass('orange').removeClass('green').html('Não');
- } else {
- urlPush = obj.urlPush;
- $('#pushURL').addClass('green').removeClass('orange').html('Sim');
- }
- $('#urlPushField').html(urlPush);
- campaignIdSelected = obj.campId;
- transform.colonToEmoji(obj.msgBody, '#msgBody');
- transform.colonToEmoji(obj.msgBody, '#msgPreview');
- $("#campaign").next('.js-error').remove();
- $("#campaign").removeClass("error-outline");
- });
- });
- new Tether({
- element: '#campaignsList',
- target: '#selectCampaign',
- attachment: 'top left',
- targetAttachment: 'bottom left'
- });
- var selectedDays = [];
- var timeJson;
- timeJson = scriptForPage.automation.timeSlider(selectedDays, timeJson, days);
- scriptForPage.newAudience('', audienceJson, criteriaJson, appId, false);
- // transform.emojiPicker();
- scriptForPage.pushScript('newAutomation');
- behaviors.autoTextArea();
- $('#footerSave').on('click', function () {
- if (validate.multiFields([['#componentName', 'Precisamos de um nome para a automação'],
- [validate.fieldCampaignAutomation, campaignIdSelected, automationId],
- [validate.fieldsAdditionalData],
- [validate.fieldsAudienceCampaign, true],
- [validate.fieldsAudienceCriteria, false]])) {
- var audiencesSelected = scriptForPage.getSelectedAudiences();
- var data = {
- 'automationId': automationId,
- 'campaignId': campaignIdSelected,
- 'campaignName': $('#campName').html(),
- 'audiencesSelected': audiencesSelected,
- 'selectedDays': '"' + selectedDays.toString() + '"',
- 'timeInit': $("#timeIntervalRange").slider("values", 0),
- 'timeEnd': $("#timeIntervalRange").slider("values", 1)
- };
- modal.getModal('modal-save-automation.php', false, data);
- }
- });
- scriptForPage.getCampaignRecipients(allAudiences, countSubscribers);
- validate.quantitySubscribers(countSubscribers);
- $('#footerCancel').on('click', function () {
- navigateTo.app.push.automations();
- });
- },
- populateAutomation: function (automationId, automationJson, appId, pushCriteriaJson, automationAudienceJson, additionalJson, automationScheduledJson) {
- if (automationId > 0) {
- var name = automationJson['automation_name'];
- var description = automationJson['automation_description'];
- var campaignId = automationJson['campaign_id'];
- populateAudience(automationAudienceJson);
- populateCriteria(pushCriteriaJson);
- populateAdditionalData(additionalJson);
- scriptForPage.automation.populateScheduled(automationScheduledJson);
- $('#componentName').val(name);
- $('#componentDescription').val(description);
- $('#camp' + campaignId).trigger('click');
- action.findReachAudience(appId);
- $('.page-title').html(name);
- }
- function populateCriteria(pushCriteriaJson) {
- var i = 0;
- $.each(pushCriteriaJson, function (index, value) {
- if ((i > 0) && (value !== null) && (value !== undefined)) {
- $("#addNewCondition").trigger("click");
- }
- var selectField = $("#select" + i + "0").attr('value', value.audience_criteria_id);
- selectField.val(value.audience_field_id);
- selectField.next('a').css({color: 'inherit'});
- var varType = selectField.find('option[value=' + selectField.val() + ']').attr('data-type');
- scriptForPage.showConditionField('#jsConditionRow' + i, varType);
- var objectTypeCondition = $('#jsConditionRow' + i).find('.js-' + varType + '-condition');
- if (varType == 'boolean') {
- objectTypeCondition.find('a[href="#' + value.audience_value + '"]').trigger('click');
- } else {
- objectTypeCondition.find('select[name=operator]').val(value.audience_field_condition_id);
- objectTypeCondition.find('select[name=operator]').attr('value', value.audience_field_condition_id);
- objectTypeCondition.find('select[name=operator]').next('a').css({color: 'inherit'});
- objectTypeCondition.find('input[name=val]').val(value.audience_value);
- }
- i++;
- });
- }
- function populateAudience(automationAudienceJson) {
- if (automationAudienceJson == null || automationAudienceJson == '0') {
- $('#audienceSelected0').attr('checked', true);
- $('#audienceSelected0').trigger('change');
- } else {
- var allRowsAudience = $("input[class*='audience']");
- $.each(automationAudienceJson, function (index, value) {
- var elementAudienceId = $(allRowsAudience).filter(function () {
- return this.value == value.audience_id
- }).attr('id');
- $('#' + elementAudienceId).attr('checked', true);
- $('#' + elementAudienceId).trigger('change');
- });
- }
- }
- function populateAdditionalData(additionalJson) {
- //verify if automation has additional data
- if ((additionalJson !== null) && (additionalJson !== undefined)) {
- var additionalBlock = $('#additionalBlock');
- $.each(additionalJson, function (index, value) {
- if ((value !== null) && (value !== undefined) && (value.key_data !== undefined)) {
- // add row
- additionalBlock.find('.addNewData').trigger('click');
- // insert data
- additionalBlock.find('.js-dataTemplate').prev()
- .find('[name="additional-key"]').attr('value', value.key_data).end()
- .find('[name="additional-value"]').attr('value', value.value_data);
- }
- });
- }
- }
- }
- },
- generalConfig: {
- /* Register when user copy the element and supports a button to do the copy
- *
- * @param btnId Button ID to copy text
- * @param idToCopy Text ID to copy
- * @param timeOut Timeout time
- * */
- copyContent: function (btnId, idToCopy, timeOut) {
- var copyBtn = $(btnId);
- var copyThis = $(idToCopy);
- timeOut = timeOut || 1000;
- var originalBtnText = copyBtn.html();
- var originalBtnClass = copyBtn.attr('class');
- /* Use clipboard.js plugin
- * Ref: https://github.com/zenorocha/clipboard.js.git
- * */
- copyBtn.attr('data-clipboard-target', idToCopy);
- new Clipboard(btnId);
- copyThis.on('copy', function () {
- copyBtn.html('Copiado!').removeClass('button-clean-gray').addClass('button-blue');
- setTimeout(function () {
- copyBtn.html(originalBtnText);
- if (originalBtnClass.search('button-blue') == -1) {
- copyBtn.switchClass('button-blue', originalBtnClass, 400);
- }
- }, timeOut);
- });
- // DISABLE COPY CUT PASTE
- // copyBtn.on('cut copy paste', function (e) {
- // e.preventDefault(); //disable cut,copy,paste
- // });
- },
- updateField: function (valueField, formData, token) {
- $.ajax({
- type: 'POST',
- url: '/appConfigValidation',
- data: formData,
- dataType: 'json',
- encode: true
- })
- .done(function (data) {
- console.log(data);
- if (!data.success) {
- if (data.errors.password) {
- $('#password-group').addClass('has-error');
- $('#password-group').append('<div class="help-block">' + data.errors.password + '</div>');
- }
- if (data.errors.loginError) {
- //$('#message-login').append('<div class="alert-box">' + data.errors.loginError + '</div>');
- $('#password-group').addClass('has-error');
- $('#password-group').append('<div class="help-block">' + data.errors.loginError + '</div>');
- }
- } else {
- $(valueField).text(formData['appName']);
- var appTitleBtn = $('#appTitleBtn');
- /* update in menu side */
- var nonText = appTitleBtn.html();
- nonText = nonText.substring(nonText.indexOf('<'));
- appTitleBtn.html(formData['appName'] + nonText);
- $('#menuName' + token).text(formData['appName']);
- }
- })
- .fail(function (data) {
- console.log(data);
- });
- },
- updateIcon: function (token) {
- $("#uploadIconForm").on('submit', (function (e) {
- e.preventDefault();
- var uploadMessage = $("#uploadMessage");
- var uploadBtn = $('#uploadIconBtn');
- uploadMessage.empty();
- var formData = new FormData(this);
- formData.append('object', 'appIcon');
- $.ajax({
- url: "/actions/imageUpload.php", // Url to which the request is send
- type: "POST", // Type of request to be send, called as method
- data: formData, // Data sent to server, a set of key/value pairs (i.e. form fields and values)
- contentType: false, // The content type used when sending data to the server.
- cache: false, // To unable request pages to be cached
- processData: false, // To send DOMDocument or non processed data file it is set to false
- success: function (data) { // A function to be called if request succeeds
- var result = $.parseJSON(data);
- console.log('done');
- console.log(data);
- if (result.hasOwnProperty("img")) {
- uploadMessage.css({color: '#3bdb7b', fontWeight: '600'}).text(result.msg);
- uploadBtn.text('Enviado!')
- .removeClass('button-clean-blue')
- .addClass('button-green');
- setTimeout(function () {
- uploadBtn.switchClass('button-green', 'button-clean-blue', 400).text('Upload');
- }, 1500);
- var path = ref.getUploads + '/app_icons/' + result.img;
- $('#appIcon').attr('src', path)
- .attr('data', path);
- /* update in menu side */
- $('#menuImg' + token).attr('src', path);
- } else {
- uploadMessage.attr('style', '""').text(result.msg);
- }
- },
- fail: function (data) {
- console.log('fail');
- console.log(data);
- }
- });
- }));
- }
- },
- getAdditionalData: function () {
- var elements = $('.js-dataRow');
- var dict = [];
- $.each(elements, function (num, obj) {
- var key = $(obj).find('input[name="additional-key"]').val();
- var value = $(obj).find('input[name="additional-value"]').val();
- if ((key !== '') && (value !== '')) {
- dict.push({key: key, value: value});
- }
- });
- return dict;
- },
- // TODO deletar essa função quando o list estiver funcionando
- getCustomFields: function (customFieldsJson) {
- var num = 0; // uniquer number for ids
- $("#addCustomField").hover(function () {
- $(this).css({fontWeight: '400'});
- behaviors.svgChangeTo.hover($(this).children('img'));
- }, function () {
- $(this).attr('style', '');
- behaviors.svgChangeTo.hover($(this).children('img'));
- }).on("click", function () {
- // if ($('.js-customField').length < 5) {
- var $template = $('#templateCustomFields'),
- $clone = $template
- .clone()
- .removeClass('hide template')
- .addClass('js-customField')
- .removeAttr('id')
- .insertBefore($template);
- var amountData = $('.js-customField').length;
- num++;
- // Update the name attributes
- $clone
- .find('#customFieldName').attr('name', 'data[' + num + '].custom_field')
- .attr('id', 'customFieldName' + num).end()
- .find('#customFieldType').attr('id', 'customFieldType' + num).end();
- transform.customSelect('customFieldType' + num);
- //add click atribute
- // remove();
- $.each($('#customFieldForm').find('.numberField'), function (key, obj) {
- $(obj).html('Campo customizável ' + (key + 1));
- });
- if (amountData >= 5) {
- $(".addData").addClass('hide');
- }
- // }
- });
- $("#customFieldsBlock").on('hover', '.js-removeData', function () {
- behaviors.svgChangeTo.hover($(this).children('img'));
- }, function () {
- behaviors.svgChangeTo.hover($(this).children('img'));
- }).on("click", '.js-removeData', function () {
- // Remove element containing the fields
- $(this).parents('.control-panel-row').remove();
- // re-write the titles
- $.each($('#customFieldForm').find('.numberField'), function (key, obj) {
- $(obj).html('Campo customizável ' + (key + 1));
- });
- var amountData = $('.js-customField').length;
- if (amountData <= 5) {
- $(".addData").removeClass('hide');
- } else {
- $(".addData").addClass('hide');
- }
- });
- // function remove() {
- // $(".js-dataRow").on('hover', '.js-removeData', function () {
- // behaviors.svgChangeTo.hover($(this).children('img'));
- // }, function () {
- // behaviors.svgChangeTo.hover($(this).children('img'));
- // }).on("click", '.js-removeData', function () {
- // // Remove element containing the fields
- // $(this).parents('.control-panel-row').remove();
- //
- // // re-write the titles
- // $.each($('#customFieldForm').find('.numberField'), function (key, obj) {
- // $(obj).html('Campo customizável ' + (key + 1));
- // });
- //
- // var amountData = $('.js-customField').length;
- // if (amountData <= 5) {
- // $(".addData").removeClass('hide');
- // } else {
- // $(".addData").addClass('hide');
- // }
- // });
- // }
- var i = 0;
- //verify if app has custom fields
- if ((customFieldsJson !== null) && (customFieldsJson !== undefined)) {
- $.each(customFieldsJson, function (index, value) {
- i++;
- if ((i == 1) && (value !== null) && (value !== undefined) && (value.custom_field_name !== undefined)) {
- $("[name='data[0].custom_field']").attr('value', value.custom_field_name);
- var selectField = $("#customFieldType0").attr('value', value.custom_field_type);
- selectField.val(value.custom_field_type);
- selectField.next('a').css({color: 'inherit'});
- } else if ((value !== null) && (value !== undefined) && (value.custom_field_name !== undefined)) {
- // var $template = $('#templateCustomFields'),
- // $clone = $template
- // .clone()
- // .removeClass('hide')
- // .addClass('.js-customField')
- // .removeAttr('id')
- // .insertBefore($template);
- //
- // var amountData = $('.js-customField').length - 1;
- // num = amountData + 1; // initialize num
- $('#addCustomField').trigger('click');
- // .find('#customFieldName').attr('name', 'data[' + num + '].custom_field')
- $('#customFieldName' + num).attr('value', value.custom_field_name);
- // $('#customFieldType' + num).attr('value', value.custom_field_type);
- // Update the name and value attributes
- // $clone
- // .find('[name="custom_field"]').attr('name', 'data[' + amountData + '].custom_field').attr('value', value.custom_field_name).end()
- // .find('#customFieldType').attr('id', 'customFieldType' + amountData).end()
- // .find('.numberField').html('Campo customizável ' + (amountData + 1)).end();
- var selectField = $("#customFieldType" + num).attr('value', value.custom_field_type);
- selectField.val(value.custom_field_type);
- selectField.next('a').css({color: 'inherit'});
- // $(".js-removeData").trigger("click");
- // transform.customSelect('customFieldType' + amountData);
- // if (amountData == 4)
- // $(".addData").addClass('hide');
- }
- });
- if (i > 1) {
- $('.js-removeData').first().removeClass('hide');
- }
- }
- // remove();
- },
- getSelectedAudiences: function () {
- var elements = $('.list-checkbox');
- var dict = '';
- for (var i = 0; i < elements.length; i++) {
- if ($('#audienceSelected' + i + ':checked').length > 0) {
- var audience = $('#audienceSelected' + i).val();
- if (audience !== '') {
- if (dict == '')
- dict = audience;
- else
- dict += ',' + audience;
- }
- }
- }
- return '"' + dict + '"';
- },
- getAudienceCriteria: function () {
- var elements = $(".js-condition-row");
- var dict = [];
- for (var i = 0; i < elements.length; i++) {
- var row = "#" + elements[i].id;
- var selectCriteria = $(row.replace("jsConditionRow", "select") + '0');
- var nameSelectCriteria = selectCriteria.val();
- if (nameSelectCriteria != '' && nameSelectCriteria != undefined) {
- var nameGroupCriteria = selectCriteria.find(':selected').closest('optgroup').attr('label');
- var nameTypeCriteria = $(selectCriteria).find('option[value=' + nameSelectCriteria + ']').attr('data-type');
- var objectTypeCondition = $(row).find('.js-' + nameTypeCriteria + '-condition');
- var nameInputDeclaration, nameSelectCondition = '';
- if (nameTypeCriteria == 'boolean') {
- nameSelectCondition = objectTypeCondition.find('.ui-state-active').attr('data-value');
- nameInputDeclaration = objectTypeCondition.find('.ui-state-active').find('a').attr("href").replace('#', '');
- } else {
- nameSelectCondition = objectTypeCondition.find('select[name=operator]').val();
- nameInputDeclaration = objectTypeCondition.find('input[name=val]').val();
- }
- var nomeCriteria = $(selectCriteria).find(':selected')[0].innerText;
- if ((nameSelectCriteria !== '') && (nameSelectCondition !== '') && (nameInputDeclaration !== '')) {
- dict.push({
- criteria: nameSelectCriteria,
- nameCriteria: nomeCriteria,
- groupCriteria: nameGroupCriteria,
- typeCriteria: nameTypeCriteria,
- condition: nameSelectCondition,
- value: nameInputDeclaration
- });
- }
- }
- }
- return dict;
- },
- insertRecentAudience: function (recentAudienceId) {
- var $template = $('#templateAudienceRecent'),
- $clone = $template
- .clone()
- .removeClass('hide')
- .removeAttr('id')
- .insertBefore($template);
- var amountData = $('.templateRowAudience').length - 1;
- var date = new Date();
- var month = ("0" + (date.getMonth() + 1)).slice(-2);
- var today = date.getDate() + '/' + month + '/' + date.getFullYear();
- var rangeLocalFormat = parseInt($("#rangeNumber").text()).toLocaleString(locale);
- $clone
- .find('input[type=checkbox]').attr('value', recentAudienceId).attr('checked', true).end()
- .find('input[id=audienceSelected]').attr('id', 'audienceSelected' + amountData).end()
- .find('label[for=audienceSelected]').attr('for', 'audienceSelected' + amountData).end()
- .find('[name="name"]').attr('name', 'nameAudience' + amountData).html($("#componentName").val()).end()
- .find('[name="size"]').attr('name', 'sizeAudience' + amountData).html(rangeLocalFormat).end()
- .find('[name="rank"]').attr('name', 'rankAudience' + amountData).html('-').end()
- .find('[name="dateCreation"]').attr('name', 'dateCreationAudience' + amountData).html(today).end();
- //update the range number
- var rangeFullNumber = parseInt($('.range-full-number').html()) + parseInt($("#rangeNumber").text());
- var rangeFullLocalFormat = rangeFullNumber.toLocaleString(locale);
- $('.range-full-number').html(rangeFullLocalFormat);
- $("#allAudiences").find('[id="sumSize"]').html(rangeFullLocalFormat);
- $('#qtRecipients').html(rangeFullLocalFormat);
- }
- };
- var charts = {
- jsChart: '',
- chartBg: '',
- chartCanvas: '',
- createDonutChart: function (context, value) {
- var chart = value == 0 ? 'doughnut' : 'RoundedDoughnut';
- Chart.defaults.RoundedDoughnut = Chart.helpers.clone(Chart.defaults.doughnut);
- Chart.controllers.RoundedDoughnut = Chart.controllers.doughnut.extend({
- draw: function (ease) {
- var ctx = this.chart.chart.ctx;
- var easingDecimal = ease || 1;
- Chart.helpers.each(this.getDataset().metaData, function (arc, index) {
- arc.transition(easingDecimal).draw();
- var vm = arc._view;
- var radius = (vm.outerRadius + vm.innerRadius) / 2;
- var thickness = (vm.outerRadius - vm.innerRadius) / 2;
- var angle = Math.PI - vm.endAngle - Math.PI / 2;
- ctx.save();
- ctx.fillStyle = vm.backgroundColor;
- ctx.translate(vm.x, vm.y);
- ctx.beginPath();
- ctx.arc(radius * Math.sin(angle), radius * Math.cos(angle), thickness, 0, 2 * Math.PI);
- ctx.arc(radius * Math.sin(Math.PI), radius * Math.cos(Math.PI), thickness, 0, 2 * Math.PI);
- ctx.closePath();
- ctx.fill();
- ctx.restore();
- });
- }
- });
- var deliveredData = {
- labels: [
- "Value"
- ],
- datasets: [
- {
- data: [value, (100 - value)],
- backgroundColor: [
- "#3ec556",
- "rgba(0,0,0,0)"
- ],
- hoverBackgroundColor: [
- "#3ec556",
- "rgba(0,0,0,0)"
- ],
- borderWidth: [
- 0, 0
- ]
- }]
- };
- var deliveredOpt = {
- cutoutPercentage: 88,
- animation: {
- animationRotate: true,
- duration: 1000
- },
- legend: {
- display: false
- },
- tooltips: {
- enabled: false
- }
- };
- this.jsChart = $('.js-chart');
- this.chartBg = $('.chart-background');
- this.chartCanvas = $('.chart-canvas');
- $(window).on('resize', function () {
- charts.resizeChartDiv();
- });
- return new Chart($(context), {
- type: chart,
- data: deliveredData,
- options: deliveredOpt
- });
- },
- resizeChartDiv: function () {
- charts.jsChart.each(function () {
- var width = $(this).width();
- $(this).height(width);
- charts.chartBg.each(function () {
- var width = charts.chartCanvas.width() * 0.065;
- $(this).css({borderWidth: width});
- })
- });
- }
- };
- var validate = {
- /**
- *
- * @param idValue id or OBJECT to be validated (must not be null or '')
- * @param message string message to be shown if there is error
- * @param redBox object [optional] where the red border is to be drawn. if not set will use the idValue
- * @param errorPosition object [optional] the message will be shown after this obj. if not set will use the idValue
- *
- * */
- field: function (idValue, message, redBox, errorPosition, setError) {
- var valid = true;
- var field = $(idValue);
- if (redBox != undefined) {
- var fieldBox = $(redBox);
- } else {
- fieldBox = $(idValue);
- }
- if (errorPosition != undefined) {
- var aboveError = $(errorPosition);
- } else {
- aboveError = $(idValue);
- }
- var errorElement = "<div class='has-error error-pad js-error'>" +
- "<span class='help-block'>" + message + "</span></div>";
- var jsError = aboveError.next('.js-error');
- //jsError.remove();
- fieldBox.off('focus.valid').on('focus.valid', function () {
- if (fieldBox.hasClass('error-outline')) {
- var jsError = aboveError.next('.js-error');
- fieldBox.removeClass('error-outline');
- fieldBox.one('blur', function () {
- if (field.val() == null || field.val() == '') {
- jsError.remove();
- fieldBox.addClass('error-outline');
- aboveError.after(errorElement);
- } else {
- // $('#error-pushContent').slideUp('fast');
- jsError.slideUp('fast', function () {
- this.remove();
- });
- // get rid of the error message at footer bar
- $('#footerError').fadeOut('fast', function () {
- $(this).html('');
- $(this).show();
- });
- }
- });
- }
- });
- if (field.val() == null || field.val() == '' || setError == true) {
- // $('i').after("<div class='has-error js-error' style='line-height: 3em;'><span class='help-block'>" + message + "</span></div>");
- jsError.remove();
- aboveError.after(errorElement);
- fieldBox.addClass('error-outline');
- valid = false;
- }
- return valid;
- },
- /**
- * To validate all fields at once. Pass an Array of arrays.
- * If is to validate using validate.field, then pass an array with the parameters for this function.
- * If it is a validation function, pass an array where the first element is the function name (without ()) and the
- * other elements are parameters (if needed).
- *
- * @param array array = [[idValue, message, redBox, errorPosition], [idValue, message], [function, param1, param2]]
- *
- * */
- multiFields: function (array) {
- var valid = [];
- var validated = true;
- $.each(array, function (index, obj) {
- if (typeof obj[0] === 'function') {
- var params = [];
- for (var i = 1; i < obj.length; i++) {
- params.push(obj[i]);
- }
- valid.push(obj[0].apply(this, params));
- } else {
- valid.push(validate.field(obj[0], obj[1], obj[2], obj[3]));
- }
- });
- $.each(valid, function (key, value) {
- if (!value) {
- validated = false;
- }
- });
- return validated;
- },
- fieldsAdditionalData: function () {
- var elements = $('#additionalBlock').find('.js-dataRow');
- var valid = [];
- var validated = true;
- $.each(elements, function (num, obj) {
- var keyObj = $(obj).find('input[name="additional-key"]');
- var valueObj = $(obj).find('input[name="additional-value"]');
- var key = keyObj.val();
- var value = valueObj.val();
- if (key != '' || value != '') {
- valid.push(validate.field(keyObj, 'Qual a chave?'));
- valid.push(validate.field(valueObj, 'Qual o valor?'));
- }
- });
- $.each(valid, function (key, value) {
- if (!value)
- validated = false;
- });
- return validated;
- },
- fieldsAudienceCriteria: function (mandatoryCriteria) {
- var elements = $(".js-condition-row");
- var valid = [];
- var validated = true;
- var atLeastOne = false;
- for (var i = 0; i < elements.length; i++) {
- var row = "#" + elements[i].id;
- var selectCriteria = $(row.replace("jsConditionRow", "select") + '0');
- //var nameGroupCriteria = selectCriteria.find(':selected').closest('optgroup').attr('label');
- if (selectCriteria.val() !== '' && mandatoryCriteria) {
- atLeastOne = true; // at least 1 criteria has to be set
- var nameTypeCriteria = $(selectCriteria).find('option[value=' + selectCriteria.val() + ']').attr('data-type');
- var objectTypeCondition = $(row).find('.js-' + nameTypeCriteria + '-condition');
- var selectCondition = objectTypeCondition.find('select[name=operator]');
- var inputDeclaration = objectTypeCondition.find('input[name=val]');
- if ($(selectCriteria).val() == '') {
- valid.push(validate.field(selectCriteria['selector'], 'Qual o critério?'),
- $(selectCriteria['selector']).nextAll('a'), $(selectCriteria['selector']).nextAll('a'));
- } else if ($(selectCondition).val() == '') {
- valid.push(validate.field(selectCondition, 'Qual a condição?',
- $(selectCondition).next('a'), $(selectCondition).next('a')));
- if ($(inputDeclaration).val() == '')
- valid.push(validate.field(inputDeclaration['selector'], 'Com o que vamos comparar?'));
- } else if ($(inputDeclaration).val() == '')
- valid.push(validate.field(inputDeclaration['selector'], 'Com o que vamos comparar?'));
- }
- }
- if (!atLeastOne) {
- row = "#" + elements[0].id;
- selectCriteria = $(row.replace("jsConditionRow", "select") + '0');
- if (!validate.field(selectCriteria['selector'], 'Precisamos de pelo menos um critério',
- $(selectCriteria['selector']).next('a'), $('.js-errorPosition').parent('span'))) {
- validated = false;
- }
- } else {
- $.each(valid, function (key, value) {
- if (!value)
- validated = false;
- });
- }
- return validated;
- },
- fieldCampaignAutomation: function (campaignId, automationId) {
- if (automationId == 0 && (campaignId == '' || campaignId == '0')) {
- validate.field('#campaign', 'Por favor, selecione uma campanha para automatizar', '#selectCampaign');
- return false;
- }
- return true;
- },
- /**
- * @param requireUsers boolean If the service needs audience with users (true) or not (false)
- * */
- fieldsAudienceCampaign: function (dontRequireUsers) {
- var elements = $(".list-checkbox");
- var valid = [];
- var validated = true;
- var qtAudiencesSelected = 0;
- for (var i = 0; i < elements.length; i++) {
- if ($('#audienceSelected' + i + ':checked').length > 0)
- qtAudiencesSelected += 1;
- }
- var qtSelected = $('.range-full-number').html();
- $(document).off('ajaxComplete.valid'); // remove ajax so it won't be bound twice if there is another error,
- // like audience with no users
- function showErrorMessage(text) {
- validated = false;
- valid.push(validate.field('label', text, $('none'), $('.table-be-table')));
- $('.js-audienceLabel').css({borderColor: '#EC7E7E'});
- $(document).on('ajaxComplete.valid', function (e, xhr, options) {
- validate.fieldsAudienceCampaign(); //validate again on audience selection
- if (options.url != '/handleSubscribersAudience') { //remove this handler if user change pages
- $(document).off('ajaxComplete.valid');
- }
- });
- }
- if (qtAudiencesSelected == 0) {
- showErrorMessage('Por favor, selecione uma audiência para enviar sua mensagem');
- } else if (qtSelected == 0 && !dontRequireUsers) {
- showErrorMessage('As audiências selecionadas não possuem usuários. Por favor, selecione outra.');
- } else {
- $('#audienceSelectTable').next('.js-error').remove();
- $('.js-audienceLabel').removeClass("error-outline").css({borderColor: ''});
- $('.push-row').find('input[type=checkbox]').off('change.error');
- }
- return validated;
- },
- quantitySubscribers: function (countSubscribers) {
- var valid = [];
- var validated = true;
- if (countSubscribers == 0) {
- // validated = false;
- // valid.push(validate.field('label', 'Não há nenhum usuário cadastrado para esse app'));
- // $('.has-error').css({marginTop: '-31px'});
- $('.list-checkbox').children('label').css({borderColor: '#EC7E7E'});
- $('#footerError').html('Não há nenhum usuário cadastrado.<br>Infelizmente não podemos enviar nenhum push.');
- $('#sendPushBtn').off('click').css({backgroundColor: '#b5b5b5', cursor: 'default'});
- } else {
- // $('.js-error').remove();
- // $('.list-checkbox').children('label').removeClass("error-outline").css({borderColor: ''});
- // $('.has-error').css({marginTop: ''});
- }
- return validated;
- }
- };
Add Comment
Please, Sign In to add comment