(function () {
	///  On keyup Event hide the apple store errors///
	$('#appnameStore').keyup(function(){
		$('.appnameStoreError').hide();
		$('.appnameGoogleError').hide();
	});

	///  Getting the apple store  url data on keyup event by typing or by pasting the code///
	var appnameStore = false;
	$('.appnameStore').keyup(function(event){
		if(event.keyCode != 17 && event.keyCode != 65){
			if(($('#appnameStore').val().indexOf('http:') > -1) || ($('#appnameStore').val().indexOf('https:') > -1))
			{
					//check if its playstore url 
				if($('#appnameStore').val().indexOf('itunes.apple.com') > -1)
				{

					GetAppDeatils($('#appnameStore').val(),'store');
					$('.appnameStoreIndexError').css({'color':'red','display':'none'});
					$('.appnameGoogleIndexError').css({'color':'red','display':'none'});
					$('.appnameWebIndexError').css({'color':'red','display':'none'});
				}
				else
				{
					appnameStore = true;
				}
			}
			else
			{
				SetAppForName($('#appnameStore').val());
			}
		}
	});
	// Apple code ends here ///

	///  On keyup Event hide the paly store errors///
	$('#appnameGoogle').keyup(function(){
		$('.appnameGoogleError').hide();
		$('.appnameStoreError').hide();
	});
	// android erros ends here //
	var appnameGoogle = false;
	// Getting the play store  url data on keyup event by typing or by pasting the code //
	$('.appnameGoogle').keyup(function(event){		
		if(event.keyCode != 17 && event.keyCode != 65){
			if(($('#appnameGoogle').val().indexOf('http:') > -1) || ($('#appnameGoogle').val().indexOf('https:') > -1))
			{//check if its playstore url 
				if($('#appnameGoogle').val().indexOf('play.google.com') > -1)
				{
					GetAppDeatils($('#appnameGoogle').val(),'google');
					$('.appnameGoogleIndexError').css({'color':'red','display':'none'});
					$('.appnameStoreIndexError').css({'color':'red','display':'none'});
					$('.appnameWebIndexError').css({'color':'red','display':'none'});
				}
				else
				{
					appnameGoogle = true;
					//showMessage('Please enter Google Play Appstore Url.');
				}
			}
			else
			{
				SetAppForName($('#appnameGoogle').val());
			}
		}
		
	});
	//  Play store  code ends here//

	///  On keyup Event hide the apple store errors///
	$('#appnameWeb').keyup(function(){
		$('.appnameStoreError').hide();
		$('.appnameGoogleError').hide();
		$('.appnameWebError').hide();
	});

	// ///  Getting the apple store  url data on keyup event by typing or by pasting the code///
	var appnameWeb = false;
	$('.appnameWeb').keyup(function(event){
		if(event.keyCode != 17 && event.keyCode != 65){
			if(($('#appnameWeb').val().indexOf('http:') > -1) || ($('#appnameWeb').val().indexOf('https:') > -1))
			{
					//check if its playstore url 
				if($('#appnameWeb').val().indexOf('itunes.apple.com') > -1)
				{

					GetAppDeatils($('#appnameWeb').val(),'web');
					$('.appnameStoreIndexError').css({'color':'red','display':'none'});
					$('.appnameGoogleIndexError').css({'color':'red','display':'none'});
					$('.appnameWebIndexError').css({'color':'red','display':'none'});
				}
				else
				{
					appnameWeb = true;
				}
			}
			else
			{
				SetAppForName($('#appnameWeb').val());
			}
		}
	});
	// // Apple code ends here ///

	// Three step wizard wizard which will lead to create app start here//
	var emailSent = false;
	var appCreated = false;

	$("#setupwizard").bwizard({validating: function (e, ui) {
		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);
		  }
		// In case of Application Name User input to contain only alphabet, number and space
		function validateAlphaNumericString(value){
			var re = /^[0-9A-Za-z\s\-]+$/;
            if (!re.test(value)) {
                return false;
            }
			return true
		}
		
		var appName_url = $('#appnameStore').val()
		var googleName_url = $('#appnameGoogle').val()
		var web_url = $('#appnameWeb').val()
		var validated = false;

		if(appName_url != '' && !validateUrl(appName_url) && !validateAlphaNumericString(appName_url) ){
			$('.appnameStoreIndexError').css({'color':'red','display':'block'});
			$('.appnameWebIndexError').css({'color':'red','display':'none'});
			$('.appnameGoogleIndexError').css({'color':'red','display':'none'});
			$('#appnameStore').val('');
			appnameStore = false;
			return false;
		}else{
			validated = true ;
		}
		
		if(googleName_url != '' && validated == false && !validateUrl(googleName_url) && !validateAlphaNumericString(googleName_url ) ){
			$('.appnameGoogleIndexError').css({'color':'red','display':'block'});
			$('.appnameStoreIndexError').css({'color':'red','display':'none'});
			$('.appnameWebIndexError').css({'color':'red','display':'none'});

			$('#appnameGoogle').val('');
			appnameGoogle = false;
			return false;
		}else{
			validated = true ;
		}
		if(web_url != '' && validated == false &&  !validateUrl(web_url)){
			$('.appnameWebIndexError').css({'color':'red','display':'block'});
			$('.appnameStoreIndexError').css({'color':'red','display':'none'});
			$('.appnameGoogleIndexError').css({'color':'red','display':'none'});
			$('#appnameWeb').val('');
			appnameWeb = false;
			return false;
		}else{

		}
		
		if(appnameStore == true){
			$('.appnameStoreIndexError').css({'color':'red','display':'block'});
			$('.appnameGoogleIndexError').css({'color':'red','display':'none'});
				$('#appnameStore').val('');
				appnameStore = false;
				return false;
		}else if(appnameGoogle == true){
			$('.appnameGoogleIndexError').css({'color':'red','display':'block'});
			$('.appnameStoreIndexError').css({'color':'red','display':'none'});
			$('#appnameGoogle').val('');
			appnameGoogle = false;
			return false;
		}else if(appnameWeb == true){
			$('.appnameGoogleIndexError').css({'color':'red','display':'block'});
			$('.appnameStoreIndexError').css({'color':'red','display':'none'});
			$('.appnameWebIndexError').css({'color':'red','display':'none'});
			$('#appnameWeb').val('');
			appnameWeb = false;
			return false;
		}

		if(($.trim($('#appnameStore').val()) == '') && ($.trim($('#appnameGoogle').val()) == '') && ($.trim($('#appnameWeb').val()) == '')){
			$('.appnameStoreError').css({'color':'red','display':'block'});
	        $('.appnameGoogleError').css({'color':'red','display':'block'});
	        $('.appnameWebError').css({'color':'red','display':'block'});
	        $('.bwizard-buttons').find('.previous').click();
	        return false;
		}
		
	    if($.trim($('#appnameStore').val()) == '' || $.trim($('#appnameGoogle').val()) != '' || $.trim($('#appnameWeb').val()) == '' ){
	    	return true;	
		}
		
	    if(($.trim($('#appnameGoogle').val()) == '' || $.trim($('#appnameStore').val()) != '' || $.trim($('#appnameWeb').val()) == '' )  ){
	    	return true;	
		}
		if(($.trim($('#appnameGoogle').val()) == '' || $.trim($('#appnameStore').val()) == '' || $.trim($('#appnameWeb').val()) != '' )  ){
	    	return true;	
		}
	}, activeIndexChanged: function (e, ui) {	
		if(ui.index == 1 && appCreated == false){
			appCreated = true;
			createappbtn();
	    	//appCreated = createappbtn();
		}else if(ui.index == 1 && appCreated == true){
			updateApps();
		}
			if(ui.index == 2 && !emailSent){
				//Send Email to dev 
				var devemailid = $('#devemailid').val();
				var appid=localStorage.getItem("hdnApp_id")
				var sendSteps;
		 		if(($.trim($('#appnameGoogle').val())!='') && ($.trim($('#appnameStore').val())!='')){
					sendSteps='both';
				}
				else{
					if($.trim($('#appnameGoogle').val())!=''){
		        		sendSteps='andriod';
		    		}                  			 
		    		if($.trim($('#appnameStore').val())!=''){             	
		    			sendSteps='ios';
		    		}
		    		if($.trim($('#appnameWeb').val())!=''){             	
		    			sendSteps='web';
		    		}
				}  			 

			if(devemailid){
				$.ajax({
					type:"GET",
					url:semusiCommon.API_PARTS.apps.w + '/SendDevData',
					data:{
					args:JSON.stringify({
						app_id: localStorage.getItem("hdnApp_id"),
						app_key: localStorage.getItem("hdnApp_key"),
					    devemailid:devemailid,
					    a_appname:$('#appnameGoogle').val(),
					    i_appname:$('#appnameStore').val(),
					    w_appname:$('#appnameWeb').val(),
					    sendSteps:sendSteps
				    }),    
					//api_key: "<%= member.api_key %>"
					uniqueNumber : semusiCommon.randomNumber(),
					api_key: semusiCommon.getActiveUser.api_key
					},
					
					success:function (data) {
						emailSent = true;
				}});

			}
		}
	} });

	/// Three step wizard ends here///

	/// Create app function that will create app for android or apple play store ///
	function createappbtn(){
		var appName = $('#appname').text();				
		var imagesrc = $('#appImage').attr('src');
		var isAppDeleted="false";
		var category=$('#appCategory').text();
		var appType = '';
		if(category=='semusi'){
			category='';
		}
		var ARGS= {
		name: appName,
		category:category,
		icon:imagesrc,
		isAppDeleted:isAppDeleted,
		}
		// Insert Keys in the args only if they exist 
		if($('#lblappnamegp').text() != undefined && $('#lblappnamegp').text() != "" ){
			ARGS.googleUrl = $('#lblappnamegp').text();
		}
		if($('#lblappnameas').text() != undefined && $('#lblappnameas').text() != ""){
			ARGS.iosUrl = $('#lblappnameas').text();
		}

		if(appName != '' && category!='setexample'){
			//alert('appName');
		    $.ajax({
	        	type:"GET",
	            url:semusiCommon.API_PARTS.apps.w + '/create',
	            data:{
	                args:JSON.stringify(ARGS),
	                //api_key: "<%= member.api_key %>"
					uniqueNumber : semusiCommon.randomNumber(),
	                api_key: semusiCommon.getActiveUser.api_key
	            },
	            
	            success:function (data) {
	                var newAppObj = {
	                    "_id":data._id,
	                    "name":data.name,
	                    "key":data.key		                       
	                };	
					localStorage.setItem("hdnApp_id", data._id);
				    localStorage.setItem("hdnApp_key", data.key);		                    
	                $('#appCategory').text('setexample')
	                if($.trim($('#appnameGoogle').val())!=''){			  
	     				AndriodSteps(data._id, data.key);
	     			}
	     			else{
	     			 	$('#stepAndriod').css('display','none');
					 }
					if($.trim($('#appnameWeb').val())!=''){			  
						WebSteps(data._id, data.key);
					}
					else{
						 $('#stepWeb').css('display','none');
					}
	     			if($.trim($('#appnameStore').val())!=''){
	     				$('#stepIOS').find('a').click();
	     				IOSSteps(data._id, data.key);
	     			}
	     			else{
	     			 	$('#stepIOS').css('display','none');
	     			}
					$('#createappbtn').removeClass("btn btn-white disabled");			
					$('#createappbtn').addClass("btn btn-success btn-lg");	
					return true;			       
			}});
		}
		/*else{
			showMessage('Please provide an AppName');
			return false;
		}*/

	}

	// Update button for updating the both app like apple and android //
	$("#btnUpdateApp").click(function(){
		if(($.trim($('#hdn_googleUrl').val())=='') && ($.trim($('#hdn_iosUrl').val())==''))
		{
			var appName = $('#appname').text();					
			var imagesrc = $('#appImage').attr('src');
			var isAppDeleted="false";						
			 $.ajax({
	            type:"POST",
	            url:semusiCommon.API_PARTS.apps.w + '/updateApp',
	            data:{
	                args:JSON.stringify({
	                	app_id: localStorage.getItem("hdnApp_id"),
	                    name:appName,	
	                    icon:imagesrc,	                       
	                	isAppDeleted:isAppDeleted,
	                	googleUrl:$('#lblappnamegp').text(),
	                	iosUrl:$('#lblappnameas').text()
	                }),
					uniqueNumber : semusiCommon.randomNumber(),
	                app_id: semusiCommon.ACTIVE_APP_ID,
	                api_key: semusiCommon.getActiveUser.api_key
	            },
				headers: {
					'csrf-token': appiceCookies.getCookie('_csrf')
				},
	            
	            success:function (data) {
					semusiCommon.getCsrfToken();
	                $('#appCategory').text('setexample')
	                 if($.trim($('#hdn_googleUrl').val())==''){			
	     				AndriodSteps(data._id, data.key);
	     			 }
	     			 else{
	     			 	$('#stepAndriod').css('display','none');
	     			 }
	     			 if($.trim($('#hdn_iosUrl').val())==''){  
	     				IOSSteps(data._id, data.key);
	     			 }
	     			 else{
	     			 	$('#stepIOS').css('display','none');
	     			 }

	     			 showMessagesucess("App updated successfully.");
	 			} 
	        });
		}else if(!($.trim($('#hdn_googleUrl').val())=='') || !($.trim($('#hdn_iosUrl').val())==''))
		{
			var appName = $('#appname').text();					
			var imagesrc = $('#appImage').attr('src');
			var isAppDeleted="false";						
			 $.ajax({
	            type:"GET",
	            url:semusiCommon.API_PARTS.apps.w + '/updateApp',
	            data:{
	                args:JSON.stringify({
	                	app_id:localStorage.getItem("hdnApp_id"),
	                    name:appName,	
	                    icon:imagesrc,	                       
	                	isAppDeleted:isAppDeleted,
	                	googleUrl:$('#lblappnamegp').text(),
	                	iosUrl:$('#lblappnameas').text()
	                }),
	                //api_key: "<%= member.api_key %>"
					uniqueNumber : semusiCommon.randomNumber(),
	                api_key: semusiCommon.getActiveUser.api_key
	            },
	            
	            success:function (data) {
	                $('#appCategory').text('setexample')
	                 if($.trim($('#hdn_googleUrl').val())==''){			
	     				AndriodSteps(data._id, data.key);
	     			 }
	     			 else{
	     			 	$('#stepAndriod').css('display','none');
	     			 }
	     			 if($.trim($('#hdn_iosUrl').val())==''){  
	     				IOSSteps(data._id, data.key);
	     			 }
	     			 else{
	     			 	$('#stepIOS').css('display','none');
	     			 }

	     			 showMessagesucess("App updated successfully.");
	 			} 
	        });
		}
	});

	// Android sdk code that will generate in second step of app creation//

	function AndriodSteps(id, key)
	{
	var part1='&lt;!-- Play service meta-data --&gt;  <br>&lt;meta-data<br>  &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; android:name="com.google.android.gms.version" <br> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; android:value="@integer/google_play_services_version" /&gt; <br><br/> &lt;!-- Required Meta-Data keys for SemusiSDK --&gt; <br/>&lt;meta-data  <br> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; android:name="com.semusi.analytics.appid"<br> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; android:value="' ;
		 part1=part1+ id;

	     part1=part1+'"/&gt; <br/> &lt;meta-data <br> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; android:name="com.semusi.analytics.appkey"<br> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; android:value="';
	    part1=part1+ key;

	   	part1= part1+ '"/&gt;<br/>&lt;meta-data <br> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; android:name="com.semusi.analytics.apikey" <br> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; android:value="';
	   	part1=part1+""+semusiCommon.getActiveUser.api_key;
	   	part1=part1+'"/&gt;<br/><br> &lt;!-- End of required meta-data --&gt;';
	    $('#devdata').html(part1); 
	}

	function WebSteps(id, key)
	{
	var part1='&lt;head&gt;&lt;link rel=manifest href=/manifest.json&gt; &lt;br&gt;&lt;script&gt; &lt;br&gt;var Appice = Appice || {}; &nbsp;&lt;br&gt;(function () { &lt;br&gt;var doc = document; &lt;br&gt;var jsElm = doc.createElement(script); &lt;br&gt;jsElm.type = text/javascript; &lt;br&gt;jsElm.async = true; &lt;br&gt;jsElm.src = https://cdn.appice.io/javascripts/appice.common.js; &lt;br&gt;jsElm.onload = function(){ &lt;br&gt;Appice.initialize(); &lt;br&gt;}; &lt;br&gt;var s = doc.getElementsByTagName(script)[0]; &lt;br&gt;s.parentNode.insertBefore(jsElm, s); &lt;br&gt;} &lt;br&gt;)(); &lt;br&gt;&lt;/script&gt; &lt;br&gt;&amp;lt;/head&amp;';
	$('#devdata').html(part1); 
	}

	// IOS sdk code that will generate in second step of app creation//
	function IOSSteps(id, key)
	{
	var	part1= '---- Define meta-data keys for semusi SDK <br>#define appICE_App_Key "'+key+'" <br>#define appICE_App_id "'+id+'" <br>#define appICE_Api_Key "'+semusiCommon.getActiveUser.api_key+'" <br>&nbsp;// Step to start context <br>&nbsp;&nbsp;[[appICE sharedInstance]startContext]; <br>&nbsp;// to deliver device token to appICE sdk <br>&nbsp;&nbsp;- (void)application:(UIApplication*)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData*)deviceToken <br>{ <br>&nbsp;&nbsp;&nbsp;[[appICE sharedInstance] APIRegisterUser:deviceToken]; <br>}<br>&nbsp;// To get custom variable value <br>&nbsp;&nbsp;&nbsp;[appICE.sharedInstance getCustomVariableString:@"userIdVal" ]; <br>&nbsp;// To send custom event <br>&nbsp;&nbsp;&nbsp;[[appICE sharedInstance] recordEvent:@"button-click" count:1]; <br>';
				
		$('#devdataIOS').html(part1);

	}

	//Show message function //

	function showMessage(key) {		
		$('#message').show();					
		$('#messagebox').text(key);
	}

	/// Function for getting data of pasted url of app of android or apple////
	function GetAppDeatils(appurl,loc){					
		$('#page-loader').toggleClass('hide');
		//call the nginx to get us the data
		var category=$.trim($('#appCategory').text());
		$.ajax({
            type:"GET",
            url:semusiCommon.API_PARTS.apps.w + '/getAppStoreInfo',
            data:{
                args:JSON.stringify({
                storeurl:appurl
                }),
                //api_key: "<%= member.api_key %>"
				uniqueNumber : semusiCommon.randomNumber(),
                api_key: semusiCommon.getActiveUser.api_key
            },
            
            success:function (data) {
            	$('#page-loader').toggleClass('hide');
            	if(data != '')
            	{
            		if($.trim(data.result.appname)!= $.trim(($('#appname').text())))
            		{
                    	$('#appname').text($.trim(data.result.appname));
                    	$('#app_name').text($.trim(data.result.appname));
                    }
                    if(category=='setexample')
                   {
                    	$('#lblappnamegp').text('');
                    	$('#lblappnameas').text('');

                    }
                    if(loc=='google')
                	{
                		$('#lblappnamegp').text($('#appnameGoogle').val());
                	}
                	else
                	{
						$('#lblappnameas').text($('#appnameStore').val());
                	}
                	
                	if(category=='setexample' || ((category!='setexample') && $.trim(data.result.appImage) != ''))
                	{
                    	$('#appImage').show();
                    	$('#appImage').attr('src',$.trim(data.result.appImage));
                    	$('#app_Image').show();
                    	$('#app_Image').attr('src',$.trim(data.result.appImage));
                	}
                	if(data.result.appCategory != '')
                	{
                		$('#appCategory').text();
                		//$('#appCategory').show();	                    		
                		$('#appCategory').text(data.result.appCategory);
                	}
                	$('#entry').html('Entry of App');
                	
            	}	
            }});
		}
	/// url app getting data ends here ///

	/// emailId focus out event ///
	$('#devemailid').focusout(function(){				
		//$('#dev_emailid').text($('#devemailid').val());
		$.ajax({
              type:"GET",
              url:semusiCommon.API_PARTS.apps.w + '/checkemaildomain',
              data:{
                  args:JSON.stringify({
                    devemailid:$('#devemailid').val()                  
                  }),
                  //api_key: "<%= member.api_key %>"
				  uniqueNumber : semusiCommon.randomNumber(),
                  api_key: semusiCommon.getActiveUser.api_key
              },
              
              success:function (data) {
              	if(data.message!='allowed domain')
              	{    
                  	$('#emailissue').html(data.message);
                  	
                  	$('#emailissue').addClass("alert alert-danger");
                  	$('#emailissue').show();                  	
             	}
             	else{
             		$('#emailissue').html(data.message);
                  	
                  	$('#emailissue').addClass("alert alert-danger");
                  	$('#emailissue').hide();                 	
             	}
        }});
	});
	// emailid focusout event ends here//

	//Setup app name for android or applestore//
	function SetAppForName(appName)
	{
		$('#appname').text(appName);
		$('#app_name').text(appName);
		$('#lblappnamegp').text('');
		$('#lblappnameas').text('');
		$('#appImage').show();
		$('#appImage').attr('src','assets/img/app-store-logos.jpg');
		$('#app_Image').show();
		$('#app_Image').attr('src','assets/img/app-store-logos.jpg');
		$('#appCategory').text('semusi');
		$('#entry').html('Entry of App');
	}
	//End Setup app name for android or applestore//

	//  After creation of app click to go to app dashboard of android or apple app///
	$('#createappbtn').click(function(){
		var appid = localStorage.getItem("hdnApp_id")
		window.location =  appiceEncode.encodePayload("dashboard?action=dashboard&app_id=" + appid);	
	});

	//App click to go dashboard ends here///

	// Delete app function on dashboard //
	$('#deleteApp').on('click', function(e){
		e.preventDefault();
		var isAppDeleted = "true";	
		var app_id = localStorage.getItem('hdnAppId')
		 $.ajax({
	        type:"GET",
	        url:semusiCommon.API_PARTS.apps.w + '/delete',
	        data:{
	            args:JSON.stringify({
	                app_id:app_id,
	                isAppDeleted:isAppDeleted
	            }),
	            //api_key: "<%= member.api_key %>"
				uniqueNumber : semusiCommon.randomNumber(),
	            api_key: semusiCommon.getActiveUser.api_key
	            
	        },
	        
	        success:function (data) {
	            var newAppObj = {
	                "_id":data._id,
	                "name":data.name,
	                "key":data.key		                       
	            };		                    
	        window.location =  "/dashboard";
        }});
	})
	// Delete app function ends here//

	function updateApps(){
		var appName = $('#appname').text();					
			var imagesrc = $('#appImage').attr('src');
			var isAppDeleted="false";						
			 $.ajax({
	            type:"GET",
	            url:semusiCommon.API_PARTS.apps.w + '/updateApp',
	            data:{
	                args:JSON.stringify({
						app_id: localStorage.getItem("hdnApp_id"),
	                    name:appName,	
	                    icon:imagesrc,	                       
	                	isAppDeleted:isAppDeleted,
	                	googleUrl:$('#lblappnamegp').text(),
	                	iosUrl:$('#lblappnameas').text()
	                }),
	                //api_key: "<%= member.api_key %>"
					uniqueNumber : semusiCommon.randomNumber(),
	                api_key: semusiCommon.getActiveUser.api_key
	            },
	            
	            success:function (data) {
	              
	 			} 
	        });
	}

    function getParameterByName(name, url) {
        if (!url) {
            url = window.location.href;
        }
        name = name.replace(/[\[\]]/g, "\\$&");
        var regex = new RegExp("[?&]" + name + "(=([^&#]*)|&|#|$)"),
            results = regex.exec(url);
        if (!results) return null;
        if (!results[2]) return '';
        return decodeURIComponent(results[2].replace(/\+/g, " "));
    }


