appice.controller('campaignsController',function ($scope, $sce ,appIceService,$routeParams,$location, $timeout, $window) {
    $scope.redirectQueryParams=new URLSearchParams(location.search)
    $scope.cshortUrl = {};
    $scope.leftCharacter = '';
    $scope.leftCharBottom = '0';
    $scope.isvariantManualType = false;
    $scope.booleanOptions = [  { label: 'True', value: true },  { label: 'False', value: false }];
    $scope.expandedNotificationImageFile = '';
    $scope.expandedNotificationImageFile2 = '';
    $scope.engageMentToolOpt = false;
    $scope.inAppSurvey       = true;
    $scope.inAppRate         = true;
    $scope.textMessage       = true;
    $scope.oldTemplateName = '';
    $scope.multiple_c_event  = false;
    $scope.day = [false, false, false, false, false, false, false];
    $scope.c_operator        = "AND";
    $scope.c_arr             =  [];
    $scope.allowedUrlList    = [] ;
    $scope.blobUrls          = [] ;
    $scope.textSms           = true;
    $scope.web_push          = false;
    $scope.checkedId         = '';
    $scope.active_pre        = "";
    $scope.show_mac_bg           = false;
    $scope.show_win_bg      =false;
    $scope.show_and_bg       = false;
    $scope.hide_mac          = true;
    $scope.hide_android      = true;
    $scope.hide_windows      = false;
    $scope.variantType = false;
    $scope.eventFlag = false;
    $scope.variantArr = [];
    $scope.totalVariantPer = 0;
    $scope.controlGroupValue = 0;
    $scope.defaultSliderTimeRange = ['0800','2000']
    $scope.gif_imgs = [];
    $scope.m = "" ;
    $scope.bu = "";
    $scope.img_type = "";
    $scope.frame_ext = "";
    $scope.btnFbSavePush = true;
    $scope.btnFbUpdatePush = false;
    $scope.fb = {};
    $scope.fb.ads_account = '';
    $scope.fb.pageId = '';
    $scope.fb.websiteurl = '';
    $scope.fb.heading = '';
    $scope.fb.message = '';
    $scope.fb_ads_image = '';
    $scope.user_role =localStorage.getItem('user_role');
    $scope.camp_state='';
    $scope.email_Camp = false 
    $scope.stringOperators = [{"text":"Equals","label":"eq"},{"text":"Not Equals","label":"ne"},{"text":"Contains","label":"contains"},{"text":"In (Set operator","label":"in"},{"text":"Not in (Set Operator)","label":"nin"},{"text":"Starts the String","label":"startsWith"},{"text":"Ends the String","label":"endsWith"},{"text":"Does not start the string","label":"doesnt startsWith"},{"text":"Does not end the string","label":"doesnt endsWith"}];	
    /* web pop object initiate */
    $scope.web_pop_obj = { 
        title : '',
        message : '',
        icon : false,
        url : '',
        mode : 'Box',
        ps : 'T-L',
        br : '',
    }
    $scope.web_push_obj = {
        title : '',
        message : '',
        icon : false,
        url : '',
    }
    var mergeTags = [
        {
            name: 'name',
            value: "{{userinfo.name}}"
        },
        {
            name: 'phone',
            value: '{{userinfo.phone}}'
        },
        {
            name: 'email',
            value: '{{userinfo.email}}'
        },
        {
            name: 'gender',
            value: '{{userinfo.gender}}' 
        },
        {
            name: 'age',
            value: '{{userinfo.age}}' 
        },
        {
            name: 'dob',
            value: '{{userinfo.dob}}' 
        },
        {
            name: 'profession',
            value: '{{userinfo.profession}}' 
        },
        {
            name: 'educationalQualifications',
            value: '{{userinfo.educationalQualifications}}' 
        },
        {
            name: 'employed',
            value: '{{userinfo.employed}}' 
        },
        {
            name: 'isMarried',
            value: '{{userinfo.isMarried}}' 
        }
    ];
    $scope.btnWebSavePush = true;
    $scope.btnWebUpdatePush = false;
    // end survey variable defining
    $scope.isConversion      = false;
    // push notificationapp
    $scope.action = {};
    $scope.action.actionType = 'dl';
    $scope.action.actionName = '';
    $scope.action.actionExternalUrl = '';
    $scope.actionStyle = false;
    $scope.ifActionIsYes = false;
    $scope.ifActionIsNo = true;
    $scope.webIfActionIsNo = true;
    //add array variant variable name
    $scope.variantVariableName = [];
    $scope.activeVariance = 0;
    $scope.savevariantdata = [];

    // deep link
    $scope.customDataStyle = false;
    $scope.isCustomData = false;
    $scope.customDataList = [
        {
            key:"",
            value:""
        }
    ]
    $scope.customData = [
        {
            type:"k",
            name:""
        }
    ];
    $scope.customDataVariant = [];
    $scope.customDataVariant[0] = [{
        key:"",
        value:""
    }];

    // add new customData 
    $scope.addCustomData = function(index){
        $scope.customDataList.push({
                key:"",
                value:""
            }
        );
        $scope.customDataList[index].isRemove = !$scope.customDataList[index].isRemove;
        $scope.customDataList =  $scope.customDataList;
       
    }
    $scope.addKeyValuePair = function(parentIndex,index){

        $scope.customDataList[parentIndex].value.push({
            jkey: "",
            jvalue: ""
        })
    }

    $scope.removeKeyValuePair = function(parentIndex,index){
        $scope.customDataList[parentIndex].value.splice(index,1)
    }
    
    $scope.onCdataTypeChange = function(selectedCustomType,parentIndex){
        if(selectedCustomType === "json"){

              $scope.customDataList[parentIndex].value  = [] 
              $scope.customDataList[parentIndex].value.push({
                jkey:"",
                jvalue:""
            })
        }else{
            $scope.customDataList[parentIndex].value  = ''
        }
    };

    // remove customData
    $scope.removeCustomData = function(index){
        $scope.customDataList.splice(index, 1);
    }

    // image height and width
    $scope.imgHeight = 60;
    $scope.imgWidth  = 60;
    $scope.validationMessage = false;
    $scope.validationErrorMessage = "";
    $scope.email = {};
    $scope.sms = {};
    $scope.tobj = {};
    $scope.template_url_error = '';
    $scope.template_title_error = '';
    $scope.template_message_error = ''

    // selected create new segment
    if (store.get("semusi_active_app")) {
        if (store.get("semusi_active_app")) {
            semusiCommon.ACTIVE_APP_KEY = store.get("semusi_active_api_key");
            $scope.ACTIVE_APP_NAME = store.get("semusi_active_appName");
            $scope.ACTIVE_APP_ICON = store.get("semusi_active_appIcon");
        }
    }

    init();

    function init(){
        getCustomVariables();
    }

       /**
     * setCustomdata method creates cdata array to represent it in UI ,  
     * @param {*} template ,can be any push, inapp template
     * @return {*} returns the cdata in a format in which it can be rendered in the UI
     */
    function setCustomdata(template){
        let newTemplate = template 
        newTemplate.template = Array.isArray(newTemplate.template) ? newTemplate.template[0] : newTemplate.template;
        const cdataArr = (Array.isArray(newTemplate.template.cdata)) ?  newTemplate.template.cdata : convertOldCdataIntoArr(newTemplate.template.cdata)

            // if it is already in right format set it and return 
            const isFormattCorrect = cdataArr.every(obj => obj.hasOwnProperty('key') && obj.hasOwnProperty('value') && obj.hasOwnProperty('type'));
            if (isFormattCorrect) {
                $scope.customDataList = cdataArr
                return 
            }
        
        $scope.customDataList = [];
        cdataArr.forEach(cObj => {
            const keys = Object.keys(cObj);
            const keyWithoutType = keys.find(key => key !== "type");

            // check if key is empty string
            if (keyWithoutType != "") {
                let obj = {
                    key: keyWithoutType,
                    type: cObj.type
                };

                //For string Cases we do encoding only
                if (cObj.type == "string") {
                    obj.value = decodeURIComponent(cObj[keyWithoutType])
                }else if (cObj.type == "image") {
                    const imgUrl = decodeURIComponent(cObj[keyWithoutType]);
                    obj.value = imgUrl.value !== undefined ? imgUrl.value : imgUrl;
                    $scope.isImageHidden = true;
                    $scope.isInputShown = true;
                }  
                else {
                    // For Rest Cases 
                    const value = JSON.parse(decodeURIComponent(cObj[keyWithoutType]));
                    obj.value = (cObj.type=="json") ? convertToObjectArray(value): value;
                }
        
            $scope.customDataList.push(obj);
               
            }
        });

    }

    /**
     * openAskWindow method opens the respective modal dyanmically,  
     * @param {*} 
     */
    $scope.openAskWindow = function(field,index){
      
        $scope.ImageType = field
        $scope.index = index
        $('#exampleModal'+index).modal('show');
    }
    
    $scope.openUrlInput = function(field){
        //show input and save button on URL type 
        $scope.urlbasedImgUpload = true

    }
    


    $scope.saveUserUrl = function (inputImgUrl) {
        // Function to check if the URL points to an image or gif or mp4
        function isImage(url) {
            return /\.(jpg|mp4|jpeg|png|webp|avif|gif|svg)$/.test(url);
        }

        // Show User that it is not a valid URL
        if (inputImgUrl == '' || !isImage(inputImgUrl)) {
            // Hide modal and show alert for invalid image URL
            showMessage("Please  enter a valid Image URL");
            $("#message").delay(3000).fadeOut(300);
            $("#exampleModal" + $scope.index).modal("hide");            
            return;
        }

        const baseURL = new URL(inputImgUrl).origin ;

        var url = inputImgUrl.split(baseURL)[1]
        var obj = { baseURL, url }
        let ext = /^.+\.([^.]+)$/.exec(inputImgUrl);
        let fileType = ext == null ? "" : ext[1];
        obj.type = fileType;


        const isPresentInAllowedUrl = $scope.allowedUrlList.includes(baseURL);
        const isPresentInBlobs = $scope.blobUrls.includes(baseURL);

        // Check if baseUrl is present in any of the arrays
        if (isPresentInAllowedUrl || isPresentInBlobs) {

            if (fileType == 'mp4') {
                const video = document.createElement('video');
                video.src = inputImgUrl; 

                // Listen for the 'loadeddata' event which is triggered when the first frame of the video has finished loading
                video.addEventListener('loadeddata', function () {
                    // Code to execute once the video is loaded
                    if ($scope.ImageType == "expandedNotify") {

                        const res = semusiCommon.validateImageDimension(this.videoWidth, this.videoHeight, semusiCommon.MIN_HEIGHT_PUSH_EXPANDEDNOTIFICATION, semusiCommon.MIN_WIDTH_PUSH_EXPANDEDNOTIFICATION, semusiCommon.MAX_HEIGHT_PUSH_EXPANDEDNOTIFICATION, semusiCommon.MAX_WIDTH_PUSH_EXPANDEDNOTIFICATION);
                        if (!res) {
                            return;
                        }
                    }

                    const notify = $scope.ImageType


                    if (notify == 'expandedNotify') {
                        $scope.exploderImg = false;
                        $scope.isFbAdsImg = true;
                        $('#expImguploader').hide();
                        $('#WebExpImguploader').hide();
                        $scope.expandedNotificationImageFile = '';
                        $scope.fb_ads_image = '';
                    }

                    $scope.commonFunctionUpload(obj, $scope.ImageType)
                });

            } else {
                const img = new Image()
                img.src = inputImgUrl
                img.onload = function () {
                    if ($scope.ImageType == "basicNotify" || $scope.ImageType == 'inAppImageFileheader' || $scope.ImageType == 'inAppImageFilefooter' || $scope.ImageType == "webpushfile") {
                        // ICON IMAGE
                        const res = semusiCommon.validateImageDimension(this.width, this.height, semusiCommon.MIN_HEIGHT_PUSH_NOTIFICATION, semusiCommon.MIN_WIDTH_PUSH_NOTIFICATION, semusiCommon.MAX_HEIGHT_PUSH_NOTIFICATION, semusiCommon.MAX_WIDTH_PUSH_NOTIFICATION)
                        if (!res) {
                            return
                        }
                    }
                    if ($scope.ImageType == "expandedNotify") {
                        // Expaneded IMAGE
                        const res = semusiCommon.validateImageDimension(this.width, this.height, semusiCommon.MIN_HEIGHT_PUSH_EXPANDEDNOTIFICATION, semusiCommon.MIN_WIDTH_PUSH_EXPANDEDNOTIFICATION, semusiCommon.MAX_HEIGHT_PUSH_EXPANDEDNOTIFICATION, semusiCommon.MAX_WIDTH_PUSH_EXPANDEDNOTIFICATION);
                        if (!res) {
                            return;
                        }
                    }


                    if ($scope.ImageType === 'inAppImagefullScreen') {
                         $scope.ImageType = 'inAppImageFilefullScreen';
                    }

                    if ($scope.ImageType == "inAppImageFilefullScreen") {
                        //inapp Fullscreen image

                        const res = semusiCommon.validateImageDimension(this.width, this.height, semusiCommon.MIN_HEIGHT_INAPP_FULLSCREEN, semusiCommon.MIN_WIDTH_INAPP_FULLSCREEN, semusiCommon.MAX_HEIGHT_INAPP_FULLSCREEN, semusiCommon.MAX_WIDTH_INAPP_FULLSCREEN);
                        if (!res) {
                            return;
                        }
                    }
                    if ($scope.ImageType === 'inAppImageMini') {
                        $scope.ImageType = 'inAppImageFilemini';
                   }
                    if ($scope.ImageType == "inAppImageFilemini") {
                        //inapp mini 
                        const res = semusiCommon.validateImageDimension(this.width, this.height, semusiCommon.SIZE_INAPP_MINISCREEN, semusiCommon.MIN_HEIGHT_INAPP_MINISCREEN, semusiCommon.MIN_WIDTH_INAPP_MINISCREEN, semusiCommon.MAX_HEIGHT_INAPP_MINISCREEN, semusiCommon.MAX_WIDTH_INAPP_MINISCREEN);
                        if (!res) {
                            return;
                        }
                    }


                    const notify = $scope.ImageType
                
                    if (notify == 'webPush' || notify == "webpushfile") {
                        $scope.ImageType = "webPush";
                        $scope.loderImg = false;
                    } else if (notify == 'basicNotify') {
                        $scope.loderImg = false;
                        $scope.notificationImageFile = '';
                        $scope.isBasicS3Img = true;
                        $scope.isBasicStaticImg = true;
                    } else if (notify == 'expandedNotify') {
                        $scope.exploderImg = false;
                        $('#expImguploader').hide();
                        $('#WebExpImguploader').hide();
                        $scope.expandedNotificationImageFile = '';
                    }

                    else if (notify == 'inAppIconImageFile' ||notify =='inAppImageHeader' ||  notify == "inAppImageFileheader" || notify == "inAppImageFilefooter" || notify == "inAppImageFilemini" || notify == "inAppImageFilefullScreen") {
                        $scope.ImageType = "inAppIconImageFile";
                        if ($scope.inApp.view_mode == "Fullscreen") {
                            $scope.fullScreenImgIcon = false;
                            $scope.isBasicStaticImgFull = true;
                        }
                        else if ($scope.inApp.view_mode == "Mini") {
                            $scope.inAppBasicS3Img = true;
                            $scope.miniScreenImgIcon = false;
                        }
                        else if ($scope.inApp.view_mode == "Header") {
                            $scope.inAppBasicS3ImgHeader = true;
                            $scope.headerScreenImgIcon = false;
                        }
                        else if ($scope.inApp.view_mode == "Footer") {
                            $scope.inAppBasicS3ImgFooter = true;
                            $scope.footerScreenImgIcon = false;
                        }

                        $scope.loderImg = false;
                    }


                    $scope.isBasicStaticImgInApp = true;
                    $scope.isExpendedImg = true;
                    $scope.urlbasedImgUpload = false
                    $scope.commonFunctionUpload(obj, $scope.ImageType)
                }

            }
        } else {
            showMessage("This CDN is not allowed as per content security policy. Please add them in Setting tab under campaign section");
            $("#message").delay(3000).fadeOut(300);
            $("#exampleModal" + $scope.index).modal("hide");
            return;
        }

    }
    function emailScreen(){
        if(semusiCommon.getEmailState){       
      setTimeout(function(){

        appIceService.getIEmailEditor().then(function(data){
            if(data){
                 token = data;
                 beeConfig = {
                    uid: '22', // [mandatory]
                    container: 'bee-plugin-container', // [mandatory]
                    autosave: 30, // [optional, default:false]
                    language: 'en-US',
                    trackChanges: true,
                    mergeTags,

                    workspace: {  // [optional, default: {type : 'default'}]
                        onSave: function (jsonFile, htmlFile) { },
                        onChange: function (jsonFile, response) { },
                        onSaveAsTemplate: function (jsonFile) { },
                        onAutoSave: function (jsonFile) { },
                        onSend: function (htmlFile) { },
                        onLoad: function (jsonFile) { },
                        onError: function (errorMessage) { },
                    }
                }
             BeePlugin.create(token, beeConfig, function (bee) {
                    bee.start({})
                    
                });

                beeConfig.onSave = function (jsonFile, htmlFile) {
                    if($scope.cTools.template_name == undefined || $scope.cTools.template_name == ''){
                        $scope.template_name_error = 'Please enter template name.';
                        $('#template_name_error').html('Please enter template name.')
                    
                    }else if( $('#subjectData').val() == '' || $('#subjectData').val() == '' == undefined){
                        $scope.template_name_error = 'Please enter subjectData';
                        $('#template_name_error').html('Please enter subjectData')
                    } else{
                    $('#template_name_error').html('')
                        var data = {
                            template_name: $scope.cTools.template_name,
                            template_type:'EMAIL',
                            template:{
                                subjectData : $('#subjectData').val(),
                                bodyHtmlData : htmlFile,
                                jsonData : jsonFile,                        
                            },
                            isTemplateDeleted:"false",
                            createdOn:semusiCommon.getCurrentDate(),
                            modifiedOn:"",
                        }
                    
                        appIceService.saveSettingsTools(data).then(function(data){
                            if(data != ''){
                                $scope.template_id = data._id;
                                $('#campaignwizard').bwizard('next');
                            }
                        });
                      }
                    }
                }
            });

        }, 500)
      }
    }
       /**
     *  convertOldCdataIntoArr function converts old cdata into newData format  
     * @param {*} data is a cdata from push or inapp template in old format
     * @return {*} returns the cdata in a new format.
     */
    function convertOldCdataIntoArr(data) {
        const dataArray = Object.entries(data).map(([key, value]) => ({
            [key]: value,
            type: "string"
        }));
        return dataArray
    }
    function getCustomVariables(){
        var promise = appIceService.getCustomVariables();
        promise.then(function(data) {
            $scope.customFields=[];
            if(data && data.result){
                data.result.forEach(function(item){
                   $scope.customFields.push({name:item.name.replace("_custom_","")}); 
                });
            }
        });
    }


    $scope.setPushVariables = function(){
        $scope.cTools = {};
        $scope.sound= false;
        $scope.vibrate= false;
        $scope.badge= false;
        $scope.isExpendedImg = false;
        $scope.cTools.defaultDevice = false;
        $scope.cTools.notifyType = false;
        $scope.cTools.expendedImg = false;
        $scope.cTools.expendedText = false;
        $scope.cTools.notificationType  = '';
        $scope.notificationImageFile = '';
        $scope.expandedNotificationImageFile = '';
        $scope.action = {};
        $scope.action.actionType = 'dl';
        $scope.expImgHeight = '';
        $scope.expImgWidth = '';
        $scope.actionStyle = false;
        //$scope.selectPushTemplate = '';
        $scope.isBasicS3Img = true;
        $scope.isBasicStaticImg = false;
        $scope.btnSavePush = false;
        $scope.btnUpdatePush = true;
        $scope.actionsList = [];
        setTimeout(function(){
            $('#actionStyle').bootstrapSwitch('state', false);
            $('#notificationType').bootstrapSwitch('state', false);
            $('#expendedImg').bootstrapSwitch('state', false);
            $('#sound').bootstrapSwitch('state', false);
            $('#vibrate').bootstrapSwitch('state', false);
            $('#badge').bootstrapSwitch('state', false);
            $('#isExpanded').hide();
            $('#txtExpanded').show();
        })
        $('#isBasicStaticImg').css('border','1px solid #2d353c')
    }

    /*$scope.clearTemplate = function(){
        $scope.selectTool($scope.templateType);
        $scope.setPushVariables();
        clearPushTemplate();
    }
    function clearPushTemplate(){
        //$scope.selectPushTemplate = '';
        $('#selectPushTemplate').val('');
    }*/

    $scope.setSurveyVariables = function(){
        $scope.surveyCounter    = 0;
        $scope.survey           = {};
        $scope.survey.state     = false;
        $scope.survey.surveyName= '';
        $scope.surveyQuestions  = [];
        $scope.isBack           = false;
        $scope.isNext           = false;
        $scope.surveyName_error = false;
        $scope.question_error   = false;
        $scope.isErrorMessage   = false;
        $scope.survey.otherOption = false;
        $scope.template_id      = '';
        $scope.surveyButton     = "Submit"; 
        surveyQuestionsInit();
        getAppTemplatesByType(type);        
    }

    $scope.setRatingVariables = function(){
        // defining rating variables
        $scope.starItems = [];
        $scope.ratingButton = 'Submit';
        $scope.appRating = {};
        $scope.appRating.action = 'Submit';
        $scope.activeImage = '', //'/images/dashboard/star-hover.png';
        $scope.disabledImage = '', //'/images/dashboard/star-empty.png';
        $scope.showRatingImg = ratingImg();
        getAppTemplatesByType(type);
    }

    $scope.setInAppVariables = function(){
          // in app preview
        $scope.inApp = {};
        $scope.inAppImgHeight = 48;
        $scope.inAppImgWidth  = 48;
        $scope.inAppImgHeightFull = 170;
        $scope.inAppImgWidthFull  = 220;
        $scope.inAppFullImageFile = '';
        $scope.fullScreenImgIcon = true;
        $scope.miniScreenImgIcon = true;
        $scope.headerScreenImgIcon = true;
        $scope.footerScreenImgIcon = true;
        $scope.inAppBasicS3Img = true;
        $scope.inAppBasicS3ImgHeader = true;
        $scope.inAppBasicS3ImgFooter = true;
        $scope.isBasicStaticImgFull = true;
        $scope.notificationImageFile = '';
        $scope.expandedImageInapp_ = false;
        $scope.inApp.view_mode = "Fullscreen";

        $scope.inApp.sCta = true;
        $scope.hideCta = true;
        $scope.inAppFull = true;
        $scope.inAppMini = false;
        $scope.header    = false;
        $scope.footer    = false;
        $scope.btnSaveInApp = false;

        $scope.inAppImages = {
            "Fullscreen":{
                    inactive: '/appimages/fullscreen.png',
                    active: '/appimages/fullscreen_on.png'
            },
            "Mini":{
                    inactive: '/appimages/mini.png',
                    active: '/appimages/mini_on.png'
            },
            "Header":{
                    inactive: '/appimages/header.png',
                    active: '/appimages/header_on.png'
            },
            "Footer":{
                    inactive: '/appimages/footer.png',
                    active: '/appimages/footer_on.png'
            }
        }

        $scope.inAppDefaultFullImg = $scope.inAppImages.Fullscreen.active;
        $scope.inAppDefaultMiniImg = $scope.inAppImages.Mini.inactive;
        $scope.inAppDefaultHeaderImg = $scope.inAppImages.Header.inactive;
        $scope.inAppDefaultFooterImg = $scope.inAppImages.Footer.inactive;

    }

    /*angular.element(document).ready(function () {
       $('#campIphonePreview').css('display','none');
       $('#campAndroidPreview').css('display','block');
    });*/
    
    $scope.openFileWindow = function(fileId){
        $("#"+fileId).click();
        if(fileId === "cDataImage"){
            document
            .getElementById("cDataImage")
            ?.addEventListener("change", function () {
              angular.element(this).scope().uploadcDataImg(this.files,"cDataImage");
            });
          document
            .getElementById("cDataImage")
            ?.addEventListener("click", function () {
              $(this).val("");
            });
        }
    }    

    $scope.markAllSelected = function () {
        if ($scope.selectedAll) {
            $scope.selectedAll = true;
        } else {
            $scope.selectedAll = false;
        }
        angular.forEach($scope.childApps, function (item) {
            item.selected = $scope.selectedAll;            
        });
    };

    $scope.deselectSelectedAllFlag = function(state){
        if(state==false){
            $scope.selectedAll =false;
        }
    }

    $scope.markAllApproved = function () {
        if ($scope.approvedAll) {
            $scope.approvedAll = true;
        } else {
            $scope.approvedAll = false;
        }
        angular.forEach($scope.childApps, function (item) {
            item.approved = $scope.approvedAll;            
        });
    };
    $scope.sliderVariance = 1;
    $scope.sliderStatus = function (val) {
        $scope.sliderVariance = val;
    }
    $scope.isVisible = false;
    $scope.controlGroupInput = function(val) {
        if($('#togControlGroup').is(':checked')){
            $scope.controlGroupValue = val;
            $scope.isVisible = true;
            $('#controlGroupNum').val(val);
            $scope.totalPer()
        } else {
            $scope.controlGroupValue = 0;
            $('#controlGroupNum').val(0);
            $scope.totalPer()
            $scope.isVisible = false;
        }

    }

    $scope.deselectApprovedAllFlag = function(state){
        if(state==false){
            $scope.approvedAll =false;
        }
    }
    $scope.saveCampaign = function(){
        $scope.isError=false;
                
        var childIds = [];
        angular.forEach($scope.childApps,function(item){
            if(item.selected){
                childIds.push({id:item.childappid,approved:(item.approved)?item.approved:false,deleted:(item.deleted)?item.deleted:false});
            }
        });     
        //Check if any of the child app is selected.
        if(childIds.length>0){
            $("#childapps-dialog").modal("hide");           
            //This function is defined in semusi.engagementtools.js
            saveCampaign(childIds); 
        }
        else{
            $scope.isError=true;
        }
        
    }

    $scope.saveCampaignDefault = function(){
        saveCampaign();   
    }

    $scope.cancel = function(){
        $scope.populateSelectedChildsApps();
        $scope.approvedAll=false;
        $scope.selectedAll =false;
        $scope.markAllSelected();
        $scope.markAllApproved();
    }

    // this case has to be handeled in edit campaign case in chield apps section//
    $scope.selectedChildIds = [];
    $scope.populateSelectedChildsApps = function(){
        //$scope.editMode = viewModel.editMode();
        var childIds = $scope.selectedChildIds;
        childIds.forEach(function(selectedId){
            angular.forEach($scope.childApps,function(item){
                if(item.childappid == selectedId.id && selectedId.deleted==false){
                    item.selected = true;
                    item.approved = selectedId.approved;
                    item.deleted = selectedId.deleted;
                    item.hide = true;
                }
            }); 
        });      
    }

    $scope.refreshCustomFields = function(field){
        getCustomVariables();
        if(! $scope.eventFlag){
            $scope.getEvents();
        }
        $scope.customFields.forEach(function(item){
            delete item['selected'];
            delete item['defaultValue'];
        });
        $scope.currentField = field;
        $scope.currentPostion = document.getElementById($scope.currentField).selectionStart;
        
    }

    $scope.cevent = {};
    $scope.embedCustomField =  function(){
        var embedText = "";
        $scope.customFields.forEach(function(item){
            if(item.selected==true){
                var value = (item.defaultValue!=undefined)?item.defaultValue:"";
                embedText += " <<"+item.name+":"+value+">> ";
            }
        });
        if($scope.cevent.selectedCheckbox){
            if($scope.cevent.selectedAttribute != '' && $scope.cevent.selectedAttribute!=undefined){
                embedText += " <<eventattribute:"+$scope.cevent.selectedAttribute+">> ";
            }else{
                embedText += " <<eventname:"+JSON.parse($scope.cevent.selectedEvent).event+">> ";
            }
        }
        var contents = $("#"+$scope.currentField).val();
        $("#"+$scope.currentField).val(contents.substring(0, $scope.currentPostion) + embedText + contents.substring($scope.currentPostion) ).change();
        $("#"+$scope.currentField).focus();
        $scope.cevent.selectedCheckbox = false;
        $scope.cevent.selectedAttribute = 0;
        $scope.cevent.selectedEvent = 0;
    }

/// Campaign EngageMenttools code start here ////
    $scope.engageMentTool = true;
    $scope.pushNotification = true;
    $scope.templateType = '';
    $scope.btnUpdatePush = true;
    $scope.btnSavePush = false;
    $scope.campaignId = '';
    $scope.template_id = '';
    $scope.lcamp = {};
    $scope.lcamp.stag = {}; 
    $scope.cTools = {};
    $scope.lcamp.editselectedDays = [];
    $scope.cTools.notificationType  = 'dl';
    $scope.lcamp.dlvy = 'a';
    $scope.lcamp.cy = 'e';
    $scope.lcamp.ft = 'o';
    $scope.lcamp.m = 'd';
    $scope.lcamp.AbTypeSelector = 'manual';
    // calling funtion before updating the value recieved of edited Campaign
    selectAllWeek();

    function fillFirstobj(obj) {
      // fill details of first event list
      $scope.eventLists.forEach(function (event) {
        if (event.event == obj.event) {
          $scope.c_event = event;
          $scope.c_period = obj.period;
          //if event has attribute
          if (obj.attr != undefined) {
            var attrList = event.list;
            // get attributes of the selected event
            $scope.c_attribute_list = attrList;
            attrList.forEach(function (attribute) {
              // get the details of selected attribute
              if (obj.attr == attribute.name) {
                $scope.c_eventAttribute = attribute; //fill attribute value
                $scope.c_event_attr_type = attribute.type;
                $scope.getSegementValueBox(attribute);
                $scope.c_event_operator = obj.operator; //fill operator
                $scope.c_event_operator_value = obj.value; //fill operator_value
              }
            });
          }
        }
      });
    }

    function fillSecondobj(obj, operator) {
      // open the second event section
      $scope.multiple_c_event = false;
      $scope.addSecondEvent();

      // set the operator between events
      if (operator == "OR") {
        $scope.conversionOperator = true;
      }

      // fill details of second event list
      $scope.eventLists.forEach(function (event) {
        if (event.event == obj.event) {
          $scope.c_event_2 = event;
          $scope.c_period_2 = obj.period;
          //if event has attribute
          if (obj.attr != undefined) {
            var attrList = event.list;
            // get attributes of the selected event
            $scope.c_attribute_list_2 = attrList;
            attrList.forEach(function (attribute) {
              // get the details of selected attribute
              if (obj.attr == attribute.name) {
                $scope.c_eventAttribute_2 = attribute;
                $scope.c_event_attr_type_2 = attribute.type;
                $scope.getSegementValueBox(attribute);
                $scope.c_event_operator_2 = obj.operator;
                $scope.c_event_operator_value_2 = obj.value;
              }
            });
          }
        }
      });
    }

    function fillConversionData(c_arr) {
        // if the data has two events then fill both 
      if (c_arr.length > 0 && c_arr.length == 2) {
        fillFirstobj(c_arr[0]);
        fillSecondobj(c_arr[1], c_arr[0].E_operator);
      } else if (c_arr.length == 1) {
    // if the data has only one event then fill firstEvent only  
        fillFirstobj(c_arr[0]);
      }
    }
    //check if the template id  and template type is  present in url go to next step (i,e: select audience)
    if($scope.redirectQueryParams.get("tid") && ($scope.redirectQueryParams.get("type") || $routeParams.type)){
         $scope.template_id=$scope.redirectQueryParams.get("tid")
         $scope.templateType=$scope.redirectQueryParams.get("type") || $routeParams.type
        setTimeout(()=>{
            $('#campaignwizard').bwizard('next');
           
        },100)
    }
   
    // For Campaign Edit Case using route params //
    if($routeParams && $routeParams.id && $routeParams.type){
        //check if type is WHATSAPP set type and go to next step
        if($routeParams.type=="WHATSAPP"){
            $scope.templateType=$routeParams.type
            setTimeout(()=>{
                $('#campaignwizard').bwizard('next');
               
            },100)
        }
        var cid = $routeParams.id;
        var type = $routeParams.type;
        selectToolByType($routeParams.type,$routeParams.id);
        var data = {
                d:true,
                ud:semusiCommon.getCurrentEpoch()
            };
        appIceService.getCampaignById(cid,data).then(function(data){

            if(data != ''){
                // hide the readOnly Sections for Active Edit Case 
                if(data.st == "ACTIVE"){
                $('.readOnly').css('pointer-events','none');
                $scope.camp_state ="ACTIVE"
               }
                $scope.lcamp.campaignName = data.nm ;
                $scope.lcamp.startDate = semusiCommon.getDateFromEpoch(parseInt(data.sd),false,true);
                $scope.lcamp.endDate = semusiCommon.getDateFromEpoch(parseInt(data.ed), true,true);
                $scope.lcamp.cmpexpiry = data.appinbox_et ? moment.utc(parseInt(data.appinbox_et) + (semusiCommon.getOffset() * 1000)).format(semusiCommon.getDateFormatt() + " HH:mm:ss"): '';
                $scope.campaignId = data._id;
                $scope.lcamp.cy = data.cy
                if(data.tid != ''){
                    $scope.selectPushTemplate = data.tid;
                    $scope.template_id =  $scope.templateType=="WHATSAPP"?($scope.template_id ||data.tid):data.tid;
                    $scope.clearTemplateId = data.tid;
                }
                if(data.abTypeRange) {
                    $scope.otherProbs = data.abTypeRange;
                }
                if(data.AbTypeSelector) {
                    $scope.lcamp.AbTypeSelector = data.AbTypeSelector
                }
                // During Edit Case
                if(data.dlvy){
                    $scope.lcamp.dlvy = data.dlvy;
                    // If dlvy type is direct only hide the appinbox expiry div
                    if (data.dlvy === "d") {
                        $("#appinboxexp").hide();
                    } else {
                        $("#appinboxexp").show();
                    }
                }
                if(data.controlGroup){
                    $scope.isChecked = true;
                    $('#togControlGroup').attr('checked', true);
                    $scope.controlGroupValue = data.controlGroup
                    $scope.isVisible = true;
                }
                if(data.email_cost){
                    $scope.email_cost = data.email_cost
                }
                if(data.aud != ''){
                    $scope.audienceSegmentId = data.aud;  
                    setTimeout(() => {
                        $scope.audienceSegmentId = data.aud;  
                        $('#segment_'+$scope.audienceSegmentId).addClass('active');
                        $('#select_'+data.aud).show();
                        $('#unselect_'+data.aud).hide();  
                    }, 300)   
                }
                if(data.stag){
                    if(data.stag.max_batch){
                        $scope.lcamp.stag.max_batch = data.stag.max_batch;
                    }
                    if(data.stag.time){
                        $scope.lcamp.stag.time = data.stag.time;
                    }
                    if(data.stag.t_unit){
                        $scope.lcamp.stag.t_unit = data.stag.t_unit;
                    }
                }
                if(data.childIds && data.childIds.length > 0 && data.childIds != undefined ){
                    $scope.selectedChildIds = data.childIds; 
                }
                // $scope.web_push_obj.title = '';
                // $scope.web_push_obj.message = '';
                // $scope.web_push_obj.icon = '';
                // set campaigs
                
                // if the campaigns is saved with new implementation as c_arr
                if(data.c_arr && data.c_arr.length != 0){
                    setTimeout(function(){ 
                        fillConversionData(data.c_arr)
                    }, 2000);      
                    $('#conversion_event').prop('checked', true);
                    $scope.isConversion = true;
                    $scope.isPopboxOpen = true;
                }else if(data.c_event){
                     // support for the existing campaigns which have c_event and c_period

                    setTimeout(function(){ 
                        $scope.c_event = data.c_event;
                        $scope.c_period = data.c_period;
                     }, 3000);      
                    $('#conversion_event').prop('checked', true);
                    $scope.isConversion = true;
                    $scope.isPopboxOpen = true;
                }

                $scope.frequency = data.fre;
                $scope.limitedTo = data.limitedTo;
                $scope.limitedToValue =data.limitVal;
                $scope.liveEvent = data.liveEvent;
                $scope.lcamp.daySelector =data.daySelector;
                $scope.lcamp.editselectedDays = data.days
                $scope.lcamp.selectedDays = (data.days.length>0)? "'"+data.days.join("','")+"'": [];
                // support for existing value , then turn specifictime into specific 
                $scope.lcamp.timeSelector = (data.timeSelector && data.timeSelector == "SPECIFICTIME") ? "SPECIFIC": data.timeSelector;
                $scope.lcamp.selectedTime = [];
                // $scope.lcamp.selectedTime = data.time.map(convertToTime)
                $scope.lcamp.selectedTime = data.time.t ? data.time.t.map(convertToTime) : $scope.defaultSliderTimeRange;
                // set delayed
                setTimeout(function(){
                    if(data.delays!=0){
                        $('#delayInterval').val(data.delayi);
                        $('#delayDurationUnit').val(data.delayu);
                        $('#rdbDelay').click();
                    }
                }, 1000)

                initTimeSlider();    
                bindWeekDaysOnEdit();
                setFrequency();
                hideDisabledFeature();
                $scope.getTemplateMetaData();
                if(data.data){
                    switch(data.data.template_type){
                        case "PUSH":
                            fillPushScreen(data.data);
                            //selectTool('PUSH',1);
                            break;
                        case "IN-APP":
                            fillInAppScreen(data.data);
                            //selectTool('IN-APP',2);
                            divId=2;
                            break;
                        case "SURVEY":
                            fillSurveyScreen(data.data);
                            break;
                        case "RATING":
                            fillRatingScreen(data.data);
                            break;
                        /*case "FEEDBACK":
                         fillFeedbackScreen(data.data);
                         selectTool('FEEDBACK',5);
                         divId=5;
                         break;*/
                         case "SMS":
                            $scope.template_id  =  data.data._id;
                            fillSmsScreen(data.data);
                            break; 
                         case "WEB_PUSH":
                            $scope.template_id  =  data.data._id;
                            fillWebPushScreen(data.data);
                            break;
                        case "WEB_POPUP":
                            $scope.template_id  =  data.data._id;
                            fillWebPopUpScreen(data.data);
                            break;
                        case "EMAIL":
                            $scope.template_id  =  data.data._id;
                            fillEmailScreen(data.data);
                            break;  
                        case "FACEBOOK_ADS":
                            $scope.template_id  =  data.data._id;
                            fillFbScreen(data.data);
                            break;          
                    }
                    /*$("#createCampaignDiv").show();
                     $("#homeCampaignDiv").hide();*/
                }
                else{
                    if(data.t == 'Email'){
                        $scope.tobj.messageSubject = data.m_sub;
                        $scope.tobj.messageContent = data.m_cont;
                        $scope.email.configuration = data.e_cfg;
                        $scope.sms.configuration = data.s_cfg;
                        $scope.template_id  = data._id;
                        $scope.textMessage  = false;
                        $scope.web_push = false;
                    }
                    else if(data.t == 'SMS'){
                        $scope.tobj.smsContent = data.m_cont;
                        $scope.email.configuration = data.e_cfg;
                        $scope.sms.configuration = data.s_cfg;
                        $scope.template_id  = data._id;
                        $scope.textSms  = false;
                        $scope.web_push = false;
                    }
                }
            }
        });    
    }

    // Edit Case for In-App Campaign tool///

    function fillInAppScreen(inAppTemplate){

        $scope.setInAppVariables();

         $scope.btnSaveInApp = true;
         $scope.btnUpdateInApp = false;
        if(inAppTemplate != ''){
            $scope.id = inAppTemplate._id;
            if(inAppTemplate.template_type != ''){
               $scope.templateType = inAppTemplate.template_type;    
            }else{
                $scope.templateType = '';
            }
            if(inAppTemplate.template_name != ''){
                $scope.inApp.template_name = inAppTemplate.template_name;
                $scope.oldTemplateName = inAppTemplate.template_name;
            }else{
                $scope.inApp.template_name = '';
            }
            if(inAppTemplate.template.view_mode != ''){
                $scope.inApp.view_mode = inAppTemplate.template.view_mode;
            }else{
                $scope.inApp.view_mode = '';
            }
            if(inAppTemplate.template.showAction ){
                $scope.$applyAsync(() => {
                    $scope.inApp.sCta = inAppTemplate.template.showAction;
                    $scope.setCta()
                });   
            }else{
                $scope.$applyAsync(() => {
                    $scope.inApp.sCta = false 
                    $scope.setCta()
                });   
            }

            // for edit case in-app handle btw deeplink and Landing Page
            if(inAppTemplate.template.notificationType && inAppTemplate.template.notificationType != "" ){
                if(inAppTemplate.template.notificationType == 'dl'){
                    $scope.cTools.notificationType = 'dl';
                    $scope.cTools.notifyType = false;

                }else if(inAppTemplate.template.notificationType == 'lp'){
                    $scope.cTools.notifyType = true;
                    $scope.cTools.notificationType = 'lp';
                }
            }
            if(inAppTemplate.template.actionUrl != ''){
                $scope.inApp.inAppActionUrl = inAppTemplate.template.actionUrl;
            }
            if(inAppTemplate.template.actionTitle != ''){
                $scope.inApp.inAppActionTitle = inAppTemplate.template.actionTitle;
            }

            if(inAppTemplate.template.headerTextClr != ''){
                $scope.inApp.headerTextClr = inAppTemplate.template.headerTextClr;
            }

            if(inAppTemplate.template.descriptionTextClr != ''){
                $scope.inApp.descriptionTextClr = inAppTemplate.template.descriptionTextClr;
            }

            if(inAppTemplate.template.submitBtnTextClr != ''){
                $scope.inApp.submitBtnTextClr = inAppTemplate.template.submitBtnTextClr;
            }

            if(inAppTemplate.template.backgroundColor != ''){
                $scope.inApp.backgroundColor = inAppTemplate.template.backgroundColor;
            }
            /* cdata fill for in-app */
            if(inAppTemplate.template.cdata && Object.keys(inAppTemplate.template.cdata).length > 0){
                setCustomdata(inAppTemplate)
                $scope.customDataStyle = true;
                $scope.isCustomData = true;
            }
            // set view mode
            $scope.changeViewMode(inAppTemplate.template.view_mode);
            if($scope.inApp.view_mode == 'Fullscreen'){
                $scope.inApp.inAppDescription = inAppTemplate.template.notificationDescription;
                $scope.inApp.inAppHeader = inAppTemplate.template.notificationHeader;
                if(inAppTemplate.template.notificationImage != ''){
                    $scope.isBasicStaticImgFull  = false;
                    $scope.inAppBasicS3Img       = true;
                    $scope.inAppBasicS3ImgFooter = true;
                    $scope.inAppBasicS3ImgHeader = true;
                    $scope.fullScreenImgIcon     = false;
                    if(isValidUrl(inAppTemplate.template.notificationImage)){
                        $scope.inAppFullImageFile    =  inAppTemplate.template.notificationImage;
                    }else{
                        $scope.inAppFullImageFile    = inAppTemplate.blobContainerCDN + inAppTemplate.template.notificationImage;
                    }
                }
            }
            else if($scope.inApp.view_mode == 'Mini'){
                $scope.inApp.inAppMiniDesc = inAppTemplate.template.notificationDescription;
                if(inAppTemplate.template.iconImage != ''){
                    $scope.inAppBasicS3Img = false;
                    $scope.inAppBasicS3ImgFooter = true;
                    $scope.isBasicStaticImgFull  = true;
                    $scope.inAppBasicS3ImgHeader = true;
                    $scope.miniScreenImgIcon     = false;
                    if(isValidUrl(inAppTemplate.template.iconImage)){
                        $scope.iconInAppImageFile    =  inAppTemplate.template.iconImage;
                    }else{
                        $scope.iconInAppImageFile = inAppTemplate.blobContainerCDN + inAppTemplate.template.iconImage;
                    }
                    
                }
            }
            else if($scope.inApp.view_mode == 'Header'){
                if(inAppTemplate.template.el ){
                    $('#expandedHeader').show();
                    $('#legacyHeader').hide();
                    $scope.$applyAsync(() => {
                        $scope.expandedImageInapp_ = inAppTemplate.template.el;
                       });
                }else{
                    $('#expandedHeader').hide();
                    $('#legacyHeader').show();
                    $scope.$applyAsync(() => {
                        $scope.expandedImageInapp_ = inAppTemplate.template.el;
                       });

                }

                $scope.inApp.inAppHeaderDesc = inAppTemplate.template.notificationDescription;
                if(inAppTemplate.template.iconImage != ''){
                    $scope.inAppBasicS3ImgHeader = false;
                    $scope.inAppBasicS3Img = true;
                    $scope.isBasicStaticImgFull  = true;
                    $scope.inAppBasicS3ImgFooter = true;
                    $scope.headerScreenImgIcon   = false;
                    if(isValidUrl(inAppTemplate.template.iconImage)){
                        $scope.iconInAppImageFileHeader =  inAppTemplate.template.iconImage;
                    }else{
                        $scope.iconInAppImageFileHeader = inAppTemplate.blobContainerCDN + inAppTemplate.template.iconImage;
                    }
                    
                }
            }
            else if($scope.inApp.view_mode == 'Footer'){
                
                if(inAppTemplate.template.el ){
                    $('#expandedFooter').show();
                    $('#legacyFooter').hide();
                    $scope.$applyAsync(() => {
                        $scope.expandedImageInapp_ = inAppTemplate.template.el;
                    });

                }else{
                    $('#expandedFooter').hide();
                    $('#legacyFooter').show();
                    $scope.$applyAsync(() => {
                        $scope.expandedImageInapp_ = inAppTemplate.template.el;
                    });

                }

                $scope.inApp.inAppFooterDesc = inAppTemplate.template.notificationDescription;
                if(inAppTemplate.template.iconImage != ''){
                    $scope.inAppBasicS3ImgFooter = false;
                    $scope.inAppBasicS3Img = true;
                    $scope.isBasicStaticImgFull  = true;
                    $scope.inAppBasicS3ImgHeader = true;
                    $scope.footerScreenImgIcon = false;
                    if(isValidUrl(inAppTemplate.template.iconImage)){
                        $scope.iconInAppImageFileFooter =  inAppTemplate.template.iconImage;
                    }else{
                        $scope.iconInAppImageFileFooter = inAppTemplate.blobContainerCDN + inAppTemplate.template.iconImage;
                    }
                    
                }
            }

        }
    }

     
  // Edit case for push campaign tool edit///
  function fillPushScreen(pushTemplate){
    if(pushTemplate.template.ty != "" && pushTemplate.template.ty != undefined ){
        $(document).ready(function() {
            $('#diff_col').show();
            $('#loop_col').show();
            $('#gap_col').show();
          });

          document.getElementById("diff").value = pushTemplate.template.and.d;
          document.getElementById("loop").value = pushTemplate.template.and.l;
          document.getElementById("gap").value = pushTemplate.template.and.g;
    }


    if (pushTemplate.template && pushTemplate.template.and) {
        if (pushTemplate.template.and.i) {
            $scope.gif_imgs = pushTemplate.template.and.i;
        }
        
        if (pushTemplate.template.and.b) {
            $scope.bu = pushTemplate.template.and.b;
        }
        
        if (pushTemplate.template.ty) {
            $scope.img_type = pushTemplate.template.ty;
        }
        
        if (pushTemplate.template.and.f) {
            $scope.frame_ext = pushTemplate.template.and.f;
        }
        
        if (pushTemplate.template.and.m) {
            $scope.m = pushTemplate.template.and.m;
        }
    }


    $scope.setPushVariables();
        $scope.btnSavePush = true;
        $scope.btnUpdatePush = false;
        $scope.id = pushTemplate._id;
        if (Array.isArray(pushTemplate.template)) {
            $scope.variantType = true;
            $scope.savevariantdata = pushTemplate.template;
            $scope.activeVariance = 0;
            $scope.cTools = $scope.savevariantdata[0];
            let obj = $scope.savevariantdata[0];
            if(obj['variance_name'] != undefined && obj['variance_name'] != $scope.cTools.template_name){
                $scope.cTools.template_name = obj['variance_name'];
            }
            if(!$scope.campaignId) $scope.setRangeSliderVariance($scope.savevariantdata, ($scope.controlGroupValue) ? $scope.controlGroupValue : 0);
            $scope.totalPer()
            $scope.cTools.template_name = pushTemplate.template_name
            $scope.oldTemplateName = pushTemplate.template_name;
            $scope.cTools.notificationHeader =  obj['notificationHeader'];
            $scope.cTools.notificationDescription = obj['notificationDescription'];
            $scope.cTools.expandedNotificationDescription = obj['expandedNotificationDescription'];
            if(obj['notificationImage'] != ''){
                if(isValidUrl(obj['notificationImage'])){
                    $scope.notificationImageFile =  obj['notificationImage'];
                }else{
                    $scope.notificationImageFile = pushTemplate.blobContainerCDN + obj['notificationImage'];  
                }
            } else {
                $scope.notificationImageFile = '';
            }
            if(obj['expandedNotificationImage'] != ''){
                if(isValidUrl(obj['expandedNotificationImage'])){
                    $scope.expandedNotificationImageFile = obj['expandedNotificationImage'];
                }else{
                    $scope.expandedNotificationImageFile = pushTemplate.blobContainerCDN +obj['expandedNotificationImage'];
                }
            } else {
                $scope.expandedNotificationImageFile = '';
            }
            if(obj['notificationImage']){
                $scope.isBasicS3Img = false;
                $scope.isBasicStaticImg = true;
            }

            if(obj['expandedNotificationImage'] != ''){
                $scope.cTools.expendedImg = true; 
                $scope.isExpendedImg = true;
                setTimeout(function(){
                    $('#txtExpanded').hide();
                    $('#isExpanded').show();
                    $('#pencilUpload').show();
                    $('#expImguploader').hide();
                    $scope.expImgHeight = 145;
                    $scope.expImgWidth = 240;
                    $('#isExpanded').css('height','145px');
                    $('#isExpanded').css('border','1px solid #2d353c');
                }, 200)

            }
            $scope.cTools.externalUrl = obj['externalUrl'];
            $scope.cTools.actionsList =obj['actionsList'];
            $scope.cTools.customDataList = obj['customDataList'];
            $scope.cTools.expendedImg = obj['expendedImg'];
            $scope.actionStyle =  obj['actionStyle'];
            $scope.sound = obj['sound'];
            $scope.vibrate =obj['vibrate'];
            $scope.badge = obj['badge'];
            $scope.cTools.notifyType = obj['notifyType'];
            
            //handle data if it is not object based (only for new formatt) 
            if(Array.isArray(pushTemplate.template[0].cdata)){
                $scope.customDataList = pushTemplate.template[0].cdata;
               }
                $scope.customDataVariant = [];
                if(pushTemplate.template.length == 2){
                    if(Array.isArray(pushTemplate.template[0].cdata)){
                        $scope.customDataVariant.push(pushTemplate.template[0].cdata);
                    }else{
                        $scope.customDataVariant.push(pushTemplate.template[0].customDataList);
                    }
                    if(Array.isArray(pushTemplate.template[1].cdata)){
                        $scope.customDataVariant.push(pushTemplate.template[1].cdata);
                    }else{
                        $scope.customDataVariant.push(pushTemplate.template[1].customDataList);
                    }
                    
                }
                $scope.variantArr = [];
                $scope.customDataVariant = [];
                pushTemplate.template.forEach((item) => {
                    if(item.variance_top_name.includes('Variant')){
                            $scope.variantArr.push({
                                name : item.variance_top_name,
                                _id : item.variance_id
                            });
                    }
                    $scope.customDataVariant.push(item.customDataList);
                })            
            //handle data if it is object based (support for Old formatt) 
                const cObject =   pushTemplate.template[0].cdata; 
                    pushTemplate.template.cdata = pushTemplate.template[0].cdata; 
                    if(cObject && Object.keys(cObject).length > 0){ 
                        
                        if(Array.isArray(cObject) && cObject[0] && cObject[0].type){
                            setCustomdata(pushTemplate)
    
                        }else{
                            $scope.showVariantPushData(0, 'PUSH', 'Multivariate')
                        }
                        $scope.customDataStyle = true;
                        $scope.isCustomData = true;
                }
        } else {
            $scope.variantArr = [];
            $scope.otherProbs = [];
            $scope.controlGroupValue = 0;
            $scope.variantType = false;
            $scope.savevariantdata = [];
            if(pushTemplate.template_name != ''){
                $scope.cTools.template_name = pushTemplate.template_name; 
                $scope.oldTemplateName = pushTemplate.template_name;
            }else{
                $scope.cTools.template_name = '';
            }
            if(pushTemplate.template_type != ''){
                $scope.templateType = pushTemplate.template_type;    
            }else{
                $scope.templateType = '';
            }
            if( pushTemplate.template.notificationHeader != ''){
                $scope.cTools.notificationHeader = pushTemplate.template.notificationHeader;    
            }else{
                $scope.cTools.notificationHeader = '';
            } 
            if(pushTemplate.template.notificationDescription != ''){
                $scope.cTools.notificationDescription = pushTemplate.template.notificationDescription;
            }else{
                $scope.cTools.notificationDescription = '';
                $scope.notificationImageFile = '';
            }
            if(pushTemplate.template.expandedNotificationDescription != ''){
                $scope.cTools.expendedText = true;
                $('#exptextdiv').show();
                $('#isExpanded').hide();
                $scope.cTools.expandedNotificationDescription = pushTemplate.template.expandedNotificationDescription;
            }else{
                $scope.cTools.expandedNotificationDescription = '';
                $scope.cTools.expendedText = false;
                $('#exptextdiv').hide();
                $('#isExpanded').show();
            }
            if(pushTemplate.template.notificationImage != ''){
                if(isValidUrl(pushTemplate.template.notificationImage)){
                    $scope.notificationImageFile =  pushTemplate.template.notificationImage;
                }else{
                    $scope.notificationImageFile = pushTemplate.blobContainerCDN + pushTemplate.template.notificationImage;
                }
               
            }else{
                $scope.notificationImageFile = '';

            }
            if(pushTemplate.template.expandedNotificationImage != ''){
                $('#txtExpanded').hide();

                    $('#isExpanded').show();
                    $('#pencilUpload').show();
                    $('#expImguploader').hide();
                $scope.expImgHeight = 145;
                if(isValidUrl(pushTemplate.template.expandedNotificationImage)){
                    $scope.expandedNotificationImageFile =  pushTemplate.template.expandedNotificationImage;
                }else{
                  // if and key is present and inside and m key is present 
                 if(pushTemplate.template.and && pushTemplate.template.and.m){
                    let ext = /^.+\.([^.]+)$/.exec(pushTemplate.template.and.m);
                    let fileType = ext == null ? "" : ext[1];
                    // if It IS MP4
                    if (fileType == 'mp4') {
                        $scope.expandedNotificationVideoFile = $sce.trustAsResourceUrl(pushTemplate.blobContainerCDN +  pushTemplate.template.expandedNotificationImage);
                    }else{
                          // Case Of GIF
                        $scope.expandedNotificationImageFile = pushTemplate.blobContainerCDN +  pushTemplate.template.expandedNotificationImage;
                    }
                    }else{
                        // Case of Norrmal Expanded 
                        $scope.expandedNotificationImageFile = pushTemplate.blobContainerCDN +  pushTemplate.template.expandedNotificationImage;
                    }
                }
                $scope.expImgWidth = 240;
               
            }else{
                $scope.expandedNotificationImageFile = '';
                $scope.expImgHeight = 0;
                $scope.expImgWidth = 0;
            }
            if($scope.cTools.expendedText == false){
                $scope.cTools.expandedNotificationDescription = "";
            }
            if($scope.cTools.expendedText == true){
                $scope.cTools.expandedNotificationDescription = pushTemplate.template.expandedNotificationDescription;
            }

            if(pushTemplate.template.pushType != ''){
                if(pushTemplate.template.pushType == "expanded"){
                    $scope.cTools.expendedImg = true; 
                    $scope.isExpendedImg = true; 
                    $('#txtExpanded').hide();

                    $('#isExpanded').show();
                    $('#isExpanded').css('height','145px');
                    $('#isExpanded').css('border','1px solid #2d353c');
                    $('#expImguploader').show();
                    $('#pencilUpload').show();
                }else{
                    $scope.cTools.expendedImg = false;
                    $('#txtExpanded').show();
                    $('#isExpanded').hide();
                    $('#isExpanded').css('border','none');
                    $('#isExpanded').css('height','0px');
                    $scope.isExpendedImg = false;
                    $('#pencilUpload').hide();
                }                
            }else{
                $scope.cTools.expendedImg = false;
            }

            if(pushTemplate.template.expandedNotificationImage != ''){
                setTimeout(function(){
                    $('#txtExpanded').hide();

                    $('#isExpanded').show();
                    $('#pencilUpload').show();
                    $('#expImguploader').hide();
                    if(isValidUrl(pushTemplate.template.expandedNotificationImage)){
                        $scope.expandedNotificationImageFile =  pushTemplate.template.expandedNotificationImage;
                    }else{
                        $scope.expandedNotificationImageFile = pushTemplate.blobContainerCDN + pushTemplate.template.expandedNotificationImage;
                    }
                    
                },500)
            }else{
                $scope.expandedNotificationImageFile = '';
            }
            

            if(pushTemplate.template.externalUrl != ''){
                $scope.cTools.externalUrl = pushTemplate.template.externalUrl;
                $('#external_Url_div').show();
            }else{
                $scope.cTools.externalUrl = '';
            }

            if($scope.notificationImageFile != ''){
                $scope.isBasicS3Img = false;
                $scope.isBasicStaticImg = true;
            }


            if(pushTemplate.template.actions.length > 0 && pushTemplate.template.notificationType == "" ){
                $scope.actionStyle = true;
                
                setTimeout(function() {
                    $('.ifActionIsYes').show(); 
                    $('#addActionBtn').show();                               
                    $('#ifActionIsNo').hide();
                    $('#webIfActionIsNo').hide();  
                }, 500);

                $scope.actionsList = pushTemplate.template.actions;
                var tempArr = [];
                
                angular.forEach(pushTemplate.template.actions, function(value,key){
                    tempArr.push({actionName:value.nh,actionType:value.et,actionExternalUrl:value.eurl})  
                })
                $scope.actionsList = tempArr;                              
            }else{
                $scope.actionStyle = false;
                setTimeout(function() {
                    $('.ifActionIsYes').hide();
                    $('#addActionBtn').hide();                               
                    $('#ifActionIsNo').show();
                    $('#webIfActionIsNo').show();  
                }, 500);                               
            }

            if(pushTemplate.template.actions.length == 0 &&pushTemplate.template.notificationType != ''){            
                if(pushTemplate.template.notificationType == 'dl'){
                    $scope.cTools.notificationType = 'dl';
                    $scope.cTools.notifyType = false;
                    $scope.actionStyle = false;
                    setTimeout(function(){
                        $('.ifActionIsYes').hide();                                
                        $('#ifActionIsNo').show();                                
                    },1100)
                }else if(pushTemplate.template.notificationType == 'lp'){
                    $scope.cTools.notifyType = true;
                    $scope.cTools.notificationType = 'lp';
                }
            }


            if(pushTemplate.template.actions.length == 2){
                setTimeout(function(){
                    $('.addAction').prop('disabled',true);
                },1000);
            }   

            /// Special Attribute Sound Edit Section////
            if(pushTemplate.template.sound != ''){
                if(pushTemplate.template.sound == true){
                    $scope.sound = true;
                }else{
                    $scope.sound = false;
                }                
            }
            /// Special Attribute Vibrate Edit Section////
            if(pushTemplate.template.vibrate != ''){
                if(pushTemplate.template.vibrate == true){
                    $scope.vibrate = true; 
                }else{
                    $scope.vibrate = false;
                }                
            }
            /// Special Attribute Vibrate Edit Section////
            if(pushTemplate.template.badge != ''){
                if(pushTemplate.template.badge == true){
                    $scope.badge = true; 
                }else{
                    $scope.badge = false; 
                }                
            }

            // custom data
            if(pushTemplate.template.cdata && Object.keys(pushTemplate.template.cdata).length > 0){
                setCustomdata(pushTemplate)

                $scope.customDataStyle = true;
                $scope.isCustomData = true;
            }
        }
    }

    function selectToolByType(type,id){
        //hide email part 
        initFilterTemplateSelect(type);
        onTemplateSelect();
        if(type == 'PUSH'){
            getPushCharLimit();
            hideDisabledFeature();
            $scope.templateType = type;
            $scope.pushNotification = false;
            $scope.engageMentTool = false;   
            $scope.inAppNotification = false;
            $scope.web_push          = false;
            $scope.web_popup       = false;
        }
        else if(type == 'IN-APP'){
            getAppTemplatesByType(type);
            $scope.inAppNotification = true;
            $scope.pushNotification = true;
            $scope.inAppRate      = true;
            $scope.engageMentTool = false;
            $scope.web_push          = false;
            $scope.web_popup       = false;
        }
        else if(type == 'SURVEY'){
            $scope.templateType = type;
            getAppTemplatesByType(type);
            $scope.pushNotification = true;
            $scope.inAppRate      = true;
            $scope.engageMentTool = false;  
            $scope.inAppSurvey    = false; 
            $scope.web_push          = false;
            $scope.web_popup       = false;
        }
        else if(type == 'RATING'){
            $scope.templateType = type;
            getAppTemplatesByType(type);
            $scope.pushNotification = true;
            $scope.engageMentTool = false;  
            $scope.inAppSurvey    = true;
            $scope.inAppRate      = false; 
            $scope.web_push          = false;
            $scope.web_popup       = false;
        }
        else if(type == "EMAIL"){
            //show this on email 
            $scope.email_Camp = true
            getAppTemplatesByType(type);
            $scope.cTools.template_name = '';
            $scope.templateType = type;
            $scope.email_screen = true;
            $scope.engageMentTool = false;
            $scope.inAppSurvey    = true;
            $scope.inAppRate      = true;
            $scope.textSms        = true;
            $scope.textMessage    = true;
            $scope.web_push       = false;
        }
        else if(type == "SMS"){
            $scope.cTools.template_name = '';
            $scope.tobj.smsContent = '';
            $scope.cTools.shortUrlSaved = '';
            $scope.btnSaveSms = false;
            $scope.btnUpdateSms = true;
            $scope.templateType = type;
            getShortUrls();
            getAppTemplatesByType(type);
            $scope.pushNotification = true;
            $scope.engageMentTool = false;
            $scope.inAppSurvey    = true;
            $scope.inAppRate      = true;
            $scope.web_popup       = false;
            $scope.web_push       = false;
            $scope.textSms  = false;
        }
        else if(type == "WEB_PUSH"){
            initiateOpenWindows();
            $scope.selectPushTemplate = '';
            $scope.web_push_obj.title = '';
            $scope.web_push_obj.message = '';
            $scope.web_push_obj.icon = '';
            $scope.web_push_obj.url = '';
            $scope.cTools.template_name = '';
            $scope.btnWebSavePush = true;
            $scope.btnWebUpdatePush = false;
            $scope.templateType = type;
            getAppTemplatesByType(type);
            $scope.pushNotification = true;
            $scope.engageMentTool = false;
            $scope.inAppSurvey    = true;
            $scope.inAppRate      = true;
            $scope.textSms        = true; 
            $scope.textMessage    = true;
            $scope.web_push       = true;
            $scope.web_popup       = false;
        }
        else if(type == "WEB_POPUP"){
            $scope.selectPushTemplate = '';
            $scope.web_pop_obj.mode = 'Box';
            $scope.web_pop_obj.title = '';
            $scope.web_pop_obj.message = '';
            $scope.web_pop_obj.icon = '';
            $scope.web_pop_obj.url = '';
            $scope.web_pop_obj.ps = 'T-L';
            $scope.web_pop_obj.br = '';
            $scope.web_pop_obj.bg = '';
            $scope.web_pop_obj.hc = '';
            $scope.web_pop_obj.dc = '';
            $scope.web_pop_obj.wh = '';
            $scope.cTools.template_name = '';
            $scope.btnWebPopUpSavePush = true;
            $scope.btnWebPopUpUpdatePush = false;
            $scope.templateType = type;
            getAppTemplatesByType(type);
            $scope.pushNotification = true;
            $scope.engageMentTool = false;
            $scope.inAppSurvey    = true;
            $scope.inAppRate      = true;
            $scope.textSms        = true; 
            $scope.textMessage    = true;
            $scope.web_popup       = true;
            $scope.web_push       = false;
        }
        else if(type == "FACEBOOK_ADS"){
            $scope.templateType = type;
            getAppTemplatesByType(type);
            $scope.pushNotification = true;
            $scope.engageMentTool = false;  
            $scope.inAppSurvey    = true;
            $scope.inAppRate      = true; 
            $scope.textSms        = true; 
            $scope.textMessage    = true; 
            $scope.web_push       = false;
            $scope.facebook_ads = true
            $scope.fb.ads_account = '';
            $scope.fb.pageId = '';
            $scope.fb.websiteurl = '';
            $scope.fb.heading = '';
            $scope.fb.message = '';
            $scope.fb_ads_image = '';
        }
    }

    //Trigger on template select from select filter
    function onTemplateSelect() {
        
        $('.template-select').on('select2:select', function (e) {
            let data = e.params.data;
            $scope.getAppTemplatesById(data.id)
        });
    }

    if($routeParams && $routeParams.aud == 'new'){
        if($routeParams.template_id != '' || $routeParams.template_id != undefined){
            selectToolByType($routeParams.templateType,$routeParams.template_id);
            getAppTemplatesById($routeParams.template_id);
            onTemplateSelect();
            $scope.selectPushTemplate = $routeParams.template_id;
            $scope.template_id = $routeParams.template_id;
        }
       
        setTimeout(function(){
            $('#campaignwizard').bwizard('next');
        },500);

        if($routeParams.aud_id != '' || $routeParams.aud_id != undefined){
            $scope.audienceSegmentId = '';
            setTimeout(function(){
                $scope.audienceSegmentId = $routeParams.aud_id; 
            },500)  
        }
    }

    //Initilize initSelect2 Filter
    function initFilterTemplateSelect(type) {
    startLoader('Loading necessary Resources')
    setTimeout(function(){
        $(".template-select").select2({
            ajax: {
                data:  $scope.jsonData,
                url: semusiCommon.API_PARTS.templates.r + '/getTemplatesByType',
                dataType: 'json',
                // delay: 250,
                data: function(params) {
                   
                   // search term
                    return {
                        app_id: semusiCommon.ACTIVE_APP_ID,
                        template_type: type,
                        query: params.term,  
                        api_key: semusiCommon.getActiveUser.api_key,
                        page: params.page,
                        pagination:true,
                        "uniqueNumber": semusiCommon.randomNumber(),
                    }
                },
                processResults: function(data, params, page) {
                    params.page = params.page || 1;
                    let results = data.result;
                    results = results.sort((a, b) =>{
                        let aCreatedAt = a.createdAt*1000
                        let bCreatedAt = b.createdAt*1000
                        return bCreatedAt-aCreatedAt;
                    })
                    return {
                        results: $.map(data.result, function(item) {
                            return {
                                text: item.template_name,
                                id: item._id
                            }
                            
                        }),
                        pagination: {
                            more: (params.page * 100) < data.total_count
                        }
                    };
                },
                cache: true
            },
            minimumInputLength: 0      
        })
        onTemplateSelect();
        endLoader()
    },1500) 
    }
    
    $scope.createWhatsappTemp=function(type){
        //check if type is WHATSAPP redirect to new panel
         if($scope.templateType=="WHATSAPP" || type=="WHATSAPP"){
            window.location= appiceEncode.encodePayload(`${semusiCommon.getPanelURL}/redirect/whatsapp/template/create?key=${store.get("semusi_active_api_key")}&id=${store.get("semusi_active_app")}${$scope.template_id?("&tid="+$scope.template_id):""}`+location.hash);
        }
       }
    $scope.selectTool = function(type){  
        if(type=="WHATSAPP"){
            $scope.createWhatsappTemp(type)
            return
        }
        $scope.selectPushTemplate = '';
        $scope.leftCharacter = '';
        initFilterTemplateSelect(type);
        $scope.getTemplateMetaData();
        onTemplateSelect();
        if(type == 'PUSH'){
            getPushCharLimit();
            hideDisabledFeature();
            $scope.setPushVariables();
            $scope.templateType = type;
            $scope.pushNotification = false;
            $scope.engageMentTool = false;   
            $scope.inAppNotification = false;
            $scope.inAppRate      = true; 
            $scope.customDataStyle = false;
            $scope.isCustomData = false;
            $scope.email_screen = false;
            $scope.customDataList = [
                {
                    key:"",
                    value:""
                }
            ];
            $scope.web_push       = false;
        }
        else if(type == 'IN-APP'){
            $scope.templateType = type;
            $scope.setInAppVariables();
            getAppTemplatesByType(type);
            $scope.inAppNotification = true;
            $scope.pushNotification = true;
            $scope.engageMentTool = false;
            $scope.inAppRate      = true; 
            $scope.web_push       = false;
            $scope.email_screen = false;
        }
        else if(type == 'SURVEY'){
            $scope.templateType = type;
            $scope.setSurveyVariables();
            getAppTemplatesByType(type);
            $scope.pushNotification = true;
            $scope.engageMentTool = false;  
            $scope.inAppSurvey    = false; 
            $scope.inAppRate      = true; 
            $scope.web_push       = false;
            $scope.email_screen = false;
        }
        else if(type == "RATING"){
            $scope.templateType = type;
            $scope.setRatingVariables();
            getAppTemplatesByType(type);
            $scope.pushNotification = true;
            $scope.engageMentTool = false;  
            $scope.inAppSurvey    = true;
            $scope.inAppRate      = false;  
            $scope.web_push       = false;
            $scope.email_screen = false;
        }
        else if(type == "EMAIL"){
            emailScreen()
            $scope.email_Camp = true
            getAppTemplatesByType(type);
            $scope.cTools.template_name = '';
            $scope.templateType = type;
            $scope.email_screen = true;
            $scope.engageMentTool = false;  
            $scope.inAppSurvey    = true;
            $scope.inAppRate      = true;
            $scope.textSms        = true; 
            $scope.textMessage    = true; 
            $scope.web_push       = false;
        }
        else if(type == "SMS"){
            $scope.cTools.template_name = '';
            $scope.tobj.smsContent = '';
            $scope.cTools.shortUrlSaved = '';
            $scope.templateType = type;
            $scope.btnSaveSms = false;
            $scope.btnUpdateSms = true;
            getShortUrls();
            getAppTemplatesByType(type);
            $scope.pushNotification = true;
            $scope.engageMentTool = false;
            $scope.inAppSurvey    = true;
            $scope.inAppRate      = true;
            $scope.web_push       = false;
            $scope.email_screen = false;
            $scope.textSms  = false;
        }
        else if(type == "WEB_PUSH"){
            initiateOpenWindows();
            $scope.selectPushTemplate = ''
            $scope.web_push_obj.title = '';
            $scope.web_push_obj.message = '';
            $scope.web_push_obj.icon = '';
            $scope.web_push_obj.url = '';
            $scope.cTools.template_name = '';
            $scope.btnWebSavePush = true;
            $scope.btnWebUpdatePush = false;
            $scope.templateType = type;
            getAppTemplatesByType(type);
            $scope.pushNotification = true;
            $scope.engageMentTool = false;
            $scope.inAppSurvey    = true;
            $scope.inAppRate      = true;
            $scope.textSms        = true; 
            $scope.textMessage    = true;
            $scope.web_push       = true;
            $scope.email_screen = false;
            $scope.template_url_error = '';
            $scope.template_title_error = '';
            $scope.template_message_error = '';
        }
        else if(type == "WEB_POPUP"){
            $scope.selectPushTemplate = '';
            $scope.web_pop_obj.mode = 'Box';
            $scope.web_pop_obj.title = '';
            $scope.web_pop_obj.message = '';
            $scope.web_pop_obj.icon = '';
            $scope.web_pop_obj.url = '';
            $scope.web_pop_obj.ps = 'T-R';
            $scope.web_pop_obj.br = '0';
            $scope.web_pop_obj.brType = '%';
            $scope.web_pop_obj.whType = 'px';
            $scope.web_pop_obj.bg = '#ffffff';
            $scope.web_pop_obj.hc = '#444444';
            $scope.web_pop_obj.dc = '#666666';
            $scope.web_pop_obj.wh = '';
            $scope.cTools.template_name = '';
            $scope.btnWebPopUpSavePush = true;
            $scope.btnWebPopUpUpdatePush = false;
            $scope.templateType = type;
            getAppTemplatesByType(type);
            $scope.pushNotification = true;
            $scope.engageMentTool = false;
            $scope.inAppSurvey    = true;
            $scope.inAppRate      = true;
            $scope.textSms        = true; 
            $scope.textMessage    = true;
            $scope.web_push       = false;
            $scope.web_popup       = true;
            $scope.email_screen = false;
            $scope.template_url_error = '';
            $scope.template_title_error = '';
            $scope.template_message_error = '';
        }
        else if(type == "FACEBOOK_ADS"){
            $scope.templateType = type;
            getAppTemplatesByType(type);
            $scope.pushNotification = true;
            $scope.engageMentTool = false;  
            $scope.inAppSurvey    = true;
            $scope.inAppRate      = true; 
            $scope.textSms        = true; 
            $scope.textMessage    = true; 
            $scope.web_push       = false;
            $scope.email_screen   = false;
            $scope.facebook_ads = true
            $scope.fb.ads_account = '';
            $scope.fb.pageId = '';
            $scope.fb.websiteurl = '';
            $scope.fb.heading = '';
            $scope.fb.message = '';
            $scope.fb_ads_image = '';
        }
    }
// this function sets the type of templates and redirects to the templates page
    $scope.editTemplate = function(type){  
        appIceService.tempType= type;
          window.location= encodeURI("/dashboard?action=camp#/temp");
        }
    // $scope.selectTool = function(type){  
    //     $scope.selectPushTemplate = '';
    //     $scope.leftCharacter = '';

    //     if(type == 'PUSH'){
    //         $scope.setPushVariables();
    //         getAppTemplatesByType(type);
    //         $scope.templateType = type;
    //         $scope.pushNotification = false;
    //         $scope.engageMentTool = false;   
    //         $scope.inAppNotification = false;
    //         $scope.inAppRate      = true; 
    //         $scope.customDataStyle = false;
    //         $scope.isCustomData = false;
    //         $scope.customDataList = [
    //             {
    //                 key:"",
    //                 value:""
    //             }
    //         ];
    //         $scope.web_push       = false;
    //     }
    //     else if(type == 'IN-APP'){
    //         $scope.templateType = type;
    //         $scope.setInAppVariables();
    //         getAppTemplatesByType(type);
    //         $scope.inAppNotification = true;
    //         $scope.pushNotification = true;
    //         $scope.engageMentTool = false;
    //         $scope.inAppRate      = true; 
    //         $scope.web_push       = false;
    //     }
    //     else if(type == 'SURVEY'){
    //         $scope.templateType = type;
    //         $scope.setSurveyVariables();
    //         getAppTemplatesByType(type);
    //         $scope.pushNotification = true;
    //         $scope.engageMentTool = false;  
    //         $scope.inAppSurvey    = false; 
    //         $scope.inAppRate      = true; 
    //         $scope.web_push       = false;
    //     }
    //     else if(type == "RATING"){
    //         $scope.templateType = type;
    //         $scope.setRatingVariables();
    //         getAppTemplatesByType(type);
    //         $scope.pushNotification = true;
    //         $scope.engageMentTool = false;  
    //         $scope.inAppSurvey    = true;
    //         $scope.inAppRate      = false;  
    //         $scope.web_push       = false;
    //     }
    //     else if(type == "Email"){
    //         $scope.templateType = type;
    //         $scope.pushNotification = true;
    //         $scope.engageMentTool = false;  
    //         $scope.inAppSurvey    = true;
    //         $scope.inAppRate      = true; 
    //         $scope.textSms        = true; 
    //         $scope.textMessage    = false; 
    //         $scope.web_push       = false;
    //     }
    //     else if(type == "SMS"){
    //         $scope.templateType = type;
    //         $scope.pushNotification = true;
    //         $scope.engageMentTool = false;
    //         $scope.inAppSurvey    = true;
    //         $scope.inAppRate      = true;
    //         $scope.textSms        = false; 
    //         $scope.textMessage    = true;
    //         $scope.web_push       = false;
    //     }
    //     else if(type == "WEB_PUSH"){
    //         $scope.selectPushTemplate = ''
    //         $scope.web_push_obj.title = '';
    //         $scope.web_push_obj.message = '';
    //         $scope.web_push_obj.icon = '';
    //         $scope.web_push_obj.url = '';
    //         $scope.cTools.template_name = '';
    //         $scope.btnWebSavePush = true;
    //         $scope.btnWebUpdatePush = false;
    //         $scope.templateType = type;
    //         getAppTemplatesByType(type);
    //         $scope.pushNotification = true;
    //         $scope.engageMentTool = false;
    //         $scope.inAppSurvey    = true;
    //         $scope.inAppRate      = true;
    //         $scope.textSms        = true; 
    //         $scope.textMessage    = true;
    //         $scope.web_push       = true;
    //         $scope.template_url_error = '';
    //         $scope.template_title_error = '';
    //         $scope.template_message_error = '';
    //     }
    //     else if(type == "WEB_POPUP"){
    //         $scope.selectPushTemplate = '';
    //         $scope.web_pop_obj.mode = 'Box';
    //         $scope.web_pop_obj.title = '';
    //         $scope.web_pop_obj.message = '';
    //         $scope.web_pop_obj.icon = '';
    //         $scope.web_pop_obj.url = '';
    //         $scope.web_pop_obj.ps = 'T-R';
    //         $scope.web_pop_obj.br = '0';
    //         $scope.web_pop_obj.brType = 'px';
    //         $scope.web_pop_obj.whType = 'px';
    //         $scope.web_pop_obj.bg = '#ffffff';
    //         $scope.web_pop_obj.hc = '#444444';
    //         $scope.web_pop_obj.dc = '#666666';
    //         $scope.web_pop_obj.wh = '';
    //         $scope.cTools.template_name = '';
    //         $scope.btnWebPopUpSavePush = true;
    //         $scope.btnWebPopUpUpdatePush = false;
    //         $scope.templateType = type;
    //         getAppTemplatesByType(type);
    //         $scope.pushNotification = true;
    //         $scope.engageMentTool = false;
    //         $scope.inAppSurvey    = true;
    //         $scope.inAppRate      = true;
    //         $scope.textSms        = true; 
    //         $scope.textMessage    = true;
    //         $scope.web_push       = false;
    //         $scope.web_popup       = true;
    //         $scope.template_url_error = '';
    //         $scope.template_title_error = '';
    //         $scope.template_message_error = '';
    //     }
    // }

    //array that contains the previous templates///
    $scope.pushTemplates = [];
    $scope.template_type = ''
    function getAppTemplatesByType (type){
        $scope.pushTemplates = [];
        appIceService.getAppTemplatesByType(type).then(function(data){
            if(data.result.length > 0){
                $('#selectPushTemplate').select2({
                    width: '35em'
                });
               $scope.email_cost_limit = (data.total_email_budget) ? parseInt(data.total_email_budget) : undefined 
                $scope.pushTemplates = data.result;
            }
        })
    }

    $scope.pushType = 'basic';
    $scope.isBasic = false;
    $scope.isExpanded = true;
   
    function getPushCharLimit (){
        appIceService.getPushCharLimit().then(function(data){
            if (data) {
             if(data.pushNotificationCharLimit){
                if (data.pushNotificationCharLimit.hl) {
                    let headerLimit = data.pushNotificationCharLimit.hl;
                    $('#notificationHeader').attr('maxlength', headerLimit);
                }

                if (data.pushNotificationCharLimit.dl) {
                    let descriptionLimit = data.pushNotificationCharLimit.dl;
                    $('.push_notification_description').attr('maxlength', descriptionLimit);
                }

                if (data.pushNotificationCharLimit.edl) {
                    let expDescriptionLimit = data.pushNotificationCharLimit.edl;
                    $('#expNotify-dis').attr('maxlength', expDescriptionLimit);
                    $('#expandedNotificationDescription').attr('maxlength', expDescriptionLimit);
                }
              }
            }
        })
    } 
     // below code is for SMS module
     function getShortUrls() {
        appIceService.getShortUrls().then(function(data) {
            if (data) {
                $scope.shortUrls = data.filter(item => item !== null && item !== undefined && item.shortUrl !== undefined && item.shortUrl !== null);
            }
        });
    };
    
    $scope.openShortUrlModal = function() {
        $('#shortUrlField').modal('show');
    };
    
    $scope.saveShortUrlSelected = function() {
        $('#shortUrlSaved').show();
        $scope.cTools.shortUrlSaved = $scope.cshortUrl.selectedShortUrl;
    };
    
    $scope.cursorPosition = 0; // Initialize cursor position
    
    $scope.onTextareaFocus = function() {
         var textarea = document.getElementById('messageContent');
         $scope.cursorPosition = textarea.selectionStart;
    };
    
    $scope.insertShortUrl = function() {
        var selectedUrl = $scope.cshortUrl.selectedShortUrl;
    
        if (selectedUrl) {
            var spaceToAdd = $scope.cursorPosition === 0 ? '' : ' ';
            var wrappedUrl = ' ' + selectedUrl;
    
            $scope.tobj.smsContent = [
                $scope.tobj.smsContent.slice(0, $scope.cursorPosition),
                $scope.tobj.smsContent.slice($scope.cursorPosition),
                spaceToAdd + wrappedUrl
            ].join('');
    
            $scope.cursorPosition += spaceToAdd.length + wrappedUrl.length;
        }
    };    
    ///function for uploading basic notification image of campaign ////
    $scope.uploadNotificationImage = function(files,basicNotify){
        var file = files[0];
        semusiCommon.validateImageSize('notificationImageFile',file,semusiCommon.SIZE_PUSH_NOTIFICATION,semusiCommon.MIN_HEIGHT_PUSH_NOTIFICATION,semusiCommon.MIN_WIDTH_PUSH_NOTIFICATION,semusiCommon.MAX_HEIGHT_PUSH_NOTIFICATION,semusiCommon.MAX_WIDTH_PUSH_NOTIFICATION, function(res){
            if(res){
                $scope.uploadCampaignImage(files,'basicNotify');
            }
        });
    }
    $scope.commonFunctionUpload = function(objWithURL,notify){
        
        $('#exampleModal'+$scope.index).modal('hide');  
        $('#inputImgUrl_'+$scope.index).val("")
        
        $timeout(function() {
            
            document.getElementById("btnUpdatePush").disabled = false;

            let data = objWithURL.baseURL + objWithURL.url;    //image url and base url merge for image display
            if (objWithURL.type === "gif" || objWithURL.type === "mp4") {
                if (objWithURL.type === "gif") {
                    let gif_imgs = objWithURL.imgs.map(imgUrl => imgUrl.replace(/\.png$/, '')); //frame extenion output after uploading the gif will be in .png
                    $scope.gif_imgs = gif_imgs;
                }
                $scope.bu = objWithURL.baseURL;
                $scope.m = data;
                $scope.img_type = "asb"
                $scope.frame_ext = objWithURL.fe;
                $('#diff_col').show();
                $('#loop_col').show();
                $('#gap_col').show();
            } else {
                $scope.img_type = ""
                $('#diff_col').hide();
                $('#loop_col').hide();
                $('#gap_col').hide();
            }
            if(data){
                if(notify == 'webPush'){
                    $scope.loderImg = true;
                    $scope.web_push_obj.icon = data;
                }else if(notify == 'basicNotify'){
                    $scope.isBasicS3Img = false;
                    $scope.loderImg = true;
                    $scope.notificationImageFile = data;
                }else if(notify == 'expandedNotify'){
                    $scope.isExpendedS3Img = false;
                    $scope.loderImg = true;
                    $('#pencilUpload').show();
                    $scope.exploderImg = true;
                    $scope.isExpendedImg = true;
                    $scope.fb_ads_image = data;
                    if(objWithURL.type === "mp4"){
                        $scope.$applyAsync(() => {
                            $scope.expandedNotificationVideoFile = $sce.trustAsResourceUrl(data);
                            $scope.expandedNotificationImageFile = data
                           });                      
                    }else{
                        $scope.expandedNotificationVideoFile = '';
                        $scope.expandedNotificationImageFile = data;
                    }
                    $scope.expandedNotificationImageFile2 = data;
                }else if(notify == 'inAppImageFile'){
                    $scope.loderImg = true;
                    $scope.isBasicS3Img = false;
                    $scope.inAppnotificationImageFile = data;
                }
                else if(notify == 'cDataImage'){
                   var newDataObject = {
                       value: data
                   };
               
                   if (!$scope.cdataImgData) {
                       $scope.cdataImgData = [];
                   }
               
                   $scope.cdataImgData.push(newDataObject);
                }
                else if(notify == 'inAppIconImageFile'){
                    $scope.loderImg = true;
                    if($scope.inApp.view_mode == "Fullscreen"){
                        $scope.isBasicStaticImgFull = false;
                        $scope.inAppFullImageFile = data;
                    }
                    else if($scope.inApp.view_mode == "Mini"){
                        $scope.inAppBasicS3Img = false;
                        $scope.iconInAppImageFile = data;
                    }
                    else if($scope.inApp.view_mode == "Header"){
                        $scope.inAppBasicS3ImgHeader = false;
                        $scope.iconInAppImageFileHeader = data;
                    }
                    else if($scope.inApp.view_mode == "Footer"){
                        $scope.inAppBasicS3ImgFooter = false;
                        $scope.iconInAppImageFileFooter = data;
                    }

                    
                }
                else if(notify == 'ratingActiveImageFile'){
                    $scope.loderImg = true;
                    $scope.activeImage = data;
                }
                else if(notify == 'ratingDisabledImageFile'){
                    $scope.loderImg = true;
                    $scope.disabledImage = data;
                    $scope.showRatingImg = ratingImg();
                }
            }
          }, 1000)
    }

      ///function for uploading basic notification image of campaign ////
    $scope.uploadWebPushIcon = function(files,basicNotify){
        var file = files[0];
        semusiCommon.validateImageSize('notificationImageFile',file,semusiCommon.SIZE_PUSH_NOTIFICATION,semusiCommon.MIN_HEIGHT_PUSH_NOTIFICATION,semusiCommon.MIN_WIDTH_PUSH_NOTIFICATION,semusiCommon.MAX_HEIGHT_PUSH_NOTIFICATION,semusiCommon.MAX_WIDTH_PUSH_NOTIFICATION, function(res){
        if(res){
                $scope.uploadCampaignImage(files,'webPush');
            }
        });
     }


     // Funciton for uplaoding upload expended campaign image///
     $scope.uplodExpendedImg = function(files,expendednotify){
        var file = files[0];
        semusiCommon.validateImageSize('expandedNotify',file,semusiCommon.SIZE_PUSH_EXPANDEDNOTIFICATION,semusiCommon.MIN_HEIGHT_PUSH_EXPANDEDNOTIFICATION,semusiCommon.MIN_WIDTH_PUSH_EXPANDEDNOTIFICATION,semusiCommon.MAX_HEIGHT_PUSH_EXPANDEDNOTIFICATION,semusiCommon.MAX_WIDTH_PUSH_EXPANDEDNOTIFICATION, function(res){
            if(res){
                $scope.uploadCampaignImage(files,'expandedNotify');
            }
        });
     }
     
        // Funciton for uplaoding upload cdata image///
        $scope.uploadcDataImg = function(files,cDataImage){
          var file = files[0];
          semusiCommon.validateImageSize('cDataImage',file,semusiCommon.SIZE_PUSH_EXPANDEDNOTIFICATION,semusiCommon.MIN_HEIGHT_PUSH_EXPANDEDNOTIFICATION,semusiCommon.MIN_WIDTH_PUSH_EXPANDEDNOTIFICATION,semusiCommon.MAX_HEIGHT_PUSH_EXPANDEDNOTIFICATION,semusiCommon.MAX_WIDTH_PUSH_EXPANDEDNOTIFICATION, function(res){
              if(res){
                  $scope.uploadCampaignImage(files,'cDataImage');
              }
          });
       }

     $scope.uploadExpendedInAppImage = function(files,inAppImageFile){
        var file = files[0];
        semusiCommon.validateImageSize('inAppImageFile',file,semusiCommon.SIZE_INAPP_FULLSCREEN,semusiCommon.MIN_HEIGHT_INAPP_FULLSCREEN,semusiCommon.MIN_WIDTH_INAPP_FULLSCREEN,semusiCommon.MAX_HEIGHT_INAPP_FULLSCREEN,semusiCommon.MAX_WIDTH_INAPP_FULLSCREEN, function(res){
            if(res){
                $scope.uploadCampaignImage(files,'inAppImageFile');
            }
        });
     }

     $scope.uploadExpendedInAppImageHeaderFooter = function(files,inAppIconImageFile){
        var file = files[0];
        semusiCommon.validateImageSize('inAppIconImageFile',file,semusiCommon.SIZE_INAPP_EXP_HEADER_FOOTER,semusiCommon.MIN_HEIGHT_INAPP_EXP_HEADER_FOOTER,semusiCommon.MIN_WIDTH_INAPP_EXP_HEADER_FOOTER,semusiCommon.MAX_HEIGHT_INAPP_EXP_HEADER_FOOTER,semusiCommon.MAX_WIDTH_INAPP_EXP_HEADER_FOOTER, function(res){
            if(res){
                $scope.uploadCampaignImage(files,'inAppIconImageFile');
            }
        });
     }


     $scope.uploadInAppImageFile =  function(files,inAppIconImageFile){
        var file = files;
        semusiCommon.validateInAppImageSize('inAppIconImageFile', file,semusiCommon.SIZE_INAPP_FULLSCREEN,semusiCommon.MIN_HEIGHT_INAPP_FULLSCREEN,semusiCommon.MIN_WIDTH_INAPP_FULLSCREEN,semusiCommon.MAX_HEIGHT_INAPP_FULLSCREEN,semusiCommon.MAX_WIDTH_INAPP_FULLSCREEN, function(res){
            if(res){
                $scope.uploadMultiCampaignImage(files,'inAppIconImageFile');   
            }
        });
     }

     $scope.uploadInAppIconImg =  function(files,inAppIconImageFile){
        var file = files[0];
        semusiCommon.validateImageSize('inAppIconImageFile',file,semusiCommon.SIZE_INAPP_ICONSCREEN,semusiCommon.MIN_HEIGHT_INAPP_ICONSCREEN,semusiCommon.MIN_WIDTH_INAPP_ICONSCREEN, semusiCommon.MAX_HEIGHT_INAPP_ICONSCREEN,semusiCommon.MAX_WIDTH_INAPP_ICONSCREEN, function(res){
            if(res){
                $scope.uploadCampaignImage(files,'inAppIconImageFile');   
            }
        });
     }

    $scope.uploadInAppMiniImg =  function(files,inAppIconImageFile){
        var file = files[0];
        semusiCommon.validateImageSize('inAppIconImageFile',file,semusiCommon.SIZE_INAPP_MINISCREEN,semusiCommon.MIN_HEIGHT_INAPP_MINISCREEN,semusiCommon.MIN_WIDTH_INAPP_MINISCREEN, semusiCommon.MAX_HEIGHT_INAPP_MINISCREEN,semusiCommon.MAX_WIDTH_INAPP_MINISCREEN, function(res){
            if(res){
                $scope.uploadCampaignImage(files,'inAppIconImageFile');   
            }
        });
    }

    $scope.uploadInAppRatingIcon =  function(files, type){
        var file = files[0];
        semusiCommon.validateImageSize(type,file,semusiCommon.SIZE_RATING_ICON,semusiCommon.MIN_HEIGHT_RATING_ICON,semusiCommon.MIN_WIDTH_RATING_ICON,semusiCommon.MAX_HEIGHT_RATING_ICON,semusiCommon.MAX_WIDTH_RATING_ICON, function(res){
            if(res){
                $scope.uploadCampaignImage(files,type);  
            }   
        });
     }

    ///function for uploading basic web  pop up  notification image of campaign ////
    $scope.uploadWebPopUpIcon = function(files,basicNotify){
        var file = files[0];
        semusiCommon.validateImageSize('notificationImageFile',file,semusiCommon.SIZE_POP_NOTIFICATION,semusiCommon.MIN_HEIGHT_POP_NOTIFICATION,semusiCommon.MIN_WIDTH_POP_NOTIFICATION,semusiCommon.MAX_HEIGHT_POP_NOTIFICATION,semusiCommon.MAX_WIDTH_POP_NOTIFICATION, function(res){
            if(res){
                $scope.uploadCampaignImage(files,'webPopUp');
            }
        });
     }
     $scope.uploadWebPopUpBannerIcon = function(files,basicNotify){
        var file = files[0];
        semusiCommon.validateImageSize('notificationImageFile',file,semusiCommon.SIZE_PUSH_NOTIFICATION,semusiCommon.MIN_HEIGHT_PUSH_NOTIFICATION,semusiCommon.MIN_WIDTH_PUSH_NOTIFICATION,semusiCommon.MAX_HEIGHT_PUSH_NOTIFICATION,semusiCommon.MAX_WIDTH_PUSH_NOTIFICATION, function(res){
        if(res){
                $scope.uploadCampaignImage(files,'webPopUpBanner');
            }
        });
     }

    //Upload Campaign Image Section Using services///
    $scope.isBasicStaticImg = false;
    $scope.isBasicStaticImgInApp = false;
    $scope.isBasicS3Img = true;
    $scope.isExpendedImg = false;
    $scope.isExpendedS3Img = true;
    $scope.loderImg = true;
    $scope.exploderImg = true;

    $scope.uploadCampaignImage = function(files,notify) {
        //var imageFile = $('.'+imgClass).get(0).files;   
        var imageFile = files;    
        var imageFile = files;        

         if(imageFile.length >= 1 )  
         {
            d = new Date();
            if(notify == 'webPush'){
                $scope.loderImg = false;
            }else if(notify == 'webPopUp'){
                $scope.loderImg = false;
            }else if(notify == 'webPopUpBanner'){
                $scope.loderImg = false;
            }
            else if(notify == 'basicNotify'){
                $scope.loderImg = false;   
                $scope.isFbAdsImg = true;
                $scope.notificationImageFile = '';
                $scope.fb_ads_image = '';
                $scope.isBasicS3Img = true;
                $scope.isBasicStaticImg = true;
            }else if(notify == 'expandedNotify'){
               $scope.exploderImg = false;
               $scope.isFbAdsImg = true;
               $('#expImguploader').hide();
               $('#WebExpImguploader').hide();
               $scope.expandedNotificationImageFile = '';
               $scope.fb_ads_image = '';
            }

            else if(notify == 'inAppIconImageFile'){

                if($scope.inApp.view_mode == "Fullscreen"){
                    $scope.fullScreenImgIcon = false;
                    $scope.isBasicStaticImgFull = true;
                }
                else if($scope.inApp.view_mode == "Mini"){
                    $scope.inAppBasicS3Img = true;
                    $scope.miniScreenImgIcon = false;
                }
                else if($scope.inApp.view_mode == "Header"){
                    $scope.inAppBasicS3ImgHeader = true;
                    $scope.headerScreenImgIcon = false;
                }
                else if($scope.inApp.view_mode == "Footer"){
                    $scope.inAppBasicS3ImgFooter = true;
                    $scope.footerScreenImgIcon = false;
                }
                
                $scope.loderImg = false;
            }
           
          /*  $scope.isBasicS3Img = true;
            $scope.isBasicStaticImg = true;*/
           // $scope.loderImg = false;

            $scope.isBasicStaticImgInApp = true;
            $scope.isExpendedImg = true;
            var fd = new FormData();
            fd.append('image', imageFile[0]);                              
            fd.append('image_id',imageFile[0].name);  
            fd.append('appid',semusiCommon.ACTIVE_APP_ID);   
            appIceService.uploadCampaignImage(fd).then(function(objWithURL){
                $scope.commonFunctionUpload(objWithURL,notify)
            }) 
        }
    }

    $scope.uploadMultiCampaignImage = function(files,notify) {  
        var imageFile = files;
        $scope.responseImages=[];  
        
        for(var i=0;i<imageFile.length;i++){
            
               d = new Date();
               if(notify == 'webPush'){
                   $scope.loderImg = false;
               }else if(notify == 'basicNotify'){
                   $scope.loderImg = false;   
                   $scope.notificationImageFile = '';
                   $scope.isBasicS3Img = true;
                   $scope.isBasicStaticImg = true;
               }else if(notify == 'expandedNotify'){
                  $scope.exploderImg = false;
                  $('#expImguploader').hide();
                  $scope.expandedNotificationImageFile = '';
               }
   
               else if(notify == 'inAppIconImageFile'){
   
                   if($scope.inApp.view_mode == "Fullscreen"){
                       $scope.fullScreenImgIcon = false;
                       $scope.isBasicStaticImgFull = true;
                   }
                   else if($scope.inApp.view_mode == "Mini"){
                       $scope.inAppBasicS3Img = true;
                       $scope.miniScreenImgIcon = false;
                   }
                   else if($scope.inApp.view_mode == "Header"){
                       $scope.inAppBasicS3ImgHeader = true;
                       $scope.headerScreenImgIcon = false;
                   }
                   else if($scope.inApp.view_mode == "Footer"){
                       $scope.inAppBasicS3ImgFooter = true;
                       $scope.footerScreenImgIcon = false;
                   }
                   
                   $scope.loderImg = false;
               }
              
             /*  $scope.isBasicS3Img = true;
               $scope.isBasicStaticImg = true;*/
              // $scope.loderImg = false;
   
               $scope.isBasicStaticImgInApp = true;
               $scope.isExpendedImg = true;
               var fd = new FormData();
               fd.append('image', imageFile[i]);                              
               fd.append('image_id',imageFile[i].name);  
               fd.append('appid',semusiCommon.ACTIVE_APP_ID);   
               appIceService.uploadCampaignImage(fd).then(function(objWithURL){
                     $scope.commonFunctionUpload(objWithURL,notify)
               }) 
           
        }
         
    }

    $scope.setAction = function(type){
        if(type == true){
            $scope.ifActionIsYes = true;
            $scope.ifActionIsNo = false;
            $scope.webIfActionIsNo = false;
        }else if(type == false){
            $scope.ifActionIsYes = false;
            $scope.ifActionIsNo = true;
            $scope.webIfActionIsNo = true;
        }

    }

    // funciton for adding actions ///
    
    $scope.actionsList = [];
    $scope.addToActions = function(){
        $scope.actionNameError = '';
        $scope.actionUrlError = '';

        if($scope.action.actionName == undefined || $scope.action.actionName ==''){
            $scope.actionNameError = 'Action name is required !!';
            return false;
        }
        if($scope.action.actionExternalUrl == undefined || $scope.action.actionExternalUrl == ''){
            $scope.actionUrlError = 'Action external url is required !!';
            return false;
        }
        if( ($scope.action.actionName != undefined || $scope.action.actionExternalUrl != undefined) && ($scope.action.actionName != '' || $scope.action.actionExternalUrl != '') ){
            $scope.actionsList.shift();
            $scope.actionsList.push({actionName:$scope.action.actionName,actionType:$scope.action.actionType,actionExternalUrl:$scope.action.actionExternalUrl});
            
            if($scope.actionsList.length > 0){
                $('#webActionsDialog').modal('hide');
                $('#actions-dialog').modal('hide');    
            }
            if($scope.actionsList.length == 2){
                $('.addAction').prop('disabled',true);
            }            
        }
        return false;
    }
    
    $scope.actionSave = true;
    $scope.actionIndexSave = false;
    $scope.editAction =  function(index){
        $scope.actionIndexSave = true;
        $scope.actionSave = false;
        $scope.actionEditIndex = index;
        var actionIndex = $scope.actionsList[index];
        $scope.action = actionIndex;
        //$scope.action = {};
    }

    $scope.addToActionsUpdate = function(){

        $scope.actionNameError = '';
        $scope.actionUrlError = '';

        if($scope.action.actionName == undefined || $scope.action.actionName ==''){
            $scope.actionNameError = 'Action name is required !!';
            return false;
        }
        if($scope.action.actionExternalUrl == undefined || $scope.action.actionExternalUrl == ''){
            $scope.actionUrlError = 'Action external url is required !!';
            return false;
        }

        var actionEditIndex = ($scope.actionEditIndex) ? ($scope.actionEditIndex) : 0;
        if(actionEditIndex != -1){
            $scope.actionsList[actionEditIndex] = {actionName:$scope.action.actionName,actionType:$scope.action.actionType,actionExternalUrl:$scope.action.actionExternalUrl};
            if($scope.actionsList.length > 0){
                $('#actions-dialog').modal('hide');
                $('#webActionsDialog').modal('hide');    
            }
        }
        $scope.actionSave = false;
        $scope.actionIndexSave = true;
    }

    $scope.deleteAction = function(){
        if(confirm('Are you sure want to delete')){
            var deleteIndex = $scope.actionEditIndex;
            $scope.actionsList.splice(deleteIndex,1);  

            if($scope.actionsList.length < 2){
                $('.addAction').prop('disabled',false);
            } 

            $scope.actionSave = true;
            $scope.actionIndexSave = false;
            $('#actions-dialog').modal("hide");
        }
    }

       /**
     *  getCustomDataList function dataset of cdata in the format in which it will stored  
     * @param {*} customDataListobject is a cdata format in which it is taken from the UI
     * @return {*} returns the cdata in the format.
     */
    function getCustomDataList(customDataListobject,checkdl) {
        let customDataList = []

         // Check if customDataListobject has only one element and that element's key or value is empty
        const firstElement = customDataListobject[customDataListobject.length-1]; // Access the first element
        if (customDataListobject.length === 1 && (firstElement.key === '' || firstElement.value === '')) {
            return customDataList;
        }
        angular.forEach(customDataListobject, function (customData) {


            // First conversion of Array of objects to single JSON object 
            if (customData.type == "json") {
                customData.value = convertToSingleObject(customData.value);
            }
            // Assign each object of $scope.cdataImgData array to corresponding customData.value if type is "image"
            if (customData.type == "image" && $scope.cdataImgData) {
                customData.value = $scope.cdataImgData[0].value;
            }
        
            // Handle string case 
            if (customData.key.trim() != "" && customData.type == "string") {
                customDataList.push({
                    [customData.key]: encodeURIComponent(customData.value),
                    type: customData.type
                });
            } else {
                // Handle rest cases 
                customDataList.push({
                    [customData.key]: encodeURIComponent(JSON.stringify(customData.value)),
                    type: customData.type
                });
            }
        });
        
        return customDataList;
        
    }
    function convertToObjectArray(input) {
        if ( input === null) {
    
            return input.toString(); // Return 'true' or 'false' as a string

        }
    
        const resultArray = [];
    
        for (const key in input) {
            if (Object.hasOwnProperty.call(input, key)) {
                const jkey = key;
                const jvalue = input[key];
    
                resultArray.push({ jkey, jvalue });
            }
        }
    
        return resultArray;
    }
    function validateUrl(value) {   
        var res = value.match(/^([a-zA-Z][a-zA-Z0-9+.-]*:\/\/)?(www\.)?[-a-zA-Z0-9@:%._\+~#=]{1,256}\.[a-zA-Z0-9()]{1,6}\b([-a-zA-Z0-9()@:%_\+.~#?&//=]*)$|^([a-zA-Z][a-zA-Z0-9+.-]*):\/\/([-a-zA-Z0-9@:%._\+~#=\/?&]*)$/);
        return res !== null;
    }

    function validatePushInputs(){
        if($scope.cTools.notificationHeader == '' || $scope.cTools.notificationHeader == undefined){
            $scope.template_name_error = "Please enter a valid Push Header";
            return true 
        }
        if($scope.cTools.notificationDescription == '' || $scope.cTools.notificationDescription == undefined){
            $scope.template_name_error = "Please enter a valid Push Description";
            return true 
        }
              //setting default Values
         // Default value for ExternalURL
          if($scope.cTools.externalUrl == undefined || $scope.cTools.externalUrl == '' || !validateUrl($scope.cTools.externalUrl) ){
              $scope.cTools.externalUrl = '';
           }else{
              $scope.cTools.externalUrl = $scope.cTools.externalUrl;
          }            
         // Default value for notificationType as 'dl'
         $scope.cTools.notificationType = $scope.cTools.notificationType ? $scope.cTools.notificationType : 'dl';

         // Default value for expandedNotificationImageFile
         $scope.expandedNotificationImageFile = $scope.expandedNotificationImageFile ? $scope.expandedNotificationImageFile : '';

         // Default value for expandedNotificationDescription
         $scope.cTools.expandedNotificationDescription = $scope.cTools.expandedNotificationDescription ? $scope.cTools.expandedNotificationDescription : '';

         return false; // No validation errors

    }
    function convertToSingleObject(arrayOfObjects) {
        const resultObject = {};
      
        for (const obj of arrayOfObjects) {
            //Checking If it is an empty string 
            if(obj.jkey!= ""){
                resultObject[obj.jkey] = obj.jvalue;
            }
        }
      
        return resultObject;
      }
    $scope.saveSettingsTools = function(){
        let diff = $('#diff').val();
        let loop = $('#loop').val();
        let gap = $('#gap').val();

        var customDataList = getCustomDataList($scope.customDataList,true)

           // Now This Function will validate Inputs and also set default value
        if(validatePushInputs()){
            return
        }

		//   Validating the template name to contain only alphabet, number and space
        var regex = /^[a-zA-Z0-9 ]+$/;
        if($scope.cTools.template_name == undefined  || $scope.cTools.template_name == ""){
            $scope.template_name_error = 'Please enter a valid template name.';
        }else if (!regex.test($scope.cTools.template_name)){
            $scope.template_name_error = 'Template name must contain only letters, numbers, spaces';
        }else{
            $scope.template_name_error = '';
            var actionsList         = [];
             if($scope.actionsList.length > 0 && $scope.actionStyle == true){
                for(var i=0; i<$scope.actionsList.length; i++){
                    actionsList.push({
                        nh      : $scope.actionsList[i].actionName,
                        et      : $scope.actionsList[i].actionType,
                        eurl    : $scope.actionsList[i].actionExternalUrl
                    });

                    $scope.cTools.externalUrl = '';
                    $scope.cTools.notificationType = '';
                }
            }
         
        
            var expanded = '';
            if($scope.cTools.expendedImg){
                expanded = 'expanded';
            }
            if ($scope.savevariantdata.length > 0) {
                $scope.variantType = true;        
                $scope.savevariantdata[$scope.activeVariance].variance_name = $scope.cTools.template_name;
                $scope.savevariantdata[$scope.activeVariance].notificationHeader =  $scope.cTools.notificationHeader;
                $scope.savevariantdata[$scope.activeVariance].notificationDescription = $scope.cTools.notificationDescription;
                $scope.savevariantdata[$scope.activeVariance].expandedNotificationDescription = $scope.cTools.expandedNotificationDescription;
                $scope.savevariantdata[$scope.activeVariance].notificationImage = $scope.notificationImageFile;
                $scope.savevariantdata[$scope.activeVariance].expandedNotificationImage = $scope.expandedNotificationImageFile;
                $scope.savevariantdata[$scope.activeVariance].expandedNotificationImageFile =  $scope.expandedNotificationImageFile;
                $scope.savevariantdata[$scope.activeVariance].externalUrl = $scope.cTools.externalUrl;
                $scope.savevariantdata[$scope.activeVariance].actionsList =  $scope.actionsList;
                $scope.savevariantdata[$scope.activeVariance].customDataList = $scope.customDataList;
                $scope.savevariantdata[$scope.activeVariance].sound = $scope.sound;
                $scope.savevariantdata[$scope.activeVariance].vibrate = $scope.vibrate;
                $scope.savevariantdata[$scope.activeVariance].badge = $scope.badge;
                $scope.savevariantdata[$scope.activeVariance].pushType = expanded;
                $scope.customDataVariant.forEach((variant , index) => {
                    $scope.savevariantdata[index].cdata = getCustomDataList(variant);
                });
                $scope.customDataList = $scope.customDataVariant[$scope.activeVariance];
        
                // cdata:customDataList
                $('#rdbAbManual').prop("checked", true);
                $scope.setRangeSliderVariance($scope.savevariantdata);
                $scope.totalPer()
         

            var data = {
                template_name: $scope.cTools.template_name,
                template_type: 'PUSH',
                template: $scope.savevariantdata,
                isTemplateDeleted: "false",
                createdOn: semusiCommon.getCurrentDate(),
                modifiedOn: ""
            }

            }

            else {
                $scope.variantType = false;
            var data = {
                template_name:$scope.cTools.template_name,
                template_type:'PUSH',
                template:{
                        notificationHeader:$scope.cTools.notificationHeader,
                        notificationDescription:$scope.cTools.notificationDescription,
                        notificationImage:removeBaseUrl($scope.notificationImageFile,$scope.blobUrls),
                        expandedNotificationDescription: ($scope.expandedNotificationImageFile && $scope.expandedNotificationImageFile !='')? '' : $scope.cTools.expandedNotificationDescription,
                        expandedNotificationImage:removeBaseUrl($scope.expandedNotificationImageFile,$scope.blobUrls),
                        and:{
                            b: $scope.bu,  // BaseUrl
                            i: $scope.gif_imgs,    // Series of images that we extract from the gif
                            d: diff ? diff : 0,   // Time difference between images display
                            l: loop ? loop : 0,  // How much time gap before repeating the images
                            g: gap ? gap : 0,   // How many times to loop the entire sequence
                        f: $scope.frame_ext,   // Extension of frames extracted from gif
                        m: $scope.m, // Full media url
                        },
                        ty:$scope.img_type, // Type of image uploaded
                        externalUrl:$scope.cTools.externalUrl,
                        pushType: expanded,
                        notificationType:$scope.cTools.notificationType,
                        actions: actionsList,
                        sound: $scope.sound,
                        vibrate: $scope.vibrate,
                        badge: $scope.badge,
                        cdata:customDataList
                    },
                isTemplateDeleted:"false",
                createdOn:semusiCommon.getCurrentDate(),
                modifiedOn:"",
            }
            if($scope.cTools.expendedText != true ){
                data.template.expandedNotificationDescription = "";
            }
        }
        //validate template name before saving Push Setting
		$scope.validateTemplateName(data.template_type, $scope.cTools.template_name, async function(response){
			if(!response){
            appIceService.saveSettingsTools(data).then(function(data){
                if(data==undefined)$scope.template_name_error = "Oops! Something went wrong. Please try again.";
                if(data != ''){
                    $scope.template_id = data._id;
                    $('#campaignwizard').bwizard('next');
                }
            });

            }
         });
        }
    }

    $scope.saveFbAdsSettingsTools = function(){
        if($scope.cTools.template_name == undefined){
            $scope.template_name_error = 'Please enter template name.';
        }else{
            let flag = false;
            let error = "";
            if($scope.fb.heading == undefined || $scope.fb.heading == ''){
                error = 'Please enter heading';
                flag = true;
            }
            if($scope.fb.message == undefined || $scope.fb.message == ''){
                error = 'Please enter message';
                flag = true;
            }
            var regexQuery = "^(http:\/\/www\.|https:\/\/www\.|http:\/\/|https:\/\/)[a-z0-9]+([\-\.]{1}[a-z0-9]+)*\.[a-z]{2,5}(:[0-9]  {1,5})?(\/.*)?$";
            var url = new RegExp(regexQuery);
            let isValidUrl = url.test($scope.fb.websiteurl);
            if (!isValidUrl) {
                error = 'Please enter valid redirect url (eg: http://google.com)';
                flag = true;
            } 
            $scope.template_name_error = error;
            if(flag == true){
                return false;
            }
            var data = {
                template_name:$scope.cTools.template_name,
                template_type:'FACEBOOK_ADS',
                template:{
                    title: $scope.fb.heading,
                    message:$scope.fb.message,
                    icon: $scope.expandedNotificationImageFile,
                    url: $scope.fb.websiteurl,
                    pageId : $scope.fb.pageId,
                    adsAccountId : $scope.fb.ads_account
                },
                isTemplateDeleted:"false",
                createdOn:semusiCommon.getCurrentDate(),
                modifiedOn:"",
            }

            appIceService.saveSettingsTools(data).then(function(data){
                if(data != ''){
                    $scope.template_id = data._id;
                    $('#campaignwizard').bwizard('next');
                }
            });
        }
    }

    $scope.validateTemplateName = function(type , name , cb){

    
        if( $scope.oldTemplateName != name){

            promise = appIceService.validateTemplateName(type,name);
			promise.then(function(response) { 

	        	// show error if template is found
	        	if(response){
                    $scope.template_name_error = "Template name already exists!";
              
	        	}
                // pass callback 
	        	if(cb != undefined){
	        		cb(response);
	        	}
	    	});	

        }else{

            cb(false);
        }

		
	}
    $scope.updateFbAdsTemplateSettingsTools = function(){
        if($scope.cTools.template_name == undefined){
            $scope.template_name_error = 'Please enter template name.';
        }else{
            let flag = false;
            let error = "";
            if($scope.fb.heading == undefined || $scope.fb.heading == ''){
                error = 'Please enter heading';
                flag = true;
            }
            if($scope.fb.message == undefined || $scope.fb.message == ''){
                error = 'Please enter message';
                flag = true;
            }
            var regexQuery = "^(http:\/\/www\.|https:\/\/www\.|http:\/\/|https:\/\/)[a-z0-9]+([\-\.]{1}[a-z0-9]+)*\.[a-z]{2,5}(:[0-9]  {1,5})?(\/.*)?$";
            var url = new RegExp(regexQuery);
            let isValidUrl = url.test($scope.fb.websiteurl);
            if (!isValidUrl) {
                error = 'Please enter valid redirect url (eg: http://google.com)';
                flag = true;
            } 
            $scope.template_name_error = error;
            if(flag == true){
                return false;
            }
           
            
            var data = {
                template_name:$scope.cTools.template_name,
                template_type:'FACEBOOK_ADS',
                template:{
                    title: $scope.fb.heading,
                    message:$scope.fb.message,
                    icon: $scope.expandedNotificationImageFile,
                    url: $scope.fb.websiteurl,
                    pageId : $scope.fb.pageId,
                    adsAccountId : $scope.fb.ads_account
                },
                isTemplateDeleted:"false",
                createdOn:semusiCommon.getCurrentDate(),
                modifiedOn:"",
            }

            if($scope.camp_state=='ACTIVE' && (  $scope.user_role == "marketer"  ||  $scope.user_role == '"marketer"' )){
                $scope.template_name_error = "You are not authorized to Perform this action.";
                return false;
            }
            appIceService.updateTemplateSettingsTools($scope.template_id,data).then(function(data){
                if(data != ''){
                    //submitAction(data._id);
                    $scope.template_id = data._id;
                    $('#campaignwizard').bwizard('next');
                }
            });
        }
    }


    /* web pop code */
    $scope.saveWebPopUpSettingsTools = function(){
        if($scope.cTools.template_name == undefined || $scope.cTools.template_name == ''){
            $scope.template_name_error = 'Please enter template name.';
        }else{
            let flag = false;
            let error = "";
            if($scope.web_pop_obj.title == undefined || $scope.web_pop_obj.title == ''){
                error = 'Please enter title';
                flag = true;
            }
            if($scope.web_pop_obj.message == undefined || $scope.web_pop_obj.message == ''){
                error = 'Please enter message';
                flag = true;
            }

            var regexQuery = "^(http:\/\/www\.|https:\/\/www\.|http:\/\/|https:\/\/)[a-z0-9]+([\-\.]{1}[a-z0-9]+)*\.[a-z]{2,5}(:[0-9]  {1,5})?(\/.*)?$";
            var url = new RegExp(regexQuery);
            let isValidUrl = url.test($scope.web_pop_obj.url);

            if (!isValidUrl) {
                error = 'Please enter valid redirect url (eg: http://google.com)';
                flag = true;
            } 

            $scope.template_name_error = error;
            if(flag == true){
                return false;
            }
           
            
            var data = {
                template_name:$scope.cTools.template_name,
                template_type:'WEB_POPUP',
                template:{
                    title: $scope.web_pop_obj.title,
                    message:$scope.web_pop_obj.message,
                    iconB: $scope.web_pop_obj.iconB,
                    icon: $scope.web_pop_obj.icon,
                    url: $scope.web_pop_obj.url,
                    mode: $scope.web_pop_obj.mode,
                    ps: $scope.web_pop_obj.ps,
                    br: $scope.web_pop_obj.br,
                    wh: $scope.web_pop_obj.wh,
                    hc: $scope.web_pop_obj.hc,
                    dc: $scope.web_pop_obj.dc,
                    bg: $scope.web_pop_obj.bg
                },
                isTemplateDeleted:"false",
                createdOn:semusiCommon.getCurrentDate(),
                modifiedOn:"",
            }

            appIceService.saveSettingsTools(data).then(function(data){
                if(data != ''){
                    $scope.template_id = data._id;
                    $('#campaignwizard').bwizard('next');
                }
            });
        }
    }


    $scope.updateWebPopUpTemplateSettingsTools = function(){
        if($scope.cTools.template_name == undefined || $scope.cTools.template_name == ''){
            $scope.template_name_error = 'Please enter template name.';
        }else{
            let error = "";
            if($scope.web_pop_obj.title == undefined || $scope.web_pop_obj.title == ''){
                error = 'Please enter title';
            }
            if($scope.web_pop_obj.message == undefined || $scope.web_pop_obj.message == ''){
                error = 'Please enter message';
            }

            var regexQuery = "^(http:\/\/www\.|https:\/\/www\.|http:\/\/|https:\/\/)[a-z0-9]+([\-\.]{1}[a-z0-9]+)*\.[a-z]{2,5}(:[0-9]{1,5})?(\/.*)?$";
            var url = new RegExp(regexQuery);
            let isValidUrl = url.test($scope.web_pop_obj.url);

            if (!isValidUrl) {
                error = 'Please enter valid redirect url (eg: http://google.com)';
            } 

            $scope.template_name_error = error;
            if(error != ""){
                return false;
            }
            
            var data = {
                template_name:$scope.cTools.template_name,
                template_type:'WEB_POPUP',
                template:{
                    title: $scope.web_pop_obj.title,
                    message:$scope.web_pop_obj.message,
                    iconB: $scope.web_pop_obj.iconB,
                    icon: $scope.web_pop_obj.icon,
                    url: $scope.web_pop_obj.url,
                    mode: $scope.web_pop_obj.mode,
                    ps: $scope.web_pop_obj.ps,
                    br: $scope.web_pop_obj.br,
                    wh: $scope.web_pop_obj.wh,
                    hc: $scope.web_pop_obj.hc,
                    dc: $scope.web_pop_obj.dc,
                    bg: $scope.web_pop_obj.bg
                    },
                isTemplateDeleted:"false",
                createdOn:semusiCommon.getCurrentDate(),
                modifiedOn:"",
            }

            if($scope.camp_state=='ACTIVE' && (   $scope.user_role == "marketer"  || $scope.user_role == '"marketer"' )){
                $scope.template_name_error = "You are not authorized to Perform this action.";
                return false;
            }
            appIceService.updateTemplateSettingsTools($scope.template_id,data).then(function(data){
                if(data != ''){
                    //submitAction(data._id);
                    $scope.template_id = data._id;
                    $('#campaignwizard').bwizard('next');
                }
            });
        }
    }


    /* end web pop code */

          /* START of SMS code */
          $scope.saveMessageTemp = function(){
               
              //   Validating the template name to contain only alphabet, number and space
              var regex = /^[a-zA-Z0-9 ]+$/;
              if($scope.cTools.template_name == undefined  || $scope.cTools.template_name == ""){
                  $scope.template_name_error = 'Please enter a template name.';
              }else if (!regex.test($scope.cTools.template_name)){
                  $scope.template_name_error = 'Template name must contain only letters, numbers, spaces';
              }else if ($scope.tobj.smsContent == undefined || $scope.tobj.smsContent.trim() == "") {
                  $scope.template_name_error= 'Please enter a message.';
              }else{
                  var data = {
                      template_name:$scope.cTools.template_name,
                      template_type:'SMS',
                      template:{
                          message:$scope.tobj.smsContent
                      },
                      isTemplateDeleted:"false",
                      createdOn:semusiCommon.getCurrentDate(),
                      modifiedOn:"",
                  }
          
                  appIceService.saveSettingsTools(data).then(function(data){
                      if(data != ''){
                          $scope.template_id = data._id;
                          $('#campaignwizard').bwizard('next');
                      }
                  });
              }
          }
          
          
          $scope.updateMessageTemp = function(){
          
          var data = {
          template_name:$scope.cTools.template_name,
          template_type:'SMS',
          template:{
              message:$scope.tobj.smsContent
          },
          isTemplateDeleted:"false",
          createdOn:semusiCommon.getCurrentDate(),
          modifiedOn:"",
          }
          if($scope.camp_state=='ACTIVE' && ( $scope.user_role == "marketer"  || $scope.user_role == '"marketer"' )){
              $scope.template_name_error = "You are not authorized to Perform this action.";
              return false;
          }
          appIceService.updateTemplateSettingsTools($scope.template_id,data).then(function(data){
          if(data != ''){
              $scope.template_id = data._id;
              $('#campaignwizard').bwizard('next');
          }
          });
          }
          /* end of SMS code */
    $scope.saveWebSettingsTools = function(){
        if($scope.cTools.template_name == undefined){
            $scope.template_name_error = 'Please enter template name.';
        }else{
            let flag = false;
            let error = "";
            if($scope.web_push_obj.title == undefined || $scope.web_push_obj.title == ''){
                error = 'Please enter title';
                flag = true;
            }
            if($scope.web_push_obj.message == undefined || $scope.web_push_obj.message == ''){
                error = 'Please enter message';
                flag = true;
            }
            if($scope.actionsList.length == 0){
            var regexQuery = "^(http:\/\/www\.|https:\/\/www\.|http:\/\/|https:\/\/)[a-z0-9]+([\-\.]{1}[a-z0-9]+)*\.[a-z]{2,5}(:[0-9]{1,5})?(\/.*)?$";
            var url = new RegExp(regexQuery);
            let isValidUrl = url.test($scope.web_push_obj.url);

            if (!isValidUrl) {
                error = 'Please enter valid redirect url (eg: http://google.com)';
                flag = true;
            }
        }
            if($scope.web_push_obj.url === undefined || $scope.web_push_obj.url === ''){
                flag = false;
            }  

            $scope.template_name_error = error;
            if(flag == true){
                return false;
            }
            // For saving in default case i.e, Non varaint 
            const customDataList = getCustomDataList($scope.customDataList,true)

            if ($scope.savevariantdata.length > 0) {
                $scope.variantType = true;        
                $scope.savevariantdata[$scope.activeVariance].title = $scope.web_push_obj.title;
                $scope.savevariantdata[$scope.activeVariance].message = $scope.web_push_obj.message ;
                $scope.savevariantdata[$scope.activeVariance].url = $scope.web_push_obj.url;
                $scope.savevariantdata[$scope.activeVariance].icon = $scope.web_push_obj.icon;
                $scope.savevariantdata[$scope.activeVariance].extendedImage = $scope.expandedNotificationImageFile;
                $scope.savevariantdata[$scope.activeVariance].actions = $scope.actionsList;         
                // For saving in varaint case     
                $scope.customDataVariant.forEach((variant , index) => {
                    $scope.savevariantdata[index].cdata = getCustomDataList(variant);
                });
                $scope.customDataList = $scope.customDataVariant[$scope.activeVariance];
                $scope.setRangeSliderVariance($scope.savevariantdata);
                $scope.totalPer()
              var data = {
                template_name: $scope.cTools.template_name,
                template_type: 'WEB_PUSH',
                template: $scope.savevariantdata,
                isTemplateDeleted: "false",
                createdOn: semusiCommon.getCurrentDate(),
                modifiedOn: ""
              }

            } else{
            
            var data = {
                template_name:$scope.cTools.template_name,
                template_type:'WEB_PUSH',
                template:{
                    title: $scope.web_push_obj.title,
                    message:$scope.web_push_obj.message,
                    icon: removeBaseUrl($scope.web_push_obj.icon,$scope.blobUrls),
                    extendedImage: removeBaseUrl($scope.expandedNotificationImageFile,$scope.blobUrls),
                    externalUrl: ($scope.web_push_obj.url) ? $scope.web_push_obj.url : undefined,
                    actions: ($scope.actionsList.length > 0) ?$scope.actionsList : undefined ,
                    cdata:customDataList    // adding cdata in nonn varaint case 
                },
                isTemplateDeleted:"false",
                createdOn:semusiCommon.getCurrentDate(),
                modifiedOn:"",
            }
            }
          //validate template name before saving Web-Push Setting  
        $scope.validateTemplateName(data.template_type, $scope.cTools.template_name, async function(response){

            if(!response){

            appIceService.saveSettingsTools(data).then(function(data){
                if(data==undefined)$scope.template_name_error = "Oops! Something went wrong. Please try again.";
                if(data != ''){
                    $scope.template_id = data._id;
                    $('#campaignwizard').bwizard('next');
                }
            });

          }
         });
        }
    }

    $scope.getValuesOnChange = function (event, param) {
        let value = event.target.value;
        if(param == 'url'){
            if(value.length < 256){
                $scope.template_url_error = (500 - value.length) + ' Characters Left';
            }
        }
        else if(param == 'title'){
            if(value.length < 50){
                $scope.template_title_error = (49 - value.length) + ' Characters Left';
            }
        }
        else if(param == 'message'){
            if(value.length < 120){
                $scope.template_message_error = (119 - value.length) + ' Characters Left';
            }
        }
    }

    $scope.updateWebTemplateSettingsTools = function(){
        if($scope.cTools.template_name == undefined){
            $scope.template_name_error = 'Please enter template name.';

        }else{
            let error = "";
            let flag = false;
            if($scope.web_push_obj.title == undefined || $scope.web_push_obj.title == ''){
                error = 'Please enter title';
                flag=true;
            }
            if($scope.web_push_obj.message == undefined || $scope.web_push_obj.message == ''){
                error = 'Please enter message';
                flag=true;
            }
            if($scope.actionsList.length == 0){
            var regexQuery = "^(http:\/\/www\.|https:\/\/www\.|http:\/\/|https:\/\/)[a-z0-9]+([\-\.]{1}[a-z0-9]+)*\.[a-z]{2,5}(:[0-9]{1,5})?(\/.*)?$";
            var url = new RegExp(regexQuery);
            let isValidUrl = url.test($scope.web_push_obj.url);

            if (!isValidUrl) {
                error = 'Please enter valid redirect url (eg: http://google.com)';
                flag = true;
            }
        }
            if($scope.web_push_obj.url === undefined || $scope.web_push_obj.url === ''){
                flag = false;
            }  

            $scope.template_name_error = error;
            if(flag==true){
                return false;
            }
            // For Updating non varaint Case
            const customDataList = getCustomDataList($scope.customDataList,true)
            
            if ($scope.savevariantdata.length > 0) {
                $scope.variantType = true;        
                $scope.savevariantdata[$scope.activeVariance].title = $scope.web_push_obj.title;
                $scope.savevariantdata[$scope.activeVariance].message = $scope.web_push_obj.message ;
                $scope.savevariantdata[$scope.activeVariance].url = $scope.web_push_obj.url;
                $scope.savevariantdata[$scope.activeVariance].icon = $scope.web_push_obj.icon;
                $scope.savevariantdata[$scope.activeVariance].extendedImage = $scope.expandedNotificationImageFile;
                $scope.savevariantdata[$scope.activeVariance].actions = $scope.actionsList;
                // For Updating  varaint Case
                $scope.customDataVariant.forEach((variant , index) => {
                    $scope.savevariantdata[index].cdata = getCustomDataList(variant);
                });
                $scope.customDataList = $scope.customDataVariant[$scope.activeVariance];
                $scope.setRangeSliderVariance($scope.savevariantdata);
                $scope.totalPer()

              var data = {
                template_name: $scope.cTools.template_name,
                template_type: 'WEB_PUSH',
                template: $scope.savevariantdata,
                isTemplateDeleted: "false",
                createdOn: semusiCommon.getCurrentDate(),
                modifiedOn: ""
              }

            } else{

            var data = {
                template_name:$scope.cTools.template_name,
                template_type:'WEB_PUSH',
                template:{
                        title: $scope.web_push_obj.title,
                        message:$scope.web_push_obj.message,
                        icon:removeBaseUrl($scope.web_push_obj.icon,$scope.blobUrls),
                        extendedImage: removeBaseUrl($scope.expandedNotificationImageFile,$scope.blobUrls),
                        externalUrl: ($scope.web_push_obj.url) ? $scope.web_push_obj.url : undefined,
                        actions: ($scope.actionsList.length > 0) ?$scope.actionsList : undefined ,
                        cdata:customDataList
                    },
                isTemplateDeleted:"false",
                createdOn:semusiCommon.getCurrentDate(),
                modifiedOn:"",
            }
        }
        if($scope.camp_state=='ACTIVE' && (   $scope.user_role == "marketer"  ||  $scope.user_role == '"marketer"' )){
            $scope.template_name_error = "You are not authorized to Perform this action.";
            return false;
        }
        //validate template name before updating web-Push Setting
        $scope.validateTemplateName(data.template_type,$scope.cTools.template_name, async function(response){
            if(!response){

            appIceService.updateTemplateSettingsTools($scope.template_id,data).then(function(data){
                if(data != ''){
                    //submitAction(data._id);
                    $scope.template_id = data._id;
                    $('#campaignwizard').bwizard('next');
                }
            });

            }
          });
        }
    }

    $scope.audienceSegmentId = '';
    $scope.selectAudienceSegment = function(index,id){
    	if($scope.audienceSegments[index]._id == id){
            if($scope.checkedId==id){
                $('#select_'+id).hide();
                $('#unselect_'+id).show();
                $('#segment_'+$scope.audienceSegmentId).removeClass('active');
                $scope.checkedId = '';
                $scope.audienceSegmentId = '';
            }else{
            $('.audience-segments').removeClass('active');
            $('.activeicon').hide();
            $('.inactiveicon').show();
            $scope.audienceSegmentId = id;
            $scope.checkedId = id;
            $('#segment_'+$scope.audienceSegmentId).addClass('active');
            $('#select_'+id).show();
            $('#unselect_'+id).hide();
            }
        }
        else{
            $scope.audienceSegmentId = '';   
        }
        if(semusiCommon.dynamicSegment && semusiCommon.dynamicSegment.includes($scope.audienceSegmentId)){
            $scope.lcamp.cy = "t";
        }
    }



    // Get Audience Segment listing ////
    $scope.audienceSegments = [];
    $scope.getAudienceSegments =  function(){
        var promise = appIceService.getAudienceSegments();
        promise.then(function(audienceSegments){
            $('#overlay').hide();
            if(audienceSegments){
            	$scope.audienceSegments = audienceSegments;
                $('.audience-segments').removeClass('active');
                $('#segment_' + $scope.audienceSegmentId).addClass('active');
                $('#rdbNow').prop('checked', 'true');
                $('#delayInterval').prop('disabled', 'disabled');
                $('#delayDurationUnit').prop('disabled', 'disabled');
            }
            else {
                $('.audience-segments').removeClass('active');
            }
        })
        .catch(function(error){
            $('#overlay').hide();
        });
    }

    $scope.getAudienceSegments();

    ///launch campaign start here///

    // Initiliaze startup varbalbes///

    $scope.lcamp.daySelector = "ALLWEEK";
    $scope.lcamp.timeSelector = "ALLDAY";
    // Initiliaze startup varbalbes ends here///

    $scope.$watch('lcamp.timeSelector', function (newVal, oldVal) {
        if (newVal != '') {
            $scope.lcamp.timeSelector = newVal;
        }
    })

    $("#campaignStartDate").datepicker({
        todayHighlight: true,
        autoclose: true,
        startDate: '-0m',
        forceParse: false,
        format: 'M d, yyyy'
    });

    $("#campaignEndDate").datepicker({
        todayHighlight: true,
        autoclose: true,
        startDate: '-0m',
        forceParse: false,
        format: 'M d, yyyy'
    });


        $(document).ready(function(){
            $('#specificDaysOfMonth').datepicker({
              format: 'dd', // Show only the date (day) without month and year
              startDate: '1', // Start date (1st day of the month)
              endDate: '30', // End date (30th day of the month)
              autoclose: true, // Close the datepicker after selection
              multidate: true, // Enable multidate selection
              todayHighlight: true, // Highlight today's date
              showOtherMonths: false, // Hide other month days
              minViewMode: 0, // Show only days in the datepicker
              calendarWeeks: false, // Hide calendar weeks
              beforeShowMonth: function(date){
                return false; // Hide the month header
              }
            });


            $('#multiDatePicker').datepicker({
                format: 'yyyy-mm-dd', // Date format
                autoclose: true, // Close the datepicker after selection
                multidate: true // Enable multidate selection
              });

              $("#continuousDate").datepicker({
                todayHighlight: true,
                autoclose: true,
                startDate: '-0m',
                forceParse: false,
                format: 'M d, yyyy'
            });

          });



    // for inbox 
    $('#datetimepicker').datetimepicker({
        todayHighlight: true,
        autoclose: true,
        startDate: '-0m',
        forceParse: false,
        format: 'M dd yyyy hh:ii'
    });


        initTimeSlider();
        $("#rdbAllWeek").click(function(){
            selectAllWeek();
        });

    /**
     * Support for existing format of time range i.e. 8, 12, etc to be converted into 0800, 1200 etc.
     * Converts a given string into a 24-hour format time string. 
     * @param {string | number} inputStr - The input string representing the hour
     * @returns {string} - The time string in 24-hour format (HHMM).
     */
    function convertToTime(inputInt) {
    
        // Convert integer to string and pad with leading zeros if necessary
        const inputStr = String(inputInt).padStart(4, '0');
        
        // Extract the hour and minute parts
        const hour = inputStr.slice(0, 2);
        const minutes = inputStr.slice(2);
    
        // Return the formatted time string
        return `${hour}${minutes}`;
    }

    // Watch for changes in the 'lcamp.timeSelector' variable
    // and update the slider accordingly
    $scope.$watch('lcamp.timeSelector', function (newVal, oldVal) {
        // Check if the new value is 'ALLDAY'
        if (newVal === 'ALLDAY') {
            // Disable slider 
            $("#timeRange").slider("option", "disabled", true);
        } else if (newVal === 'SPECIFIC') {
            // Enable slider for the case of specific time
            $("#timeRange").slider("option", "disabled", false);
        }
    });


    /**
    * Converts total minutes to a 24-hour format time string.
    * @param {number} minutes - Total minutes generated by the time-range slider to be converted
    * @returns {string} - Time string formatted in 24-hour format (HHMM)
    */
    function formatMinutesTo24Hour(minutes) {
        
        const hours = Math.floor(minutes / 60);
        const mins = minutes % 60;
    
        let formattedTime;
    
        if (hours === 0 && mins === 0) {
            formattedTime = 0; // 12:00 am should be 0
        } else if (hours === 12 && mins === 0) {
            formattedTime = 1200; // 12:00 pm should be 1200
        } else if (hours < 12) {
            formattedTime = hours * 100 + mins; // Morning times
        } else {
            formattedTime = (hours === 12 ? 12 : hours - 12) * 100 + mins + 1200; // Afternoon times
        }
        return formattedTime.toString();
    }

    function formatMinutesTo24Hour4label(minutes) {
        const hours = Math.floor(minutes / 60);
        const mins = minutes % 60;
        return (hours < 10 ? '0' : '') + hours + (mins < 10 ? '0' : '') + mins; // Add leading zero if needed
    }


    /**
    * Converts a time string in 24-hour format (HHMM) back to total minutes.
    * @param {string} time - Time string in 24-hour format (HHMM) to the format which is used in the time-range slider
    * @returns {number} - Total minutes equivalent to the input time
    */
    function toOriginalState(time) {
        const hours = parseInt(time.substring(0, 2), 10);       // Extract hours from the time string and convert to integer
        const mins = parseInt(time.substring(2), 10);           // Extract minutes from the time string and convert to integer
        return hours * 60 + mins;                           // Calculate total minutes by multiplying hours with 60 and adding minutes
    }

    /**
    * Converts a time string in 24-hour format (HHMM) to human-readable format (hh:mm am/pm) so that can be used in the time-range slider in UI/UX for better user experience.
    * @param {string} time - Time string in 24-hour format (HHMM)
    * @returns {string} - Human-readable time string in 12-hour format (hh:mm am/pm)
    */
    function toHumanReadable(time) {
        let hours = parseInt(time.substring(0, 2), 10);
        const mins = parseInt(time.substring(2), 10);
        let ampm = hours >= 12 ? 'pm' : 'am';
        hours = hours % 12 || 12; // Convert 0 to 12 for 12-hour format
        return `${String(hours).padStart(2, '0')}:${String(mins).padStart(2, '0')} ${ampm}`;
    }

        function selectAllWeek(){
            setTimeout(() => {
                $("input[name='weekdayX']").prop('checked',true);
                $("input[name='weekday']").prop('checked',true);
                $("input[name='weekday']").prop('disabled','disabled');
                $scope.lcamp.selectedDays = [0,1,2,3,4,5,6];
            }, 500)
        }

        $scope.addSpecificDay = function(value,model){
           
            if(model){
               
                if( $scope.lcamp.editselectedDays.length > 0 ){
                    $scope.lcamp.editselectedDays.forEach(function(elem, key){
                        
                        if(value == elem){
                            $scope.lcamp.editselectedDays.splice(key,1);
                            return false;
                        }
                    });                    
                    $scope.lcamp.editselectedDays.push(value)
                }else{
                    $scope.lcamp.selectedDays.push(value);
                }

            }else{
            
                if( $scope.lcamp.editselectedDays.length > 0 ){
                    $scope.lcamp.editselectedDays.forEach(function(elem, key){
                        
                        if(value == elem){
                            $scope.lcamp.editselectedDays.splice(key,1);
                            return false;
                        }
                    });                    
                }else{
                    $scope.lcamp.selectedDays.forEach(function(elem, key){
                        
                        if(value == elem){
                            $scope.lcamp.selectedDays.splice(key,1);
                            return false;
                        }
                    });
                }
            }
        }

        $("#rdbSpecificDays").click(function(){
            $scope.lcamp.daySelector =  $("#rdbSpecificDays").val()
            selectOption();
        });

        function selectOption(){
            setTimeout(() => {
                $("input[name='weekday']").prop('disabled',false);
                $("input[name='weekday']").prop('checked',false);
                $scope.lcamp.selectedDays = [];
                $scope.lcamp.editselectedDays = [];
                $("input[name='optionsDays']").prop('checked',true);
            }, 200)   
        }

        $("#rdbDelay").click(function () {
            $("#delayInterval").prop('disabled', false);
            $('#delayDurationUnit').prop('disabled', false);
            $scope.lcamp.selectedDays = [];
            $scope.lcamp.editselectedDays = [];
        });
        $("#rdbNow").click(function () {
            $("#delayInterval").prop('disabled', true);
            $('#delayDurationUnit').prop('disabled', true);
            $scope.lcamp.selectedDays = [];
            $scope.lcamp.editselectedDays = [];
        });
        // on selection of Delivery type
        $("#deliveryType").click(function () {
            // If dlvy type is direct only hide the appinbox expiry div
            if ($(this).val() === "d") {
                $("#appinboxexp").hide();
            } else {
                $("#appinboxexp").show();
            }
        });

        $("#rdbAllTime").click(function(){
            $scope.lcamp.selectedTime = $scope.defaultSliderTimeRange;
        });

        $("#rdbSpecificTime").click(function(){
            //by default setting the time range (if the user will select time range but not use time slider)
            $scope.lcamp.selectedTime =  $scope.defaultSliderTimeRange;
        });

        function initTimeSlider(){

            if($scope.lcamp.selectedTime == undefined || $scope.lcamp.selectedTime.length==0){
                $scope.lcamp.selectedTime = [];
                $scope.lcamp.selectedTime = $scope.defaultSliderTimeRange
                $scope.lcamp.selectedTimeinOldFormat = $scope.defaultSliderTimeRange
            }

            $( "#timeRange" ).slider({
              range: true,
              min: 60,
              max: 24*60,
              step:15,
              values: $scope.lcamp.selectedTime.map(toOriginalState),
              slide: function( event, ui ) {
                $scope.lcamp.selectedTime = [];
                $scope.lcamp.selectedTimeinOldFormat = [];
                $scope.lcamp.selectedTime = ui.values.map(formatMinutesTo24Hour);
                $scope.lcamp.selectedTimeinOldFormat = ui.values.map(formatMinutesTo24Hour4label);
                $( "#timeRangeLabel" ).text(toHumanReadable(formatMinutesTo24Hour4label( ui.values[ 0 ]) )+ " - " + toHumanReadable(formatMinutesTo24Hour4label(ui.values[ 1 ]))  );
              }
            });

            $( "#timeRangeLabel" ).text(toHumanReadable($scope.lcamp.selectedTime[0]) + " - " +toHumanReadable($scope.lcamp.selectedTime[1]) ); 
        }

    angular.element(document).ready(function () {
        setTimeout(function () {
            $("#campaignwizard").bwizard({
                activeIndexChanged: function (e, ui) {
                    //  if (ui.index == 2 && $scope.templateType != "PUSH") {
                    //     $("#ddlShow").prop('disabled', 'disabled');
                    //     $("#txtInterval").prop('disabled', 'disabled');
                    //     //$("#delayInterval").prop('disabled', 'disabled');
                    //     $("#ddlDurationUnit").prop('disabled', 'disabled');
                    //     //$("#delayDurationUnit").prop('disabled', 'disabled');
                    //     $("#ddlShow").val('1');
                    //     $("#ddlDurationUnit").val('ss');
                    //     $("#txtInterval").val('0');
                    //     $("#ddlRangeStatus").prop('disabled', 'disabled');
                    //     $("#ddlRangeStatus").val('lt');
                    //     $('#txtRangeValue').prop('disabled', 'disabled');
                    //     $('#txtRangeValue').val('');
                    //     $('#txtPastDays').prop('disabled', 'disabled');
                    //     $('#txtPastDays').val('');
                    //     // $('#rdbNow').prop('checked', 'true');
                    //     // $('#delayInterval').prop('disabled', 'disabled');
                    //     // $('#delayDurationUnit').prop('disabled', 'disabled');
                    // }
                    // else {
                        $("#ddlShow").removeAttr("disabled");
                        $("#ddlRangeStatus").removeAttr("disabled");
                        $("#txtRangeValue").removeAttr("disabled");
                        $("#txtPastDays").removeAttr("disabled");
                        $("#txtInterval").removeAttr("disabled");
                        $("#ddlDurationUnit").removeAttr("disabled");
                    // }

                }
            });

            // delay or now campaign
            $('#rdbNow').prop('checked', 'true');
            $('#delayInterval').prop('disabled', 'disabled');
            $('#delayDurationUnit').prop('disabled', 'disabled');

        }, 10)
    });
    
    // on conversion event click generate attributes   
    $scope.showAttribute = function (param,level) {
      if (level == 1) {
        $scope.c_attribute_list = $scope.eventLists[param].list;
        $scope.c_event = $scope.eventLists[param];
      } else {
        $scope.c_attribute_list_2 = $scope.eventLists[param].list;
        $scope.c_event_2 = $scope.eventLists[param];
      }
    };

    // set the operator value 
    $scope.getSegementValueBox = function (segData) {
      if (segData.type == "string") {
        segData.operators = $scope.stringOperators;
      }
    };

    $scope.showAttributeOperators = function (attribute) {
        $scope.c_eventAttribute = attribute;  
        $scope.getSegementValueBox(attribute);
        $scope.c_event_attr_type = attribute.type;
    };
    $scope.showAttributeOperatorsforSecondEvent = function (attribute) {
        $scope.c_eventAttribute_2 = attribute;  
        $scope.getSegementValueBox(attribute);
        $scope.c_event_attr_type_2 = attribute.type;
    };
    $scope.selectAttrributeOperator = function (operator) {
        $scope.c_event_operator = operator;
    };
    $scope.selectAttrributeOperatorforSecondEvent = function (operator) {
        $scope.c_event_operator_2 = operator;
    };
    $scope.setValueforOperator = function(operator_value){
        $scope.c_event_operator_value = operator_value
    }
    $scope.setValueforOperatorforSecondEvent = function(operator_value){
        $scope.c_event_operator_value_2 = operator_value
    }
        
    // for OR and AND button in Conversion 
    $scope.$on("conversionOperatorChange", function (event, state) {
      if (state) {
        $scope.c_operator = "OR";
      } else {
        $scope.c_operator = "AND";
      }
    });

    /**
     * convertToColonSeparatedTime function converts a time string to a colon-separated format
     * 
     * @param {string} timeStr - The time string to be converted (format: 'HHMM')
     * @returns {string} - The time string in colon-separated format (e.g., 'HH:MM')
     */
    function convertToColonSeparatedTime(timeStr) {
        // Extract the hours and minutes from the time string
        // Concatenate them with a colon in between to form the desired format
        return timeStr.substr(0, 2) + ':' + timeStr.substr(2);
    }
     function saveCampaign(childIds){

    
        if($scope.camp_state=='ACTIVE' && ( $scope.user_role == "marketer"  ||   $scope.user_role == '"marketer"' )){
            $scope.campaignNameError = "You are not authorized to Perform this action.";
            return false;
        }
        $scope.campaignNameError = "";
        $scope.cToolsIdError = "";
        $scope.startDateError = "";
        $scope.endDateError = "";
        $scope.startgtDateError = "";
        $scope.startCurrDError = "";
        $scope.stag_max_batchError = "";
        $scope.stag_timeError = "";
        $scope.stag_unitError = "";
        $scope.endDateLtError = "";
        $scope.abRangeError = "";
        $scope.campEmailCostError = "";
	//   Validating the Campaign name to contain only alphabet, number and space
			var regex = /^[a-zA-Z0-9 ]+$/;
        if($scope.lcamp.campaignName==undefined || $scope.lcamp.campaignName =="" || $scope.lcamp.campaignName.trim().length==0){
            //Enable button
	        $("#save_cmp").prop('disabled', false);
            $scope.campaignNameError = "Enter a valid campaign name.";
            return false;
        }
        if(!regex.test($scope.lcamp.campaignName)){
            $("#save_cmp").prop('disabled', false);
            $scope.campaignNameError = "Campaign name must contain only letters, numbers, spaces";
            return false;
        }
        if($scope.audienceSegmentId === '' || $scope.audienceSegmentId === undefined){
            $("#save_cmp").prop('disabled', false);
            $scope.campaignNameError = "Please select any Audience";
            return false;
        }
        if($scope.lcamp.AbTypeSelector == "manual" && $scope.otherProbs && $scope.otherProbs.length > 1) {
            if($scope.totalVariantPer != 100) {
                $scope.abRangeError = "Total Variant range and Control group should be 100% ";
                return false;
            }
            $scope.controlGroupValue = isNaN(parseInt($('#controlGroupNum').val())) ? 0 : parseInt($('#controlGroupNum').val());
        }
        if ($scope.templateType == "EMAIL") {
          //check email cost
          if ($scope.email_cost_limit == undefined) {
            $("#save_cmp").prop("disabled", false);
            $scope.campEmailCostError ="Kindly Set The Total Budget in Settings.";
            return false;
          } else {
            if ( $scope.email_cost == undefined || $scope.email_cost == "" || parseInt($scope.email_cost) == 0 || $scope.email_cost > $scope.email_cost_limit ) {
              $("#save_cmp").prop("disabled", false);
              $scope.campEmailCostError = "Campaign Budget Should be greater than zero and less than total Budget.";
              return false;
            }
          }
        }
       
        if($scope.template_id==undefined || $scope.template_id=="" ){
             //Enable button
	        $("#save_cmp").prop('disabled', false);
            $scope.cToolsIdError = "Engagement tool is not selected for this campaign.";
            return false;
        }

        if($scope.lcamp.startDate == undefined || $scope.lcamp.startDate == "" ){
            //Enable button
	        $("#save_cmp").prop('disabled', false);
            $scope.startDateError ="Enter campaign start date.";
            return false;
        }

        if($scope.lcamp.endDate == undefined ||$scope.lcamp.endDate == ""){
             //Enable button
	        $("#save_cmp").prop('disabled', false);
            $scope.endDateError = "Enter campaign end date.";
            return false;
        }
        
        if(moment($scope.lcamp.startDate)>moment($scope.lcamp.endDate)){
            //Enable button
	        $("#save_cmp").prop('disabled', false);
            $scope.startgtDateError = "Campaign start date cannot be greater than campaign end date.";
            return false;
        }

        //validate this check for New Campaign Only  ( Not edited Campaign ) 
        if($scope.campaignId == undefined || $scope.campaignId ==""){
        if(moment($scope.lcamp.startDate).valueOf()/1000<parseInt(moment().hours(0).minutes(0).seconds(0).valueOf()/1000)){
            //Enable button
	        $("#save_cmp").prop('disabled', false);
            $scope.startCurrDError="Campaign start date cannot be less than current date.";
            return false;
        }
    }
        if(moment($scope.lcamp.endDate).valueOf()/1000<parseInt(moment().hours(0).minutes(0).seconds(0).valueOf()/1000)){
            //Enable button
	        $("#save_cmp").prop('disabled', false);
            $scope.endDateLtError="Campaign end date cannot be less than current date.";
            return false;
        }

        
        //Staggered Push Validation starts
        if($scope.lcamp.stag.max_batch != undefined){
            
            if(!$scope.lcamp.stag.max_batch.match('^[0-9]*$') ||  $scope.lcamp.stag.max_batch <= 0 || $scope.lcamp.stag.max_batch > 100 ){
                 //Enable button
	            $("#save_cmp").prop('disabled', false);
                $scope.stag_max_batchError ="Maximum Batch size should be 1 - 100%.";
                return false;
            }

            if($scope.lcamp.stag.time == undefined){
                 //Enable button
	             $("#save_cmp").prop('disabled', false);   
                $scope.stag_timeError ="Time field is required";
                    return false;
            }
           
        }
        if($scope.lcamp.stag.time != undefined) {
            if($scope.lcamp.stag.time <= 0  || !$scope.lcamp.stag.time.match('^[0-9]*$')) {
                //Enable button
	            $("#save_cmp").prop('disabled', false);
                $scope.stag_timeError ="Time should be greater than 0";
                return false;
            }

            if($scope.lcamp.stag.max_batch == undefined  ){
                //Enable button
	            $("#save_cmp").prop('disabled', false);
                $scope.stag_max_batchError ="Please enter maximum batch size";
                return false;
            }

            if($scope.lcamp.stag.t_unit == undefined ){
                //Enable button
	            $("#save_cmp").prop('disabled', false);
                $scope.stag_unitError ="Please select time unit";
                return false;
            }
            
        }
        if($scope.lcamp.stag.t_unit != undefined) {
            if($scope.lcamp.stag.time == undefined){
                //Enable button
	            $("#save_cmp").prop('disabled', false);
                $scope.stag_timeError ="Time feild is required";
                return false;
            }
            if($scope.lcamp.stag.max_batch == undefined  ) {
                //Enable button
	            $("#save_cmp").prop('disabled', false);
                $scope.stag_max_batchError ="Please enter maximum batch size";
                return false;
            } 
        }

     //Staggered Push Validation ends

        
        if(typeof $scope.lcamp.selectedDays === 'string' && $scope.lcamp.selectedDays != ''){
            $scope.lcamp.selectedDays = $scope.lcamp.selectedDays.split("','");
        }

        
        if($scope.lcamp.daySelector == "SPECIFICDAYS"){
            if($scope.lcamp.selectedDays.length==0 || (typeof $scope.lcamp.selectedDays === 'string' && $scope.lcamp.selectedDays == '')){
                //Enable button
	            $("#save_cmp").prop('disabled', false);
                $scope.specificDayError= "When specific days is selected, atleast one day should be selecetd.";
                return false; 
            }else{
                $scope.specificDayError = "";
            }
        }
        
        getFrequency();
        $scope.limitedTo = '';
        $scope.limitedToValue = '';
        var state;
        var delayiValue = $('#delayInterval').val();
        var delayuValue = $("#delayDurationUnit option:selected").text();
        var delayValue = $('#rdbDelay').val();
        if ($('#rdbDelay').is(':checked')) {
            state = 1;
        }
        else if ($('#rdbNow').is(':checked')) {
            state = 0;
            delayiValue = '';
            delayuValue = ''
        }
        
        var variant = false;
        if($scope.campaignId ==undefined || $scope.campaignId ==""){
            if ($scope.savevariantdata.length > 0) {
                variant = true;
            }
            var data = {
                    variant: variant,
                    nm:$scope.lcamp.campaignName.trim(),
                    sd:moment(moment($scope.lcamp.startDate).format('YYYY-MM-DD') + ' '+ convertToColonSeparatedTime($scope.lcamp.selectedTimeinOldFormat[0]) ).valueOf(),
                    ed:moment(moment($scope.lcamp.endDate).format('YYYY-MM-DD')+' '+ convertToColonSeparatedTime($scope.lcamp.selectedTimeinOldFormat[1])).valueOf(),
                    cd:semusiCommon.getCurrentEpoch(),
                    appinbox_et: $scope.lcamp.cmpexpiry ? (new Date($scope.lcamp.cmpexpiry).valueOf() ):0,
                    ud:semusiCommon.getCurrentEpoch(),
                    st:"DRAFT",
                    liveEvent: $scope.liveEvent,
                    t:$scope.templateType,
                    stag: $scope.lcamp.stag,
                    AbTypeSelector : $scope.lcamp.AbTypeSelector ? $scope.lcamp.AbTypeSelector:undefined, 
                    abTypeRange : $scope.lcamp.AbTypeSelector == "manual" ? $scope.otherProbs:[],
                    controlGroup : ($scope.controlGroupValue != 0) ? $scope.controlGroupValue : undefined,
                    d:false,
                    tid:$scope.template_id,
                    pa : ($scope.pushAmp == "true") ? true : false, 
                    aud:$scope.audienceSegmentId,
                    fre:$scope.frequency,
                    limitedTo:$scope.limitedTo,
                    limitVal:$scope.limitedToValue,
                    daySelector:$scope.lcamp.daySelector,
                    days:$scope.lcamp.selectedDays,
                    timeSelector:$scope.lcamp.timeSelector,
                    time: $scope.lcamp.selectedTime,
                    childIds:(childIds)?childIds:[],
                    c_arr :[],
                    m_sub:($scope.tobj.messageSubject != '' && $scope.tobj.messageSubject != undefined)? $scope.tobj.messageSubject : '',
                    m_cont:($scope.tobj.messageContent != '' && $scope.tobj.messageContent != undefined)? $scope.tobj.messageContent : '',
                    s_cfg:($scope.templateType != 'SMS')? '':$scope.sms.configuration,
                    e_cfg:($scope.templateType != 'Email')? '':$scope.email.configuration,
                    diff: semusiCommon.getOffset(),
                    delays: state,
                    delayi: delayiValue,
                    delayu: delayuValue,
                    dlvy:$scope.lcamp.dlvy,
                    cy:$scope.lcamp.cy
             }        
             if ($scope.templateType == "EMAIL") {
                data.email_cost=$scope.email_cost
            }
            if ($scope.templateType == "IN-APP") {
                delete data.appinbox_et
            }

            // add conversion 
            if($scope.isConversion){
                data.c_arr = $scope.c_arr ;
            }

            appIceService.createCampaign(data).then(function(data){
                if(data==undefined)$scope.campDupError = "Oops! Something went wrong. Please try again.";
                if(data.status && data.status=="error"){
                    //Enable button
	                $("#save_cmp").prop('disabled', false);
                    $scope.campDupError = "Campaign with this name already exists.";
                    return;
                }
              window.location.href = appiceEncode.encodePayload("dashboard?action=campaigns"); 
            })
        }else{
            if($scope.lcamp.editselectedDays.length == 0){ // check selecte daySelector
               $scope.lcamp.editselectedDays = $scope.lcamp.selectedDays;
            }
            if ($scope.savevariantdata.length > 0) {
                variant = true;
            }
            var data = {     
                    variant: variant,           
                    nm:$scope.lcamp.campaignName.trim(),
                    sd:moment(moment($scope.lcamp.startDate).format('YYYY-MM-DD') + ' '+ convertToColonSeparatedTime($scope.lcamp.selectedTimeinOldFormat[0]) ).valueOf(),
                    ed:moment(moment($scope.lcamp.endDate).format('YYYY-MM-DD')+' '+ convertToColonSeparatedTime($scope.lcamp.selectedTimeinOldFormat[1]) ).valueOf(),
                    ud:semusiCommon.getCurrentEpoch(),
                    appinbox_et: $scope.lcamp.cmpexpiry ? (new Date($scope.lcamp.cmpexpiry).valueOf()):0,
                    t:$scope.templateType,
                    AbTypeSelector : $scope.lcamp.AbTypeSelector ? $scope.lcamp.AbTypeSelector:undefined, 
                    abTypeRange : $scope.lcamp.AbTypeSelector == "manual" ? $scope.otherProbs: [],
                    controlGroup : ($scope.controlGroupValue != 0) ? $scope.controlGroupValue : 0,
                    d:false,
                    tid:$scope.template_id,
                    pa : ($scope.pushAmp == "true") ? true : false, 
                    aud:$scope.audienceSegmentId,
                    stag: $scope.lcamp.stag,
                    fre:$scope.frequency,
                    limitedTo:$scope.limitedTo,
                    limitVal:$scope.limitedToValue,
                    liveEvent: $scope.liveEvent,
                    daySelector:$scope.lcamp.daySelector,
                    days:$scope.lcamp.editselectedDays,
                    timeSelector:$scope.lcamp.timeSelector,
                    time: $scope.lcamp.selectedTime,
                    childIds:(childIds)?childIds:[],
                    c_arr:[],
                    m_sub:($scope.tobj.messageSubject != '' && $scope.tobj.messageSubject != undefined)? $scope.tobj.messageSubject : '',
                    m_cont:($scope.tobj.messageContent != '' && $scope.tobj.messageContent != undefined)? $scope.tobj.messageContent : '',
                    s_cfg:($scope.templateType != 'SMS')? '':$scope.sms.configuration,
                    e_cfg:($scope.templateType != 'Email')? '':$scope.email.configuration,
                    diff:semusiCommon.getOffset(),
                    delays: state,
                    delayi: delayiValue,
                    delayu: delayuValue,
                    dlvy:$scope.lcamp.dlvy,
                    cy:$scope.lcamp.cy
                }

                if ($scope.templateType == "EMAIL") {
                    data.email_cost=$scope.email_cost
                }
                // add conversion
                if($scope.isConversion){
                    data.c_arr = $scope.c_arr
                }
                appIceService.updateCampaign($scope.campaignId,data).then(function(data){
                    if(data.status == 500 || undefined )$scope.campDupError = data.data.result;
                    if(data.status && data.status=="error"){
                        $scope.UpdatevalidationMessage = "Campaign with this name already exists.";
                        return false;
                    }
                    window.location.href = appiceEncode.encodePayload("dashboard?action=campaigns"); 
                })
            }
    }

    // Function to get selected days as indices
    function getSelectedDays() {
        var selectedDays = [];
        var dayIds = ['checkbox_0', 'checkbox_1', 'checkbox_2', 'checkbox_3', 'checkbox_4', 'checkbox_5', 'checkbox_6'];
        
        for (var i = 0; i < dayIds.length; i++) {
            if ($('#' + dayIds[i]).prop('checked')) {
                selectedDays.push(i);
            }
        }
        
        return selectedDays;
    }
    


// Function to set specific days as checked with a delay
function setSelectedDays(selectedDays) {
    if (selectedDays !== undefined) {
        $(".weekday_").prop('disabled', false); // Enable checkboxes if disabled

        // Set checkboxes based on the selectedDays array after a delay
        for (var i = 0; i < selectedDays.length; i++) {
            var dayIndex = selectedDays[i];
            setTimeout(function(index) {
                return function() {
                    $("#checkbox_" + selectedDays[index]).prop('checked', true);
                }
            }(i), i * 100); 
        }
    }
}




   // function for getting the frequency object///
    function getFrequency(){
        let selectedDays = getSelectedDays();
        $scope.frequency = frequencyObject($("#ddlShow").val(),$("#ddlRangeStatus").val(),$("#txtRangeValue").val(),$("#txtPastDays").val(),parseInt($("#txtInterval").val()),$("#ddlDurationUnit").val(),$('#excludeCampFromAllLimits').val(),$('#noOfTimesCampShowninSession').val(),$('#noOfTimesCampShowninDay').val(),$('#noOfTimesCampShowninLifetime').val(),$('#frequencyType').val(),$('#modeFreq').val(),$('#startTimeFreq').val(),selectedDays,$('#continuousDate').val(),$('#fre_interval').val(),$('#fre_intervalUnit').val(),$('#multiDatePicker').val(),$('#specificDaysOfMonth').val()); 
    }

    // Function for creatting the frequency object///

    function frequencyObject(show, rangeStatus, rangeValue, pastDays, interval, iUnit, excludeCampFromAllLimits, noOfTimesCampShowninSession, noOfTimesCampShowninDay, noOfTimesCampShowninLifetime, ft, m, t, selectedDays,rDate, i, iu, r, dt) {
        let result = {
            show: show,
            rangeStatus: rangeStatus,
            rangeValue: rangeValue,
            pastDays: pastDays,
            interval: interval,
            iUnit: iUnit,
            e: excludeCampFromAllLimits,
            ss: noOfTimesCampShowninSession,
            d: noOfTimesCampShowninDay,
            l: noOfTimesCampShowninLifetime,
        };
        let rD = rDate
           //case multi
           if (ft !== "o" && ft === "mm") {
               result.s = {
                   ft: ft,
                   r: r.split(',').map(function(dateStr) { return moment(dateStr.trim() + ' ' + t, 'YYYY-MM-DD HH:mm').valueOf() / 1000})
               };
           }
        //    case recurring with daily 
           else if (ft !== "o" && ft == 'r' && m == 'd') { 
            result.s = {
                ft: ft,
                m: m,
                t: t,
            };
        }
        //    case recurring with weekly
        else if (ft !== "o" && ft == 'r' && m == 'w') { 
            result.s = {
                ft: ft,
                m: m,
                t: t,
                d: selectedDays
            };
        }
        //    case recurring with monthly
        else if (ft !== "o" && ft == 'r' && m == 'm') { 
            result.s = {
                ft: ft,
                m: m,
                t: t,
                dt:[dt]
            };
        }
        //    case recurring with continous/hourly
        else if (ft !== "o" && ft == 'r' && m == 'c') { 
            result.s = {
                ft: ft,
                m: m,
                i:i,
                iu:iu,
                r: moment(rD, "MMM DD, YYYY").unix()
            };
        }
    
        return result;
    }
    
    // function fo setting the frequncy object///
    setFrequency = function(){
        if($scope.frequency){

            if($scope.frequency.show){
                $("#ddlShow").val($scope.frequency.show);    
            }
            if($scope.frequency.rangeStatus){
                $("#ddlRangeStatus").val($scope.frequency.rangeStatus);    
            }
            if($scope.frequency.rangeValue){
                $("#txtRangeValue").val($scope.frequency.rangeValue);    
            }
            if($scope.frequency.pastDays){
                $("#txtPastDays").val($scope.frequency.pastDays);    
            }
            if($scope.frequency.interval){
                $("#txtInterval").val($scope.frequency.interval);    
            }
            if($scope.frequency.iUnit){
                $("#ddlDurationUnit").val($scope.frequency.iUnit);    
            }
                  if($scope.frequency.e){
                if($scope.frequency.e === 'yes'){
                 $('#excludeCampFromAllLimits').val('yes');
                 $('#noOfTimesCampShowninSession').prop('disabled', true);
                 $('#noOfTimesCampShowninDay').prop('disabled', true);
                 $('#noOfTimesCampShowninLifetime').prop('disabled', true);
                }else{
                 $('#excludeCampFromAllLimits').val('no');
                }
             }
             if($scope.frequency.ss){
                $('#noOfTimesCampShowninSession').val($scope.frequency.ss)
             }
             if($scope.frequency.d){
                $('#noOfTimesCampShowninDay').val($scope.frequency.d)
             }
             if($scope.frequency.l){
                $('#noOfTimesCampShowninLifetime').val($scope.frequency.l)
             }

             if ($scope.frequency && $scope.frequency.s && $scope.frequency.s.ft == "mm") {
                $scope.lcamp.ft = $scope.frequency.s.ft;

                let dates = [];
                let times = [];

                $scope.frequency.s.r.forEach(function(timestamp) {
                    let dateMoment = moment.unix(timestamp);
                    dates.push(dateMoment.format('YYYY-MM-DD'));
                    times.push(dateMoment.format('HH:mm'));
                });
                $('#startTimeFreq').val(times[0])
                $('#multiDatePicker').val(dates)
             }
            if ($scope.frequency && $scope.frequency.s) {
                if ($scope.frequency.s.ft == "r" && $scope.frequency.s.m == "d") { //daily recurring

                    $scope.lcamp.m = $scope.frequency.s.m;
                    $scope.lcamp.ft = $scope.frequency.s.ft;
                    $('#startTimeFreq').val($scope.frequency.s.t)
                }

                if ($scope.frequency.s.ft == "r" && $scope.frequency.s.m == "w") { //weekly
                    $scope.lcamp.m = $scope.frequency.s.m;
                    $scope.lcamp.ft = $scope.frequency.s.ft;
                    $('#startTimeFreq').val($scope.frequency.s.t)

                    setSelectedDays($scope.frequency.s.d)

                }
                if ($scope.frequency.s.ft == "r" && $scope.frequency.s.m == "m") { // monthly specific
                    $scope.lcamp.m = $scope.frequency.s.m;
                    $scope.lcamp.ft = $scope.frequency.s.ft;
                    $('#startTimeFreq').val($scope.frequency.s.t)


                    let dateString = $scope.frequency.s.dt.join(", ");
                    $("#specificDaysOfMonth").val(dateString);
                }
                if ($scope.frequency.s.ft == "r" && $scope.frequency.s.m == "c") { //contineous
                    $scope.lcamp.m = $scope.frequency.s.m;
                    $scope.lcamp.ft = $scope.frequency.s.ft;
                    $('#continuousDate').val(moment.unix($scope.frequency.s.r).format("MMM DD, YYYY"));
                    $timeout(function () {
                        $('#fre_interval').val($scope.frequency.s.i);
                        $('#fre_intervalUnit').val($scope.frequency.s.iu);
                    }, 100);
                }
            } 
        }
    
    }

    // funciton for bindWeekDaysOnEdit of the campaign////
    function bindWeekDaysOnEdit(){
        if($scope.lcamp.daySelector=="SPECIFICDAYS"){
            var elements = document.getElementsByName('optionsDays');
            var index = 2;
            setTimeout(function() {
              if (index < elements.length) {
                elements[index].checked = true;
              }
            }, 2000);
            $(".weekday").prop('disabled',false);
            $(".weekday").prop('checked',false);
            
        }else{
                    selectAllWeek();
        }
        var days = $(".weekday");
        for(var x=0;x<days.length;x++){
            if($.inArray(days[x].value, $scope.lcamp.selectedDays) != -1){
                days[x].checked=true;
            }    
        }
        
    }

    /// function for getting the template setting tools by template id///
    function getAppTemplatesById(templateId){
   
        if(templateId != ''){
            $scope.btnUpdatePush = false;
            $scope.btnSavePush = true;
            $scope.watcherCounter = 1;
            appIceService.getAppTemplatesById(templateId).then(function(data){
                switch(data.template_type){
                case "PUSH":
                    $scope.updateTemplateId = data._id;
                    $scope.template_id  =  data._id;
                    fillPushScreen(data);
                    break;
                case "IN-APP":
                    $scope.template_id  =  data._id;
                    fillInAppScreen(data);
                    break;
                case "SURVEY":
                    $scope.template_id  =  data._id;
                    fillSurveyScreen(data);
                    break;
                case "RATING":
                    $scope.template_id  =  data._id;
                    fillRatingScreen(data);
                    break;
                    case "SMS":
                        $scope.template_id  =  data._id;
                        fillSmsScreen(data);
                        break; 
                case "WEB_PUSH":
                    $scope.template_id  =  data._id;
                    fillWebPushScreen(data);
                    break;
                case "WEB_POPUP":
                    $scope.template_id  =  data._id;
                    fillWebPopUpScreen(data);
                    break;
                case "EMAIL":
                    $scope.template_id  =  data._id;
                    fillEmailScreen(data);
                    break; 
                case "FACEBOOK_ADS":
                    $scope.template_id  =  data._id;
                    fillFbScreen(data);
                    break;      
                }
            });
        }
        else{
            $scope.selectTool($scope.templateType);
        }
    }
   
    $scope.getAppTemplatesById = function(templateId){

        if(templateId != ''){
            $scope.btnUpdatePush = false;
            $scope.btnSavePush = true;
            appIceService.getAppTemplatesById(templateId).then(function(data){
                switch(data.template_type){
                case "PUSH":
                    $scope.updateTemplateId = data._id;
                    $scope.template_id  =  data._id;
                    $scope.clearTemplateId = '';
                    fillPushScreen(data);
                    break;
                case "IN-APP":
                    $scope.template_id  =  data._id;
                    fillInAppScreen(data);
                    break;
                case "SURVEY":
                    $scope.template_id  =  data._id;
                    fillSurveyScreen(data);
                    break;
                case "RATING":
                    $scope.template_id  =  data._id;
                    fillRatingScreen(data);
                    break;
                    case "SMS":
                        $scope.template_id  =  data._id;
                        fillSmsScreen(data);
                        break; 
                case "WEB_PUSH":
                    $scope.template_id  =  data._id;
                    fillWebPushScreen(data);
                    break;
                case "WEB_POPUP":
                    $scope.template_id  =  data._id;
                    fillWebPopUpScreen(data);
                    break;
                case "EMAIL":
                    $scope.template_id  =  data._id;
                    fillEmailScreen(data);
                    break;   
                case "FACEBOOK_ADS":
                    $scope.template_id  =  data._id;
                    fillFbScreen(data);
                    break;   
                }
                
            });
        }
        else{
            $scope.selectTool($scope.templateType);
        }
    }

    /* Push notification form water for active update btn   */
    $timeout( function(){
        $scope.watcherCounter = 0;
        $scope.$watchCollection('cTools', function(newValue, oldValue) {
            if(newValue != oldValue){
                
                if($scope.watcherCounter > 2){
                    document.getElementById("btnUpdatePush").disabled = false;
                }else{
                    $scope.watcherCounter++;
                    // document.getElementById("btnUpdatePush").disabled = true;
                }
            }
          });
    }, 3000);

    $scope.updateTemplateSettingsTools =  function(){
        let diff = $('#diff').val();
        let loop = $('#loop').val();
        let gap = $('#gap').val();
        
        var customDataList = getCustomDataList($scope.customDataList,true)

           // Now This Function will validate Inputs and also set default value
        if(validatePushInputs()){
            return
        }        
        // hide and remove validation message
        $scope.validationMessage        = false;
        $scope.validationErrorMessage   = ""; 

        var actionsList         = [];
        if($scope.actionsList.length > 0 && $scope.actionStyle == true){
            for(var i=0; i<$scope.actionsList.length; i++){
                actionsList.push({
                    nh      : $scope.actionsList[i].actionName,
                    et      : $scope.actionsList[i].actionType,
                    eurl    : $scope.actionsList[i].actionExternalUrl
                });
            }
            $scope.cTools.externalUrl = '';
            $scope.cTools.notificationType = '';
        }


        var expanded = '';
        if($scope.cTools.expendedImg){
            expanded = 'expanded';
        }
        if ($scope.savevariantdata.length > 0) {
            $scope.variantType = true;
            $scope.savevariantdata[$scope.activeVariance].variance_name = $scope.cTools.template_name;
            $scope.savevariantdata[$scope.activeVariance].notificationHeader =  $scope.cTools.notificationHeader;
            $scope.savevariantdata[$scope.activeVariance].notificationDescription = $scope.cTools.notificationDescription;
            $scope.savevariantdata[$scope.activeVariance].expandedNotificationDescription = $scope.cTools.expandedNotificationDescription;
            $scope.savevariantdata[$scope.activeVariance].notificationImage = $scope.notificationImageFile;
            $scope.savevariantdata[$scope.activeVariance].expandedNotificationImage = $scope.expandedNotificationImageFile;
            $scope.savevariantdata[$scope.activeVariance].expandedNotificationImageFile =  $scope.expandedNotificationImageFile;
            $scope.savevariantdata[$scope.activeVariance].externalUrl = $scope.cTools.externalUrl;
            $scope.savevariantdata[$scope.activeVariance].actionsList =  $scope.actionsList;
            $scope.savevariantdata[$scope.activeVariance].customDataList = $scope.customDataList;
            $scope.savevariantdata[$scope.activeVariance].sound = $scope.sound;
            $scope.savevariantdata[$scope.activeVariance].vibrate = $scope.vibrate;
            $scope.savevariantdata[$scope.activeVariance].badge = $scope.badge;
            $scope.savevariantdata[$scope.activeVariance].pushType = expanded;
            //$scope.savevariantdata[$scope.activeVariance].cdata = $scope.customDataVariant[$scope.activeVariance];
            // $scope.customDataList = $scope.customDataVariant[$scope.activeVariance];
            $scope.customDataVariant.forEach((variant , index) => {
                $scope.savevariantdata[index].cdata = getCustomDataList(variant);
            });
            // cdata:customDataList
            $('#rdbAbManual').prop("checked", true);
            $scope.lcamp.AbTypeSelector = 'manual';
            $scope.setRangeSliderVariance($scope.savevariantdata, ($scope.controlGroupValue) ? $scope.controlGroupValue : 0);
            $scope.totalPer()
        var data = {
            template_name: $scope.cTools.template_name,
            template_type: 'PUSH',
            template: $scope.savevariantdata,
            isTemplateDeleted: "false",
            createdOn: semusiCommon.getCurrentDate(),
            modifiedOn: ""
        }

        }

        else {
            $scope.variantType = false;
        var data = {
            template_name:$scope.cTools.template_name,
            template_type:$scope.templateType,
            template:{
                    notificationHeader:$scope.cTools.notificationHeader,
                    notificationDescription:$scope.cTools.notificationDescription,
                    notificationImage:removeBaseUrl($scope.notificationImageFile,$scope.blobUrls),
                    expandedNotificationDescription: $scope.cTools.expandedNotificationDescription,
                    expandedNotificationImage:removeBaseUrl($scope.expandedNotificationImageFile,$scope.blobUrls),
                    and:{
                        b: $scope.bu,   // BaseUrl
                        i: $scope.gif_imgs,    // Series of images that we extract from the gif
                        d: diff ? diff : 0,   // Time difference between images display
                        l: loop ? loop : 0,  // How much time gap before repeating the images
                        g: gap ? gap : 0,   // How many times to loop the entire sequence
                    f: $scope.frame_ext,   // Extension of frames extracted from gif
                    m: $scope.m, // Full media url
                    },
                    ty:$scope.img_type, // Type of image uploaded
                    externalUrl:$scope.cTools.externalUrl,
                    notificationType:$scope.cTools.notificationType,
                    pushType:expanded,
                    actions: actionsList,
                    sound: $scope.sound,
                    vibrate: $scope.vibrate,
                    badge: $scope.badge,
                    cdata:customDataList
                },
            isTemplateDeleted:"false",
            modifiedOn:semusiCommon.getCurrentDate()
            }
            if($scope.cTools.expendedText != true ){
                data.template.expandedNotificationDescription = "";
            }
        }
        if($scope.camp_state=='ACTIVE' && (  $scope.user_role == "marketer"  ||  $scope.user_role == '"marketer"' )){
            $scope.template_name_error = "You are not authorized to Perform this action.";
            return false;
        }
        //validate template name before updating Push Setting 
     $scope.validateTemplateName(data.template_type, $scope.cTools.template_name, async function(response){
       if(!response){
        appIceService.updateTemplateSettingsTools($scope.template_id,data).then(function(data){
            if(data==undefined)$scope.template_name_error = "Oops! Something went wrong. Please try again.";
            if(data != ''){
                //submitAction(data._id);
                $scope.template_id = data._id;
                $('#campaignwizard').bwizard('next');
            }
        });
       }
    })
    }

    $scope.closeTemplate = function(clearTemplateId){
        if(clearTemplateId == '' || clearTemplateId == undefined){
            $scope.cTools = {};
            $scope.pushNotification = true;
            $scope.engageMentTool = true;
            $scope.inAppSurvey = true;
            $scope.inAppNotification = false;
            $scope.inAppRate = true;
            $scope.textMessage = true;
            $scope.textSms = true;
            $scope.web_push = false;
            $scope.facebook_ads = false;
        }else{
            window.location= appiceEncode.encodePayload("/dashboard?action=campaigns");     
        }
    }

    // function for cancelling the campaign///
    $scope.cancelCampaign = function(){
        window.location= appiceEncode.encodePayload("/dashboard?action=campaigns");
    }

    ///Pushnotification ends here////

    /// In-App Notification starts Here///
    $scope.setCta = function(){
        $scope.setAction = false;
        if($scope.inApp.sCta == true){
            $scope.setAction = true;
        }
    }

    $scope.changeViewMode = function(view){
        $scope.inApp.view_mode = view;
        $scope.leftCharacter = '';

        if(view == 'Fullscreen'){
            $scope.inAppFull = true;
            $scope.inAppMini = false;
            $scope.actionTapUrl = false;
            $scope.setAction = true;
            $scope.hideCta = true;
            $scope.header    = false;
            $scope.footer    = false;

            // manage view mode
            $scope.inAppDefaultFullImg = $scope.inAppImages.Fullscreen.active;
            $scope.inAppDefaultMiniImg = $scope.inAppImages.Mini.inactive;
            $scope.inAppDefaultHeaderImg = $scope.inAppImages.Header.inactive;
            $scope.inAppDefaultFooterImg = $scope.inAppImages.Footer.inactive;

        }else if(view == 'Mini') {
            $scope.inAppFull = false;
            $scope.inAppMini = true;
            $scope.actionTapUrl = true;
            $scope.setAction = true;
            $scope.hideCta = true;
            $scope.header    = false;
            $scope.footer    = false;

            // manage view mode
            $scope.inAppDefaultFullImg = $scope.inAppImages.Fullscreen.inactive;
            $scope.inAppDefaultMiniImg = $scope.inAppImages.Mini.active;
            $scope.inAppDefaultHeaderImg = $scope.inAppImages.Header.inactive;
            $scope.inAppDefaultFooterImg = $scope.inAppImages.Footer.inactive;
        }
        else if(view == 'Header') {
            $scope.inAppFull = false;
            $scope.inAppMini = false;
            $scope.actionTapUrl = true;
            $scope.setAction = false;
            $scope.hideCta = false;
            $scope.header    = true;
            $scope.footer    = false;

            // manage view mode
            $scope.inAppDefaultFullImg = $scope.inAppImages.Fullscreen.inactive;
            $scope.inAppDefaultMiniImg = $scope.inAppImages.Mini.inactive;
            $scope.inAppDefaultHeaderImg = $scope.inAppImages.Header.active;
            $scope.inAppDefaultFooterImg = $scope.inAppImages.Footer.inactive;
        }
        else if(view == 'Footer') {
            $scope.inAppFull = false;
            $scope.inAppMini = false;
            $scope.actionTapUrl = true;
            $scope.setAction = false;
            $scope.hideCta = false;
            $scope.header    = false;
            $scope.footer    = true;

            // manage view mode
            $scope.inAppDefaultFullImg = $scope.inAppImages.Fullscreen.inactive;
            $scope.inAppDefaultMiniImg = $scope.inAppImages.Mini.inactive;
            $scope.inAppDefaultHeaderImg = $scope.inAppImages.Header.inactive;
            $scope.inAppDefaultFooterImg = $scope.inAppImages.Footer.active;
        }
    }

    $scope.manageCurrentImg = function(){

    }

    /// Save InApp settings///
    $scope.saveInAppSettings = function(){
        function validateUrl(value) {
			return /^(?:(?:(?:https?|ftp):)?\/\/)(?:\S+(?::\S*)?@)?(?:(?!(?:10|127)(?:\.\d{1,3}){3})(?!(?:169\.254|192\.168)(?:\.\d{1,3}){2})(?!172\.(?:1[6-9]|2\d|3[0-1])(?:\.\d{1,3}){2})(?:[1-9]\d?|1\d\d|2[01]\d|22[0-3])(?:\.(?:1?\d{1,2}|2[0-4]\d|25[0-5])){2}(?:\.(?:[1-9]\d?|1\d\d|2[0-4]\d|25[0-4]))|(?:(?:[a-z\u00a1-\uffff0-9]-*)*[a-z\u00a1-\uffff0-9]+)(?:\.(?:[a-z\u00a1-\uffff0-9]-*)*[a-z\u00a1-\uffff0-9]+)*(?:\.(?:[a-z\u00a1-\uffff]{2,})))(?::\d{2,5})?(?:[/?#]\S*)?$/i.test(value);
		 }		
        	//   Validating the Campaign name to contain only alphabet, number and space
        if($scope.inApp.template_name=="" || $scope.inApp.template_name == undefined  || $scope.inApp.template_name.trim().length==0 ){
            $scope.template_name_error = "Enter a valid template name.";
            return false;
        }
        /* code start  for inapp cdata  */
        var customDataList = getCustomDataList($scope.customDataList,false)
        /* code end for inapp cdata  */
        var nh = '';
        var nd = '';
        var iconImg = '';

        if($scope.inApp.view_mode == 'Fullscreen'){
            nd = $scope.inApp.inAppDescription;
            nh = $scope.inApp.inAppHeader;
        }
        else if($scope.inApp.view_mode == 'Mini'){
            nd = $scope.inApp.inAppMiniDesc;
            iconImg = $scope.iconInAppImageFile;
        }
        else if($scope.inApp.view_mode == 'Header'){
                nd = $scope.inApp.inAppHeaderDesc;
                iconImg = $scope.iconInAppImageFileHeader;
            }
            else if($scope.inApp.view_mode == 'Footer'){
                nd = $scope.inApp.inAppFooterDesc;
                iconImg = $scope.iconInAppImageFileFooter;
        }
        if($scope.inApp.headerTextClr == undefined || $scope.inApp.headerTextClr == ''){
            $scope.inApp.headerTextClr = '#000000'
           }
           if($scope.inApp.descriptionTextClr == undefined || $scope.inApp.descriptionTextClr == ''){
            $scope.inApp.descriptionTextClr = '#000000'
           }
           if($scope.inApp.backgroundColor == undefined || $scope.inApp.backgroundColor == ''){
            $scope.inApp.backgroundColor = '#000000'
           }
           if($scope.inApp.submitBtnTextClr == undefined || $scope.inApp.submitBtnTextClr == ''){
            $scope.inApp.submitBtnTextClr = '#000000'
           }

        var data = {
            template_name:$scope.inApp.template_name,
            template_type:'IN-APP',
            template:{
                        view_mode:$scope.inApp.view_mode,
                        notificationHeader: nh,
                        notificationDescription: nd,
                        notificationImage:removeBaseUrl($scope.inAppFullImageFile,$scope.blobUrls),
                        iconImage: removeBaseUrl(iconImg,$scope.blobUrls),
                        notificationType: $scope.cTools.notificationType, 
                        actionUrl:$scope.inApp.inAppActionUrl,
                        showAction:$scope.inApp.sCta,
                        el: $scope.expandedImageInapp_,
                        headerTextClr:$scope.inApp.headerTextClr,
                        descriptionTextClr:$scope.inApp.descriptionTextClr,
                        submitBtnTextClr:$scope.inApp.submitBtnTextClr,
                        backgroundColor:$scope.inApp.backgroundColor,
                        cdata:customDataList
                    },
            isTemplateDeleted:"false",
            createdOn:semusiCommon.getCurrentDate(),
            modifiedOn:""
        }
        // pass action Tittle Only if Call to action is true 
        if ($scope.inApp.sCta) {
            //if user has given value pass it otherwise pass empty string
            data.template.actionTitle = $scope.inApp.inAppActionTitle || '';
        }
       //validate template name before Saving InApp Setting  
    $scope.validateTemplateName(data.template_type,$scope.inApp.template_name, async function(response){
       if(!response){

        appIceService.saveInAppSettings(data).then(function(data){
            if(data==undefined)$scope.template_name_error = "Oops! Something went wrong. Please try again.";
            if(data != ''){
                $scope.template_id = data._id;
                $('#campaignwizard').bwizard('next');
            }
        })

            }
        })
    } 
    $scope.savevariantDataPush = function (lang, type) {
        if ($scope.cTools.template_name == "" || $scope.cTools.template_name == undefined || $scope.cTools.template_name.trim().length == 0) {
            $scope.template_name_error = "Enter template name.";
            return false;
        } else {
            $scope.template_name_error = '';  
        }
        var data;
        if(type == 'webpush'){
           data = {
            variance_top_name: lang.name,
            variance_id: lang._id,
            title : $scope.web_push_obj.title,
            message : $scope.web_push_obj.message,
            url : $scope.web_push_obj.url,
            icon : $scope.web_push_obj.icon,
            extendedImage : $scope.expandedNotificationImageFile,
            actions : $scope.actionsList,
            actionName  : $scope.action.actionName,
            actionExternalUrl : $scope.action.actionExternalUrl,
            actionType : $scope.action.actionType,
            customDataList: $scope.customDataList,
           }
        } else {
         data = {
            variance_top_name: lang.name,
            variance_id: lang._id,
            variance_name: $scope.cTools.template_name,
            notificationHeader:  $scope.cTools.notificationHeader ,
            notificationDescription:$scope.cTools.notificationDescription,
            expandedNotificationDescription: $scope.cTools.expandedNotificationDescription,
            notificationImage:  $scope.notificationImageFile,
            expandedNotificationImage:  $scope.expandedNotificationImageFile,
            expandedNotificationImageFile:  $scope.expandedNotificationImageFile,
            externalUrl: $scope.cTools.externalUrl,
            actionsList:  $scope.actionsList,
            customDataList: $scope.customDataList,
            expendedImg : $scope.cTools.expendedImg,
            actionStyle : $scope.actionStyle, 
            notifyType: $scope.cTools.notifyType,
            sound: $scope.sound,
            vibrate: $scope.vibrate,
            badge: $scope.badge,
            // cdata:customDataList
           
        }
         }

        $scope.variantType = true;

        $scope.savevariantdata.push(data);
        $scope.showVariantPushData($scope.savevariantdata.length -1, type,variantType)
    }

    function handleVaraintChange(index) {
        if (typeof $scope.customDataVariant[index] === 'undefined') {
            if ($scope.customDataList.length > 0 && ($scope.savevariantdata[index].customDataList != $scope.savevariantdata[index - 1].customDataList)) {
                $scope.customDataVariant[index] = ($scope.savevariantdata[index].customDataList)
                $scope.customDataList = $scope.customDataVariant[index];
            } else {

                $scope.customDataVariant.push([{
                    key: "",
                    value: ""
                }]);
                $scope.customDataList = $scope.customDataVariant[index];
            }
        }
        else {
            const { key } = $scope.customDataVariant[index].length > 0 ? $scope.customDataVariant[index][0] : {};

            // Check the keys and call the appropriate function
            if (key == undefined) {
                const temp = {
                    template: {
                        cdata: $scope.customDataVariant[index]
                    }
                }
                setCustomdata(temp)

            } else {
                $scope.customDataList = $scope.customDataVariant[index];
            }
        }
    }
    $scope.copyTemplateVariantPush = function (index) {

        var data = {
            variance_name:  'copy' + $scope.savevariantdata[index].variance_name,
            notificationHeader:  $scope.cTools.notificationHeader ,
            notificationDescription:$scope.cTools.notificationDescription,
            expandedNotificationDescription: $scope.cTools.expandedNotificationDescription,
            notificationImage:  $scope.notificationImageFile,
            expandedNotificationImage: $scope.expandedNotificationImageFile,
            expandedNotificationImageFile:  $scope.expandedNotificationImageFile,
            externalUrl: $scope.cTools.externalUrl,
            actionsList:  $scope.actionsList,
            customDataList: $scope.customDataList,
            expendedImg : $scope.cTools.expendedImg,
            actionStyle : $scope.actionStyle, 
            notifyType: $scope.cTools.notifyType,
            sound: $scope.sound,
            vibrate: $scope.vibrate,
            badge: $scope.badge
        }

        $scope.savevariantdata.push(data);
    }
    $scope.updateCdata  = function (){

        $scope.customDataVariant[$scope.activeVariance] = $scope.customDataList;
        $scope.watcherCounter = 3;
    }

    $scope.showVariantPushData = function (index, type, variantType) {
        if($scope.cTools.template_name != undefined){
            $scope.savevariantdata[$scope.activeVariance].variance_name = $scope.cTools.template_name;
        }
        var arr = []
        $scope.savevariantdata.forEach((item) => {
               arr.push({
                variance_top_name : item.variance_top_name,
                variance_id : item.variance_id,
                variant_type : variantType,
                typeVariant : (item.typeVariant) ? item.typeVariant : undefined
            })
        })
        $scope.savevariantdata[$scope.activeVariance] = {};
        for(i = 0; i<arr.length; i++){
            $scope.savevariantdata[i].variance_top_name = arr[i].variance_top_name;
            $scope.savevariantdata[i].variance_id = arr[i].variance_id;
            $scope.savevariantdata[i].variant_type = variantType;
            $scope.savevariantdata[i].typeVariant = (arr[i].typeVariant) ? arr[i].typeVariant : undefined;
            } 
            if(type == 'webpush'){
                $scope.savevariantdata[$scope.activeVariance].title = $scope.web_push_obj.title;
                $scope.savevariantdata[$scope.activeVariance].message = $scope.web_push_obj.message ;
                $scope.savevariantdata[$scope.activeVariance].url = $scope.web_push_obj.url;
                $scope.savevariantdata[$scope.activeVariance].icon = $scope.web_push_obj.icon;
                $scope.savevariantdata[$scope.activeVariance].extendedImage = $scope.expandedNotificationImageFile;
                $scope.savevariantdata[$scope.activeVariance].customDataList = $scope.customDataList;
                $scope.savevariantdata[$scope.activeVariance].cdata = $scope.customDataList;
                $scope.savevariantdata[$scope.activeVariance].actions = [{
                    actionName : $scope.action.actionName,
                    actionExternalUrl : $scope.action.actionExternalUrl,
                    actionType : $scope.action.actionType
                }]
                $scope.savevariantdata[$scope.activeVariance].actionName = $scope.action.actionName
                $scope.savevariantdata[$scope.activeVariance].actionExternalUrl = $scope.action.actionExternalUrl;
                var obj = $scope.savevariantdata[index];
                if(obj['variance_name'] != undefined && obj['variance_name'] != $scope.cTools.template_name){
                    $scope.cTools.template_name = obj['variance_name'];
                }
                $scope.web_push_obj.title =  obj['title'];
                $scope.web_push_obj.message = obj['message'];
                $scope.web_push_obj.url = obj['url'];
                $scope.web_push_obj.icon = obj['icon'];
                $scope.expandedNotificationImageFile = obj['extendedImage'];
                $scope.actionsList = obj['actions'];
                $scope.action.actionName = obj['actionName'];
                $scope.action.actionExternalUrl = obj['actionExternalUrl'];
                $scope.activeVariance = index;
                if(typeof $scope.actionsList == 'undefined'){
                    if($scope.actionsList && $scope.savevariantdata[index].actions != $scope.savevariantdata[index-1].actions){
                        $scope.actionsList = $scope.savevariantdata[index].actions
                    } else {
                        $scope.action.actionName = '';
                        $scope.action.actionExternalUrl = '';
                        $scope.action.actionType = 'dl';
                        $scope.actionsList = ([{
                            actionName:$scope.action.actionName,actionType:$scope.action.actionType,actionExternalUrl:$scope.action.actionExternalUrl
                        }]);
                    }
                }
                var a = document.querySelectorAll(".downSlide");
                for (var i = 0, length = a.length; i < length; i++) {
                    var b = document.querySelector("li.downSlide.active");
                    if (b) b.classList.remove("active");
                }
                setTimeout(function(){
                    document.querySelectorAll(".downSlide")[index].classList.add('active')
                }, 200)
                if(obj['extendedImage']=='' || obj['extendedImage'] == undefined){
                    $scope.cTools.expendedImg = false;
                    $scope.isExpendedImg = false; 
                    setTimeout(function(){
                        $('#WebIsExpanded').hide();
                        $('#WebExpImguploader').show();
                    }, 200)
                }else{
                    $scope.cTools.expendedImg = true; 
                    $scope.isExpendedImg = true;
                    setTimeout(function(){
                    $('#WebIsExpanded').show();
                    $('#WebExpImguploader').hide(); 
                },200)
                }
                if(obj['actions'] && obj['actions'].length > 0 && obj['actions'][0].actionExternalUrl !='' && obj['actions'][0].actionExternalUrl != undefined) {
                    $scope.actionStyle = true;
                    $scope.actionIndexSave = true;
                    $scope.actionSave = false;
                    $scope.action = obj['actions'][0];
                    setTimeout(function(){ 
                            $('.ifActionIsYes').show(); 
                            $('#webAddActionBtn').show();                               
                            $('#ifActionIsNo').hide();
                            $('#webIfActionIsNo').hide();
                    },300)  
                } else{
                    $('#webAddActionBtn').hide();
                    $('#webIfActionIsNo').show();
                    $scope.actionStyle = false;
                }
                //for web-push notification
                $scope.cTools.customDataList = obj['customDataList'];
                handleVaraintChange(index)
            } else {       
        $scope.savevariantdata[$scope.activeVariance].notificationHeader = $scope.cTools.notificationHeader;
        $scope.savevariantdata[$scope.activeVariance].notificationDescription = $scope.cTools.notificationDescription;
        $scope.savevariantdata[$scope.activeVariance].expandedNotificationDescription = $scope.cTools.expandedNotificationDescription;
        $scope.savevariantdata[$scope.activeVariance].notificationImage = $scope.notificationImageFile;
        $scope.savevariantdata[$scope.activeVariance].expandedNotificationImage = $scope.expandedNotificationImageFile;
        $scope.savevariantdata[$scope.activeVariance].externalUrl = $scope.cTools.externalUrl;
        $scope.savevariantdata[$scope.activeVariance].actionsList = $scope.actionsList;
        $scope.savevariantdata[$scope.activeVariance].customDataList = $scope.customDataList;
        $scope.savevariantdata[$scope.activeVariance].expendedImg = $scope.cTools.expendedImg
        $scope.savevariantdata[$scope.activeVariance].actionStyle = $scope.actionStyle,
        $scope.savevariantdata[$scope.activeVariance].sound = $scope.sound;
        $scope.savevariantdata[$scope.activeVariance].vibrate = $scope.vibrate;
        $scope.savevariantdata[$scope.activeVariance].badge = $scope.badge;
        $scope.savevariantdata[$scope.activeVariance].notifyType =  $scope.cTools.notifyType;
        $scope.savevariantdata[$scope.activeVariance].cdata = $scope.customDataList;
        $scope.savevariantdata[$scope.activeVariance].pushType =  ($scope.cTools.expendedImg) ? "expanded" : '';
      
        var obj = $scope.savevariantdata[index];
        
        if(obj['variance_name'] != undefined && obj['variance_name'] != $scope.cTools.template_name){
            $scope.cTools.template_name = obj['variance_name'];
        }


        $scope.cTools.notificationHeader =  obj['notificationHeader'];
        $scope.cTools.notificationDescription = obj['notificationDescription'];
        $scope.cTools.expandedNotificationDescription = obj['expandedNotificationDescription'];
        $scope.notificationImageFile = obj['notificationImage'];
        $scope.expandedNotificationImageFile = obj['expandedNotificationImage'];
        $scope.cTools.externalUrl = obj['externalUrl'];
        $scope.cTools.actionsList =obj['actionsList'];
        $scope.cTools.customDataList = obj['customDataList'];
        $scope.cTools.expendedImg = obj['expendedImg'];
        $scope.actionStyle =  obj['actionStyle'];
        $scope.sound = obj['sound'];
        $scope.vibrate =obj['vibrate'];
        $scope.badge = obj['badge'];
        $scope.cTools.notifyType = obj['notifyType'];
        $scope.pushType = obj['pushType']
        setTimeout(function(){
        $scope.expandedNotificationImageFile != '' ? $('#expImguploader').hide() : $('#expImguploader').show()
        }, 50)
              //Reset config
        resetUiChangeOnVariant($scope.cTools.expendedImg, $scope.actionStyle);
        $scope.activeVariance = index;
        // for push templates
        // made a common  function for add and edit as both are almost same
         handleVaraintChange(index)
        } 
        //controlling the custom data Button on variant 
        //manage custom data for new formatt array type
        if(Array.isArray($scope.customDataList)){
        if( $scope.customDataList[0].key != '' &&  $scope.customDataList[0].value != ''){
            $scope.customDataStyle = true;
            $scope.isCustomData = true;
        }else{
            $scope.customDataStyle = false;
            $scope.isCustomData = false;
        }
       }else{
        //manage custom data for new formatt array type
        var customList = $scope.customDataList
        $scope.customDataList=[]
        var cDataObj = Object.keys(customList);
            angular.forEach(cDataObj, function(key){
                $scope.customDataList.push({
                    key: key,
                    value: decodeURIComponent(customList[key])
                });
            });
       }
        var a = document.querySelectorAll(".pushSlide");
        for (var i = 0, length = a.length; i < length; i++) {
            var b = document.querySelector("li.pushSlide.active");
            if (b) b.classList.remove("active");
        }
        document.querySelectorAll(".pushSlide")[index].classList.add('active')
        $scope.variantType = true;
    }

    function resetUiChangeOnVariant(isexpended,isaction) {
        //Expanded Image Config
        if(isexpended){
            if(isaction){
                $scope.leftCharBottom = 170;
            }else{
                $scope.leftCharBottom = 200;
            }
            $('#txtExpanded').hide();

            $('#isExpanded').show();
            $('#isExpanded').css('height','145px');
            $('#isExpanded').css('border','1px solid #2d353c');
            $('#expImguploader').show();
            $scope.isExpendedImg = true;
            if($('#expandedNotificationImageFile').val() == ''){
                $('#expImguploader').show();
                $('#pencilUpload').hide();
            }else if($scope.expandedNotificationImageFile != ''){
                $('#pencilUpload').show();
                $('#expImguploader').hide();                    
            }
        }
        else{
            if(isaction){
                $scope.leftCharBottom = 320;
            }else{
                $scope.leftCharBottom = 355;
            }
            $('#txtExpanded').show();
            $('#isExpanded').hide();
            $scope.isExpendedImg = false;
            $scope.expandedNotificationImageFile = '';
        }  
        
        //Action Style Config
        if(isaction){
            $scope.leftCharBottom -= 40;
            $('.ifActionIsYes').show();
            $('#addActionBtn').show();
            $('#ifActionIsNo').hide();
            $('#webIfActionIsNo').hide();
        }else{
            $scope.leftCharBottom += 40;
            $('.ifActionIsYes').hide();
            $('#addActionBtn').hide();
            $('#ifActionIsNo').show();
            $('#webIfActionIsNo').show();
        } 

    }

    //REMOVE CREATED VARIANT 
    $scope.removevariant = function(index, type) {
        $scope.variantArr.splice(index, 1);
        $scope.savevariantdata.splice(index, 1);
        if($scope.activeVariance == index) {
            $scope.activeVariance = 0;
            $scope.web_push_obj.title = $scope.savevariantdata[$scope.activeVariance].title  
            $scope.web_push_obj.message = $scope.savevariantdata[$scope.activeVariance].message
            $scope.web_push_obj.url =$scope.savevariantdata[$scope.activeVariance].url ;
            $scope.web_push_obj.icon =$scope.savevariantdata[$scope.activeVariance].icon;
            $scope.expandedNotificationImageFile = $scope.savevariantdata[$scope.activeVariance].extendedImage;
            $scope.actionsList = $scope.savevariantdata[$scope.activeVariance].actions;
            $scope.action.actionName = $scope.savevariantdata[$scope.activeVariance].actionName;
            $scope.action.actionExternalUrl = $scope.savevariantdata[$scope.activeVariance].actionExternalUrl; 
            $scope.showVariantPushData(0, type)
        } else {
            $scope.showVariantPushData($scope.savevariantdata.length - 1, type)
        }
        switch(type) {
            case 'PUSH':
                $scope.showVariantDataPush(index);
            case 'INAPP':
                $scope.showVariantDataInApp(index);
            case 'RATING':
                $scope.showVariantRatingData(index);
            case 'SURVEY':
                $scope.showVariantSurveyData(index);
            case 'WEBPUSH':
                $scope.showVariantWebPush(index);   
            default:
                return;    
        }
     }
    $scope.updateInAppSettingsTools  = function(){

        var nh = '';
        var nd = '';
        var iconImg = '';

        if($scope.inApp.view_mode == 'Fullscreen'){
            nd = $scope.inApp.inAppDescription;
            nh = $scope.inApp.inAppHeader;
        }
        else if($scope.inApp.view_mode == 'Mini'){
            nd = $scope.inApp.inAppMiniDesc;
            iconImg = $scope.iconInAppImageFile;
        }
        else if($scope.inApp.view_mode == 'Header'){
               if( $scope.inApp.inAppHeaderDesc == "" ||$scope.inApp.inAppHeaderDesc == undefined  ){
                $scope.template_name_error = "Kindly Enter Template Description.";
                return false
               } else{
            nd = $scope.inApp.inAppHeaderDesc;
            nh = $scope.inApp.inAppHeaderDesc;
            iconImg = $scope.iconInAppImageFileHeader;
            }
        }
        else if($scope.inApp.view_mode == 'Footer'){
            if( $scope.inApp.inAppFooterDesc == "" ||$scope.inApp.inAppFooterDesc == undefined  ){
                $scope.template_name_error = "Kindly Enter Template Description.";
                return false
               } else{
            nd = $scope.inApp.inAppFooterDesc;
            nh = $scope.inApp.inAppFooterDesc;
            iconImg = $scope.iconInAppImageFileFooter;
         }
        }
        /* code start  for inapp cdata  */
        var customDataList = getCustomDataList($scope.customDataList,false)
        /* code end for inapp cdata  */
        var data = {
            template_name:$scope.inApp.template_name,
            template_type:'IN-APP',
            template:{
                        view_mode:$scope.inApp.view_mode,
                        notificationHeader:nh,
                        notificationDescription:nd,
                        notificationImage:removeBaseUrl($scope.inAppFullImageFile,$scope.blobUrls),
                        iconImage: removeBaseUrl(iconImg,$scope.blobUrls),
                        notificationType: $scope.cTools.notificationType,
                        actionUrl:$scope.inApp.inAppActionUrl,
                        showAction:$scope.inApp.sCta,
                        el: $scope.expandedImageInapp_,
                        headerTextClr:$scope.inApp.headerTextClr,
                        descriptionTextClr:$scope.inApp.descriptionTextClr,
                        submitBtnTextClr:$scope.inApp.submitBtnTextClr,
                        backgroundColor:$scope.inApp.backgroundColor,
                        cdata:customDataList
                    },
            isTemplateDeleted:"false",
            modifiedOn:semusiCommon.getCurrentDate()
        }
 

        // pass action Tittle Only if Call to action is true 
        if ($scope.inApp.sCta) {
             //if user has given value pass it otherwise pass empty string
            data.template.actionTitle = $scope.inApp.inAppActionTitle || '';
        }

//validate template name before updating InApp Setting
   $scope.validateTemplateName(data.template_type,$scope.inApp.template_name, async function(response){
     if(!response){
        appIceService.updateInAppSettingsTools($scope.template_id,data).then(function(data){
            if(data != ''){
                $scope.template_id = data._id;
                $('#campaignwizard').bwizard('next');
            }
        })
        
      }
     })
    }


    /** =================== survey template start ====================== **/  

    function surveyQuestionsInit (){
        $scope.surveyQuestions[$scope.surveyCounter] = {
                                                  question : '',
                                                  showQues : true,
                                                  ischoice : true,
                                                  isTextField : false,
                                                  options:[],
                                                  questionType : "radiobuttonchoice",
                                                  otherOption: false
                                                }
    }

    // mange question box
    $scope.showQuestionBox = function(){
        $scope.surveyQuestions[$scope.surveyCounter].showQues = true;
    }

    // manage survey question type
    $scope.changeQuestionType = function(questionType){
        $scope.surveyQuestions[$scope.surveyCounter].questionType = questionType;
        if(questionType == "radiobuttonchoice"){
            $scope.surveyQuestions[$scope.surveyCounter].ischoice = true;
            $scope.surveyQuestions[$scope.surveyCounter].isTextField = false;
        }
        else if(questionType == "textinput"){
            $scope.surveyQuestions[$scope.surveyCounter].ischoice = false;
            $scope.surveyQuestions[$scope.surveyCounter].isTextField = true;
        }
    }

    $scope.addOption = function(){
        var submitFlag = true;
        $scope.isErrorMessage = false;
        $scope.question_error   = false;
        $scope.surveyName_error = false;

        if($scope.surveyQuestions[$scope.surveyCounter].ischoice && $scope.surveyQuestions[$scope.surveyCounter].question != '' ){
            $scope.surveyQuestions[$scope.surveyCounter].options.forEach(function(optionValue, index){
               if(optionValue == ''){
                    submitFlag = false;
                    $scope.isErrorMessage = true;
                    $scope.errorMessage = "Please enter option";
                    return false;          
               }
            });

            if(!submitFlag){
                return false;  
            }
        }

        if($scope.surveyQuestions[$scope.surveyCounter].question != ''){
            var len = $scope.surveyQuestions[$scope.surveyCounter].options.length
            if(len < 5){
                $scope.surveyQuestions[$scope.surveyCounter].options[len] = '';
            }
        }
    }

    $scope.addToQuestions = function(){
        $scope.question_error   = false;
        $scope.isErrorMessage = false;
        $scope.surveyName_error = false;

        if($scope.surveyQuestions[$scope.surveyCounter].ischoice 
            && $scope.surveyQuestions[$scope.surveyCounter].question != '' ){
            var  submitFlag = true;
            $scope.surveyQuestions[$scope.surveyCounter].options.forEach(function(optionValue, index){
               if(optionValue == ''){
                    submitFlag = false;
                    $scope.isErrorMessage = true;
                    $scope.errorMessage = "Please enter option";
                    return false;          
               }
            });
            if(!submitFlag){
                return false;  
            }
        }

        if($scope.surveyQuestions[$scope.surveyCounter].question == '' || $scope.surveyQuestions[$scope.surveyCounter].question == undefined){
            $scope.question_error_text = "Please enter question";
            $scope.question_error   = true;
            return false;
        }

        if( $scope.surveyQuestions[$scope.surveyCounter].options.length > 1 
            || $scope.surveyQuestions[$scope.surveyCounter].isTextField){

            $scope.surveyCounter = $scope.surveyQuestions.length-1;
            $scope.surveyCounter = ($scope.surveyQuestions[$scope.surveyCounter].question == '')? $scope.surveyQuestions.length-1: $scope.surveyQuestions.length;
            surveyQuestionsInit();
            $scope.isBack = true;
            $scope.isNext = false;
            $scope.survey.state = false;            
        }
        else{
            $scope.question_error   = true;
            $scope.question_error_text = "Please add more then 1 option of question";
            return false;
        }
    }

    $scope.SubmitSurvey = function(){
        $scope.surveyName_error = false;
        $scope.errorMessage = "";

        if($scope.survey.surveyName == ""){
            $scope.surveyName_error = true;
            return false;
        }

        var q = [];
        var submitFlag = true;
        $scope.isErrorMessage = false;

        // validate question and options
        $scope.surveyQuestions.forEach(function(val, key){
            if( (val.question == '' || val.question == undefined) && key == 0 ){
                submitFlag = false;
                $scope.isErrorMessage = true;
                $scope.errorMessage = "Please enter question name";
                return false;
            }

            if(val.ischoice && val.question != '' ){
                var flag = true;
                $scope.surveyQuestions[$scope.surveyCounter].options.forEach(function(optionValue, index){
                    if(optionValue == ''){
                        flag = false;
                        $scope.isErrorMessage = true;
                        $scope.errorMessage = "Please enter option";
                        return false;          
                   }
                });
                if(!flag){
                    submitFlag = false;
                    return false;  
                }
            }

            if(val.ischoice && val.options.length < 2 
                && val.question != '' ){
                submitFlag = false;
                $scope.isErrorMessage = true;
                $scope.errorMessage = "Please enter more then 1 options";
                return false;
            }

            if( ((val.ischoice && val.options.length > 0 
                &&  val.question == '') || (val.isTextField)) && val.question == '' ){
                submitFlag = false;
                $scope.isErrorMessage = true;
                $scope.errorMessage = "Please enter question name";
                return false;
            }


            if(val.question != '' && val.question != undefined){
                q.push({
                    id:key,
                    questionText : val.question,
                    questionOptions : getOptionsOfQues(key),
                    questionType    : val.questionType,
                    sampleText      : "Your answer goes here..",
                    otherOption     : val.otherOption
                });
            }
        });

        if(submitFlag){
 
            var obj = {
                template_name: $scope.survey.surveyName,
                template_type: "SURVEY",
                template: {
                    q: q,
                    nt: $scope.survey.nt,
                    st: $scope.survey.st,
                    bgclr: $scope.survey.bgclr,
                    txclr: $scope.survey.txclr,
                    isSurvey: $scope.survey.selectedBorder,
                    bobgclr: $scope.survey.bobgclr
                },
                isTemplateDeleted: "false",
                createdOn: semusiCommon.getCurrentDate(),
                modifiedOn: ""
            }
            
            if($scope.template_id == ''){
                var promise = appIceService.createSurvey(obj);
                promise.then(function(response){
                    if(response != ''){
                        $scope.template_id = response._id;
                        $('#campaignwizard').bwizard('next');
                    }
                });
            }
            else{
                var promise = appIceService.updateSurvey(obj, $scope.template_id);
                promise.then(function(response){
                    if(response != ''){
                        $scope.template_id = response._id;
                        $('#campaignwizard').bwizard('next');
                    }
                });
            }            
        }
    }

    var getOptionsOfQues = function(index){
        var tmp = [];
        $scope.surveyQuestions[index].options.forEach(function(value){
            tmp.push({optionText:value});
        });

        return tmp;
    }

    var setOptionsOfQues = function(options){
        var tmp = [];
        options.forEach(function(value){
            tmp.push(value.optionText);
        });

        return tmp;
    }

    $scope.removeOption = function($index){
        $scope.surveyQuestions[$scope.surveyCounter].options.splice($index,1);
    }

    $scope.removeSurvey = function(index){
        $scope.surveyQuestions[index].splice(index,1);   
    }

    $scope.back = function(){

        $scope.surveyCounter--;
        if($scope.surveyCounter == 0 ){
            $scope.isBack = false;
        }

        if( ($scope.surveyCounter+1) == $scope.surveyQuestions.length ){
            $scope.isNext = false;
        }
        else{
            $scope.isNext = true;
        }

        var state = false;
        if( $scope.surveyQuestions[$scope.surveyCounter].isTextField){
           state = true;
        }
        
        $scope.survey.state = state;
    }

    $scope.next = function(){
        $scope.surveyCounter++;
        if( ($scope.surveyCounter+1) == $scope.surveyQuestions.length ){
            $scope.isNext = false;
        }

        var state = false;
        if( $scope.surveyQuestions[$scope.surveyCounter].isTextField){
            state = true;
        }
        $scope.survey.state = state;
        $scope.isBack = true;
    }

    $scope.deleteSurvey = function(){
        if($scope.surveyCounter > 0){
            $scope.surveyQuestions.splice($scope.surveyCounter,1);
            $scope.isNext = false;
            $scope.back();
        }
        else{
            if($scope.surveyQuestions.length > 1){
                $scope.surveyQuestions.splice($scope.surveyCounter,1);
                $scope.isNext = false;
                $scope.isBack = false;
                if($scope.surveyQuestions.length > 1 && $scope.surveyCounter >= 0 ){
                    $scope.isNext = true;
                }

                var state = false;
                if( $scope.surveyQuestions[$scope.surveyCounter].isTextField){
                    state = true;
                }

                $scope.survey.state = state;
            }
            else{
                surveyQuestionsInit();
            }
        }
    }

    var fillWebPushScreen = async function(data){
        $scope.btnWebSavePush = false;
        $scope.btnWebUpdatePush = true;
        if (Array.isArray(data.template)) {
            $scope.variantType = true;
            $scope.savevariantdata = data.template;
            $scope.activeVariance = 0;
            $scope.web_push_obj = $scope.savevariantdata[0];
            let obj = $scope.savevariantdata[0];
            if(obj['variance_name'] != undefined && obj['variance_name'] != $scope.cTools.template_name){
                $scope.cTools.template_name = obj['variance_name'];
            }
            if(!$scope.campaignId) $scope.setRangeSliderVariance($scope.savevariantdata, ($scope.controlGroupValue) ? $scope.controlGroupValue : 0);
            $scope.totalPer()
            $scope.cTools.template_name = data.template_name
            $scope.oldTemplateName = data.template_name;
            $scope.web_push_obj.title = obj['title'];
            $scope.web_push_obj.message = obj['message'];
            if(obj['icon'] != ''){
                if(isValidUrl(obj['icon'])){
                    $scope.web_push_obj.icon =  obj['icon'];
                }else{
                    $scope.web_push_obj.icon = pushTemplate.blobContainerCDN + obj['icon'];
                }
            } else {
                $scope.web_push_obj.icon = '';
            }

            if(obj['extendedImage'] != ''){
                if(isValidUrl(obj['extendedImage'])){
                    $scope.expandedNotificationImageFile = obj['extendedImage'];
                }else{
                    $scope.expandedNotificationImageFile = pushTemplate.blobContainerCDN +obj['extendedImage'];
                }
             } else {
                $scope.expandedNotificationImageFile = '';
             }
            if(obj['actions']){
                $scope.actionsList = obj['actions'];
            } else {
                $scope.actionsList = []
            }
            if(data.template.extendedImage != ''){
                $scope.cTools.expendedImg = true; 
                $scope.isExpendedImg = true;
                setTimeout(function(){
                $('#WebIsExpanded').show();
                $('#WebExpImguploader').hide(); 
            },200)
            }else{
                $scope.cTools.expendedImg = false;
                $scope.isExpendedImg = false; 
                $('#WebIsExpanded').hide();
                $('#WebExpImguploader').show(); 
            }

            if(obj['actions'] && obj['actions'].length > 0) {
                $scope.actionStyle = true;
                $scope.actionIndexSave = true;
                $scope.actionSave = false;
                $scope.action = obj['actions'][0];
                setTimeout(function(){ 
                        $('.ifActionIsYes').show(); 
                        $('#webAddActionBtn').show();                               
                        $('#ifActionIsNo').hide();
                        $('#webIfActionIsNo').hide();
                },300)  
            } else{
                $('#webAddActionBtn').hide();
                $('#webIfActionIsNo').show();
                $scope.actionStyle = false;
            }
            // Rendering custom data for varaint type webppush templates
            $scope.customDataVariant = [];
            data.template.forEach((item) => {
                if(item.variance_top_name.includes('Variant')){
                        $scope.variantArr.push({
                            name : item.variance_top_name,
                            _id : item.variance_id
                        });
                }
                $scope.customDataVariant.push(item.customDataList);
            })         

                $scope.variantArr = [];
                data.template.forEach((item) => {
                    if(item.variance_top_name.includes('Variant')){
                            $scope.variantArr.push({
                                name : item.variance_top_name,
                                _id : item.variance_id
                            });
                    }
                })
                $scope.showVariantPushData(0, 'webpush',data.template.variant_type)           
        } else{
        $scope.variantArr = [];
        $scope.savevariantdata = [];
        $scope.otherProbs = [];
        $scope.controlGroupValue = 0;
        $scope.templateType = data.template_type;   
        $scope.cTools.template_name = data.template_name;
        $scope.oldTemplateName = data.template_name;
        $scope.web_push_obj.title = data.template.title;
        $scope.web_push_obj.message = data.template.message;
        if(data.template.icon != ''){
            if(isValidUrl(data.template.icon)){
                $scope.web_push_obj.icon = data.template.icon;
             }else{
                $scope.web_push_obj.icon = data.blobContainerCDN + data.template.icon;
            }
        }else {
            $scope.web_push_obj.icon = '';
        }

        if(data.template.extendedImage != ''){
            if(isValidUrl(data.template.extendedImage)){
                $scope.expandedNotificationImageFile = data.template.extendedImage;
            }else{
                 $scope.expandedNotificationImageFile = data.blobContainerCDN  + data.template.extendedImage;
            }
        } else {
            $scope.expandedNotificationImageFile = '';
        }
        $scope.cTools.expandedNotificationDescription = data.template.expandedNotificationDescription;
        if(data.template.externalUrl){
            $scope.web_push_obj.url = data.template.externalUrl;
        } else {
            $scope.web_push_obj.url = '';
            data.template.externalUrl = '';
        }
        if(data.template.actions){
            $scope.actionsList = data.template.actions;
        } else {
            $scope.actionsList = []
        }
        $scope.template_url_error = (500 - data.template.externalUrl.length) + ' Characters Left';
        $scope.template_title_error = (49 - data.template.title.length) + ' Characters Left';
        $scope.template_message_error = (119 - data.template.message.length) + ' Characters Left';
        if(data.template.extendedImage != ''){
            $scope.cTools.expendedImg = true; 
            $scope.isExpendedImg = true;
            setTimeout(function(){
            $('#WebIsExpanded').show();
            $('#WebExpImguploader').hide(); 
        },200)
        }else{
            $scope.cTools.expendedImg = false;
            $scope.isExpendedImg = false; 
            $('#WebIsExpanded').hide();
            $('#WebExpImguploader').show(); 
        }
        if (data.template.actions && data.template.actions.length > 0) {
            $scope.actionStyle = true;
            $scope.actionIndexSave = true;
            $scope.actionSave = false;
            $scope.action = data.template.actions[0];
            const showAction = async () => {
              await new Promise((resolve) => setTimeout(resolve, 300));
      
              $('.ifActionIsYes').show();
              $('#webAddActionBtn').show();
              $('#ifActionIsNo').hide();
              $('#webIfActionIsNo').hide();
            };
      
            await showAction();
          } else{
            $('#webAddActionBtn').hide();
            $('#webIfActionIsNo').show();
            $scope.actionStyle = false;
        }
        // Rendering custom data for non varaint in webppush template
        if(data.template.cdata && Object.keys(data.template.cdata).length > 0){
            setCustomdata(data)
            $scope.customDataStyle = true;
            $scope.isCustomData = true;
        }
      }
    }
    var fillEmailScreen = function(data){
        $scope.cTools.template_name = data.template_name
        $('#subjectData').val(data.template.subjectData)

        if(semusiCommon.getEmailState){     
        appIceService.getIEmailEditor().then(function(updatedData){
            if(updatedData){
             token = updatedData;
             beeConfig = {
                uid: '22', // [mandatory]
                container: 'bee-plugin-container', // [mandatory]
                autosave: 30, // [optional, default:false]
                language: 'en-US',
                trackChanges: true,
                mergeTags,
                workspace: {  // [optional, default: {type : 'default'}]
                    onSave: function (jsonFile, htmlFile) { },
                    onChange: function (jsonFile, response) { },
                    onSaveAsTemplate: function (jsonFile) { },
                    onAutoSave: function (jsonFile) { },
                    onSend: function (htmlFile) { },
                    onLoad: function (jsonFile) { },
                    onError: function (errorMessage) { },
                }
            }
            BeePlugin.create(token, beeConfig, function (bee) {

                var temp = JSON.parse(data.template.jsonData)
                bee.start(temp)
                    $scope.cTools.template_name = data.template_name
                    $('#subjectData').val(data.template.subjectData)                
                
            });
            beeConfig.onSave = function (jsonFile, htmlFile) {

                if($scope.cTools.template_name == undefined || $scope.cTools.template_name == ''){
                    $scope.template_name_error = 'Please enter template name.';
                    $('#template_name_error').html('Please enter template name.')
                
                }else if( $('#subjectData').val() == '' || $('#subjectData').val() == '' == undefined){
                    $scope.template_name_error = 'Please enter subjectData';
                    $('#template_name_error').html('Please enter subjectData')
                } else{
                    $('#template_name_error').html('')
                        var data = {
                            template_name:  $scope.cTools.template_name ,
                            template_type:'EMAIL',
                            template:{
                                subjectData :  $('#subjectData').val(),
                                bodyHtmlData : htmlFile,
                                jsonData : jsonFile,
                        
                            },
                            isTemplateDeleted:"false",
                            createdOn:semusiCommon.getCurrentDate(),
                            modifiedOn:"",
                        }
                        if($scope.camp_state=='ACTIVE' && ( $scope.user_role == "marketer" ||  $scope.user_role == '"marketer"' )){
                            $scope.template_name_error = "You are not authorized to Perform this action.";
                            $('#template_name_error').html($scope.template_name_error)
                            return false;
                        }
                    
                        appIceService.updateTemplateSettingsTools($scope.template_id,data).then(function(data){
                            if(data != ''){
                                $scope.template_id = data._id;
                                $('#campaignwizard').bwizard('next');
                            }
                        });
                }

                }
            }

        });
      }
    }

    var fillWebPopUpScreen = function(data){
        $scope.btnWebPopUpSavePush = false;
        $scope.btnWebPopUpUpdatePush = true;
        $scope.templateType = data.template_type;   
        $scope.cTools.template_name = data.template_name;
        $scope.web_pop_obj.mode = data.template.mode;
        $scope.web_pop_obj.title = data.template.title;
        $scope.web_pop_obj.message = data.template.message;
        if(isValidUrl(data.template.icon)){
            $scope.web_pop_obj.icon =  data.template.icon;
        }else{
            $scope.web_pop_obj.icon = data.blobContainerCDN + data.template.icon;
        }
        if(isValidUrl(data.template.iconB)){
            $scope.web_pop_obj.iconB =  data.template.iconB;
        }else{
            $scope.web_pop_obj.iconB = data.blobContainerCDN + data.template.iconB;
        }
        $scope.web_pop_obj.url = data.template.url;
        $scope.web_pop_obj.hc = data.template.hc;
        $scope.web_pop_obj.dc = data.template.dc;
        $scope.web_pop_obj.br = data.template.br;
        $scope.web_pop_obj.wh = data.template.wh;
        $scope.web_pop_obj.ps = data.template.ps;
        $scope.web_pop_obj.bg = data.template.bg;
        $scope.template_url_error = (500 - data.template.url.length) + ' Characters Left';
        $scope.template_title_error = (255 - data.template.title.length) + ' Characters Left';
        $scope.template_message_error = (1024 - data.template.message.length) + ' Characters Left';
    }


    var fillSmsScreen = function(data){
        $scope.btnSaveSms = true;
        $scope.btnUpdateSms = false;
        $scope.templateType = data.template_type;   
        $scope.cTools.template_name = data.template_name;
        $scope.tobj.smsContent = data.template.message;    
    }
    
    var fillFbScreen = function(data){
        $scope.btnFbUpdatePush = true;
        $scope.btnFbSavePush = false;
        $scope.cTools.template_name = data.template_name
        $scope.fb.heading = data.template.title
        $scope.fb.message = data.template.message

        $scope.fb.websiteurl = data.template.url
        $scope.fb.pageId = data.template.pageId
        $scope.fb.ads_account = data.template.adsAccountId
        if(data.template.icon != '' && data.template.icon != undefined){
            $scope.expandedNotificationImageFile = data.template.icon
            $scope.isFbAdsImg = true;
            $scope.exploderImg = true;
        }
       
    }
    var fillSurveyScreen = function(data){
        $scope.setSurveyVariables();
        $scope.survey.surveyName = data.template_name;
        $scope.survey.nt = data.template.nt;
        $scope.survey.st = data.template.st;
        $scope.survey.bgclr = data.template.bgclr;
        $scope.survey.selectedBorder = data.template.isSurvey;
        $scope.survey.txclr = data.template.txclr;
        $scope.survey.bobgclr = data.template.bobgclr;
        $scope.template_id  = data._id;
        $scope.surveyButton     = "Update";
        var ststus = false;

        data.template.q.forEach(function(elem, index){
            $scope.surveyCounter = index;
            surveyQuestionsInit();
            $scope.surveyQuestions[$scope.surveyCounter]['question'] = elem.questionText;
            $scope.surveyQuestions[$scope.surveyCounter].showQues = true;
            $scope.surveyQuestions[$scope.surveyCounter].questionType = elem.questionType;
            $scope.surveyQuestions[$scope.surveyCounter].otherOption = elem.otherOption;

            if(elem.questionType == "radiobuttonchoice"){
                ststus = false;
                $scope.surveyQuestions[$scope.surveyCounter].ischoice = true;
                $scope.surveyQuestions[$scope.surveyCounter].isTextField = false;
            }
            else{
                ststus = true;
                $scope.surveyQuestions[$scope.surveyCounter].ischoice = false;
                $scope.surveyQuestions[$scope.surveyCounter].isTextField = true; 
            }

            $scope.surveyQuestions[$scope.surveyCounter].options = setOptionsOfQues(elem.questionOptions);
            
            $scope.isBack = true;
            //$scope.survey.otherOption = elem.otherOption;
        });

        $scope.survey.state = ststus;
    }
    /** =================== end survey template start ====================== **/

    /** =================== rating template start ========================== **/
    $scope.isErrorMessage = false;
    $scope.isShowMsg = false;

    // manage thankyou message
    $scope.thankYouMsg = function(status){
        if($scope.appRating.message != '' && $scope.appRating.message != undefined){
            $scope.isShowMsg = status;
        }
    }

    $scope.pushStarCount = function(starCount){  
        $scope.starItems=[];
        for(i=0;i<starCount;i++){
            $scope.starItems.push({'id' :  i+1, 'name' : 'star' + parseInt(i+1)});
        }
    }

    $scope.SubmitRating = function(){
        $scope.isErrorMessage = false;
        $scope.ratingErrorMessage = '';

        // validate rating template name
        if($scope.appRating.templateName == undefined || $scope.appRating.templateName == '' ){
            $scope.isErrorMessage = true;
            $scope.ratingErrorMessage = 'Please enter rating name';
            return false;
        }

        // validate rating question
        if($scope.appRating.question == undefined || $scope.appRating.question == '' ){
            $scope.isErrorMessage = true;
            $scope.ratingErrorMessage = "Please enter rating question";
            return false;
        }

        // validate action button
        if($scope.appRating.action == undefined || $scope.appRating.action == '' ){
            $scope.isErrorMessage = true;
            $scope.ratingErrorMessage = "Please enter action button name";
            return false;
        }

        // validate Star count
        if($scope.appRating.starCount == undefined || $scope.appRating.starCount == '' ){
            $scope.isErrorMessage = true;
            $scope.ratingErrorMessage = "Please enter Star Count";
            return false;
        }

        // validate Star Colour
        if($scope.appRating.starColour == undefined || $scope.appRating.starColour == '' ){
            $scope.isErrorMessage = true;
            $scope.ratingErrorMessage = "Please enter Star Colour";
            return false;
        }

        // validate background colour
        if($scope.appRating.bgColour == undefined || $scope.appRating.bgColour == '' ){
            $scope.isErrorMessage = true;
            $scope.ratingErrorMessage = "Please enter background Colour";
            return false;
        }

        // validate submit button Text
        if($scope.appRating.sbBtnText == undefined || $scope.appRating.sbBtnText == '' ){
            $scope.isErrorMessage = true;
            $scope.ratingErrorMessage = "Please enter Submit Button Text";
            return false;
        }

        // validate submit Button Colour
        if($scope.appRating.sbBtnClr == undefined || $scope.appRating.sbBtnClr == '' ){
            $scope.isErrorMessage = true;
            $scope.ratingErrorMessage = "Please enter Submit Button Colour";
            return false;
        }

        var starRatingText=[];
        for(var i=0;i<$scope.appRating.starCount;i++){
             starRatingText.push(document.getElementById("star"+(i+1)).value);
        }

        var obj = {
                template_name: $scope.appRating.templateName,
                template_type: "RATING",
                template: {
                    question: $scope.appRating.question,
                    activeImage: $scope.activeImage,
                    disabledImage: $scope.disabledImage,
                    message: $scope.appRating.message,
                    title: $scope.appRating.action,
                    starCount: $scope.appRating.starCount,
                    starColour: $scope.appRating.starColour,
                    bgColour: $scope.appRating.bgColour,
                    sbBtnText: $scope.appRating.sbBtnText,
                    sbBtnClr: $scope.appRating.sbBtnClr,
                    starRatingText:starRatingText
                },
                isTemplateDeleted: "false",
                createdOn: semusiCommon.getCurrentDate(),
                modifiedOn: ""
            }

        if($scope.template_id == ''){
            var promise = appIceService.createRating(obj);
            promise.then(function(response){
                if(response != ''){
                    $scope.template_id = response._id;
                    $('#campaignwizard').bwizard('next');
                }
            });
        }
        else{
            var promise = appIceService.updateRating(obj, $scope.template_id);
            promise.then(function(response){
                if(response != ''){
                    $scope.template_id = response._id;
                    $('#campaignwizard').bwizard('next');
                }
            });
        }
    }

    // In case of update data 
    function fillRatingScreen(data){
        $scope.setRatingVariables();
        $scope.template_id  = data._id;
        $scope.ratingButton = "Update";
        $scope.activeImage  = data.template.activeImage;
        $scope.disabledImage = data.template.disabledImage;
        $scope.appRating.templateName = data.template_name;
        $scope.appRating.question = data.template.question;
        $scope.appRating.action = data.template.title;
        $scope.appRating.message = data.template.message;
        $scope.appRating.starCount = data.template.starCount;
        $scope.appRating.starColour = data.template.starColour;
        //Rating Text Screen 
        $scope.starItems=[];
        for(var i=0; i<data.template.starRatingText.length;i++){
            $scope.starItems.push({'value' : data.template.starRatingText[i], 'name' : 'star' + parseInt(i+1)});
        }
        $scope.appRating.bgColour = data.template.bgColour;
        $scope.appRating.sbBtnText = data.template.sbBtnText;
        $scope.appRating.sbBtnClr = data.template.sbBtnClr;
        $scope.showRatingImg = ratingImg();
    }

    var ratingImg = function(){
        var tmp = [];
        for(var i=0; i<5; i++){
           tmp.push({id:i, img:$scope.disabledImage});
        }
        return tmp; 
    }
    $scope.showRatingImg = ratingImg();

    $scope.changeImg = function(index){

        if(index == 0){
            if( $scope.showRatingImg[index].img == $scope.activeImage ){
                $scope.showRatingImg[index].img = $scope.disabledImage;
            }
            else{
                $scope.showRatingImg[index].img = $scope.activeImage;
            }

            for(var i=1; i<5; i++){
               $scope.showRatingImg[i].img = $scope.disabledImage;
            }
        }
        else{
            for(var i=0; i<=index; i++){
               $scope.showRatingImg[i].img = $scope.activeImage;
            }

            for(var i=index+1; i<5; i++){
               $scope.showRatingImg[i].img = $scope.disabledImage;
            }
        }
    }

    $scope.engageMentToolOpt = true; // show bwizard steps


    $scope.cancelCamp = function(){
        window.location.href = appiceEncode.encodePayload("dashboard?action=campaigns");
    }

    // listen device preview toggle action 
    $scope.$on('devicePreview',function(event, state){
        $scope.cTools.defaultDevice = state;
        if(state){
            $('#campIphonePreview').show();
            $('#campAndroidPreview').hide();
            $('#ifIosisTrue').show();
        }
        else{
            $('#campIphonePreview').hide();
            $('#campAndroidPreview').show();
            $('#ifIosisTrue').hide();
        }    
        
    });

/******************************** switch button action listen *******************************/
    // listen expendeded toggle action 
    $scope.$on('expendedImgAction',function(event, state){
        $scope.cTools.expendedImg = state;
        if(state){

            if ($scope.cTools.expendedText) {
                // If "Expanded Text" is also on, turn it off
                $scope.cTools.expendedText = false;
            }
            
            if($scope.actionStyle){
                $scope.leftCharBottom = 170;
            }else{
                $scope.leftCharBottom = 200;
            }
            $('#txtExpanded').hide();
            $('#exptextdiv').hide();

            $('#isExpanded').show();
            $('#isExpanded').css('height','145px');
            $('#isExpanded').css('border','1px solid #2d353c');
            $('#expImguploader').show();
            $scope.isExpendedImg = true;
            if($scope.expandedNotificationImageFile2 == ''){
                $('#expImguploader').show();
                $('#pencilUpload').hide();
            }else if($scope.expandedNotificationImageFile2 != ''){
                $scope.expandedNotificationImageFile = $scope.expandedNotificationImageFile2
            $('#expandedNotificationImageFile').show();
                $('#pencilUpload').show();
                $('#expImguploader').hide();                    
            }
        }
        else{

            if (!$scope.cTools.expendedText) {
                // If "Expanded Text" is also off, turn it on
                $scope.cTools.expendedText = true;
            }

            if($scope.actionStyle){
                $scope.leftCharBottom = 320;
            }else{
                $scope.leftCharBottom = 355;
            }
            $('#txtExpanded').show();
            $('#exptextdiv').show();
            $('#isExpanded').hide();
            $scope.isExpendedImg = false;
            //$('#expandedNotificationImageFile').hide();
            //$('#expandedNotificationImageFile').attr('src','');
            //$('#expandedNotificationImageFile').attr('height','')
            //$('#expandedNotificationImageFile').attr('width','')
            $scope.expandedNotificationImageFile = '';
        }  
        
    });


    $scope.$on('expandedImageInappAction', function(event, state){
        $scope.expandedImageInapp_ = state;
        if(state){
            $('#expandedHeader').show();
            $('#legacyHeader').hide();
            $('#expandedFooter').show();
            $('#legacyFooter').hide();

        $scope.expandedImageInapp_ = true;

    
        }else{
            $('#expandedHeader').hide();
            $('#legacyHeader').show();
            $('#expandedFooter').hide();
            $('#legacyFooter').show();

        $scope.expandedImageInapp_ = false;

        }
    });


  // listen expendeded texttt toggle action 
  $scope.$on('expendedTextAction', function(event, state){
    $scope.cTools.expendedText = state;
    if(state){

        if ($scope.cTools.expendedImg) {
            // If "Expanded Image" is also on, turn it off
            $scope.cTools.expendedImg = false;
        }

        $('#exptextdiv').show();
        $('#isExpanded').hide();

        $scope.expandedNotificationImageFile = "";
    }else{

        if (!$scope.cTools.expendedImg) {
            // If "Expanded Image" is also off, turn it on
            $scope.cTools.expendedImg = true;
        }
        $('#exptextdiv').hide();
        $('#isExpanded').show();
        $scope.expandedNotificationImageFile = "";
    }
        });

    $scope.$on('WebExpandedImgAction',function(event, state){
        $scope.cTools.expendedImg = state;
        if(state){
            setTimeout(function(){
                $('#WebExpImguploader').show();
                $('#WebIsExpanded').show();
            }, 100)
            $scope.isExpendedImg = true;
            if($scope.expandedNotificationImageFile == ''){
                setTimeout(function(){
                    $('#WebExpImguploader').show();
                }, 100)
            }else if($scope.expandedNotificationImageFile != ''){
                $('#WebExpImguploader').hide();                    
            }
        }else{
            $('#WebIsExpanded').hide();
            $scope.isExpendedImg = false;
            $scope.expandedNotificationImageFile = '';
        }
    });
   $scope.openWindows = ()=>{
        initiateOpenWindows();
    };

    $scope.$on('liveEventAction', function(event,state){
        $scope.liveEvent = state;
          if(state){
             $scope.liveEvent = true;
          }else{
             $scope.liveEvent = false;
          }
      });

$scope.openAndroid = ()=>{
    $scope.hide_android = false ;
    $('#andBtn').css('opacity','1');
    $('#winBtn').css('opacity','0.5');
    $('#windows').hide();
    $('#android').show();
    $scope.active_pre = "and";
    if($scope.showing_preview){
        showPreview()
    }
};

function initiateOpenWindows (){
    $scope.hide_windows = false ;
    $('#windows').show();
    $('#android').hide();
    $scope.active_pre = "win";
    if($scope.showing_preview){
        showPreview()
    }

}

function showWinPreview(){
    $scope.show_win_bg = true;
    $('#winBtn').css('opacity','1');
    $('#andBtn').css('opacity','0.5');
    
    $('#windows').css('position','absolute');
    $('#windows').css('top','28.5%');
    $('#windows').css('left','55%');
    $('#windows').css('transform','translate(-23%, -5%)');
    // //hero
    $('#heroImg').css('position','absolute');
    $('#heroImg').css('top','43%');
    $('#heroImg').css('left','61%');
    $('#heroImg').css('transform','translate(-23%, -5%)');

}

function showAndPreview(){
$scope.show_and_bg = true;
$('#andBtn').css('opacity','1');
$('#winBtn').css('opacity','0.5');
$('#android').css('position','absolute');
$('#android').css('top','31%');
$('#android').css('left','20.5%');
$('#android').css('transform','translate(-23%, -5%)');
// //hero
$('#heroImg').css('position','absolute');
$('#heroImg').css('top','46.5%');
$('#heroImg').css('left','26.5%');
$('#heroImg').css('transform','translate(-23%, -5%)');
}

function hideWinPreview(){
$scope.show_win_bg = false;
$('#windows').css('position', 'static');
$('#windows').css('transform','translate(0, 0)');
}

function hideAndPreview(){
$scope.show_and_bg = false;
$('#android').css('position', 'static');
$('#android').css('transform','translate(0, 0)');
$('#heroImg').css('position','static');
$('#heroImg').css('transform','translate(0, 0)');
}

function showPreview(){
hideWinPreview();
hideAndPreview(); 
if($scope.active_pre === "win"){
    showWinPreview()
}else{
    showAndPreview()
}
}

$scope.$on('showBg', function(){
$scope.showing_preview = !$scope.showing_preview;
if($scope.showing_preview){//preview mode
    showPreview()
}else{ //edit mode
    hideAndPreview();
    hideWinPreview();
}
});
    // listen action toggle action 
    $scope.$on('actionType',function(event, state){
        $scope.actionStyle = state;
        if(state){
            $scope.leftCharBottom -= 40;
            $('.ifActionIsYes').show();
            $('#addActionBtn').show();
            $('#ifActionIsNo').hide();
        }else{
            $scope.leftCharBottom += 40;
            $('.ifActionIsYes').hide();
            $('#addActionBtn').hide();
            $('#ifActionIsNo').show();
        } 
        
    });

   // listen web action toggle button switch
    $scope.$on('webActionType',function(event, state){
        $scope.actionStyle = state;
        if(state){
            $scope.leftCharBottom -= 40;
            $('.ifActionIsYes').show();
            $('#webAddActionBtn').show();
            $('#webIfActionIsNo').hide();
            $scope.web_push_obj.url = '';
        }else{
            $scope.leftCharBottom += 40;
            $('.ifActionIsYes').hide();
            $('#webAddActionBtn').hide();
            $('#webIfActionIsNo').show();
            $scope.action = {}
            $scope.actionsList = []
        } 
        
    });    

     // listen action toggle action 
     $scope.$on('customDataType',function(event, state){
               //when customdata is turned off 
               if(state==false){
                $scope.customDataList = [
                {
                    key:"",
                    value:""
                }
            ]; }
        $scope.customDataStyle = state;
        $scope.isCustomData = state;
        $scope.watcherCounter = 3;
    });

    function hideDisabledFeature() {
        appIceService.hideDisabledFeature().then(function (data) {
            const hideElement = (element, condition) => {
                if (element.length > 0) {
                    condition ? element.hide() : element.show();
                }
            };
    
            hideElement($('#external_Url_div'), data && data[0].features.deepLinkUrl);
            hideElement($("#ab_testing_variant"), data && data[0].features.ab_testing_variant);
            hideElement($("#language_variant"), data && data[0].features.language_variant);
            hideElement($("#actionButtonPush"), data && data[0].features.actionbuttonSettings);
            hideElement($("#specialAttributes"), data && data[0].features.specialattributes);  
            hideElement($("#conversion_lcamp"), data && data[0].features.conversionSettings);
            hideElement($("#delayLcamp"), data && data[0].features.delayLauch);
            hideElement($("#liveEvent_lcamp"), data && data[0].features.liveEventSett);
            hideElement($("#scheduler_lcamp"), data && data[0].features.schedulerSett);
            if (data[0].features.appInboxAndDeliveryType && $('#appinboxexp').length > 0 ) {
                $scope.$applyAsync(() => {
                    $('#appinboxexp').hide();
                   });                                      
            }

            if (data[0].features.appInboxAndDeliveryType ) {
                $scope.$applyAsync(() => {
                    handleColumnVisibility(cdata.data.columnStatus);
                   });                                      $('#appinboxexp').hide();
            }
        });
    }
    // listen notification toggle action 
    $scope.$on('notificationType',function(event, state){
        $scope.cTools.notifyType = state;
        if(state){
            $scope.cTools.notificationType  = 'lp';
            $('#external_Url_div').show();
            appIceService.hideDisabledFeature().then(function(data) {
                if (data && data[0].features.landingPageView) {
                    $('#webview_browser').hide();
                    }else{
                        $('#webview_browser').show();
                    }
        });
        }else{
            $scope.cTools.notificationType  = 'dl';
            appIceService.hideDisabledFeature().then(function(data) {
                    if (data && data[0].features.deepLinkUrl) {
                        $('#external_Url_div').hide();
                        }else{
                            $('#external_Url_div').show();
                        }
            });
        } 
    });

    // listen action toggle action 
    $scope.$on('soundAction',function(event, state){
        $scope.sound = state;
    });
    // listen vibrate toggle action 
    $scope.$on('vibrateAction',function(event, state){
        $scope.vibrate = state;
    });
    // listen badge toggle action 
    $scope.$on('increMentBadge',function(event, state){
        $scope.badge = state;
    });
    // listen survey switch
    $scope.$on('surveySwitch',function(event, state){
        $scope.survey.state = state;
        if(state){
            $scope.changeQuestionType('textinput');
        }
        else{
            $scope.changeQuestionType('radiobuttonchoice');
        }
    });

    $scope.remainCharacter = function(id, maxLength, type){
        // manage inapp left character message
        if(type == 'full'){
            $scope.leftCharBottom = -23;
        }else if(type =='mini'){
            $scope.leftCharBottom = 147;
        }else if(type =='header'){
            $scope.leftCharBottom = 267;
        }else if(type =='footer'){
            $scope.leftCharBottom = -26;
        }else if(type =='servey'){
            if($scope.surveyQuestions[$scope.surveyCounter].isTextField){
                $scope.leftCharBottom = 258;
            }else{
                $scope.leftCharBottom = -10;
            }
        }else if(type == 'ratingSubmit'){
            $scope.leftCharBottom = 30;
        }

        if(type == 'androidPush' && !$scope.cTools.expendedImg){
            $scope.leftCharBottom = 355;
        }
        if(type == 'androidPush' && $scope.cTools.expendedImg){
            $scope.leftCharBottom = 200;
        }
        if(type == 'androidPush' && $scope.actionStyle && $scope.cTools.expendedImg){
            $scope.leftCharBottom = 160;
        }
        if(type == 'androidPush' && $scope.actionStyle && !$scope.cTools.expendedImg){
            $scope.leftCharBottom = 320;
        }
        if(type == 'iosPush'){
            $scope.leftCharBottom = 330;
        }
        if(type == 'iosPush' && $scope.actionStyle){
            $scope.leftCharBottom = 290;
        }
        if(type == 'iosPush' && $scope.actionStyle && $scope.actionsList.length == 2){
            $scope.leftCharBottom = 250;
        }

        var modelValue = document.getElementById(id).value;
        if(modelValue.length >= maxLength){
            $scope.leftCharacter = '';
            return false;
        }else if(modelValue.length == 0){
            $scope.leftCharacter = '';
            return false;
        }
        $scope.leftCharacter = (maxLength - modelValue.length)+' character left';
    }

    $scope.remainCharacterHide = function(){
        $scope.leftCharacter = '';
    }

    $scope.isPopboxOpen = false;
    // open and close data model for conversion
    $scope.conversionPopupBoxOpen = function(){
        if(! $scope.eventFlag){
            $scope.getEvents();
        }
        $scope.isPopboxOpen = ($scope.isPopboxOpen)? false : true;
        if($scope.isPopboxOpen) {
            $('#conversion-dialog').modal({backdrop: 'static', keyboard: false, 'show':true});
        }
        else{
            $scope.c_period = parseInt($scope.c_period);
        }

        var select2Data=[];
            for (let i = 0, len = $scope.eventLists.length; i < len; i++) {
                var data ={
                    id: i,
                    text: $scope.eventLists[i].event
                    }
                    select2Data.push(data);
            }		
            if( $scope.eventFlag){
            setTimeout(function(){
                $(".select2_event_one").select2({
                    data: select2Data
                })
                $(".select2_event_two").select2({
                    data: select2Data
                })
                if($scope.c_event){
                    var result = select2Data.filter(events => events.text == $scope.c_event.event);
                    $(".select2_event_one").val(result[0].id).trigger('change');
                }
                if($scope.c_event_2){
                    var result2 = select2Data.filter(events => events.text == $scope.c_event_2.event);
                    $(".select2_event_two").val(result2[0].id).trigger('change');
                }
            },500)
        }
    }

    $scope.conversionPopupBoxClose = function(){
        $scope.isConversion = false;
    };

    $scope.eventLists = [];
    // get events list
    $scope.getEvents = function(){
        startLoader('Loading necessary Resources')
        var promise = appIceService.getEventList();
        promise.then(function(eventsData){
            if(eventsData){
                $scope.eventsData = eventsData.data;
                if($scope.eventsData){
                	$scope.eventsData.forEach(function(event, key){
                        if(
                            event.event != 'Session_Start' 
                            && event.event != 'Session_End'
                            && event.event != 'App_Foreground' 
                            && event.event != 'App_Background'
                            && event.event != '_App_Start'
                            && event.event != '_App_Stop' 
                        ){
                            if($scope.eventLists.length == 0){
                                $scope.c_event = event.event;
                            }

                            $scope.eventLists.push(event);
                        }
                    });
                    endLoader()
                    $scope.eventFlag = true;
                    $scope.conversionPopupBoxOpen()
                }
            }
        });
    }

    /* select Attributes for selected event */
    $scope.getEventAttributes = function(selectEvent){
        $scope.eventAttributes = JSON.parse(selectEvent).list;
    };

    $scope.addSecondEvent = function(){
        $scope.multiple_c_event  = ($scope.multiple_c_event == false) ? true : false;
        if($scope.multiple_c_event==true){
         
            $('.addedEvent').css('display', 'block');
            $('#removeEvent').css('display', 'block');
            $('#addEvent').css('display', 'none');
            $('#c_operator').css('display', 'block');
        }else{

            $('.addedEvent').css('display', 'none');
            $('#removeEvent').css('display', 'none');
            $('#addEvent').css('display', 'block');
            $('#c_operator').css('display', 'none');
        }
    }

    // This function return true if the user inputs are validated else returns false
    function validateConversionEvent(c_event,period,attribute,operator,value){
        $scope.conversionError = "";
        // validate conversoin event
        if(c_event == undefined || c_event == ''){
            $scope.conversionError = "Please choose conversion event";
            return false;
        }
        // validate conversoin period
        if(period == undefined || period == ''){
            $scope.conversionError = "Please enter conversion period";
            return false;
        }
        
        // validate Attribute , operator and Value 
        if(attribute != undefined){
            if(operator == undefined){
                $scope.conversionError = "Please enter operator for attribute";
                return false
            }else{
                if(value  == undefined || value == '' || value == null){
                    $scope.conversionError = "Please enter operator value for attribute";   
                    return false;
                }
            }
        }
        return true
    }

    // this function creates the Event Obj for the conversion 
    function createEventObj(c_event, period, attribute, operator, value) {
      var obj = {};
      obj.event = c_event;
      obj.period = period;
      if (attribute) {
        obj.attr = attribute.name;
        obj.operator = operator;
        obj.value = value;
      }
      return obj;
    }

    // validate conversion 
    $scope.confirmConversion = function(){

        var c_obj = []

        // validates first event
        if(validateConversionEvent($scope.c_event.event , $scope.c_period , $scope.c_eventAttribute , $scope.c_event_operator , $scope.c_event_operator_value )){
            var Obj1 = createEventObj($scope.c_event.event , $scope.c_period , $scope.c_eventAttribute , $scope.c_event_operator , $scope.c_event_operator_value)
          if($scope.multiple_c_event==true){
            Obj1.E_operator = $scope.c_operator;
            c_obj.push(Obj1);                       //push first event obj with operator 
             // validates second event
            if(validateConversionEvent($scope.c_event_2.event , $scope.c_period_2 , $scope.c_eventAttribute_2 , $scope.c_event_operator_2 , $scope.c_event_operator_value_2)){
                var obj2 = createEventObj($scope.c_event_2.event , $scope.c_period_2 , $scope.c_eventAttribute_2 , $scope.c_event_operator_2 , $scope.c_event_operator_value_2)
                c_obj.push(obj2);                   //push second event obj 
            }else{
                // incase Second event is not properly validated
                return false
            }
          }else{
            //push first event obj without operator
            c_obj.push(Obj1);                  
          }
        }else{
            // incase first event is not properly validated
            return false
        }
        $scope.c_arr = c_obj;
        $scope.isConversion = true;
        $('#conversion-dialog').modal('hide');
        return true;
    }
    $scope.createVariant = function(){
        $('#create-variant').modal('show');
    }
    $scope.categories = getCategoryContextConfig();	
    $scope.attributes = {};
    $scope.variant = {};
    $scope.variant.operand = 'did';
    $scope.variant.operand = 'select operator';
    $scope.attributes = $scope.categories[0].attributes;
    $scope.attributes = $scope.categories[0].attributes;
    $scope.catSelected = $scope.categories[0];
    $scope.selectCategory = function(cat){
        $scope.catSelected = cat;
        $scope.attributes = cat.attributes;
    }
    $scope.selectAttribute =function(attrb){
        $scope.operators = [];
        $scope.catSelected.attributes.forEach(function(attr){
            if(attr.label == attrb){
                $scope.operators.push(attr.operators);
            }
        });
    }
    $scope.selectOperator =function(optr){

    }
    $scope.submitvariant = function(){
        $scope.verror = ''; 
        if($scope.variant.name != ''){
            if($scope.variant.attr != ''){
                promise = appIceService.saveVariant($scope.variant);
                promise.then(function(data) {
                    //$('#create-variant').modal('hide');
                    $scope.success = "submit successfully";
                    $scope.variant = {};
                    setTimeout(function(){ 
                        $scope.success = 0;
                        $scope.getTemplateMetaData();
                    }, 3000);  
                });
            }else{
                $scope.verror = "Please select attr/oprater/value";
            }
        }else{
            $scope.verror = "Please Enter variant name";
        }
    }
    $scope.variantList = [];
    $scope.getTemplateMetaData = function(){
        promise = appIceService.getTemplateMetaData();
        promise.then(function(data) {
            // set varaints , allowedURLs and blobUrls 
            $scope.variantList    = data.data.varaints ;
            $scope.allowedUrlList = data.data.allowedUrlList ;
            $scope.blobUrls       = data.data.blobUrls ;
        });
    }
    $scope.pushVariant = async function(type) {
        if($scope.variantArr.length < 5){
        if (!$scope.cTools.template_name == "" || !$scope.cTools.template_name == undefined) {
        appIceService.getObjectId().then((objId) => {
            $scope.variantArr.push( {
                _id : objId,
                name : `Variant ${ $scope.variantArr.length == 0 ? 1 : $scope.variantArr.length > 0 && Number($scope.variantArr[$scope.variantArr.length - 1].name.split(' ')[1]) + 1}`
            })
            $scope.savevariantDataPush({
                _id : objId,
                name : `Variant ${ $scope.variantArr.length == 0 ? 1 : $scope.variantArr.length > 0 && Number($scope.variantArr[$scope.variantArr.length - 1].name.split(' ')[1])}`
            }, type)
        })

    } else { 
        $scope.template_name_error = "Enter template name.";
    }
  }
}

//calculating variant can controlGroup percentage
$scope.totalPer = function() {
    $scope.totalVariantPer = 0;
    if($scope.otherProbs && $scope.otherProbs.length > 0){
    $scope.otherProbs.forEach((item) => {
        $scope.totalVariantPer += item.p
    });
  }
    $scope.totalVariantPer += isNaN(Number($('#controlGroupNum').val())) ? $scope.controlGroupValue : Number($('#controlGroupNum').val()) 
}

$scope.setRangeSliderVariance = function (template, val) {
    $scope.otherProbs = [];
    let variationArr = [];
    if (Array.isArray(template)) {
        template.forEach((item) => {
            if(item.variance_top_name.includes('Variant')){
                variationArr.push(item)
            }
        })
        var per = parseInt(((val) ? (100 - val) : 100) / variationArr.length);
        for (var i = 0; i < template.length; i++) {
            if(template[i].variance_top_name.includes('Variant')){
                $scope.otherProbs.push({ p: per, _id: template[i].variance_id, name : template[i].variance_top_name });
            }
        }
    } 
}
}); 
// remove Base url from image url
function removeBaseUrl(url,blobUrlsArr){
    if(url){
        const base_url = new URL(url).origin 
        if(blobUrlsArr.indexOf(base_url) == -1){
            return url
        }else{

        retval = url.substring(url.lastIndexOf('/'))
        return retval
      }
    }else{
        return "";
    }
}

function getCategoryContextConfig(){
    return [
          {
            "category":"Device",
            "reachable":true,
            "attributes":[
                {
                  "text":"Device Id",
                  "label":"did",
                  "type":"string",
                  "operators":[{"text":"Equals","label":"eq"},{"text":"Not Equals","label":"ne"},{"text":"In","label":"in"}]			          
                },
                {
                  "text":"Carrier",
                  "label":"c",
                  "type":"string",
                  "multiple":true,
                  "operators":[{"text":"In","label":"in"},{"text":"Not In","label":"nin"}]		          
                },
                {
                  "text":"Platform",
                  "label":"p",
                  "type":"string",
                  "multiple":false,
                  "operators":[{"text":"Equals","label":"eq"},{"text":"Not Equals","label":"ne"}]		          
                },
                {
                  "text":"Platform Version",
                  "label":"pv",
                  "type":"string",
                  "multiple":true,
                  "operators":[{"text":"In","label":"in"},{"text":"Not In","label":"nin"}]		          
                },
                {
                  "text":"App Version",
                  "label":"av",
                  "type":"string",
                  "multiple":true,
                  "operators":[{"text":"In","label":"in"},{"text":"Not In","label":"nin"}]		          
                },
                {
                  "text":"Device Make",
                  "label":"ma",
                  "type":"string",
                  "multiple":true,
                  "operators":[{"text":"In","label":"in"},{"text":"Not In","label":"nin"}]		          
                },
                {
                  "text":"Device Model",
                  "label":"d",
                  "type":"string",
                  "multiple":true,
                  "operators":[{"text":"In","label":"in"},{"text":"Not In","label":"nin"}]		          
                },
                {
                    "text":"Device Language",
                    "label":"device_lang",
                    "type":"string",
                    "multiple":false,
                    "operators":[{"text":"Equals","label":"eq"},{"text":"Not Equals","label":"ne"}]		          
                  }
                
            ]
            
          },
          {
            "category":"User property",
            "reachable":true,
            "attributes":[]
          },
          {
            "category":"App Usage",
            "reachable":true,
            "attributes":[
                {
                  "text":"First Seen",
                  "label":"fs",
                  "type":"number",
                  "operators":[{"text":"Minutes Ago","label":"minutes"},{"text":"Hours Ago","label":"hours"},{"text":"Days Ago","label":"days"}]			           

                },
                {
                  "text":"Last Seen",
                  "label":"ls",
                  "type":"number",
                  "operators":[{"text":"Minutes Ago","label":"minutes"},{"text":"Hours Ago","label":"hours"},{"text":"Days Ago","label":"days"}]			           
                },
                {
                  "text":"Session Count",
                  "label":"sc",
                  "type":"number",
                  "operators":[{"text":"Equals","label":"eq"},{"text":"Greater Than","label":"gt"},{"text":"Less Than","label":"lt"}]			           
                },
                {
                  "text":"Total Session Duration(Minutes)",
                  "label":"tsd",
                  "type":"number",
                  "operators":[{"text":"Equals","label":"eq"},{"text":"Greater Than","label":"gt"},{"text":"Less Than","label":"lt"}]			           
                }
            ]
            
          }
        ]
}

function isValidUrl(string){
    let url;
    try {
      url = new URL(string);
    } catch (_) {
      return false;  
    }
    return url.protocol === "http:" || url.protocol === "https:";   
}
