var serverURL = 'https://10.133.38.117/services/CoBrowse';
var dashboardRest = serverURL + '/v1/dashboard';
var auditRest = serverURL + '/v1/audit';
var auditEventRest = serverURL + '/v1/auditevent';
var RefreshRest = '';
var acsDashboardApp = angular.module('acsDashboardApp', ['ui.bootstrap', /* 'ngAnimate', 'ngTouch' */, 'ui.grid',  'ui.grid.resizeColumns' , 'ui.grid.selection','ui.grid.exporter','ui.grid.pagination']);


acsDashboardApp.controller('SessionReportCtrl', ['$scope', '$http','uiGridConstants',function ($scope, $http,uiGridConstants) {

$scope.calendar = {
    opened: {},
    dateFormat: 'MM/dd/yyyy',
    dateOptions: {},
    open: function($event, which) {
        $event.preventDefault();
        $event.stopPropagation();
        $scope.calendar.opened[which] = true;
    } 
};
 $scope.alerts = [];
 $scope.closeAlert = function(index) {
    $scope.alerts.splice(index, 1);
  };

  $scope.sttime = new Date();
  $scope.etime = new Date();
  $scope.hstep = 1;
  $scope.mstep = 15;

 

  $scope.changed = function () {
    console.log('Time changed to: ' + this.sttime.toTimeString());
  };


 var paginationOptions = {
    pageNumber: 1,
    pageSize: 50,
    sort: null
  };
  $scope.stateOptions = [{
        value: 'all',
        label: 'All'
    }, {
        value: 'open',
        label: 'Open'
    }, {
        value: 'closed',
        label: 'Closed'
    }];
  $scope.sessionState="";
  $scope.selectedState = $scope.stateOptions[1];
  // Grid options for session summary report
  $scope.gridSessionOptions = {
    enableSorting: true,
    columnDefs: [
      { name:'Session Key',field: 'passPhrase', cellTooltip: true,cellTemplate: '<div><a ng-click="grid.appScope.openAuditTrail(row)">{{row.entity[col.field]}}</div>' },
      { name:'Customer Name',field: 'customerName', cellTooltip: true },
	  { name:'Agent Name',field: 'agentName', cellTooltip: true },
	  { name:'Session Status',field: 'sessionStatus', cellTooltip: true },
      { name:'Duration (Seconds)',field: 'sessionDuration', cellTooltip: true },
      { name:'Start',field: 'sessionStartedAt', cellTooltip: true },
	  { name:'Stop',field: 'sessionStoppedAt', cellTooltip: true },
	  { name:'Initiated By',field: 'sessionInitiatedBy', cellTooltip: true },
	  { name:'Ended By',field: 'sessionEndedBy', cellTooltip: true },
	  { name:'Events',field: 'passPhrase', cellTooltip: true,cellTemplate: '<div><a ng-click="grid.appScope.openAuditEvent(row)">Events</div>' }
    ],
	enablePaginationControls: true,
    paginationPageSizes: [50, 100, 150],
    paginationPageSize: 50,
  /*   useExternalPagination: true,
    useExternalSorting: true, */
	jqueryUITheme: true,
 	enableColumnResizing: true,
 	enableFiltering: false, 
    enableGridMenu: true,
    enableSelectAll: true,
	rowHeight: 40, 
    exporterCsvFilename: 'SessionSummary.csv',
    exporterPdfDefaultStyle: {fontSize: 9},
    exporterPdfTableStyle: {margin: [30, 30, 30, 30]},
    exporterPdfTableHeaderStyle: {fontSize: 10, bold: true, italics: true, color: 'black'},
    exporterPdfHeader: { text: "Session Summary", style: 'headerStyle' },
    exporterPdfFooter: function(currentPage, pageCount) {
      return setFooter(currentPage, pageCount);
    },
    exporterPdfCustomFormatter: function ( docDefinition ) {
      docDefinition.styles.headerStyle = { fontSize: 22, bold: true }; 
      docDefinition.styles.footerStyle = { fontSize: 10, bold: true }; 
      return docDefinition;
    },
	exporterSuppressColumns: [ 'Events' ],

    exporterPdfOrientation: 'portrait',
    exporterPdfPageSize: 'LETTER',
    exporterPdfMaxGridWidth: 400,
    exporterCsvLinkElement: angular.element(document.querySelectorAll(".custom-csv-link-location")),
    onRegisterApi: function(gridApi){ 
      $scope.gridSessionApi = gridApi;
    }
	}
	
   //Grid options for agent summary report
	 $scope.gridAgentSessionOptions = {
    enableSorting: true,
    columnDefs: [
      { name:'Agent Name',field: 'agentName', cellTooltip: true },
      { name:'Session Key',field: 'passPhrase', cellTooltip: true },
	  { name:'Customer Name',field: 'customerName', cellTooltip: true },
	  { name:'Session Status',field: 'sessionStatus', cellTooltip: true },
	  { name:'Agent Device',field: 'getBrowserNameVersion()', cellTooltip: true },
      { name:'Duration (Seconds)',field: 'sessionDuration', cellTooltip: true },
      { name:'Start',field: 'sessionStartedAt', cellTooltip: true },
	  { name:'Stop',field: 'sessionStoppedAt', cellTooltip: true },
	  { name:'Agent Last Activity Time',field: 'agentLastActivityTime', cellTooltip: true },
	  { name:'Initiated By',field: 'sessionInitiatedBy', cellTooltip: true },
	  { name:'Ended By',field: 'sessionEndedBy', cellTooltip: true }
    ],
	enablePaginationControls: true,
    paginationPageSizes: [50, 100, 150],
    paginationPageSize: 50,
	jqueryUITheme: true,
	enableColumnResizing: true,
	enableFiltering: false, 
    enableGridMenu: true,
    enableSelectAll: true,
	rowHeight: 40,
    exporterCsvFilename: 'AgentSummary.csv',
    exporterPdfDefaultStyle: {fontSize: 9},
    exporterPdfTableStyle: {margin: [30, 30, 30, 30]},
    exporterPdfTableHeaderStyle: {fontSize: 10, bold: true, italics: true, color: 'black'},
    exporterPdfHeader: { text: "Agent Summary", style: 'headerStyle' },
    exporterPdfFooter: function(currentPage, pageCount) {
      return setFooter(currentPage, pageCount);
    },
    exporterPdfCustomFormatter: function ( docDefinition ) {
      docDefinition.styles.headerStyle = { fontSize: 22, bold: true }; 
      docDefinition.styles.footerStyle = { fontSize: 10, bold: true }; 
      return docDefinition;
    },
    exporterPdfOrientation: 'portrait',
    exporterPdfPageSize: 'LETTER',
    exporterPdfMaxGridWidth: 400,
    exporterCsvLinkElement: angular.element(document.querySelectorAll(".custom-csv-link-location")),
    onRegisterApi: function(gridApi){ 
      $scope.gridAgentApi = gridApi;
    }
	}
	
	//Grid options for customer summary report
	 $scope.gridCustomerSessionOptions = {
    enableSorting: true,
    columnDefs: [
      { name:'Customer  Name',field: 'customerName', cellTooltip: true },
      { name:'Session Key',field: 'passPhrase', cellTooltip: true },
	  { name:'Agent Name',field: 'agentName', cellTooltip: true },
	  { name:'Session Status',field: 'sessionStatus', cellTooltip: true },
	  { name:'Customer Device',field: 'getCustBrowserNameVersion()', cellTooltip: true },
      { name:'Duration (Seconds)',field: 'sessionDuration', cellTooltip: true },
      { name:'Start',field: 'sessionStartedAt', cellTooltip: true },
	  { name:'Stop',field: 'sessionStoppedAt', cellTooltip: true },
	  { name:'Customer Last Activity Time',field: 'customerLastActivitytime', cellTooltip: true },	  
	  { name:'Initiated By',field: 'sessionInitiatedBy', cellTooltip: true },
	  { name:'Ended By',field: 'sessionEndedBy', cellTooltip: true }
    ],
	enablePaginationControls: true,
    paginationPageSizes: [50, 100, 150],
    paginationPageSize: 50,
	rowHeight: 40,
	jqueryUITheme: true,
	enableColumnResizing: true,
	enableFiltering: false, 
    enableGridMenu: true,
    enableSelectAll: true,
    exporterCsvFilename: 'CustomerSummary.csv',
    exporterPdfDefaultStyle: {fontSize: 9},
    exporterPdfTableStyle: {margin: [30, 30, 30, 30]},
    exporterPdfTableHeaderStyle: {fontSize: 10, bold: true, italics: true, color: 'black'},
    exporterPdfHeader: { text: "Customer Summary", style: 'headerStyle' },
	exporterPdfFooter: function(currentPage, pageCount) {
		return setFooter(currentPage, pageCount);    
    },
    exporterPdfCustomFormatter: function ( docDefinition ) {
      docDefinition.styles.headerStyle = { fontSize: 22, bold: true }; 
      docDefinition.styles.footerStyle = { fontSize: 10, bold: true }; 
      return docDefinition;
    },
    exporterPdfOrientation: 'portrait',
    exporterPdfPageSize: 'LETTER',
    exporterPdfMaxGridWidth: 400,
    exporterCsvLinkElement: angular.element(document.querySelectorAll(".custom-csv-link-location")),
    onRegisterApi: function(gridApi){ 
      $scope.gridCustomerApi = gridApi;
    }
	}
	
	 //Grid options for audit actions 
	 $scope.gridAuditActionsOptions = {
    enableSorting: true,
    columnDefs: [
      { name:'Action By',field: 'auditActionBy', cellTooltip: true },
      { name:'Action',field: 'auditActionreason', cellTooltip: true },
	  { name:'Timestamp',field: 'auditStarttime', cellTooltip: true },
	  { name:'URL',field: 'auditNote', cellTooltip: true /* , cellTemplate:'<div><a href="{{row.entity[col.field]}}" target="_blank">{{row.entity[col.field]}}</a></div>' */ }
    ],
	enablePaginationControls: true,
    paginationPageSizes: [50, 100, 150],
    paginationPageSize: 50,
	rowHeight: 40,
	jqueryUITheme: true,
	enableColumnResizing: true,
	enableFiltering: false, 
    enableGridMenu: true,
    enableSelectAll: true,
    exporterCsvFilename: 'Audit_action_Report.csv',
    exporterPdfDefaultStyle: {fontSize: 9},
    exporterPdfTableStyle: {margin: [30, 30, 30, 30]},
    exporterPdfTableHeaderStyle: {fontSize: 10, bold: true, italics: true, color: 'black'},
    exporterPdfHeader: { text: 'Audit Actions ', style: 'headerStyle' },
	exporterPdfFooter: function(currentPage, pageCount) {
      return setFooter(currentPage, pageCount);
    },
    exporterPdfCustomFormatter: function ( docDefinition ) {
      docDefinition.styles.headerStyle = { fontSize: 22, bold: true }; 
      docDefinition.styles.footerStyle = { fontSize: 10, bold: true }; 
      return docDefinition;
    },
    exporterPdfOrientation: 'portrait',
    exporterPdfPageSize: 'LETTER',
    exporterPdfMaxGridWidth: 400,
    exporterCsvLinkElement: angular.element(document.querySelectorAll(".custom-csv-link-location")),
    onRegisterApi: function(gridApi){ 
      $scope.gridAuditApi = gridApi;
    }
	}

	//Grid options for audit events
	 $scope.gridAuditEventsOptions = {
    enableSorting: true,
    columnDefs: [
      { name:'Event Type',field: 'auditEventType', cellTooltip: true },
      { name:'Event Name',field: 'auditEventName', cellTooltip: true },
	  { name:'Element ID',field: 'auditElementDisplayName', cellTooltip: true },
	  { name:'Element Value',field: 'auditElementValue', cellTooltip: true },
	  { name:'CSS Selector',field: 'auditCSSSelector', cellTooltip: true },
	  { name:'Event By',field: 'auditLogBy', cellTooltip: true },
	  { name:'Timestamp',field: 'auditTime', cellTooltip: true },
    ],
	enablePaginationControls: true,
    paginationPageSizes: [50, 100, 150],
    paginationPageSize: 50,
	rowHeight: 40,
	jqueryUITheme: true,
	enableColumnResizing: true,
	enableFiltering: false, 
    enableGridMenu: true,
    enableSelectAll: true,
    exporterCsvFilename: 'Audit_event_Report.csv',
    exporterPdfDefaultStyle: {fontSize: 9},
    exporterPdfTableStyle: {margin: [30, 30, 30, 30]},
    exporterPdfTableHeaderStyle: {fontSize: 10, bold: true, italics: true, color: 'black'},
    exporterPdfHeader: { text: 'Audit Events' , style: 'headerStyle' },
	exporterPdfFooter: function(currentPage, pageCount) {
      return setFooter(currentPage, pageCount);
    },
    exporterPdfCustomFormatter: function ( docDefinition ) {
      docDefinition.styles.headerStyle = { fontSize: 22, bold: true }; 
      docDefinition.styles.footerStyle = { fontSize: 10, bold: true }; 
      return docDefinition;
    },
    exporterPdfOrientation: 'portrait',
    exporterPdfPageSize: 'LETTER',
    exporterPdfMaxGridWidth: 400,
    exporterCsvLinkElement: angular.element(document.querySelectorAll(".custom-csv-link-location")),
    onRegisterApi: function(gridApi){ 
      $scope.gridAuditEventApi = gridApi;
    }
	}
	
	function preprocessDashboardData(data){
		for(var i=0; i < data.length; i++){
			var customerdevice = data[i].customerDevice;
			if(customerdevice){						
				data[i].customerDevice = setDevice(customerdevice);			
			}
			var agentdevice = data[i].agentDevice;
			if(agentdevice){							
				data[i].agentDevice = setDevice(agentdevice);			
			}
		}
		return data;
	}

	function setDevice(device)
	{
		var parser = new UAParser();
		parser.setUA(device);
		return parser.getResult();
	}
	
	// Changes for Error Modal 
	function showErrorModal(info){
    $('#denyModal').modal('show');
    $('#denyModalMsg').text(info.message);
    $('#denyModalTitle').text(info.title).removeClass('label-success').addClass('label-danger');
	$('#denyModal').modal({
    backdrop: 'static',
    keyboard: false 
	})
	};
	
	// To set export footer
	function setFooter(currentPage,pageCount)
	{
	  var today = new Date();
      return {
        columns: [{
          alignment: 'left',
          text: ['Page ',{
              text: currentPage.toString(),
              italics: true
            },
            ' of ', {
              text: pageCount.toString(),
              italics: true
            }
          ]
        }, {
          alignment: 'right',
          text: [{
            text: today.toString(),
            italics: true
          }]
        }],
        style: 'footerStyle'
      };
	}
	
	function getDashboardData(){		
		$('#denyModal').hide();		
		$http.get(RefreshRest)
			.success(function(data) {
				 if(data.statusCode == '500')
				 {
					displayErrorModal(data.errorCode,data.errorMessage);
                }
				$scope.gridSessionOptions.data = preprocessDashboardData(data.acsResponse);
				$scope.orderProp = 'passPhrase';
				$scope.ViewDisplay = 'sessions';
				$scope.gridSessionOptions.enableFiltering = false;
				if(angular.isDefined($scope.gridSessionApi))
					$scope.gridSessionApi.core.notifyDataChange(uiGridConstants.dataChange.COLUMN ); 
				UpdateFilterText($scope.gridSessionOptions.enableFiltering);
			})
			.error(function(data) {
				showErrorModal({					    
						title: "Unable to fetch session data.",
						message: 'Please contact your administrator.'
						});
				console.log(data);
			});
	}
	
    //$scope.orderProp = 'passPhrase';
	$scope.ViewDisplay = 'home';
	$scope.FilterText = "Enable";
	//getDashboardData();
	
	// To fetch agent session data
	function processAgentSessionData(data){
		var agentdata  = [];
        for(var i=0; i < data.length; i++){			
				if(data[i].agentDevice){							
				data[i].agentDevice = setDevice(data[i].agentDevice);			
				}		
				agentdata.push(data[i]);
		}
		
		return agentdata;		
	}
	
	// To fetch all agents data 
	$scope.openAllAgentData = function(){
		$('#denyModal').hide();
		$http.get(RefreshRest)
			.success(function(data) {
				 if(data.statusCode == '500')
				 {
					displayErrorModal(data.errorCode,data.errorMessage);
                }
				$scope.AllAgentSessions = processAgentSessionData(data.acsResponse);
				$scope.ViewDisplay = 'allagent';
				
				angular.forEach($scope.AllAgentSessions, function(row){
					row.getBrowserNameVersion = function(){
					return this.agentDevice.browser.name + ' ' + this.agentDevice.browser.version; 
				} 
				});
				$scope.gridAgentSessionOptions.data = $scope.AllAgentSessions;
				$scope.gridAgentSessionOptions.enableFiltering = false;
				if(angular.isDefined($scope.gridAgentApi))
					$scope.gridAgentApi.core.notifyDataChange( uiGridConstants.dataChange.COLUMN );
				UpdateFilterText($scope.gridAgentSessionOptions.enableFiltering);
			})
			.error(function(data) {
				showErrorModal({					    
						title: "Unable to fetch agent data.",
						message: 'Please contact your administrator.'
						});
				console.log(data);
			});
	
	}

	// To fetch customer session data
	function processCustomerSessionData(data){
		var custdata  = [];
        for(var i=0; i < data.length; i++){					
			    if(data[i].customerDevice){							
					data[i].customerDevice = setDevice(data[i].customerDevice);			
				}	
				custdata.push(data[i]);
		}
		return custdata;		
	}
	
	$scope.openAllCustomerData = function(){
		$('#denyModal').hide();
		$http.get(RefreshRest)
			.success(function(data) {
				if(data.statusCode == '500')
				{
					displayErrorModal(data.errorCode,data.errorMessage);
                }
				$scope.AllCustomerSessions = processCustomerSessionData(data.acsResponse);
				$scope.orderProp = 'customerName';
				$scope.ViewDisplay = 'allcustomer';
				angular.forEach($scope.AllCustomerSessions, function(row){
					row.getCustBrowserNameVersion = function(){
					return this.customerDevice.browser.name + ' ' + this.customerDevice.browser.version; 
				} 
				});
				$scope.gridCustomerSessionOptions.data = $scope.AllCustomerSessions;
				$scope.gridCustomerSessionOptions.enableFiltering = false;
				if(angular.isDefined($scope.gridCustomerApi))
					$scope.gridCustomerApi.core.notifyDataChange( uiGridConstants.dataChange.COLUMN );
				UpdateFilterText($scope.gridCustomerSessionOptions.enableFiltering);
				})
			.error(function(data) {
				showErrorModal({					    
						title: "Unable to fetch customer data.",
						message: 'Please contact your administrator.'
						});
				console.log(data);
			});
	
	}
	
	$scope.openAuditTrail = function(row) {	      
		$('#denyModal').hide();	
		$http.get(auditRest + '?sessionkey=' + row.entity.passPhrase)
			.success(function(data) {
				 if(data.statusCode == '500')
				 {
					displayErrorModal(data.errorCode,data.errorMessage);
                }
				$scope.gridAuditActionsOptions.data = data.acsResponse;
				$scope.PassPhrase = row.entity.passPhrase;
				$scope.ViewDisplay = 'audit';		
				$scope.gridAuditActionsOptions.enableFiltering = false;
				if(angular.isDefined($scope.gridAuditApi))
					$scope.gridAuditApi.core.notifyDataChange( uiGridConstants.dataChange.COLUMN );
				UpdateFilterText($scope.gridAuditActionsOptions.enableFiltering);
			})
			.error(function(data) {
				showErrorModal({					    
						title: "Unable to fetch audit actions.",
						message: 'Please contact your administrator.'
						});
				console.log(data);
			});
	};
	
	$scope.openAuditEvent = function(row) {
		$('#denyModal').hide();
		$http.get(auditEventRest + '?sessionkey=' + row.entity.passPhrase)
			.success(function(data) {
				 if(data.statusCode == '500')
				 {
					displayErrorModal(data.errorCode,data.errorMessage);
                }
					$scope.gridAuditEventsOptions.data = data.acsResponse;
				$scope.PassPhrase = row.entity.passPhrase;
				$scope.ViewDisplay = 'auditevent';
				$scope.gridAuditEventsOptions.enableFiltering = false;
				if(angular.isDefined($scope.gridAuditEventApi))
					$scope.gridAuditEventApi.core.notifyDataChange( uiGridConstants.dataChange.COLUMN );
				UpdateFilterText($scope.gridAuditEventsOptions.enableFiltering);
			})
			.error(function(data) {
					showErrorModal({					    
						title: "Unable to fetch audit events.",
						message: 'Please contact your administrator.'
						});
				console.log(data);
			});
			
	};
	
	$scope.showSessionsDashboard = function(viewType,bIsRefresh) {	  
		$scope.ViewDisplay = viewType;

		if(bIsRefresh)
			getDashboardData();			
		if ($scope.ViewDisplay == 'sessions' && bIsRefresh == false)  {
					$scope.gridSessionOptions.enableFiltering = false;
					$scope.gridSessionApi.core.notifyDataChange( uiGridConstants.dataChange.COLUMN );
					UpdateFilterText($scope.gridSessionOptions.enableFiltering);
					}
	};

	$scope.toggleFiltering = function(){
			if ($scope.ViewDisplay == 'audit') {
					$scope.gridAuditActionsOptions.enableFiltering = !$scope.gridAuditActionsOptions.enableFiltering;
					$scope.gridAuditApi.core.notifyDataChange( uiGridConstants.dataChange.COLUMN );
					UpdateFilterText($scope.gridAuditActionsOptions.enableFiltering);
			} else if ($scope.ViewDisplay == 'sessions')  {
					$scope.gridSessionOptions.enableFiltering = !$scope.gridSessionOptions.enableFiltering;
					$scope.gridSessionApi.core.notifyDataChange( uiGridConstants.dataChange.COLUMN );
					UpdateFilterText($scope.gridSessionOptions.enableFiltering);
			} else if ($scope.ViewDisplay == 'allagent')  {
					$scope.gridAgentSessionOptions.enableFiltering = !$scope.gridAgentSessionOptions.enableFiltering;
					$scope.gridAgentApi.core.notifyDataChange( uiGridConstants.dataChange.COLUMN );
					UpdateFilterText($scope.gridAgentSessionOptions.enableFiltering);
			}  else if ($scope.ViewDisplay == 'allcustomer')  {
					$scope.gridCustomerSessionOptions.enableFiltering = !$scope.gridCustomerSessionOptions.enableFiltering;
					$scope.gridCustomerApi.core.notifyDataChange( uiGridConstants.dataChange.COLUMN );
					UpdateFilterText($scope.gridCustomerSessionOptions.enableFiltering);
			}	else if ($scope.ViewDisplay == 'auditevent')  {
					$scope.gridAuditEventsOptions.enableFiltering = !$scope.gridAuditEventsOptions.enableFiltering;
					$scope.gridAuditEventApi.core.notifyDataChange( uiGridConstants.dataChange.COLUMN );
					UpdateFilterText($scope.gridAuditEventsOptions.enableFiltering);
			}
		}
		
	function UpdateFilterText(bFilterText){
		if(bFilterText)
			$scope.FilterText = "Clear";
		else
			$scope.FilterText = "Enable";
	}
	
	$scope.resetDashboard = function(){
		$scope.ViewDisplay = 'home';
	}
	
	$scope.showFilterForm = function(viewType) {	  
		$scope.ViewDisplay = viewType;
		$scope.sessionState = "";
		ResetGridData();
		if($scope.ViewDisplay == 'sessionfilter')
			$scope.FilterHeader = "Search data for session summary report";
		else if($scope.ViewDisplay == 'customerfilter')
			$scope.FilterHeader = "Search data for customer summary report";
		else if($scope.ViewDisplay == 'agentfilter')
			$scope.FilterHeader = "Search data for agent summary report";
	};

	//Show Dashboard
$scope.showDashboard = function(){	
        var startTime="",endTime="",agtName="",custName="";
		if(this.selectedState)
			$scope.sessionState = this.selectedState.value;
			
		if(!this.starttime){
			$scope.alerts.push({type: 'danger', msg: 'Invalid Start Date!'});
			return;
		}
		if(!this.endtime){
			$scope.alerts.push({type: 'danger', msg: 'Invalid End Date!'});
			return;
		}	
			
		$scope.starttime  = this.starttime;	
		$scope.endtime  = this.endtime;	
		//$scope.starttime  = new Date(this.starttime.toLocaleDateString());	
		//$scope.endtime  = new Date(this.endtime.toLocaleDateString());	
		if(!this.sttime){
			$scope.alerts.push({type: 'danger', msg: 'Invalid Start time!'});
			return;
		}
		if(!this.etime){
			$scope.alerts.push({type: 'danger', msg: 'Invalid End time!'});
			return;
		}
		
		$scope.starttime.setHours(this.sttime.getHours());
		$scope.starttime.setMinutes(this.sttime.getMinutes());
		$scope.starttime.setSeconds('0');
		
		$scope.endtime.setHours(this.etime.getHours());
		$scope.endtime.setMinutes(this.etime.getMinutes());
		$scope.endtime.setSeconds('0');
		
		
		$scope.agentname = this.agentname;
		$scope.customername =  this.customername;
		
		if($scope.starttime){	
			startTime = $scope.starttime.toISOString();
		}
		if($scope.endtime){	
			endTime = $scope.endtime.toISOString();
		}
		
		if(startTime > endTime){
			$scope.alerts.push({type: 'danger', msg: 'Start time cannot be greater then end time!'});
			return;
		}
		
		
		if($scope.agentname){	
			agtName = $scope.agentname;
		}
		if($scope.customername){	
			custName = $scope.customername;
		}
	if($scope.ViewDisplay == 'sessionfilter'){

		RefreshRest = dashboardRest + '?type=session'+'&state=' + $scope.sessionState +'&starttime=' + startTime + '&endtime=' + endTime +'&customer=' + custName + '&agent=' + agtName;
		$scope.showSessionsDashboard('sessions',true);
	}
	else if($scope.ViewDisplay == 'customerfilter'){			
		RefreshRest = dashboardRest + '?type=customer'+'&state=' + $scope.sessionState +'&starttime=' + startTime + '&endtime=' + endTime +'&customer=' + custName + '&agent=' + agtName;
		$scope.openAllCustomerData();
	}
	else if($scope.ViewDisplay == 'agentfilter'){
		RefreshRest = dashboardRest + '?type=agent'+'&state=' + $scope.sessionState +'&starttime=' + startTime + '&endtime=' + endTime +'&customer=' + custName + '&agent=' + agtName;
		$scope.openAllAgentData();
	}
}
// Reset Grid data
function ResetGridData(bFilterText){
	$scope.gridSessionOptions.data = '';
	$scope.gridAuditEventsOptions.data = '';
	$scope.gridAuditActionsOptions.data = '';
	$scope.gridCustomerSessionOptions.data='';
	$scope.gridAgentSessionOptions.data='';
	}
// Displays Error Modal
	function displayErrorModal(errorCode,errorMessage)
	{
		var actionMessage = 'Please contact your administrator.';
		if(errorCode == '1072')
			actionMessage = 'Please refine your search criteria.';
						
		showErrorModal({					    
					title: errorMessage,
					message: actionMessage
					});
	}
	//Refresh Dashboard
$scope.refreshDashboard = function(){	
	if($scope.ViewDisplay == 'sessions'){
		$scope.showSessionsDashboard('sessions',true);
	}
	else if($scope.ViewDisplay == 'allcustomer'){
		$scope.openAllCustomerData();
	}
	else if($scope.ViewDisplay == 'allagent'){
		$scope.openAllAgentData();
	}
}

// Date Controls
$scope.today = function() {
    $scope.starttime = new Date();
	$scope.endtime = new Date();
  };
  $scope.today();

}]);