	appice.controller('journeyCreateController', function ($scope, appIceService, $routeParams, $location, $window) {
		var topEventChart;
		var attributeEventChart;
		var dt = {};
		var queue = [];
        var ans = [];
		var show = [];
		$scope.pointArray = [];
		var labeldate = 'lastmonth';
		var semusiCustomEvents = {}
		var validFunnel = false;
		$scope.journeyEdited = {};
		$scope.isEdit = false;
		$scope.PANEL_URL = window.location.origin;
		$scope.eventList = [];
		$scope.events = [];
		semusiCustomEvents.customEvents = [];
		$scope.drillDown = false;
		$scope.message = '';
		$scope.topGraphEvents = [];
		$scope.topEndEvents = [];
		$scope.journey={}
		$scope.journey.events = [{}];
		$scope.eventListData = [];
		$scope.journeyKey      = false;
		$scope.showJourneyDropdown = false;
		$scope.bottomGraphEvents = [];
		$scope.stackedLabels=[];
		var newGraphLabel;
		$scope.datasets = {};
		$scope.labels =[];
		$scope.isTop = false;
		$scope.initDataset =[];
		$scope.isData = false;
		$scope.isAvailable='0';
		$scope.tempVariables = [];
		$scope.startEvent='';
		$scope.endEvent='';
		$scope.st='';
		$scope.ed='';
		$scope.pf='Platform';
		$scope.journeyName = '',
		$scope.journeyDescription = ''
		$scope.errorMsg = ''
		$scope.isError = false;
		$scope.mode = 'Create';
		$scope.hideForm = false;
		$scope.jn = {};
		$scope.platform = 'all';
		$scope.jouneyHeight;
		$scope.period = 'Period';
		$("#p1").hide();
		$("#advance-daterange").hide();

		var funnelObj =  {
			"name": "",
			"description": "",
			"duration": "",
			"unit": "This Month",
			"customunit": "",
			"events": [],
			"platform": [
			  "Android",
			  "iOS",
			  "Web"
			]
		  };

function display(data, size){
	//setting html to blank for every query
	$("#container").html("");
	// create a chart and set the data
	var chart = anychart.sunburst(data, "as-tree");
	var credits = chart.credits();
	credits.text("appICE-Graph @2014-2019");  
	// set the calculation mode
	// chart.calculationMode("parent-dependent");
	chart.radius(size);

	// enable HTML for labels
	chart.labels().useHtml(true);
	chart.labels().position("circular");

	// configure labels
	chart.labels().format("<span style='font-weight:bold'>{%name}</span><br>Count:{%value}");

	// configure tooltips
	chart.tooltip().format("{%name}\n\ncount:{%value}\n{%percentage}");

	// set the chart title
	chart.title().useHtml(true);
	// chart.title("appICE-Journey");

	var funnelData = [];
	chart.listen('pointsHover', function(e){
		var item = e.point.node;
		$scope.pointArray = [];
		funnelData = [];
		$("#journey_table").show();
		$('#journey_table > tbody >tr').remove();
	
		while(item !== null){
			$scope.pointArray.push(item.na);
			item = item.getParent();
		}
		
		$scope.pointArray = $scope.pointArray.reverse();
		if (!e.currentPoint.hovered){
			funnelData.push($scope.pointArray);
			$("#journey_table").hide();
			return;
		}
		$scope.pointArray.forEach((node,index) =>{
			let percentage='';
			if(index==0){
				percentage = "100%";
			}else{
				if(node.percentage && node.percentage!==""){
					percentage = node.percentage.replace('(','');
					percentage = percentage.replace(')','');
				}
		    }
			$('#journey_table > tbody').append('<tr ><td>' + node.name +'</td><td>'+ node.value +'</td><td>'+ percentage +'</td></tr>');

		})

	  });

	  //Set create Funnel context menu on chart
	  chart.contextMenu(false);
	  var customContextMenu = anychart.ui.contextMenu();
	  customContextMenu.attach(chart);
  
	  customContextMenu.itemsProvider(function () {
		return [
			{
				text: 'Create Funnel',
				eventType: 'createFunnel'
			}
		];
	});

    // Set event listener on the context menu.
    customContextMenu.listen('createFunnel', function () {

		  //prepare funnel object
		  //reset funnelObj
			funnelObj.events = [];
			funnelObj.name = "";
			funnelObj.description = "";

		  funnelData[0].forEach(ele=>{
			  let events = {};
			  events.eventName = ele.name
			  funnelObj.events.push(events);
		  })
		  //open modal
		  $("#funnelModal").modal('show');
        
	});

	// set the container id
	chart.container("container");

	// initiate drawing the chart
	chart.draw();

	
}

//create funnel with journey
$scope.createFunnel = function(){
	//if false call create funnnel api
	let funnelName = $("#funnelname").val();
	let funnelDesc = $("#funneldesc").val();
	if(funnelName == undefined || funnelName== ""){
		alert('Please enter funnel name')
		return;
	}

	if(validFunnel){
		funnelObj.name = funnelName;
		funnelObj.description = funnelDesc;

		let promise = appIceService.createFunnel(funnelObj);
		promise.then(data=>{
			window.location.href =appiceEncode.encodePayload(window.location.origin+"/dashboard?action=insideapp#/funnels/data");
		})
		.catch(err=>{
			 
		})
		//redirect to funnel table page on success 		
		$("#funnelModal").modal('hide');
	}
  
}

//Reset funnel model
$scope.cancelFunnel = function() {
	  //reset funnelObj
	  funnelObj.events = [];
	  funnelObj.name = "";
	  funnelObj.description = "";
}

//Validate funnel creation 
$scope.validateFunnel = function() {
	let funnelname =  $("#funnelname").val();
	if(funnelname!= ""||funnelname!==undefined) {
		let promise = appIceService.validateFunnelName(funnelname)
		promise.then(res=>{
			if(res==false){
				validFunnel = true;
			}
		})
		.catch(err=>{
			validFunnel = false;
		})
	}
}	


function init() {	

	$("#container").html("");
	
	$scope.selectedEvent = "Select Event";
	$scope.selectedEventAttribute = "Select Attribute";
	$scope.selectedCEventAttribute = "Select Attribute";
	$scope.isCEventAttribute = false;
	$scope.cList = [];
	$scope.eventAttributeList = [];


	semusiCommon.setDateRange(null, null);
	angular.element(document.getElementById('container')).scope().getEventList()


	$("#downloadLink").click(function(){
		var args = {filter:{}};
		var dateRange = {sd:semusiCommon.dateRange.currentStartDate,ed:semusiCommon.dateRange.currentEndDate};
		args.filter.dateRange = dateRange;
		args.filter.dateRange.dates = [];
		var startDate =args.filter.dateRange.sd*1000;
		while(startDate < args.filter.dateRange.ed*1000 ){
			args.filter.dateRange.dates.push(moment(startDate).format('YYYY-MM-DD'));
			startDate = parseInt(moment(startDate).add(1,'days').valueOf());
		}
		var filename = "Journey"+dateRange.sd+"-"+dateRange.ed+".csv";
		let queringString = window.location.origin+'/o/metrices/getJourneyEventData?api_key=d985715d1bb48942d36d5d08de3b6a8c&app_id=5d5fd1290200e5b6009d6478&args=%7B%22startDate%22:1594319400,%22endDate%22:1594405799.999,%22startDateNew%22:%222020-07-10%22,%22endDateNew%22:%222020-07-10%22,%22eventList%22:%5B%22Chart_Screen_Scrip%22,%22More%22,%22Orders%22,%22Mutual_Funds%22,%22Refer_and_Earn%22,%22Quote_Screen%22,%22Dashboard%22,%22Rate_Us%22,%22Charts_Screen%22,%22Prelogin_Dashboard%22,%22Markets%22,%22Smallcase%22,%22Banner_1%22,%22Watchlist%22,%22Research_and_News%22,%22Chat%22,%22Portfolio_Tracker%22,%22Banner_2%22,%22LoginScreen%22,%22Positions%22,%22Alternate_Investments%22,%22Order_Screen%22,%22Funds%22%5D,%22platform%22:%22all%22,%22offset%22:0,%22limit%22:5000,%22journeyRange%22:%22yesterday%22%7D';
		var promise = appIceService.downloadJourneyCsv(queringString);
		promise.then(function (eventsData) {
				$scope.showPopup('Journey CSV', eventsData.result, 'success')
			})
		.catch(function(error){
			$scope.showPopup('Journey CSV', error, 'error')
		});
		});
	let isJourney = appIceService.isJourney;
		if(isJourney){
			$scope.mode = 'Edit';
			editJourney();
		}
	let isJourneyView = appIceService.isView;
		if(isJourneyView){
			$scope.mode = 'View';
			$scope.jn = appIceService.getJourneyView();
			$scope.isAvailable = '2';
			$scope.hideForm = true;
			display($scope.jn.paths);
		}

		// resizeJourney($scope.isAvailable);	
}

$scope.getEventList= function() {
	$scope.eventList = [];
	let promise = appIceService.getEventList();
	promise.then(function (eventsData) {
		if (eventsData.data != undefined) {
			let journeys = [];
			let events = eventsData.data;
			$scope.eventList = _.sortBy(events, 'event');
			var len = $scope.journey.events.length;
			if($scope.journey.events[len-1]?.selectedJourney == undefined || $scope.journey.events[len-1]?.selectedJourney == '' ){
				$scope.eventListData[len-1] = events;
			   }
			events.forEach(function(event){
				if(event.journey){
					journeys.push(event.journey)
					$scope.journeyKey = true;
				}
			})

			if($scope.journeyKey){
				$('.journeyDivs').removeClass('col-sm-4');
				$('.journeyDivs').addClass('col-sm-3');

			}
			const journeyArray = journeys.filter((elem, index, self) => {
				return index === self.indexOf(elem);
			});
			$scope.journeysArray = journeyArray;
 
			$scope.topGraphEvents = events.map(function (item) {

				return {name: item.event, selected: true};
			})
			$scope.topEndEvents = $scope.topGraphEvents
			setCookie("eventListData", JSON.stringify($scope.topGraphEvents),100);   
		}
	});
}
$scope.onJourneySelect = function (e) {
  $scope.showJourneyDropdown = true;

  var length = $scope.journey.events.length;
  var selectedOption = e;
  const selectedJourney = selectedOption.replace(/string:/, "");

  $scope.eventListData[length - 1] = [];
  for (let i = 0, len = $scope.eventList.length; i < len; i++) {
    if ( typeof $scope.eventList[i] === "object" && $scope.eventList[i].journey !== undefined ) {
      if ($scope.eventList[i].journey === selectedJourney) {
        $scope.eventListData[length - 1].push($scope.eventList[i]);
      }
    }
  }
  $scope.topGraphEvents = [];
  $scope.topEndEvents = [];
  $scope.topGraphEvents = $scope.eventListData[0].map(function (item) {
    return { name: item.event, selected: true };
  });
  $scope.topEndEvents = $scope.topGraphEvents;
  $scope.startEvent='';
  $scope.endEvent='';
  
};
function getEventDetails(callback){
	var flag = 0;


	var newVar = $scope.startEvent
	var newVar1 = $scope.endEvent
	$scope.getData().then((data)=>{
	$scope.startEvent = newVar;
	$scope.endEvent = newVar1;

	var dt;
	dt = data;

	let nodes = new Array();
	let de = (data.result.links ? data.result.links:[]);
	let i,j;
	if(data.result =='Failed'){
		showError("Error While loading the Journey")

		return
	}

	for(i=0;i<data.result.links.length;i++)
	{
		for(j=0;j<data.result.nodes.length;j++)
		{
			if(data.result.links[i].name==data.result.nodes[j].name)
		   {nodes.push(data.result.nodes[j]);}
		}
	}

	$("#container").html("");
	//Check That Cookie have data or not
	queue = [];
	ans = {};
	show=[];
	var obj = [];
	obj = dt.result.links;

	if($scope.startEvent=='All'){
		if($scope.endEvent!=''&&$scope.endEvent!='All')
		{
			onlyEndEvent(obj);
			show = obj;
			if(show.length==0){
				  $scope.isAvailable='1';  
			  }
				else{
				if(flag==1){
					  $scope.isAvailable = '2';
					  display(obj, '100%');
				  }
			  }
		}
		else{
			show = obj;
			$scope.isAvailable = '2';
			display(obj, '100%');
		}
		callback()
	}
	else if($scope.startEvent!=''){
		var journeyList =  JourneyList(obj);
		if(journeyList.length==0)
			  alert("No journey available");
		else{
			getSingleObject(journeyList);
			if($scope.endEvent!='')
				ans = checkPresent(ans);
			if(ans.children.length==0){
				$scope.isAvailable='1';  
			}
			else{
				show = [];
				show.push(ans);
				if(flag==1){
					$scope.isAvailable = '2';
					addPercentage(show);

				}
			}	
			callback()
		  }
	}
	else
	{
		if($scope.endEvent!='')
		{
			onlyEndEvent(obj);
			show = obj;
			if(show.length==0){
				  $scope.isAvailable='1';  
			  }
				else{
					for(let ind =0; ind<show.length; ind++){
						if(show[ind].children.length==0){
							show.splice(ind,1);
							ind--;
						}
					}
					if(show.length==0){
					  $scope.isAvailable='1';  
				  }
				else if(flag==1){
					  $scope.isAvailable = '2';
					  display(obj);
				  }
			  }
			  callback()
		}
	}

	})

}
    function resizeJourney(steps){
		if(steps==5){
			$scope.jouneyHeight = 35+'em';
		}
		if(steps==4){
			$scope.jouneyHeight =40+'em';
		}
		if(steps==3){
			$scope.jouneyHeight= 42+'em';
		}
		if(steps==2){
			$scope.jouneyHeight = 45+'em';
		}
	}

	// show popup box
	function editJourney() {
	    $scope.journeyEdited = appIceService.getJourneyEdited();
		$scope.isEdit = true;
		$scope.startEvent = $scope.journeyEdited.startEvent;
		$scope.endEvent = $scope.journeyEdited.endEvent;
		$scope.st = $scope.journeyEdited.startEvent;
		$scope.ed = $scope.journeyEdited.endEvent;
		$scope.journeyName = $scope.journeyEdited.journeyName;
		$scope.journeyDescription = $scope.journeyEdited.journeyDescription;
		$scope.pf = $scope.journeyEdited.platform;
		$scope.period = $scope.journeyEdited.period;
		show = $scope.journeyEdited.paths
		appIceService.removeJourneyEdited();
	}

	$scope.selectedPlatform = function(platform){
		$scope.pf = platform;
	}

	$scope.selectedPeriod = function(period){
		$scope.period = period;
	}

	//Update Journey data with $scope params
	$scope.updateJourney = function () {
		getEventDetails(function(){
		var ob = {
			startEvent : $scope.startEvent,
			endEvent : $scope.endEvent,
			journeyName : $scope.journeyName,
			journeyDescription : $scope.journeyDescription,
			paths : show,
			platform: $scope.pf,
			period:$scope.period,
			id: $scope.journeyEdited._id
		}
		
	//   Validating the user input to contain only allowing letters, numbers, space, commas, periods?
		var regex = /^[\.a-zA-Z0-9,!? ]*$/;					
		if($scope.startEvent=='' && $scope.endEvent=='')
			{$scope.errorMsg = 'Please select a start or end event';$scope.isError=true;}
		else if($scope.journeyName=='' || !regex.test($scope.journeyName))
			{$scope.errorMsg = 'Please provide a valid journey name';$scope.isError=true;}
		else if($scope.journeyDescription==''  || !regex.test($scope.journeyDescription))
			{$scope.errorMsg = 'Please provide a journey description';$scope.isError=true;}
		else if($scope.pf=='' || $scope.pf=='Platform')
			{$scope.errorMsg = 'Please provide a platform';$scope.isError=true;}
		else if($scope.period=='' || $scope.pf=='Period')
			{$scope.errorMsg = 'Please provide a period';$scope.isError=true;}		
		else
		{
			var promise = appIceService.updateJourney(ob);

		promise.then(data => {
			if(data != undefined){
			$scope.isError=false;
			$scope.reset();
			$("#messageboxsucess").text("Journey Updated");
			$("#messagesucess").show();

			setTimeout(() => {
				$("#messagesucess").hide();
			},3000)
		}
		else{
			alert("Failed to update journey");
		}
		}).catch(err => {
			 
		})
		
		}
	 })
	}
	$scope.showPopup = function(title, msg, type){
			// show popup box
			swal({
				title: title,
				text: msg,
					type: type, //"error"
				});
		}

	$('#platform').text('All');
// This function runs the query 
	$scope.getData = async function() {
			//Check That Cookie have data or not
			let customEvents = checkCookie("eventListData");

			var cookieEvent = [];	
			if(customEvents.length > 0){
				cookieEvent = customEvents.reduce((list, event) =>{
					if(event.selected){
						list.push(event.name);
					}
					return list;
				}, [])
			}
			var dates = {
				platform: $scope.pf,
				journeyRange:$scope.period

			};

			var result = await appIceService.getJourneyEventData(dates);
			return result 
		}



	// when saving or preview of any journey we have to get the Events again according to the seleced params
	$scope.getJourneyEventDataN = function(flag) {
		const chck = validateInputs()
	  if(chck){
		var newVar = $scope.startEvent
		var newVar1 = $scope.endEvent
		$scope.getData().then((data)=>{
		$scope.startEvent = newVar;
		$scope.endEvent = newVar1;
			var dt;
			dt = data;

			let nodes = new Array();
			let de = (data.result.links ? data.result.links:[]);
			let i,j;
			for(i=0;i<data.result.links.length;i++)
			{
				for(j=0;j<data.result.nodes.length;j++)
				{
					if(data.result.links[i].name==data.result.nodes[j].name)
				   {nodes.push(data.result.nodes[j]);}
				}
			}
		$("#container").html("");
		//Check That Cookie have data or not
		queue = [];
		ans = {};
		show=[];
		var obj = [];
		obj = dt.result.links;
		if($scope.startEvent=='All'){
			if($scope.endEvent!=''&&$scope.endEvent!='All')
			{
				onlyEndEvent(obj);
				show = obj;
				if(show.length==0){
  		        	$scope.isAvailable='1';  
  		        }
  		  		else{
					if(flag==1){
		  				$scope.isAvailable = '2';
		  				display(obj, '100%');
		  			}
		  		}
			}
			else{
				show = obj;
				$scope.isAvailable = '2';
				display(obj, '100%');
			}
			
		}
		else if($scope.startEvent!=''){
			var journeyList =  JourneyList(obj);
			if(journeyList.length==0)
	  			alert("No journey available");
			else{
				getSingleObject(journeyList);
				if($scope.endEvent!='')
					ans = checkPresent(ans);
				if(ans.children.length==0){
					$scope.isAvailable='1';  
				}
				else{
					show = [];
					show.push(ans);
					if(flag==1){
						$scope.isAvailable = '2';
						addPercentage(show);
						
					}
				}	
		  	}
		}
		else
		{
			if($scope.endEvent!='')
			{
				onlyEndEvent(obj);
				show = obj;
				if(show.length==0){
  		        	$scope.isAvailable='1';  
  		        }
  		  		else{
  		  			for(let ind =0; ind<show.length; ind++){
  		  				if(show[ind].children.length==0){
  		  					show.splice(ind,1);
  		  					ind--;
  		  				}
  		  			}
  		  			if(show.length==0){
  		        		$scope.isAvailable='1';  
  		        	}
					else if(flag==1){
		  				$scope.isAvailable = '2';
		  				display(obj);
		  			}
		  		}
			}
		}	
	 });
	 }
	}

	$scope.reset = function () {
		$scope.selectedJourney = '';
		$scope.isAvailable = '0';
		$scope.startEvent='';
		$scope.endEvent='';
		$scope.st='';
		$scope.ed='';
		$scope.journeyName = '';
		$scope.journeyDescription = '';
		show=[];
		$scope.isError = false;
		$scope.period = 'Period'
		$scope.pf = 'Platform'
		display([])

		appIceService.removeJourneyEdited();
		appIceService.removeJourneyView();
	}

	function validateInputs (){
		if($scope.pf=='' || $scope.pf=='Platform'){
			showError("Please provide a platform")
			return false;
		}
		if($scope.period=='' || $scope.period=='Period'){
			showError("Please provide a Period")
			return false;
		}
		if($scope.startEvent=='' || $scope.endEvent==''){
			showError("Please select a Start and End event")
			return false;
		}
		return true
	}
	$scope.validateJourneyName = async function() {
		if ($scope.journeyName && $scope.journeyName.trim() !== '') {
		  try {
			var regex = /^[a-zA-Z0-9 ]+$/;
			const response = await appIceService.getJourneysList();
			const isValuePresent = response.some(item => item.journeyName === $scope.journeyName);
			if(!$scope.isEdit){
				if (isValuePresent) {
					showError("Journey name already exists!")
				}
			}
			if(!regex.test($scope.journeyName)){
				showError("Journey name must contain only letters, numbers, spaces")
			}
			else if($scope.journeyDescription == '' || $scope.journeyDescription == undefined ){
				showError("Please enter journey description!")
			} else if(!regex.test($scope.journeyDescription)){
				showError("Journey description must contain only letters, numbers, spaces")
			} 
			else {
				const chck = validateInputs()
				if(chck){
					$scope.saveJourney();
				}
			}
		  } catch (error) {
			console.log("An error occurred while fetching journeys list:", error);
		  }
		} else {
			showError("Please enter journey name!");
		}
	  };
	  


	$scope.saveJourney = function () {
        if($scope.isEdit){
			$scope.updateJourney();
			return;
		}
		getEventDetails(function(){
		var ob = {
			startEvent : $scope.startEvent,
			endEvent : $scope.endEvent,
			journeyName : $scope.journeyName,
			journeyDescription : $scope.journeyDescription,
			paths : show,
			platform: $scope.pf,
			period: $scope.period
		}
			if($scope.isAvailable!='1')
			{
				var promise = appIceService.saveJourneyData(ob);
			

		promise.then(data => {
			if(data!= undefined){
			$scope.isError=false;
			$scope.reset();
			$("#messageboxsucess").text("Journey Successfully Created")
			$("#messagesucess").show();

			setTimeout(() => {
				$("#messagesucess").hide();
			},3000)
		}else{
			showError("Failed to create journey")
		}
		}).catch(err => {
			 
		})
		}
		else{
			showError("No Journey Available for this Event")
		}
		
	
	});
	}
//Calculate and add percentage in jounrey chart data
function addPercentage(object) {
	obj = object[0];
	obj.percentage = ''
	step = 2;
	for(let i=0; i< obj.children.length;i++){
		let child1 = obj.children[i];
		if(child1!=undefined){
			obj.children[i].percentage = (obj.children[i].value/obj.value)*100
			obj.children[i].percentage = obj.children[i].percentage.toFixed(2);
			obj.children[i].percentage = "(" + obj.children[i].percentage + "%)"
			for(let j=0; j<child1.children.length; j++){
				if(step < 3){
					step = 3;
				}
				let child2 = child1.children[j];
				if(child2!=undefined){
					obj.children[i].children[j].percentage = (obj.children[i].children[j].value/obj.children[i].value)*100
					obj.children[i].children[j].percentage = obj.children[i].children[j].percentage.toFixed(2);
					obj.children[i].children[j].percentage = "(" + obj.children[i].children[j].percentage + "%)";
					for(let k=0; k<child2.children.length; k++){
						if(step < 4){
							step = 4;
						}
						let child3 = child2.children[k];
						if(child3!=undefined){
							obj.children[i].children[j].children[k].percentage = (obj.children[i].children[j].children[k].value/obj.children[i].children[j].value)*100
							obj.children[i].children[j].children[k].percentage = obj.children[i].children[j].children[k].percentage.toFixed(2);
							obj.children[i].children[j].children[k].percentage = "(" + obj.children[i].children[j].children[k].percentage + "%)";
						}
					
					}
				}
			
			}
		}
	
	}

	let final = new Array();
	final.push(obj);

	if(step < 3){
		display(final, '15%')
	}
	else if(step==3){
		display(final, '25%')
	}
	else if(step>3){
		display(final, '100%')
	}
}



function onlyEndEvent(obj) {
	var l;
	for(l=0;l<obj.length;l++)
		checkPresent(obj[l]);
}


function JourneyList(obj){
	journeyList = []
	var i=0;
	for(i=0;i<obj.length;i++){
		if(obj[i].name==$scope.startEvent){
			journeyList.push(obj[i]);
		}
		else{
			queue.push(obj[i]);
			while(queue.length!=0){
				var journey = queue.pop();
				let j=0,len;
				for(j=0;j<journey.children.length;j++){
					if(journey.children[j].name==$scope.startEvent){
						journeyList.push(journey.children[j]);
					}
					else 
						queue.unshift(journey.children[j]);
				}
			}
		}
	}
	return journeyList;
}


function mergePaths(parent,journey){
	var i;
	parent.value = parent.value + journey.value;
	if(parent.children.length!=0 && journey.children.length!=0)
	{
		for(i=0;i<journey.children.length;i++)
		{
			var match = parent.children.find(e => {return e.name === journey.children[i].name;});
			if(match)
				{
					mergePaths(match,journey.children[i]);
				}
			else
				parent.children.push(journey.children[i]);
		}
	}
	if (parent.children.length == 0  && journey.children.length!=0)
	{
		parent.children.push(...journey.children);
	}

}


function getSingleObject(journeyList)
{
	ans = {...journeyList[0]};
	var i;
	for(i=1;i<journeyList.length;i++)
	{	
		mergePaths(ans,journeyList[i]);	
	}	
	
}


function checkPresent(ans)
{
	var i;
	for(i=0;i<ans.children.length;)
	{
		if(ans.children[i].children.length===0 && ans.children[i].name !== $scope.endEvent)
			{
				ans.children.splice(i,1);
			}
		else
		{
			checkPresent(ans.children[i]);
			if(ans.children[i].children.length==0 && ans.children[i].name !== $scope.endEvent)
			{	
				ans.children.splice(i,1);}
			else
			i++;
		}
	}
	return ans;
}
	//To Set cookie data

	function setCookie(data,node,exdays) {
		var d = new Date();
		d.setTime(d.getTime() + (exdays*24*60*60*1000));
		var expires = "expires=" + d.toGMTString();
		document.cookie = data + "=" + node + ";" + expires + ";path=/;secure;";
	}

	//To Get Cookie Data

	function getCookie(data) {
		var name = data + "=";
		var decodedCookie = decodeURIComponent(document.cookie);
		var ca = decodedCookie.split(';');
		for(var i = 0; i < ca.length; i++) {
			var c = ca[i];
			while (c.charAt(0) == ' ') {
				c = c.substring(1);
			}
			if (c.indexOf(name) == 0) {
				return c.substring(name.length, c.length);
			}
		}
		return "";
	}

    //To Check Cookie Data is Present or not

	function checkCookie(data) {
		var eventListData=getCookie(data);
		if (eventListData == "") {
			//Use Cookie Data
			return [];
		} else {
			// Set the Cookie Data
			return JSON.parse(eventListData);
		}
	}


	//Onclick Function for Event Filter

	$scope.selectedSpecificStartEvent=function(stack){
		stack.selected = (stack.selected)? false : true;
		let selectedData = $scope.topGraphEvents.map(function (item) {
     					return {name: item.name, selected: item.selected};
		})
		$scope.startEvent = stack;
	}

	$scope.selectedSpecificEndEvent=function(stack){
		stack.selected = (stack.selected)? false : true;
		let selectedData = $scope.topEndEvents.map(function (item) {
     					return {name: item.name, selected: item.selected};
		})
	
		$scope.endEvent = stack;
	}

	$scope.populateEventAttributes = function (eventname) {
		if ($('#swiu1').text() == 'Select Attribute') {

		} else {
			$('#swiu1').text('Select Attribute')
		}

		$scope.selectedEvent = eventname;
		$scope.eventList.forEach(function (item) {
			if (item.event == eventname) {
				$scope.eventAttributeList = item.list;
				$scope.eventAttributeList = _.sortBy($scope.eventAttributeList, 'name');
				if ($scope.eventAttributeList.length == 0) {
					$('#noAttrs').show();
				} else {
					$('#noAttrs').hide();
				}

				// hide city attributes
				$scope.selectedCEventAttribute = "Select Attribute";
				$scope.isCEventAttribute = false;
				$('#swiu2').text("Select Attribute");
			}
		});

		if(attributeEventChart!== undefined){
				attributeEventChart.destroy();
			}
		}


		$scope.showAttributeStats = function (attValue) {
			if(attributeEventChart!== undefined){
				attributeEventChart.destroy();
			}

			$('#swiu1').text(attValue)
			$scope.selectedEventAttribute = attValue;
			var promise = appIceService.getEventAttributeStats($scope.selectedEvent, $scope.selectedEventAttribute);
			promise.then(function (stats) {
				semusiCustomEvents.customEvents = stats;
				if (stats.length > 0) {
					createBarChartData(false);
				}

				if (attValue == 'City' && $scope.cList.length > 0) {
					$scope.cList = _.sortBy($scope.cList, 'name');
					$scope.isCEventAttribute = true;
				}
				else {
					$scope.selectedCEventAttribute = "Select Attribute";
					$scope.isCEventAttribute = false;
					$('#swiu2').text("Select Attribute")
				}
			});
		}
        //Display attribute stats for jounrey data
		$scope.showCAttributeStats = function (attValue) {
			if(attributeEventChart!== undefined){
						attributeEventChart.destroy();
					}

					$('#swiu2').text(attValue)
					$scope.selectedCEventAttribute = attValue;
					var promise = appIceService.getEventAttributeStats($scope.selectedEventAttribute, $scope.selectedCEventAttribute);
					promise.then(function (stats) {
						semusiCustomEvents.customEvents = stats;
						if (stats.length > 0) {
							createBarChartData(false);
						}
					});
				}

				init();
			});