//  start function for general settings
$("#btnBaseUrl").click(function(){
	function appsettingsBaseUrl(){
		let baseUrl = document.getElementById("baseUrl").value;
		function is_url(str) {
            regexp = /^(?:(?:https?|ftp):\/\/)?(?:(?!(?: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*)?$/;
            if (regexp.test(str)) {
                return true;
            }
            else {
                return false;
            }
        }
        if (baseUrl === "" || baseUrl === undefined) {
			$("#error-msg").html("Please fill the mendatory fields");
			return false
        }
        else if (is_url(baseUrl) == false) {
			$("#error-msg").html("Please provide a valid URL.");
			return false
        }
	        $.ajax({
				type:"GET",
				url:semusiCommon.API_PARTS.apps.w + '/postbaseUrl',
				data:{
					args:JSON.stringify({
						app_id: semusiCommon.ACTIVE_APP_ID,
					}),
					uniqueNumber : semusiCommon.randomNumber(),
					baseUrl: baseUrl,
					api_key: semusiCommon.getActiveUser.api_key
				},
				success:function (data) {
					showMessagesucess("Saved");
					$("#messagesucess").delay(3000).fadeOut(300);
					$("#message").delay(3000).fadeOut(300);
					location.reload();
					
				}
			});
		}
		appsettingsBaseUrl();
	});
//  End for general settings

      	//post request for saving enable/disable of features
		  $("#featuresSettings").on("click", () => {
			$.ajax({
				 type:"POST",
				 url:semusiCommon.API_PARTS.apps.w + '/savefeaturesSettings',
				 data:{
					args:JSON.stringify({
					 language_variant:$("#language_variant_input").is(":checked"),
					 ab_testing_variant:$('#ab_testing_variant_input').is(":checked"),
					 email_editor:$("#email_editor").is(":checked"),
					 demographicsState:$('#demographics').is(":checked"),
					 usageState:$('#usage').is(":checked"),
					 reportsState:$('#reports').is(":checked"),
					 audience_exports:$('#audience_exports').is(":checked"),
					 appInboxReports:$('#appInboxReports').is(":checked"),
					 maskedDids:$('#maskedDids').is(":checked"),
					 churnState:$('#churn').is(":checked"),
					 expImgState:$('#expendedImg').is(":checked"),
					 advPushState:$('#advancedPush').is(":checked"),
					 campExceptPushState:$('#campExceptPush').is(":checked"),
					 transState:$('#transactionalCamp').is(":checked"),
					 optimisationState:$('#optimisation').is(":checked"),
					 appInboxDeliveryState:$('#appInbox-deliveryType').is(":checked"),
					 userprofileImgState:$('#userProfileImg').is(":checked"),
					 funnelPeriod:$('#funnelPeriod').is(":checked"),
					 documentationState:$('#documentation').is(":checked"),
					 outsideTheAppState:$('#outsidetheapp').is(":checked"),
					 campaignDetailsCsv:$('#camp-details').is(":checked"),
					 hidegranularMonetaryCACLTV:$('#hidegranularMonetaryCACLTV').is(":checked"),
					 competingApps:$('#competingApps').is(":checked"),
					 embedCustomField:$('#embedCustomField').is(":checked"),
					 whowhatwherewhen:$('#whowhatwherewhen').is(":checked"),
					 deepLinkUrl:$('#deepLinkUrl').is(":checked"),
					 category:$('#category').is(":checked"),
					 utmBuilder:$('#utmbuilder').is(":checked"),
					 landingPageView:$('#landingPageView').is(":checked"),
					 funnelLaunchbtn:$('#funnelLaunchbtn').is(":checked"),
					 cmpInsertInToPG:$('#cmpInsertInToPG').is(":checked"),
					 advancedFreq:$('#advancedFreq').is(":checked"),
					 launchCampFreq:$('#launchCampFreq').is(":checked"),
					 actionbuttonSettings:$('#actionbuttonSettings').is(":checked"),
					 specialattributes:$('#specialattributes').is(":checked"),
					 conversionSettings:$('#conversionSettings').is(":checked"),
					 journeynavsettings:$('#journeynavsettings').is(":checked"),
					 setupAppsSettings:$('#setupAppsSettings').is(":checked"),
					 delayLauch:$('#delayLauch').is(":checked"),
					 removeWeb:$('#removeweb').is(":checked"),
					 liveEventSett:$('#liveEventSett').is(":checked"),
					 schedulerSett:$('#schedulerSett').is(":checked"),
					 cSegPhoneEmail:$('#cSegPhoneEmail').is(":checked"),
					 deviceAttributes:$('#deviceAttributes').is(":checked"),
					 appUsageAttributes:$('#appUsageAttributes').is(":checked"),
					 allowList:$('#allowList').is(":checked"),


						app_id: semusiCommon.ACTIVE_APP_ID,
					}),
					uniqueNumber : semusiCommon.randomNumber(),
					app_id: semusiCommon.ACTIVE_APP_ID,
					api_key: semusiCommon.getActiveUser.api_key
				},
				 headers: {
					 'csrf-token': appiceCookies.getCookie('_csrf')
				 },
				 success:function (data) {
					semusiCommon.getCsrfToken();
					   showMessagesucess("Saved");
					 $("#messagesucess").delay(3000).fadeOut(300);
					 $("#message").delay(3000).fadeOut(300);
					 location.reload();
				  } 
			})
		 
        });

		//post request for saving appinbox default expiry
		$("#appInboxSettings").on("click", () => {
			var dropdown = document.getElementById("numberSelect");
			var selectedValue = dropdown.value;
	
			$.ajax({
				type: "POST",
				url: semusiCommon.API_PARTS.apps.w + '/saveAppInboxSettings',
				data: {
					args: JSON.stringify({
						app_id: semusiCommon.ACTIVE_APP_ID,
						days: selectedValue
					}),
					uniqueNumber : semusiCommon.randomNumber(),
					app_id: semusiCommon.ACTIVE_APP_ID,
					api_key: semusiCommon.getActiveUser.api_key
				},
				headers: {
					'csrf-token': appiceCookies.getCookie('_csrf')
				},
				success: function (data) {
					showMessagesucess("Saved");
					$("#messagesucess").delay(3000).fadeOut(300);
					$("#message").delay(3000).fadeOut(300);
					location.reload();
				}
			})
	
		});

		$('#sso_type').change(function () {
			var selectedOption = $(this).val();
			if (selectedOption === 'ad') {
				$('#ad_settings').show();
			} else {
				$('#ad_settings').hide();
			}
			if (selectedOption === 'saml') {
				$('#saml_settings').show();
			} else {
				$('#saml_settings').hide();
			}
		});
		$("#gbl_save").on("click", () => {
			let sso_type = $("#sso_type").val();
			let is_sso = $("#is_sso").val();
			let captcha = $("#authCaptcha").val();

			
		
			if(sso_type !== 'disabled' && sso_type !== 'ad' && sso_type !== 'saml'){
				$('#gbl_setting_err').text('Please select valid SSO type')
				return
			}
		
		
			let ldapConfig ={}
			let samlConfig ={}
			  // If SSO type is AD, check if required credentials are provided
			if (sso_type === 'ad') {
				let ldap_url = $("#ldap_url").val();
				let bind_dn = $("#bind_dn").val();
				let bind_credential = $("#bind_credential").val();
				let search_base = $("#search_base").val();
				
				// Check if any of the required credentials are undefined or empty
				if (!ldap_url || !bind_dn || !bind_credential || !search_base) {
					$('#gbl_setting_err').text('Please provide all required credentials for AD SSO');
					return;
				}
				
				ldapConfig.url = ldap_url
				ldapConfig.bindDN = bind_dn
				ldapConfig.bindCredentials = bind_credential
				ldapConfig.searchBase = search_base
			}
			// define default arguments
			const arguments = {
				sso_type: sso_type,
				is_sso:is_sso,
				ldapConfig:ldapConfig,
				samlConfig :samlConfig,
				app_id: semusiCommon.ACTIVE_APP_ID,
				captcha:captcha
			}

			const portal_name = $("#portal_name").val().trim(); // Get the value and trim whitespace

			if (portal_name !== '') {
				arguments.portal_name = portal_name
			} 

			
			if (sso_type === 'saml') {
				let saml_issuer = $("#saml_issuer").val().trim();
				let saml_entryPoint = $("#saml_entryPoint").val().trim();
				let saml_callbackURL = $("#saml_callbackURL").val().trim();
				let saml_cert = $("#saml_cert").val().trim();
				
				// Check if any of the required credentials are undefined or empty
				if ( !saml_callbackURL ) {
					$('#gbl_setting_err').text('Please provide the Callback URL for Saml SSO');
					return;
				}
				let samlConfig = {};
    
				// Assign values only if they are not empty
				if (saml_issuer !== '') {
					samlConfig.saml_issuer = saml_issuer;
				}
				if (saml_entryPoint !== '') {
					samlConfig.saml_entryPoint = saml_entryPoint;
				}
				if (saml_callbackURL !== '') {
					samlConfig.saml_callbackURL = saml_callbackURL;
				}
				if (saml_cert !== '') {
					samlConfig.saml_cert = saml_cert;
				}
				
				arguments.samlConfig = samlConfig;
			}
			
			
			$.ajax({
				type:"POST",
				url:semusiCommon.API_PARTS.apps.w + '/saveSiteSetting',
				data:{
					args:JSON.stringify(arguments),
					uniqueNumber : semusiCommon.randomNumber(),
					app_id: semusiCommon.ACTIVE_APP_ID,
					api_key: semusiCommon.getActiveUser.api_key
				},
				headers: {
					'csrf-token': appiceCookies.getCookie('_csrf')
				},
				// 
				success:function (data) {
					semusiCommon.getCsrfToken();
					  showMessagesucess("Site Settings Saved");
					$("#messagesucess").delay(3000).fadeOut(300);
					$("#message").delay(3000).fadeOut(300);
				 } 
			})
		});

		//post request for saving encryption status
		$("#encryptionStatus").on("click", () => {
			var encryptionStatus = document.getElementById("encryptionStatusDropdown");
			var encryptionStatusVal = encryptionStatus.value;
		
			var encryptionKey = document.getElementById("encryptionKey");
			var encryptionKeyVal = encryptionKey.value;
		
			if (encryptionStatusVal === "true" && encryptionKeyVal === "") {
				$("#encryptionKeyValidation").show();
				return;
			}
		
			$("#encryptionKeyValidation").hide();
		
			$.ajax({
				type: "POST",
				url: semusiCommon.API_PARTS.apps.w + '/saveEncryptionStatus',
				data: {
					args: JSON.stringify({
						app_id: semusiCommon.ACTIVE_APP_ID,
						encryptionstatus: ( encryptionStatusVal=='true' ) ? true : false,
						encryptionkey: encryptionKeyVal
					}),
					uniqueNumber : semusiCommon.randomNumber(),
					app_id: semusiCommon.ACTIVE_APP_ID,
					api_key: semusiCommon.getActiveUser.api_key
				},
				headers: {
					'csrf-token': appiceCookies.getCookie('_csrf')
				},
				success: function (data) {
					showMessagesucess("Saved");
					$("#messagesucess").delay(3000).fadeOut(300);
					$("#message").delay(3000).fadeOut(300);
					location.reload();
				}
			});
		});
		

		//post request for saving encryption status
		$("#charlimit_btn").on("click", () => {
			var headerLimit = document.getElementById("header-limit").value;
			var descriptionLimit = document.getElementById("description-limit").value;
			var expDescriptionLimit = document.getElementById("exp-description-limit").value;
			var getAppDropdown = document.getElementById("getApp-dropdown").value === 'true'; 
			
		
			$.ajax({
				type: "POST",
				url: semusiCommon.API_PARTS.apps.w + '/savePushCharLimit',
				data: {
					args: JSON.stringify({
						app_id: semusiCommon.ACTIVE_APP_ID,
						hl: headerLimit,
						dl: descriptionLimit,
						edl: expDescriptionLimit,
						getAppDropdown: getAppDropdown 
					}),
					uniqueNumber : semusiCommon.randomNumber(),
					app_id: semusiCommon.ACTIVE_APP_ID,
					api_key: semusiCommon.getActiveUser.api_key
				},
				headers: {
					'csrf-token': appiceCookies.getCookie('_csrf')
				},
				success: function (data) {
					showMessagesucess("Saved");
					$("#messagesucess").delay(3000).fadeOut(300);
					$("#message").delay(3000).fadeOut(300);
					location.reload();
				}
			});
		});
		

		$(document).ready(function () {
			let editData = {};
		
			// Function to add a new partner section
			function addNewPartner(partnerName, channelValue) {
				var newPartnerHtml = `
				<div class="partner-section">
					<div class="form-group row">
						<label class="col-md-2 col-sm-2 control-label">Name</label>
						<div class="col-md-3 col-sm-3">
							<input type="text" autocomplete="off" class="form-control partner-name" placeholder="" value="${partnerName}">
						</div>
						<label class="col-md-2 col-sm-2 control-label">Channel</label>
						<div class="col-md-3 col-sm-3">
						<select name="channel" class="form-control channel" id="channel_">
						<option value="NONE" ${channelValue === 'NONE' ? 'selected' : ''}>NONE</option>
						<option value="EMAIL" ${channelValue === 'EMAIL' ? 'selected' : ''}>EMAIL</option>
						<option value="SMS" ${channelValue === 'SMS' ? 'selected' : ''}>SMS</option>
						<option value="WHATSAPP" ${channelValue === 'WHATSAPP' ? 'selected' : ''}>WHATSAPP</option>
						<option value="PUSH" ${channelValue === 'PUSH' ? 'selected' : ''}>PUSH</option>
						<option value="WEB_PUSH" ${channelValue === 'WEB_PUSH' ? 'selected' : ''}>WEB_PUSH</option>
						<option value="APP_INBOX" ${channelValue === 'APP_INBOX' ? 'selected' : ''}>APP_INBOX</option>
					</select>
						</div>
						<div class="col-md-2 col-sm-2">
							<button type="button" class="fa fa-minus btn btn-danger btn-sm remove-partner" data-toggle="tooltip" data-placement="top" title="Delete">
								<i class="bi bi-trash fa-sm"></i> <!-- Bootstrap trash icon with "fa-sm" class -->
							</button>
						</div>
					</div>
					<hr class="my-1"> 
				</div>
			`;
			
			
				// Append the new partner section to the container
				$('#Partners').append(newPartnerHtml);
			}
		
			// Adding another partner
			$('#addAnotherPair').on('click', function () {
				addNewPartner("", "NONE"); // Add an empty partner section with default channel value
			});
		
			// Removing a partner
			$('#Partners').on('click', '.remove-partner', function () {
				$(this).closest('.partner-section').remove();
			});
		
			// Saving partner info
			$("#savePartnerInfo").on("click", () => {
				var partnerDataArray = [];
		
				$('.partner-section').each(function () {
					var partnerName = $(this).find('.partner-name').val();
					var channelValue = $(this).find('.channel').val();
		
					// Check if name is provided before adding to the array
					if (partnerName) {
						partnerDataArray.push({
							partnerName: partnerName,
							channel: channelValue
						});
					}
				});
		
				// AJAX request for saving partner info
				$.ajax({
					type: "POST",
					url: semusiCommon.API_PARTS.apps.w + '/savePartnerInfo',
					data: {
						args: JSON.stringify({
							app_id: semusiCommon.ACTIVE_APP_ID,
							partnerData: partnerDataArray
						}),
						uniqueNumber: semusiCommon.randomNumber(),
						app_id: semusiCommon.ACTIVE_APP_ID,
						api_key: semusiCommon.getActiveUser.api_key
					},
					headers: {
						'csrf-token': appiceCookies.getCookie('_csrf')
					},
					success: function (data) {
						showMessagesucess("Saved");
						$("#messagesucess").delay(3000).fadeOut(300);
						$("#message").delay(3000).fadeOut(300);
						location.reload();
					}
				});
			});
		
			// Fetch editData from the server
			$.ajax({
				type: "GET",
				url: semusiCommon.API_PARTS.apps.r + '/getPartnerInfo',
				data: {
					args: JSON.stringify({
						app_id: semusiCommon.ACTIVE_APP_ID,
					}),
					app_id: semusiCommon.ACTIVE_APP_ID,
					uniqueNumber: semusiCommon.randomNumber(),
					api_key: semusiCommon.getActiveUser.api_key
				},
				success: function (data) {
					if (data && data.partnerInfo && data.partnerInfo.partnerData) {
						// Remove partner_id field for each item in the array
						data.partnerInfo.partnerData.forEach(function (item) {
							delete item.partner_id;
						});
						editData = data.partnerInfo;
		
						// Pre-fill form fields with edit data
						if (editData && editData.partnerData && editData.partnerData.length > 0) {
							editData.partnerData.forEach(function (partner) {
								addNewPartner(partner.partnerName, partner.channel);
							});
						}
						//webhook edit
						let partnerInfo = data.partnerInfo;
		
						// Function to populate the dropdown options
                     function populateDropdown(elementId) {
                         var dropdown = document.getElementById(elementId);
                         dropdown.innerHTML = "";
                         // Add options from the partnerInfo data
                         partnerInfo.partnerData.forEach(function (partner) {
                             var option = document.createElement("option");
                             option.text = partner.partnerName;
                             dropdown.add(option);
                         });
                     }
                     populateDropdown("partnerCampConfig");


					 // Function to populate the dropdown options
                      function populateDropdownForChannel(elementId) {
                          var dropdown = document.getElementById(elementId);
                          dropdown.innerHTML = "";
                          
                          // Add options from the channel data
                          partnerInfo.partnerData.forEach(function (partner) {
							var option = document.createElement("option");
							option.text = partner.channel;
							dropdown.add(option);
						});
                      }
                      
                      populateDropdownForChannel("channelCampConfig");
                      
                     
					}
				}
			});
			$('[data-toggle="tooltip"]').tooltip();
		});
		
	$(".save_campaign_settings").on("click",()=>{	


		 let anySelected = false;
		 $('#settings_message').hide();
		 const selectedColumns = {};

		// Check if any checkboxes are selected and create Data structure
		 $(".checkbox input[type='checkbox']").each(function() {
			 const columnId = $(this).attr("id");
			 const columnName = columnId.replace("-checkbox", ""); 

			 const isSelected = $(this).prop("checked");
			 selectedColumns[columnName] = isSelected;
			 if (isSelected) {
				 anySelected = true;
			 }
		 });
	 

		 // If no checkboxes are selected, show an error message
		 if (!anySelected) {
			 $('#settings_message').html("Please select at least one column.");
			 $('#settings_message').show();
			 return; 
		 }

		 // add allowed URL
		 let allowedItems = [];
		 $('#item-list li').each(function() {
			allowedItems.push($(this).text().trim());
		 });

		 $.ajax({
			type: "POST",
			url: semusiCommon.API_PARTS.apps.w + '/saveCampaignSettings',
			data: {
				args: JSON.stringify({
					app_id: semusiCommon.ACTIVE_APP_ID,
					selectedColumns : selectedColumns,
					allowedItems:allowedItems,
				}),
				uniqueNumber : semusiCommon.randomNumber(),
				api_key: semusiCommon.getActiveUser.api_key
			},
			headers: {
				'csrf-token': appiceCookies.getCookie('_csrf')
			},
			success: function (data) {
				showMessagesucess("Saved");
				$("#messagesucess").delay(3000).fadeOut(300);
				$("#message").delay(3000).fadeOut(300);
				location.reload();
			}
		})
	 

	})	
	//save allow list 
	$("#saveallowListSettings").on("click", () => {
		let allowList = $("#allow-list").val();

		$.ajax({
			type: "POST",
			url: semusiCommon.API_PARTS.apps.w + '/saveallowListSettings',
			data: {
				args: JSON.stringify({
					app_id: semusiCommon.ACTIVE_APP_ID,
					allowList : allowList,
				}),
				uniqueNumber : semusiCommon.randomNumber(),
				api_key: semusiCommon.getActiveUser.api_key
			},
			headers: {
				'csrf-token': appiceCookies.getCookie('_csrf')
			},
			success: function (data) {
				showMessagesucess("Saved");
				$("#messagesucess").delay(3000).fadeOut(300);
				$("#message").delay(3000).fadeOut(300);
				location.reload();
			}
		})

	});

	$(document).ready(function () {
		
		$("#logs-table").hide();

	    $("#getLogs").on("change", function () {
	    	if (this.checked) {
	    		$("#logs-table").show();
                createDataTableLogs();
	    	} else {
	    		$("#logs-table").DataTable().destroy();
	    		$("#logs-table").hide();
	    	}
	    });
	
	       //get logslist 
           function createDataTableLogs() {
           		let i_d = $("#i-d").val();
           	
           		$("#logs-table").DataTable({
           			"destroy": true,
           			"processing": true,
           			"serverSide": true, 
					"info": false,
           			"ajax": {
           				"type": "GET",
           				"url": semusiCommon.API_PARTS.apps.r + '/getLogs',
           				"data": function (d) {
           					return {
           						args: JSON.stringify({
           							app_id: semusiCommon.ACTIVE_APP_ID,
           							id: i_d,
           							page: (d.start / d.length) + 1, // Calculate the current page
           							length: d.length, // Number of entries per page
									value: d.search.value //searched jobid
           						}),
           						uniqueNumber: semusiCommon.randomNumber(),
           						api_key: semusiCommon.getActiveUser.api_key
           					};
           				},
           				"headers": {
           					'csrf-token': appiceCookies.getCookie('_csrf')
           				},
           				"dataType": "json",
           				"dataSrc": function (json) {
           					return json; // Data source
           				}
           			},
           			"columns": [
						{ "data": "Did", "type": "string" },
           				{ "data": "platform", "type": "string" },
           				{ "data": "date", "type": "date" },
           				{ "data": "campaign_id", "type": "string" },
           				{ "data": "reach", "type": "numeric" },
           				{ "data": "pushed_to", "type": "numeric" },
           				{ "data": "received_to", "type": "numeric" },
           				{ "data": "failed_to", "type": "numeric" },
           			],
           		});
           	
           	}
	});

	// save email configuration
	$('.saveEmailConfiguration').on('click', function(){
		function validateInputNames(value){
			var re = /^[0-9A-Za-z\s\- + .]+$/;
			if (!re.test(value)) {
				return false;
			}
			return true;
		}
	
		function validateInputEmails(value){
		  var re =  /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/
		  if (!re.test(value)) {
			return false;
		}
			 return true;
		}
	
		function checkValidation(value, type, key){
			if(type === 'name'){
				if(!validateInputNames(value)){
					$('.emailConfigError').text(`Please enter correct ${key}`)
					return false
				}else{
					$('.emailConfigError').text('')
					return true;
				} 
			}else if(type === 'email'){
				if(!validateInputEmails(value)){
					$('.emailConfigError').text(`Please enter correct ${key}`)
					return false
				}else{
					$('.emailConfigError').text('')
					return true;
				} 
			}
			
		}

		var activeTab = $('.activeTab').attr('id');
		 
		$('#emailConfigError').text("");
		if(activeTab == "smtp"){
		// validate smtp username
		if($('#'+activeTab+'_username').val() == '' || $('#'+activeTab+'_username').val() == undefined){
			$('#'+activeTab+'_username').focus();
			$('#emailConfigError').text("Please enter smtp username");
			return false;
		}
        if(!checkValidation($('#'+activeTab+'_username').val(),'name', 'smtp username')) return false;
		// validate smtp pwd
		if($('#'+activeTab+'_password').val() == '' || $('#'+activeTab+'_password').val() == undefined){
			$('#'+activeTab+'_password').focus();
			$('#emailConfigError').text("Please enter smtp password");
			return false;
		}
		if(!checkValidation($('#'+activeTab+'_password').val(),'name', 'smtp password')) return false;
		// validate smtp host
		if($('#'+activeTab+'_host').val() == '' || $('#'+activeTab+'_host').val() == undefined){
			$('#'+activeTab+'_host').focus();
			$('#emailConfigError').text("Please enter host");
			return false;
		}
		if(!checkValidation($('#'+activeTab+'_host').val(),'name', 'host')) return false;

		if($('#'+activeTab+'_fromName').val() == '' || $('#'+activeTab+'_fromName').val() == undefined){
			$('#'+activeTab+'_fromName').focus();
			$('#emailConfigError').text("Please enter Valid From Name");
			return false;
		}
        if(!checkValidation($('#'+activeTab+'_fromName').val(),'name', 'From Name')) return false;
		if($('#'+activeTab+'_fromAddress').val() == '' || $('#'+activeTab+'_fromAddress').val() == undefined){
			$('#'+activeTab+'_fromAddress').focus();
			$('#emailConfigError').text("Please enter Valid From Address");
			return false;
		}
		if(!checkValidation($('#'+activeTab+'_fromAddress').val(),'email', 'From Email Address')) return false;
		// validate smtp port
		if($('#'+activeTab+'_port').val() == '' || $('#'+activeTab+'_port').val() == undefined){
			$('#'+activeTab+'_port').focus();
			$('.emailConfigError').text("Please enter port");
			return false;
		}
		else{
			var numbers = /^[0-9]+$/;  
		    if($('#'+activeTab+'_port').val().match(numbers))  
		    {}  
		    else  
		    {  
		      $('#'+activeTab+'_port').focus();
			  $('#emailConfigError').text("Please enter numeric value in port");
		      return false;  
		    }  
		}
	  }

	  if(activeTab == "aws_ses"){
		if($('#'+activeTab+'_accessKeyId').val() == '' || $('#'+activeTab+'_accessKeyId').val() == undefined){
			$('#'+activeTab+'_accessKeyId').focus();
			$('.emailConfigError').text("Please enter accessKeyId");
			return false;
		}
		if(!checkValidation($('#'+activeTab+'_accessKeyId').val(),'name', 'accessKeyId')) return false;
		if($('#'+activeTab+'_secretAccessKey').val() == '' || $('#'+activeTab+'_secretAccessKey').val() == undefined){
			$('#'+activeTab+'_secretAccessKey').focus();
			$('.emailConfigError').text("Please enter secretAccessKey");
			return false;
		}
		if(!checkValidation($('#'+activeTab+'_secretAccessKey').val(),'name', 'secretAccessKey')) return false;
		if($('#'+activeTab+'_region').val() == '' || $('#'+activeTab+'_region').val() == undefined){
			$('#'+activeTab+'_region').focus();
			$('.emailConfigError').text("Please enter region");
			return false;
		}
		if(!checkValidation($('#'+activeTab+'_region').val(),'name', 'region')) return false;
		if($('#'+activeTab+'_sourceEmail').val() == '' || $('#'+activeTab+'_sourceEmail').val() == undefined){
			$('#'+activeTab+'_sourceEmail').focus();
			$('.emailConfigError').text("Please enter sourceEmail");
			return false;
		}
		if(!checkValidation($('#'+activeTab+'_sourceEmail').val(),'email', 'sourceEmail')) return false;
	  }
		$.ajax({
            type:"POST",
            url:semusiCommon.API_PARTS.apps.w + '/saveEmailConfiguration',
            data:{
                args:JSON.stringify({
					app_id:semusiCommon.ACTIVE_APP_ID,
                	active:activeTab,
                	smtp_username:$('#'+activeTab+'_username').val(),
                	smtp_password:$('#'+activeTab+'_password').val(),
                	smtp_host:$('#'+activeTab+'_host').val(),
					smtp_fromAddress:$('#'+activeTab+'_fromAddress').val(),
					smtp_fromName:$('#'+activeTab+'_fromName').val(),
                	smtp_port: ($('#'+activeTab+'_port').val() == '' || $('#'+activeTab+'_port').val() == undefined) ? undefined : parseInt($('#'+activeTab+'_port').val()),
					aws_accessKeyId : $('#'+activeTab+'_accessKeyId').val(),
					aws_secretAccessKey: $('#'+activeTab+'_secretAccessKey').val(),
					aws_region : $('#'+activeTab+'_region').val(),
					aws_sourceEmail : $('#'+activeTab+'_sourceEmail').val(),
                	date:new Date()
                }),
                //api_key: "<%= member.api_key %>"
				uniqueNumber : semusiCommon.randomNumber(),
				app_id: semusiCommon.ACTIVE_APP_ID,
                api_key: semusiCommon.getActiveUser.api_key
            },
			headers: {
				'csrf-token': appiceCookies.getCookie('_csrf')
			},
            
            success:function (data) {
				semusiCommon.getCsrfToken();
				showMessagesucess("Email Configuration Updated!");
        		$("#messagesucess").delay(3000).fadeOut(300);
        		$("#message").delay(3000).fadeOut(300);
 			} 
        });
	});

	// save SMS configuration
	$('#saveSMSConfiguration').on('click', function(){
		var activeTab = $('.sms .activeTab').attr('id');
		$('#smsConfigError').text("");
		// validate smtp username
		if($('#'+activeTab+'_username').val() == '' || $('#'+activeTab+'_username').val() == undefined){
			$('#'+activeTab+'_username').focus();
			$('#smsConfigError').text("Please enter user id");
			return false;
		}
		else if(!$('#'+activeTab+'_username').val().match(/^\d+/)) // numeric value validation
        {
        	$('#'+activeTab+'_username').focus();
        	$('#smsConfigError').text("Please only enter numeric characters only");
        	return false;
        }

		// validate smtp pwd
		if($('#'+activeTab+'_password').val() == '' || $('#'+activeTab+'_password').val() == undefined){
			$('#'+activeTab+'_password').focus();
			$('#smsConfigError').text("Please enter password");
			return false;
		}

		$.ajax({
            type:"POST",
            url:semusiCommon.API_PARTS.apps.w + '/saveSMSConfiguration',
            data:{
                args:JSON.stringify({
					app_id:semusiCommon.ACTIVE_APP_ID,
                	active:activeTab,
                	username:$('#'+activeTab+'_username').val(),
                	password:$('#'+activeTab+'_password').val(),
                	date:new Date()
                }),
                //api_key: "<%= member.api_key %>"
				uniqueNumber : semusiCommon.randomNumber(),
				app_id: semusiCommon.ACTIVE_APP_ID,
                api_key: semusiCommon.getActiveUser.api_key
            },
			headers: {
				'csrf-token': appiceCookies.getCookie('_csrf')
			},
            
            success:function (data) {
				semusiCommon.getCsrfToken();
              	showMessagesucess("SMS Configuration Updated!");
        		$("#messagesucess").delay(3000).fadeOut(300);
        		$("#message").delay(3000).fadeOut(300);
 			} 
        });
	});


 

//function to populate camp-config  key value  table 
function populateTable(savedData, tableId) {
    var tableBody = document.querySelector('#' + tableId + ' tbody');
    tableBody.innerHTML = ''; 

    savedData.forEach(function (row) {
        var newRow = document.createElement('tr');

        // Create input fields for each cell
        for (var i = 0; i < 6; i++) {
            var cell = document.createElement('td');
            var input = document.createElement('input');
            input.type = 'text';
            switch (i) {
                case 0:
                    input.className = 'key-input';
                    input.value = row['sourceKey'] || '';
					input.style.width = '200px';

                    break;
                case 1:
                    input.className = 'value-input';
                    input.value = row['sourceValue'] || '';
                    break;
                case 2:
                    input.className = 'type-input';
                    input.value = row['sourceDataType'] || '';
                    break;
                case 3:
                    input.className = 'destination-key-input';
                    input.value = row['destinationKey'] || '';
					input.style.width = '200px';

                    break;
                case 4:
                    input.className = 'destination-value-input';
                    input.value = row['destinationValue'] || '';
                    break;
                case 5:
                    input.className = 'destination-type-input';
                    input.value = row['destinationDataType'] || '';
                    break;
            }
            cell.appendChild(input);
            newRow.appendChild(cell);
        }

        // Add remove button
        var removeButtonCell = document.createElement('td');
        var removeButton = document.createElement('button');
        removeButton.type = 'button';
        removeButton.className = 'btn btn-sm btn-danger remove-row';
        removeButton.textContent = 'Remove';
        removeButtonCell.appendChild(removeButton);
        newRow.appendChild(removeButtonCell);

        tableBody.appendChild(newRow);
    });
}

function populateValidatorMappings(channelData) {
	
	channelData.validatorMappings.forEach(function (pair) {   

				var newRow = `
					<div class="form-group added-row keyvaluepair-row" style="margin-left: 0%;">
						<div class="col-md-3" style="margin-right: 5%; width: 200px;">
							<label class="control-label">Key</label>
							<input type="text" class="form-control key-input"  placeholder="Enter Key" value="${pair.key}">
						</div>
		
						<div class="col-md-3" style="margin-right: 3%; width: 200px;">
							<label class="control-label">Value</label>
							<input type="text" class="form-control value-input"  placeholder="Enter Value" value="${pair.value}">
						</div>
		
						<div class="col-md-3" style="margin-top: 25px;">
							<button type="button" class="fa fa-minus btn btn-danger btn-sm remove-keyvaluepair" data-toggle="tooltip" data-placement="top" title="Delete">
								<i class="bi bi-trash fa-sm"></i>
							</button>
						</div>
		
						<div class="clearfix"></div>
					</div>
				`;
				$("#keyvaluepairsGen").append(newRow);
			})
	
}


$(document).ready(function () {

		var rowCounter = 0;
		var keyValuePairs = [];
	
		// Add Query Params button click event
		$('#addRowForGen').on('click', function () {
			rowCounter++;
	
			var newRowHtml = `
				<div class="form-group added-row keyvaluepair-row" style="margin-left: 0%;">
					<div class="col-md-3" style="margin-right: 5%; width: 200px;">
						<label class="control-label">Key</label>
						<input type="text" class="form-control key-input" id="keyRow${rowCounter}" placeholder="Enter Key">
					</div>
	
					<div class="col-md-3" style="margin-right: 3%; width: 200px;">
						<label class="control-label">Value</label>
						<input type="text" class="form-control value-input" id="valueRow${rowCounter}" placeholder="Enter Value">
					</div>
	
					<div class="col-md-3" style="margin-top: 25px;">
						<button type="button" class="fa fa-minus btn btn-danger btn-sm remove-keyvaluepair" data-toggle="tooltip" data-placement="top" title="Delete">
							<i class="bi bi-trash fa-sm"></i>
						</button>
					</div>
	
					<div class="clearfix"></div>
				</div>
			`;
	
			// Append the new row
			$('#keyvaluepairsGen').append(newRowHtml);
		});
	
		// Add event listener for removing key-value pair
		$('#keyvaluepairsGen').on('click', '.remove-keyvaluepair', function () {
			var removedIndex = $(this).closest('.keyvaluepair-row').index();
			keyValuePairs.splice(removedIndex, 1); 
			$(this).closest('.keyvaluepair-row').remove();
		});

		function getKeyValuePairs() {
			var keyValuePairs = [];
		
			$('#keyvaluepairsGen .keyvaluepair-row').each(function() {
				var key = $(this).find('.key-input').val();
				var value = $(this).find('.value-input').val();
		
				if (key && value) {
					keyValuePairs.push({ key: key, value: value });
				}
			});
		
			return keyValuePairs;
		}

		
    var requestData = [];
    var responseData = [];

  // Function to add a new row to a table
function addNewRow(tableId) {
    var newRowHtml = `
        <tr>
            <td><input type="text" class="key-input"></td>
            <td><input type="text" class="value-input"></td>
            <td><input type="text" class="type-input"></td>
            <td><input type="text" class="destination-key-input"></td>
            <td><input type="text" class="destination-value-input"></td>
            <td><input type="text" class="destination-type-input"></td>
            <td><button type="button" class="btn btn-sm btn-danger remove-row">Remove</button></td> 
        </tr>`;
    $('#' + tableId + ' tbody').append(newRowHtml);
}

$('#addRequestRows').click(function() {
    addNewRow('requestData');
});

$('#addResponseRows').click(function() {
    addNewRow('responseData');
});

$('#requestData, #responseData').on('click', '.remove-row', function() {
    $(this).closest('tr').remove();
});


    // save camp configurator ========= start=========
	$('#saveCampConfigurator').click(function() {
	// Function to extract data from a table and push it into the specified array
	function extractDataToArray(tableId, dataArray) {
		$('#' + tableId + ' tbody tr').each(function() {
			var key = $(this).find('.key-input').val();
			var value = $(this).find('.value-input').val();
			var type = $(this).find('.type-input').val();
			var destinationKey = $(this).find('.destination-key-input').val();
			var destinationValue = $(this).find('.destination-value-input').val();
			var destinationType = $(this).find('.destination-type-input').val();
	
			dataArray.push({ 
				'sourceKey': key, 
				'sourceValue': value, 
				'sourceDataType': type, 
				'destinationKey': destinationKey, 
				'destinationValue': destinationValue, 
				'destinationDataType': destinationType 
			});
		});
	}

extractDataToArray('requestData', requestData);

extractDataToArray('responseData', responseData);

	
		let partner = $("#partnerCampConfig").val();
		let channel = $("#channelCampConfig").val();
		let providerType = $("#providerType").val();
		let url = $("#urlcampaignConfig").val();
		let callBackUrl = $("#destination").val();
		let httpReq = $("#verbcampConfig").val();  
		let payload_key = $("#payload_key").val();
        let validatorMappings = getKeyValuePairs()
	  $.ajax({
				type:"POST",
				url:semusiCommon.API_PARTS.apps.w + '/saveCampConfigurator',
				data:{
					args:JSON.stringify({
						app_id:semusiCommon.ACTIVE_APP_ID,
						partner : partner,
						channel : channel,
						providerType : providerType,
						url:url,
						callBackUrl : callBackUrl,
						httpRequest : httpReq,
						requestMappings: requestData,
						responseMappings : responseData,
						api_key: semusiCommon.getActiveUser.api_key,
						appKey: semusiCommon.ACTIVE_APP_KEY,
						validatorMappings:validatorMappings,
						payload_key : payload_key,
						date:new Date()
					}),
					uniqueNumber : semusiCommon.randomNumber(),
					app_id: semusiCommon.ACTIVE_APP_ID,
					api_key: semusiCommon.getActiveUser.api_key
				},
				headers: {
					'csrf-token': appiceCookies.getCookie('_csrf')
				},
				
				success:function (data) {
					semusiCommon.getCsrfToken();
					  showMessagesucess("Configuration Updated!");
					$("#messagesucess").delay(3000).fadeOut(300);
					$("#message").delay(3000).fadeOut(300);
				 } 
			});
	});
    // save camp configurator ========= end=========


	$('#removeCampConfigurator').click(function() {
		$.ajax({
			type:"POST",
			url:semusiCommon.API_PARTS.apps.w + '/removeCampConfigurator',
			data:{
				args:JSON.stringify({
					app_id:semusiCommon.ACTIVE_APP_ID,
				}),
				uniqueNumber : semusiCommon.randomNumber(),
				app_id: semusiCommon.ACTIVE_APP_ID,
				api_key: semusiCommon.getActiveUser.api_key
			},
			headers: {
				'csrf-token': appiceCookies.getCookie('_csrf')
			},
			
			success:function (data) {
				semusiCommon.getCsrfToken();
				  showMessagesucess("Configuration Updated!");
				$("#messagesucess").delay(3000).fadeOut(300);
				$("#message").delay(3000).fadeOut(300);
				location.reload();

			 } 
		});

	});


});

     //edit case for campaign configurator per channel
	 document.addEventListener("DOMContentLoaded", function() {
		let selectElement = document.getElementById("channelCampConfig");
		let partnerSelectElement = document.getElementById("partnerCampConfig");
	
		// Fetch campaign configurator data when the page loads
		$.ajax({
			type: "GET",
			url: semusiCommon.API_PARTS.apps.r + '/getPartnerInfo',
			data: {
				args: JSON.stringify({
					app_id: semusiCommon.ACTIVE_APP_ID,
				}),
				app_id: semusiCommon.ACTIVE_APP_ID,
				uniqueNumber: semusiCommon.randomNumber(),
				api_key: semusiCommon.getActiveUser.api_key
			},
			success: function(data) {
				// Store the fetched data in a variable accessible globally
				window.campaignConfigData = data.campaignConfigurator || {};
				window.appData = data.partnerInfo.partnerData || {};
			}
		});
	
		// Handle change event on channel selection
		selectElement.addEventListener("change", function() {
			let selectedChannel = this.value;
			// Retrieve data from the stored variable based on the selected channel
			var channelData = window.campaignConfigData[selectedChannel];
			if (channelData) {
				$('#urlcampaignConfig').val(channelData.url);
				$('#providerType').val(channelData.providerType);
				$('#destination').val(channelData.callBackUrl);
				$('#verbcampConfig').val(channelData.verb);
				$('#payload_key').val(channelData.payload_key);
				populateTable(channelData.requestMappings, 'requestData');
				populateTable(channelData.responseMappings, 'responseData');
			
				populateValidatorMappings(channelData);

				if (selectedChannel === "EMAIL") {
					populatePartnerDropdown("EMAIL");
				$('#err-for-camp-conf').hide();

				} else if (selectedChannel === "SMS") {
					populatePartnerDropdown("SMS");
				$('#err-for-camp-conf').hide();

				}else if (selectedChannel === "PUSH") {
					populatePartnerDropdown("PUSH");
				$('#err-for-camp-conf').hide();
				}
				else if (selectedChannel === "WEB_PUSH") {
					populatePartnerDropdown("WEB_PUSH");
				$('#err-for-camp-conf').hide();
				} 
				else if (selectedChannel === "APP_INBOX") {
					populatePartnerDropdown("APP_INBOX");
				$('#err-for-camp-conf').hide();
				} 
				else {
					populatePartnerDropdown("WHATSAPP");
				$('#err-for-camp-conf').hide();

				}
			} else {
				$('#err-for-camp-conf').show();
				$('#urlcampaignConfig').val("");
				$('#providerType').val("");
				$('#destination').val("");
				$('#payload_key').val("");
				$('#verbcampConfig').val(""); 
				populateTable([], 'requestData');
				populateTable([], 'responseData');
				// populateValidatorMappings({});
			}
			
		});
	
		// Function to populate partner dropdown as per channel
		function populatePartnerDropdown(channel) {
			partnerSelectElement.innerHTML = "";
			let partners = window.appData.filter(function(item) {
				return item.channel === channel;
			});
			partners.forEach(function(partner) {
				let option = document.createElement("option");
				option.value = partner.partnerId;
				option.textContent = partner.partnerName;
				partnerSelectElement.appendChild(option);
			});
		}
	
	});
	
	

	// save Feature Switch configuration
	$('#saveFeatureSwitchConfiguration').on('click', function(){
		var activeTab = $('.FeatureSwitch .activeTab').attr('id');
		$('#saveFeatureError').text("");
		// Validate Feature switch android sdk version
		if($('#feature_androidsdkv').val() == undefined){
			$('#feature_androidsdkv').focus();
			$('#saveFeatureError').text("Please enter android SDK version");
			return false;
		}
        // Validate Feature switch iOSSDK version
		if($('#feature_iossdkv').val() == undefined){
			$('#feature_iossdkv').focus();
			$('#saveFeatureError').text("Please enter iOS SDK version");
			return false;
		}
         // Validate Feature switch WebSDK version
		if($('#feature_websdkv').val() == undefined){
			$('#feature_websdkv').focus();
			$('#saveFeatureError').text("Please enter web SDK version");
			return false;
		}

		$.ajax({
            type:"GET",
            url:semusiCommon.API_PARTS.apps.w + '/saveFeatureSwitchConfiguration',
            data:{
                args:JSON.stringify({
					app_id:localStorage.getItem("hdnApp_id"),
                	active:activeTab,
					androidSDKV:$('#feature_androidsdkv').val(),
					iOSSDKV:$('#feature_iossdkv').val(),
                	webSDKV:$('#feature_websdkv').val(),
                	date:new Date()
                }),
                //api_key: "<%= member.api_key %>"
				uniqueNumber : semusiCommon.randomNumber(),
                api_key: semusiCommon.getActiveUser.api_key
            },
            
            success:function (data) {
              	showMessagesucess("Feature Switch Configuration Updated!");
        		$("#messagesucess").delay(3000).fadeOut(300);
        		$("#message").delay(3000).fadeOut(300);
 			} 
        });
	});
	
	function loadPage() {
        if(semusiCommon.ACTIVE_APP_ID == '583e6143ca3b1959380b54b4' || '586b4e229113fe68398c10d5' == semusiCommon.ACTIVE_APP_ID){
            $('.callback-show').show();
        }

        $('.my-div').on('click', function(){
            $( ".my-div" ).each(function( index ) {
                if($(this).hasClass('activeTab')){
                   $('#block-first-'+(index+1)).hide();
				}
                $(this).removeClass('activeTab');
            });
            $(this).addClass('activeTab');
            var selectorIndex = $(this).index();
            $('#block-first-'+(selectorIndex)).show();
		})

		//Get state of KIll Switch 
		$.ajax({
			type: "GET",
			url: semusiCommon.API_PARTS.apps.w + '/getKillSwitchState',
			data: {
				args: JSON.stringify({
					app_id: semusiCommon.ACTIVE_APP_ID,
				}),
				uniqueNumber : semusiCommon.randomNumber(),
				app_id: semusiCommon.ACTIVE_APP_ID,
				api_key: semusiCommon.getActiveUser.api_key
			},
			success: function (data) {
				if (data) {
					let state = data.kill_switch.state;
					$("#switch_state").val(state);
				}
			}
		});

				//Show saved state in security tab 2FA and reset pwd state
		$.ajax({
			type: "GET",
			url: semusiCommon.API_PARTS.apps.w + '/getAppAuthState',
			data: {
				args: JSON.stringify({
					app_id: semusiCommon.ACTIVE_APP_ID,
				}),
				app_id: semusiCommon.ACTIVE_APP_ID,
				uniqueNumber : semusiCommon.randomNumber(),
				api_key: semusiCommon.getActiveUser.api_key
			},
			success: function (data) {
				if (data) {
					if (data[0].allowList) {
						const allowListString = data[0].allowList.join(',');
						$('#allow-list').val(allowListString);
					}
					setSiteSettings(data[0])
					setEncryptionVaraible(data[0])
					setCampaignColumns(data[0])
  					insertItemsFromArray(data[0]);
					insertCustomFieldsInUI(data[0]);
					let cost_per_email = (data[0].email_Config && data[0].email_Config.cost_per_email ) ? data[0].email_Config.cost_per_email  : '';
					let total_bdgt     = (data[0].email_Config && data[0].email_Config.total_bdgt )     ? data[0].email_Config.total_bdgt      : '';
					let email_currency   = (data[0].email_Config && data[0].email_Config.email_currency )   ? data[0].email_Config.email_currency    : '';
					let demographicsState = (data[0].features && data[0].features.demographics) ? data[0].features.demographics : false;
					let usageState = (data[0].features &&  data[0].features.usage) ? data[0].features.usage : false;
					let reportsState = ( data[0].features &&  data[0].features.reports) ? data[0].features.reports : false;
					let churnState = ( data[0].features &&  data[0].features.churn) ? data[0].features.churn : false;
					let expImgState = ( data[0].features &&  data[0].features.expImg) ? data[0].features.expImg : false;
					let advPushState = ( data[0].features &&  data[0].features.advPush) ? data[0].features.advPush : false;
					let apppInboxreportsState = (data[0].features &&  data[0].features.appInboxReports != undefined) ? data[0].features.appInboxReports : true ;
					let maskedDids = (data[0].features &&  data[0].features.maskedDids != undefined ) ? !data[0].features.maskedDids : true ;
					let campExceptPushState = ( data[0].features &&  data[0].features.campExceptPush) ? data[0].features.campExceptPush : false;
					let transState = ( data[0].features &&  data[0].features.transactionalCamp) ? data[0].features.transactionalCamp : false;
					let userprofileImgState = ( data[0].features &&  data[0].features.userprofileImg) ? data[0].features.userprofileImg : false;
					let optimisationState = ( data[0].features &&  data[0].features.optimisation) ? data[0].features.optimisation : false;
					let appInboxDeliveryState = ( data[0].features &&  data[0].features.appInboxAndDeliveryType) ? data[0].features.appInboxAndDeliveryType : false;
					let funnelPeriod = ( data[0].features &&  data[0].features.funnelPeriod) ? data[0].features.funnelPeriod : false;
					let documentationState = ( data[0].features &&  data[0].features.documentation) ? data[0].features.documentation : false;
					let outsideTheAppState = ( data[0].features &&  data[0].features.outsideTheApp) ? data[0].features.outsideTheApp : false;
					let campaignDetailsCsv = ( data[0].features &&  data[0].features.campaignDetailsCsv) ? data[0].features.campaignDetailsCsv : false;
					let hidegranularMonetaryCACLTV = ( data[0].features &&  data[0].features.hidegranularMonetaryCACLTV) ? data[0].features.hidegranularMonetaryCACLTV : false;
					let competingApps = ( data[0].features &&  data[0].features.competingApps) ? data[0].features.competingApps : false;
					let embedCustomField = ( data[0].features &&  data[0].features.embedCustomField) ? data[0].features.embedCustomField : false;
					let whowhatwherewhen = ( data[0].features &&  data[0].features.whowhatwherewhen) ? data[0].features.whowhatwherewhen : false;
					let deepLinkUrl = ( data[0].features &&  data[0].features.deepLinkUrl) ? data[0].features.deepLinkUrl : false;
					let category = ( data[0].features &&  data[0].features.category) ? data[0].features.category : false;
					let utmBuilder = ( data[0].features &&  data[0].features.utmBuilder) ? data[0].features.utmBuilder : false;
					let email_editor = ( data[0].features &&  data[0].features.email_editor) ? data[0].features.email_editor : false;
					let landingPageView = ( data[0].features &&  data[0].features.landingPageView) ? data[0].features.landingPageView : false;
					let funnelLaunchbtn = ( data[0].features &&  data[0].features.funnelLaunchbtn) ? data[0].features.funnelLaunchbtn : false;  
					let cmpInsertInToPG = ( data[0].features &&  data[0].features.cmpInsertInToPG) ? data[0].features.cmpInsertInToPG : false;
					let advancedFreq = ( data[0].features &&  data[0].features.advancedFreq) ? data[0].features.advancedFreq : false;
					let launchCampFreq = ( data[0].features &&  data[0].features.launchCampFreq) ? data[0].features.launchCampFreq : false;
					let actionbuttonSettings = ( data[0].features &&  data[0].features.actionbuttonSettings) ? data[0].features.actionbuttonSettings : false;
					let specialattributes = ( data[0].features &&  data[0].features.specialattributes) ? data[0].features.specialattributes : false;
					let conversionSettings = ( data[0].features &&  data[0].features.conversionSettings) ? data[0].features.conversionSettings : false;
					let journeynavsettings= ( data[0].features &&  data[0].features.journeynavsettings) ? data[0].features.journeynavsettings : false;
					let setupAppsSettings= ( data[0].features &&  data[0].features.setupAppsSettings) ? data[0].features.setupAppsSettings : false;
					let delayLauch= ( data[0].features &&  data[0].features.delayLauch) ? data[0].features.delayLauch : false;
					let removeWeb= ( data[0].features &&  data[0].features.removeWeb) ? data[0].features.removeWeb : false;
					let liveEventSett= ( data[0].features &&  data[0].features.liveEventSett) ? data[0].features.liveEventSett : false;
					let schedulerSett= ( data[0].features &&  data[0].features.schedulerSett) ? data[0].features.schedulerSett : false;
					let cSegPhoneEmail= ( data[0].features &&  data[0].features.cSegPhoneEmail) ? data[0].features.cSegPhoneEmail : false;
					let deviceAttributes= ( data[0].features &&  data[0].features.deviceAttributes) ? data[0].features.deviceAttributes : false;
					let appUsageAttributes= ( data[0].features &&  data[0].features.appUsageAttributes) ? data[0].features.appUsageAttributes : false;
					let allowList= ( data[0].features &&  data[0].features.allowList) ? data[0].features.allowList : false;

					let audience_exports = ( data[0].features &&  data[0].features.audience_exports != undefined ) ? data[0].features.audience_exports : true;


					
					let language_variant = ( data[0].features &&  data[0].features.language_variant) ? data[0].features.language_variant : false;
					let ab_testing_variant= ( data[0].features &&  data[0].features.ab_testing_variant) ? data[0].features.ab_testing_variant : false;


					$('#language_variant_input').prop('checked', language_variant);
					$('#ab_testing_variant_input').prop('checked', ab_testing_variant);

                    // Edit case for app  settings start here
					let AppInboxExpiry = (data[0].AppInboxExpiry) ? data[0].AppInboxExpiry: 0;
					$('#demographics').prop('checked', demographicsState);
					$('#usage').prop('checked', usageState);
					$('#reports').prop('checked', reportsState);
					$('#appInboxReports').prop('checked', apppInboxreportsState);
					$('#maskedDids').prop('checked', maskedDids);
					$('#email_editor').prop('checked',email_editor)
					$('#churn').prop('checked', churnState);
					$('#expendedImg').prop('checked', expImgState);
					$('#advancedPush').prop('checked', advPushState);
					$('#campExceptPush').prop('checked', campExceptPushState);
					$('#transactionalCamp').prop('checked', transState);
					$('#userProfileImg').prop('checked', userprofileImgState);
					$('#optimisation').prop('checked', optimisationState);
					$('#appInbox-deliveryType').prop('checked', appInboxDeliveryState);
					$('#funnelPeriod').prop('checked', funnelPeriod);
					$('#documentation').prop('checked', documentationState);
					$('#outsidetheapp').prop('checked', outsideTheAppState);
					$('#camp-details').prop('checked', campaignDetailsCsv);
					$('#hidegranularMonetaryCACLTV').prop('checked', hidegranularMonetaryCACLTV);
					$('#competingApps').prop('checked', competingApps);
					$('#embedCustomField').prop('checked', embedCustomField);
					$('#whowhatwherewhen').prop('checked', whowhatwherewhen);
					$('#deepLinkUrl').prop('checked', deepLinkUrl);
					$('#category').prop('checked', category);
					$('#utmbuilder').prop('checked', utmBuilder);
					$('#landingPageView').prop('checked', landingPageView);
					$('#audience_exports').prop('checked', audience_exports);
					$('#funnelLaunchbtn').prop('checked', funnelLaunchbtn);
					$('#cmpInsertInToPG').prop('checked', cmpInsertInToPG);
					$('#advancedFreq').prop('checked', advancedFreq);
					$('#launchCampFreq').prop('checked', launchCampFreq);
					$('#actionbuttonSettings').prop('checked', actionbuttonSettings);
					$('#specialattributes').prop('checked', specialattributes);
					$('#conversionSettings').prop('checked', conversionSettings);
					$('#journeynavsettings').prop('checked', journeynavsettings);
					$('#setupAppsSettings').prop('checked', setupAppsSettings);
					$('#delayLauch').prop('checked', delayLauch);
					$('#removeweb').prop('checked', removeWeb);
					$('#liveEventSett').prop('checked', liveEventSett);   
					$('#schedulerSett').prop('checked', schedulerSett);
					$('#cSegPhoneEmail').prop('checked', cSegPhoneEmail);
					$('#deviceAttributes').prop('checked', deviceAttributes);
					$('#appUsageAttributes').prop('checked', appUsageAttributes);
					$('#allowList').prop('checked', allowList);



                  // Check for pushNotificationCharLimit and set values
                            if (data[0].pushNotificationCharLimit) {
                                const charLimit = data[0].pushNotificationCharLimit;
                                if (charLimit.hl) {
                                    $('#header-limit').val(charLimit.hl);
                                }
                                if (charLimit.dl) {
                                    $('#description-limit').val(charLimit.dl);
                                }
                                if (charLimit.edl) {
                                    $('#exp-description-limit').val(charLimit.edl);
                                }
                            }
                            
                            // Check for getAppEnabled and set value
                            if (typeof data[0].getAppEnabled === 'boolean') {
                                $('#getApp-dropdown').val(data[0].getAppEnabled.toString());
                            }
                            

							//////allow list
                            if (data[0].allowList && data[0].allowList.allow_List) {
								$('#allow-list').val(data[0].allowList.allow_List)
							}
							//app setting
					        if(data[0].appsettingsBaseUrl){
						        $('#baseUrl').val(data[0].appsettingsBaseUrl);
						    } 

				   // EDIT case campconfig while loading page first time
                       function populateData(config, type) {
                           $('#urlcampaignConfig').val(config.url);
                           $('#providerType').val(config.providerType);
                           $('#destination').val(config.callBackUrl);
                           $('#verbcampConfig').val(config.verb);
						   $('#partnerCampConfig').val(config.partner);
						   $('#payload_key').val(config.payload_key);
                       
                           // Populate the requestMappings table when the page loads
                           populateTable(config.requestMappings, 'requestData');
                       
                           // Populate the responseMappings table when the page loads
                           populateTable(config.responseMappings, 'responseData');
							populateValidatorMappings(config)
						   
                                
                       }                       
                       // Edit case while loading page first time
                       if (data[0] && data[0].campaignConfigurator) {
                           const campaignConfig = data[0].campaignConfigurator;
						   let selectedChannel = "";
						   
						if(data[0].campaignConfigurator.WHATSAPP){
							 selectedChannel = data[0].campaignConfigurator.WHATSAPP.channel;
						}
						if(data[0].campaignConfigurator.EMAIL){
							 selectedChannel = data[0].campaignConfigurator.EMAIL.channel;
						}
						if(data[0].campaignConfigurator.SMS){
							 selectedChannel = data[0].campaignConfigurator.SMS.channel;
						}
                           selectedChannel = selectedChannel.toUpperCase();

                           if (campaignConfig[selectedChannel]) {
                               populateData(campaignConfig[selectedChannel], selectedChannel);
							   $('#channelCampConfig').val(selectedChannel);
                           }
                         }else{
				             $('#err-for-camp-conf').show();
						 }

                     
                        //for gupshup
						$('#gupshup_username').val(data[0]?.smsCfg?.gupshup?.un ?? '');
						$('#gupshup_password').val(data[0]?.smsCfg?.gupshup?.ps ?? '');
						
					$('#numberSelect').val(AppInboxExpiry).change();
					let state = data[0].email_auth;
					let resetState = data[0].ResetPassswordMode;
					$("#resetPassword").val(resetState);
					$("#cost_per_email").val(cost_per_email);
					$("#total_bdgt").val(total_bdgt);
					$("#email_currency").val(email_currency);
					$("#2faAuth").val(state);
					let concurrentLogin = data[0].concurrentLogin
					$("#concurrentLogin").val(concurrentLogin);
				}
			}
		});

		// set campaign column checked 
		function setCampaignColumns(appdata) {

			// if this app has column configuration saved
			if (appdata && appdata.campaign_columns) {
				for (const key in appdata.campaign_columns) {
					$("#"+key+"-checkbox").prop('checked', appdata.campaign_columns[key]);
				}
			}
		}

		
		function setEncryptionVaraible(appdata){
			//set varaibles only if status is true
			if(appdata && appdata.encryptionstatus){
				$('#encryptionStatusDropdown').val('true');
				document.getElementById("encryptionKeyInput").style.display = "block";
				$("#encryptionKey").val(appdata.encryptionkey);
			}
		}
		function setSiteSettings (appdata){
			const sitesettings = appdata.sitesettings
			//if global Setting exist
			if(sitesettings){
				//set its type
				$('#sso_type').val(sitesettings.sso_type);
				$('#is_sso').val(sitesettings.is_sso);
				$('#authCaptcha').val(sitesettings && sitesettings.captcha ? sitesettings.captcha : 'disable');			
				$('#logo_name').val(sitesettings.logo_name);
				if(sitesettings.portal_name){
					$('#portal_name').val(sitesettings.portal_name);
				}
				// incase of ad
				if (sitesettings.sso_type === 'ad') {
					//show config UI
					$('#ad_settings').show();
					const ldapConfig = sitesettings.ldapConfig
					// set its value
					$("#ldap_url").val(ldapConfig.url);
					$("#bind_dn").val(ldapConfig.bindDN );
					$("#bind_credential").val(ldapConfig.bindCredentials);
					$("#search_base").val(ldapConfig.searchBase);
				} else {
					$('#ad_settings').hide();
				}
				if (sitesettings.sso_type === 'saml') {
					//show config UI
					$('#saml_settings').show();
					const samlConfig = sitesettings.samlConfig
					// set its value
					$("#saml_issuer").val(samlConfig.saml_issuer);
					$("#saml_entryPoint").val(samlConfig.saml_entryPoint );
					$("#saml_callbackURL").val(samlConfig.saml_callbackURL);
					$("#saml_cert").val(samlConfig.saml_cert);
				} else {
					$('#saml_settings').hide();
				}

				if(sitesettings.xml_fileName){
					$("#XMLmetadataFile_name").val(sitesettings.xml_fileName);
				}
			}
		}
	}
	$("#save_bdgt").on("click", () => {
		let cost_per_email  = $("#cost_per_email").val();
		let total_bdgt      = $("#total_bdgt").val();
		let email_currency    = $('#email_currency').val();


		if( parseInt(cost_per_email) > parseInt(total_bdgt) || cost_per_email != '' & total_bdgt == '' ){
			$('#email_setting_err').text('Total Budget cannot be Less than per campaign cost ')
			return
		}
		$.ajax({
			type:"POST",
			url:semusiCommon.API_PARTS.apps.w + '/saveEmailBudget',
			data:{
				args:JSON.stringify({
					cost_per_email:cost_per_email,
					total_bdgt: total_bdgt,
					email_currency:email_currency,
					app_id: semusiCommon.ACTIVE_APP_ID,

				}),
				uniqueNumber : semusiCommon.randomNumber(),
				app_id: semusiCommon.ACTIVE_APP_ID,
				api_key: semusiCommon.getActiveUser.api_key
			},
			headers: {
				'csrf-token': appiceCookies.getCookie('_csrf')
			},
			success:function (data) {
				semusiCommon.getCsrfToken();
				  showMessagesucess("Saved");
				$("#messagesucess").delay(3000).fadeOut(300);
				$("#message").delay(3000).fadeOut(300);
			 } 
		})
});
	$("#auth_save").on("click", () => {
		let resetState =  $("#resetPassword").val();
		let state = $("#2faAuth").val();
		let concurrentLogin = $("#concurrentLogin").val();
		if(resetState !== 'SMTP' && resetState !== 'ADMIN'){
			$('#setting_err').text('Please select valid resetState value')
			return
		}
		if(state !== 'enable' && state !== 'disable'){
			$('#setting_err').text('Please select valid state value')
			return
		}
		if(concurrentLogin !== 'ON' && concurrentLogin !== 'OFF'){
			$('#setting_err').text('Please select valid concurrentLogin value')
			return
		}
		$.ajax({
			type:"POST",
			url:semusiCommon.API_PARTS.apps.w + '/saveAppAuthState',
			data:{
				args:JSON.stringify({
					concurrentLogin:concurrentLogin,
					state: state,
					passwordResetMode :resetState,
					app_id: semusiCommon.ACTIVE_APP_ID,
				}),
				uniqueNumber : semusiCommon.randomNumber(),
				app_id: semusiCommon.ACTIVE_APP_ID,
				api_key: semusiCommon.getActiveUser.api_key
			},
			headers: {
				'csrf-token': appiceCookies.getCookie('_csrf')
			},
			// 
			success:function (data) {
				semusiCommon.getCsrfToken();
				  showMessagesucess("Saved");
				$("#messagesucess").delay(3000).fadeOut(300);
				$("#message").delay(3000).fadeOut(300);
			 } 
		})
});

 $("#addItem").on("click", () => {
    var inputBox = document.getElementById("item-input");
    var itemText = inputBox.value.trim();

    if (itemText !== "") {
        var itemList = document.getElementById("item-list");
        var newItem = document.createElement("li");
        newItem.textContent = itemText;

        var deleteButton = document.createElement("button");

        // Adding Font Awesome icon
        deleteButton.innerHTML = '<i class="fa fa-minus"></i>';
        deleteButton.classList.add("btn", "btn-danger", "btn-sm"); // Adding Bootstrap classes
		deleteButton.style.marginLeft = "10px";      // Add margin towards left

        deleteButton.onclick = function () {
            itemList.removeChild(newItem);
        };

        newItem.appendChild(deleteButton);
        itemList.appendChild(newItem);

        inputBox.value = "";
    } else {
        alert("Please enter a valid item.");
    }
});


    // Function to insert items from an array
	function insertItemsFromArray(appdata) {
		
		if (appdata && appdata.allowedItems) {

			const itemsArray = appdata.allowedItems;
			$('#item-list').empty(); // Clear previous items
			$.each(itemsArray, function(index, itemText) {
			    var newItem = $('<li>').addClass('row').append(
			        $('<div>').addClass('col-md-7').text(itemText),
			        $('<div>').addClass('col-md-2').append(
			            $('<button>').addClass('btn btn-danger btn-sm delete-btn').html('<i class="fa fa-minus"></i>').css('margin-top', '5px')
			        )
			    );
			    $('#item-list').append(newItem);
			    newItem.find('.delete-btn').click(function() {
			        $(this).closest('li').remove();
			    });
			});

		}
	}

   // This function generates the list in the UI dynamically based on the values from the UI 
   function insertCustomFieldsInUI(appdata) {
	if (appdata && appdata.customFields) {
		// Get the container where the input fields will be appended
		let container = $("#custom_field_list");

		// Clear existing input fields
		container.empty();

		// Iterate over the customFields object and create input fields dynamically
		Object.entries(appdata.customFields).forEach(([key, value]) => {
			// Create a new row
			let newRow = $("<div>").addClass("form-group row");

			// Create the column for key input
			let keyColumn = $("<div>").addClass("col-md-3");
			let keyInput = $("<input>").attr({
				type: "text",
				value: key,
				disabled: true,
				name: "custom_key",
				class: "form-control form-control-sm"
			});
			keyColumn.append(keyInput);

			// Create the column for value input
			let valueColumn = $("<div>").addClass("col-md-5");
			let valueInput = $("<input>").attr({
				type: "text",
				value: value,
				disabled: true,
				name: "custom_value",
				class: "form-control form-control-sm"
			});
			valueColumn.append(valueInput);

			// Create the column for delete button
			let deleteColumn = $("<div>").addClass("col-md-2 col-sm-2");
			let deleteButton = $("<button>").addClass("btn btn-danger btn-sm").css("marginLeft", "10px").html('<i class="fa fa-minus"></i>');
			deleteButton.on("click", function () {
				newRow.remove();
			});
			deleteColumn.append(deleteButton);

			// Append columns to the row
			newRow.append(keyColumn, valueColumn, deleteColumn);

			// Append the new row to the container
			container.append(newRow);
		});
	}


	if(appdata.scriptCode) {
		$('#custom_script').val(appdata.scriptCode);
	}
	
}

//KILL SWITCH CONFIG/VALIDATIONS
$("#switch_state").on('change', () => {
	let state = $("#switch_state").val();
	let android_versions = $("#switch_android");
	let ios_versions = $("#switch_ios");
	let web_versions = $("#switch_web");
	if(state === "0") {
		android_versions.prop('disabled', true);
		ios_versions.prop('disabled', true);
		web_versions.prop('disabled', true);
	}
	else{
		android_versions.prop('disabled', false);
		ios_versions.prop('disabled', false);
		web_versions.prop('disabled', false);
	}
});


//SAVE KILL SWICTH SETTINGS
$("#switch_save").on('click', () => {
	let state = $("#switch_state").val();
	if(state === "1" || state === "0"  ) {
		let android_versions = $("#switch_android").val();
		let ios_versions = $("#switch_ios").val();
		let web_versions = $("#switch_web").val();

		if(state === "1") {
		  if(android_versions || ios_versions || web_versions) {

		  }else{
			  alert("Please provide version details.");
			  return;
		  }
		}
		//Structure Data before save
			let obj = {};
			if(android_versions) {
				let android_v = android_versions.split(',').map(ele => {
					return {v:ele}
				})
				obj.android = android_v;
			}
			if(ios_versions) {
				let ios_v = ios_versions.split(',').map(ele => {
					return {v:ele}
				})
				obj.ios = ios_v;
			}
			if(web_versions) {
				let web_v = web_versions.split(',').map(ele => {
					return {v:ele}
				})
				obj.web = web_v;
			}

		   obj.baseurl = semusiCommon.BASEURL; 
		   obj.state = state;
		   obj.app_id = semusiCommon.ACTIVE_APP_ID;
		   
			//Save feild to app collections
			$.ajax({
				type:"POST",
				url:semusiCommon.API_PARTS.apps.w + '/savekillSwitchSetting',
				data:{
					args:JSON.stringify(obj),
					uniqueNumber : semusiCommon.randomNumber(),
					app_id: semusiCommon.ACTIVE_APP_ID,
					api_key: semusiCommon.getActiveUser.api_key
				},
				headers: {
					'csrf-token': appiceCookies.getCookie('_csrf')
				},
				
				success:function (data) {
					semusiCommon.getCsrfToken();
					showMessagesucess("Saved");
					$("#messagesucess").delay(3000).fadeOut(300);
					$("#message").delay(3000).fadeOut(300);
				} 
		})
	
	}
	else {
	   alert("Please enable switch state");
	   return;
	}
});	

window.onload = loadPage;
}());
