define("ticketChartsControllers", ["SHARED/jquery", "SHARED/juzu-ajax"], function ($, jz) {
    var ticketChartsCtrl = function ($scope, $q, $timeout, $http, $filter) {
        var ticketChartsContainer = $('#ticketCharts');
        var deferred = $q.defer();
		$scope.internal=false;
		 $scope.allSpaces = {
			groupId: "all",
			name: "All",
			internal: false
		};
        $scope.selectedSpace = $scope.allSpaces;
		$scope.currentSpace="";
        $scope.spaces=[];
        $scope.showGraphs = false;
        $scope.showSpaces = false;
        $scope.showSpaceCharts = true;
        $scope.showAllCustomerCharts = false;
        $scope.assignees=[];
		$scope.showGetAll=false;
		$scope.internalFilter={internal:false};
		$scope.spacesType="customer";

        $scope.customerSatisfactionPrc = null;
        $scope.firstTimeResponceAverage = null;
        $scope.timeToResolutionAverage = null;

		 $scope.openTab = function (tabName) {
             if(tabName=="trends"){
				 $("#timerangPicker").css("display", "block");			 
			 }else{
				 $("#timerangPicker").css("display", "none");	
			 }
            $("#charts").css("display", "none");
            $("#trends").css("display", "none");

            $("#chartsTab").removeClass("active");
            $("#trendsTab").removeClass("active");

            $("#" + tabName).css("display", "block");
            $("#" + tabName + "Tab").addClass("active");
        }

		$scope.timeMetricslinePeriod="weekly";
		$scope.openVSClosedLinePeriod="weekly";
		$scope.logbyStatusChartPeriod="weekly";
		$scope.satisfactionLinePeriod="weekly";
		
		
		
		
		$scope.setSpacesType = function () {
			if($scope.spacesType=="customer"){
				$scope.internal=false
				$scope.allSpaces.internal=false;
				$scope.selectedSpace = $scope.allSpaces;
				$scope.internalFilter={internal:false};
			}else if($scope.spacesType=="internal"){
				$scope.internal=true
				$scope.allSpaces.internal=true;
				$scope.selectedSpace = $scope.allSpaces;
				$scope.internalFilter={internal:true};
			}else{
				$scope.internalFilter={};
			}
			$scope.loadData();
		}

		
	$scope.getAssigneeByUserName = function(username){
      for (var i = 0; i < $scope.assignees.length; i++) {
        if ($scope.assignees[i].userName === username) {
           return $scope.assignees[i];
        }
      }
      return $scope.i18n.empty;
    }
		
		$scope.startDate=0;
		$scope.endDate=(new Date()).getTime();


                  var lessThan3Day = new Date();
                  lessThan3Day.setDate(lessThan3Day.getDate() - 2);
                  $scope.customTemplates = [
                    {
                      name: 'Last 3 Days',
                      dateStart: lessThan3Day,
                      dateEnd: new Date(),
                    }
                  ];
                  $scope.calendarModel = { selectedTemplate: 'Last 3 Days' };
                  $scope.pickerModel = { selectedTemplate: 'Last 3 Days' };
                  $scope.advancedModel = { selectedTemplate: 'Last 3 Days' };
                  $scope.serviceModel = { selectedTemplate: 'Last 3 Days' };
                  $scope.selectedDate = {};
                  $scope.selectedDates = [];
                  $scope.selectDateRange = function ($event, autoConfirm) {
                    $mdDateRangePicker.show({
                      model: $scope.serviceModel,
                      autoConfirm: autoConfirm,
                      targetEvent: $event,
                      customTemplates: $scope.customTemplates,
                    }).then(function (result) {
                      Object.assign($scope.serviceModel, result);
                    }).catch(function () {
                      console.log('Cancelled');
                    });
                  }
                  $scope.format = function (dateStart, dateEnd, template, templateName) {
                    return template ? 'Range of ' + (templateName || template) : (dateStart && dateEnd && (dateStart.toLocaleDateString() + ' to ' + dateEnd.toLocaleDateString()));
                  }
                  $scope.isDisabledDate = function (d) {
                    return d.getDay() === 0 || d.getDay() === 6;
                  }


        $scope.setRange = function (dates) {
			$scope.showGetAll=true;
			$scope.startDate=dates[0].getTime();
			$scope.endDate=dates[dates.length-1].getTime();
			$scope.loadData();
        }
		
        $scope.setDates = function (dates) {
			$scope.showGetAll=true;
            var date = new Date(); // Now
        	$scope.startDate=date.setDate(date.getDate() - 30);
        	$scope.endDate=(new Date()).getTime();
			var dateStart = new Date();
			var dateEnd = new Date();
			dateStart.setTime($scope.startDate);
			dateEnd.setTime($scope.endDate);
			$scope.pickerModel = {
               selectedTemplateName:$scope.getDateText(),
			   dateEnd: dateEnd,
			   dateStart: dateStart,
			   selectedTemplate: false
            };
			$scope.loadData();
        }

    $scope.getDisplayName = function(username){
      for (var i = 0; i < $scope.assignees.length; i++) {
        if ($scope.assignees[i].userName === username) {
           return $scope.assignees[i].displayName;
        }
      }
      return $scope.i18n.empty;
    }
	
	/* ========================= Begin Pie Charts ======================================== */	
	
	                $scope.getTicketsBySpaceChartData = function () {
                    $http({
                        method: 'GET',
                        url: ticketChartsContainer.jzURL('TicketChartsController.getTicketsGroupdBySpace') + "&startDate=00&endDate=0&internal="+$scope.internal
                    }).then(function successCallback(data) {
                        $scope.ticketsNumberBySpaceList = data.data;


                              var ticketsArray = [];
                                for(var i = 0; i < $scope.ticketsNumberBySpaceList.length; i++) {
                                     var obj = $scope.ticketsNumberBySpaceList[i];
                                              ticketsArray.push({ c: [{v: obj.spaceId, f:  obj.space+" "+obj.ticketNumber}, {v: obj.ticketNumber}]});
                                         }
                            $scope.pieChartBySpaceObject.data = {"cols": [
                                {id: "t", label: "Space", type: "string"},
                                {id: "s", label: "Tickets", type: "number"}
                            ], "rows":  ticketsArray
                            };

                        deferred.resolve(data);
                    }, function errorCallback(data) {
                        $scope.setResultMessage($scope.i18n.defaultError, "error");
                    });
                }


                $scope.getTicketsByOwnerChartData = function () {
                    $http({
                        method: 'GET',
                        url: ticketChartsContainer.jzURL('TicketChartsController.getTicketsGroupdByOwner')+ "&spaceId=" + $scope.currentSpace + "&startDate=0&endDate=0&internal="+$scope.internal
                    }).then(function successCallback(data) {
                        $scope.ticketsNumberByOwnerList = data.data;

                              var ticketsArray = [];
                                for(var i = 0; i < $scope.ticketsNumberByOwnerList.length; i++) {
                                     var obj = $scope.ticketsNumberByOwnerList[i];
                                              ticketsArray.push({ c: [{v: obj.owner}, {v: obj.ticketNumber}]});
                                         }
                            $scope.pieChartByOwnerObject.data = {"cols": [
                                {id: "t", label: "Owner", type: "string"},
                                {id: "s", label: "Tickets", type: "number"}
                            ], "rows":  ticketsArray
                            };

                        deferred.resolve(data);
                    }, function errorCallback(data) {
                        $scope.setResultMessage($scope.i18n.defaultError, "error");
                    });
                }

                $scope.getTicketsByStatusChartData = function () {
                    $http({
                        method: 'GET',
                        url: ticketChartsContainer.jzURL('TicketChartsController.getTicketsGroupdByStatus')+ "&spaceId=" + $scope.currentSpace + "&startDate=0&endDate=0&internal="+$scope.internal
                    }).then(function successCallback(data) {
                        $scope.ticketsNumberByStatusList = data.data;

                              var ticketsArray = [];
                                for(var i = 0; i < $scope.ticketsNumberByStatusList.length; i++) {
                                     var obj = $scope.ticketsNumberByStatusList[i];
                                              ticketsArray.push({ c: [{v: obj.status, f:  $scope.i18n[obj.status]}, {v: obj.ticketNumber}]});
                                         }
                            $scope.pieChartByStatusObject.data = {"cols": [
                                {id: "t", label: "Status", type: "string"},
                                {id: "s", label: "Tickets", type: "number"}
                            ], "rows":  ticketsArray
                            };

                        deferred.resolve(data);
                    }, function errorCallback(data) {
                        $scope.setResultMessage($scope.i18n.defaultError, "error");
                    });
                }

	
	              $scope.getOpenVsClosedTickets = function () {
                    $http({
                        method: 'GET',
                        url: ticketChartsContainer.jzURL('TicketChartsController.getOpenVsClosedTickets')+ "&spaceId=" + $scope.currentSpace + "&startDate=0&endDate=0&internal="+$scope.internal
                    }).then(function successCallback(data) {
                        $scope.ticketsNumberClosedVsOpenedList = data.data;

                              var ticketsArray = [];
                                for(var i = 0; i < $scope.ticketsNumberClosedVsOpenedList.length; i++) {
                                     var obj = $scope.ticketsNumberClosedVsOpenedList[i];
                                              ticketsArray.push({ c: [{v: obj.status, f:  $scope.i18n[obj.status]}, {v: obj.ticketNumber}]});
                                         }
                            $scope.pieChartClosedVsOpenedObject.data = {"cols": [
                                {id: "t", label: "Status", type: "string"},
                                {id: "s", label: "Tickets", type: "number"}
                            ], "rows":  ticketsArray
                            };

                        deferred.resolve(data);
                    }, function errorCallback(data) {
                        $scope.setResultMessage($scope.i18n.defaultError, "error");
                    });
                }

                $scope.getTicketsByAssigneeChartData = function () {
                    $http({
                        method: 'GET',
                        url: ticketChartsContainer.jzURL('TicketChartsController.getTicketsGroupdByAssignee')+ "&spaceId=" + $scope.currentSpace + "&startDate=0&endDate=0&internal="+$scope.internal
                    }).then(function successCallback(data) {
                        ticketsNumberByAssigneeList = data.data;

                              var ticketsArray = [];
                                for(var i = 0; i < ticketsNumberByAssigneeList.length; i++) {
                                     var obj = ticketsNumberByAssigneeList[i];
                                              ticketsArray.push({ c: [{v:  obj.assignee, f:  $scope.getDisplayName(obj.assignee)}, {v: obj.ticketNumber}]});
                                         }
                            $scope.pieChartByAssigneeObject.data = {"cols": [
                                {id: "t", label: "Assignee", type: "string"},
                                {id: "s", label: "Tickets", type: "number"}
                            ], "rows":  ticketsArray
                            };

                        deferred.resolve(data);
                    }, function errorCallback(data) {
                        $scope.setResultMessage($scope.i18n.defaultError, "error");
                    });
                }



                $scope.getTicketsBySeverityChartData = function () {
                    $http({
                        method: 'GET',
                        url: ticketChartsContainer.jzURL('TicketChartsController.getTicketsGroupdBySeverity')+ "&spaceId=" + $scope.currentSpace + "&startDate=0&endDate=0&internal="+$scope.internal
                    }).then(function successCallback(data) {
                        ticketsNumberBySeverityList = data.data;

                              var ticketsArray = [];
                                for(var i = 0; i < ticketsNumberBySeverityList.length; i++) {
                                     var obj = ticketsNumberBySeverityList[i];
                                              ticketsArray.push({ c: [{v:  obj.severity , f:  $scope.i18n[obj.severity]}, {v: obj.ticketNumber}]});
                                         }
                            $scope.pieChartBySeverityObject.data = {"cols": [
                                {id: "t", label: "severity", type: "string"},
                                {id: "s", label: "Tickets", type: "number"}
                            ], "rows":  ticketsArray
                            };

                        deferred.resolve(data);
                    }, function errorCallback(data) {
                        $scope.setResultMessage($scope.i18n.defaultError, "error");
                    });
                }


/* ========================= End Pie Charts ======================================== */	
	
/* ========================= Begin OpVsCl Time Chart ======================================== */


/* **** OpVsCl Time Chart Init *** */

        $scope.lineClvsOpChartObject = {};
        $scope.lineClvsOpChartObject.type = "LineChart";
        $scope.lineClvsOpChartObject.displayed = false;


        $scope.lineClvsOpChartObject.options = {
            "colors": ['#4285f4', '#db4437'],
            "series": {
                0: {lineWidth: 3},
                1: {lineWidth: 3}
            },

			"height": 350,
            "defaultColors": ['#4285f4', '#db4437'],
            "isStacked": "false",
            "fill": 100,
            "displayExactValues": true,
            "curveType": "function",
            "tooltip": {isHtml: true},
            "focusTarget": 'category'
        };
        $scope.lineClvsOpChartObject.view = {
            columns: [0, 1, 2]
        };
		
		
		        $scope.hideClvsOpSeries = function (selectedItem) {
            var col = selectedItem.column;
            if (selectedItem.row === null) {
                if ($scope.lineClvsOpChartObject.view.columns[col] == col) {
                    $scope.lineClvsOpChartObject.view.columns[col] = {
                        label: $scope.lineClvsOpChartObject.data.cols[col].label,
                        type: $scope.lineClvsOpChartObject.data.cols[col].type,
                        calc: function () {
                            return null;
                        }
                    };
                    $scope.lineClvsOpChartObject.options.colors[col - 1] = '#CCCCCC';
                } else {
                    $scope.lineClvsOpChartObject.view.columns[col] = col;
                    $scope.lineClvsOpChartObject.options.colors[col - 1] = $scope.lineClvsOpChartObject.options.defaultColors[col - 1];
                }
            }
        }





/* **** OpVsCl Time Chart data *** */
	
					$scope.getOpenVSClosedLineChartData = function (){
						if($scope.currentSpace==""){
							$scope.getAllOpenVSClosedLineChartData(); 
						}else{
							 $scope.getSpaceOpenVSClosedLineChartData();
						}
					}
                $scope.getAllOpenVSClosedLineChartData = function () {
					
                    $http({
                        method: 'GET',
                        url: ticketChartsContainer.jzURL('TicketChartsController.getOpenVSClosedStatLog')+ "&period=" + $scope.openVSClosedLinePeriod + "&startDate=" + $scope.startDate + "&endDate=" + $scope.endDate + "&internal="+$scope.internal
                    }).then(function successCallback(data) {
                 $scope.stats = data.data;

                 var statArray = [];
                 for (var i = 0; i < $scope.stats.length; i++) {
                     var obj = $scope.stats[i];

                     statArray.push({c: [{v: obj.statDate}, {v: obj.openedTicketNumber, f: ' '+obj.openedTicketNumber}, {v: obj.closedTicketNumber, f:' '+obj.closedTicketNumber }]});
                 }


                 $scope.lineClvsOpChartObject.data = {
                     "cols": [{
                             id: "day",
                             label: "Day",
                             type: "string"
                         }, {
                             id: "open",
                             label: $scope.i18n["open"],
                             type: "number"
                         }, {
                             id: "close",
                             label: $scope.i18n["closed"],
                             type: "number"
                         }],
                     "rows": statArray
                 };

                        deferred.resolve(data);
                    }, function errorCallback(data) {
                        $scope.setResultMessage($scope.i18n.defaultError, "error");
                    });
                }


                $scope.getSpaceOpenVSClosedLineChartData = function () {
					
                    $http({
                        method: 'GET',
                        url: ticketChartsContainer.jzURL('TicketChartsController.getSpaceOpenVSClosedStatLog')+ "&spaceId=" + $scope.currentSpace + "&period=" + $scope.openVSClosedLinePeriod + "&startDate=" + $scope.startDate + "&endDate=" + $scope.endDate + "&internal="+$scope.internal
                    }).then(function successCallback(data) {
                 $scope.stats = data.data;

                 var statArray = [];
                 for (var i = 0; i < $scope.stats.length; i++) {
                     var obj = $scope.stats[i];

                     statArray.push({c: [{v: obj.statDate}, {v: obj.openedTicketNumber, f: ' '+obj.openedTicketNumber}, {v: obj.closedTicketNumber, f:' '+obj.closedTicketNumber }]});
                 }


                 $scope.lineClvsOpChartObject.data = {
                     "cols": [{
                             id: "day",
                             label: "Day",
                             type: "string"
                         }, {
                             id: "open",
                             label: $scope.i18n["open"],
                             type: "number"
                         }, {
                             id: "close",
                             label: $scope.i18n["closed"],
                             type: "number"
                         }],
                     "rows": statArray
                 };

                        deferred.resolve(data);
                    }, function errorCallback(data) {
                        $scope.setResultMessage($scope.i18n.defaultError, "error");
                    });
                }

/* ========================= End OpVsCl Time Chart ======================================== */


/* ========================= Begin Tickets by status Time Chart ======================================== */


/* **** Tickets by status Time Chart Init *** */


 $scope.lineLogbyStatusChartObject = {};
        $scope.lineLogbyStatusChartObject.type = "LineChart";
        $scope.lineLogbyStatusChartObject.displayed = false;


        $scope.lineLogbyStatusChartObject.options = {
			"isStacked": "false",
			"height": 350,
            "fill": 100,
            "displayExactValues": true,
            "curveType": "function",
            "tooltip": {isHtml: true},
            "focusTarget": 'category'
        };
        $scope.lineLogbyStatusChartObject.view = {
            columns: [0, 1, 2, 3,4,5,6,7]
        };



        $scope.hideLogbyStatusSeries = function (selectedItem) {
            var col = selectedItem.column;
            if (selectedItem.row === null) {
                if ($scope.lineLogbyStatusChartObject.view.columns[col] == col) {
                    $scope.lineLogbyStatusChartObject.view.columns[col] = {
                        label: $scope.lineLogbyStatusChartObject.data.cols[col].label,
                        type: $scope.lineLogbyStatusChartObject.data.cols[col].type,
                        calc: function () {
                            return null;
                        }
                    };
                    $scope.lineLogbyStatusChartObject.options.colors[col - 1] = '#CCCCCC';
                } else {
                    $scope.lineLogbyStatusChartObject.view.columns[col] = col;
                    $scope.lineLogbyStatusChartObject.options.colors[col - 1] = $scope.lineLogbyStatusChartObject.options.defaultColors[col - 1];
                }
            }
        }

       

/* **** Tickets by status Time Chart data *** */

	

				$scope.getLogbyStatusChartData = function () {
                    $http({
                        method: 'GET',
                        url: ticketChartsContainer.jzURL('TicketChartsController.getLogbyStatusChartData')+ "&spaceId=" + $scope.currentSpace +"&period=" + $scope.logbyStatusChartPeriod   + "&startDate=" + $scope.startDate + "&endDate=" + $scope.endDate + "&internal="+$scope.internal
                    }).then(function successCallback(data) {
                 $scope.stats = data.data;

                 var statArray = [];
                 for (var i = 0; i < $scope.stats.length; i++) {
                     var obj = $scope.stats[i];

                     statArray.push({c: [{v: obj.statDate},
					 {v: obj.openedTicketNumber, f:  " "+obj.openedTicketNumber},
					 {v: obj.consideredTicketNumber, f:  " "+obj.consideredTicketNumber},
					 {v: obj.waitingCustomerTicketNumber, f: " "+obj.waitingCustomerTicketNumber},
					 {v: obj.waitingProductTicketNumber, f: " "+obj.waitingProductTicketNumber},
					 {v: obj.inProgressTicketNumber, f: " "+obj.inProgressTicketNumber},
					 {v: obj.resolvedWFVTicketNumber, f: " "+obj.resolvedWFVTicketNumber},
					 {v: obj.resolvedTicketNumber, f: " "+obj.resolvedTicketNumber}
					 ]});
                 }


                 $scope.lineLogbyStatusChartObject.data = {
                     "cols": [{
                             id: "day",
                             label: "Day",
                             type: "string"
                         }, {
                             id: "open",
                             label: $scope.i18n["open"],
                             type: "number"
                         },{
                             id: "considered",
                             label: $scope.i18n["considered"],
                             type: "number"
                         }, {
                             id: "waitingCustomer",
                             label: $scope.i18n["suspended_wfi"],
                             type: "number"
                         }, {
                             id: "waitingProduct",
                             label: $scope.i18n["resolved_maintenance"],
                             type: "number"
                         }, {
                             id: "inProgress",
                             label: $scope.i18n["inprogress"],
                             type: "number"
                         }, {
                             id: "waitingValidation",
                             label: $scope.i18n["resolved_wfv"],
                             type: "number"
                         }, {
                             id: "resolved",
                             label: $scope.i18n["resolved_validated"],
                             type: "number"
                         }],
                     "rows": statArray
                 };

                        deferred.resolve(data);
                    }, function errorCallback(data) {
                        $scope.setResultMessage($scope.i18n.defaultError, "error");
                    });
                }




/* ========================= End Tickets by status Time Chart ======================================== */

/* ========================= Begin Time metrics Chart ======================================== */


/* **** Time metrics Chart Init *** */


        $scope.timeMetricslineChartObject = {};
        $scope.timeMetricslineChartObject.type = "LineChart";
        $scope.timeMetricslineChartObject.displayed = false;


        $scope.timeMetricslineChartObject.options = {
            "colors": ['#4285f4', '#00b36b', '#db4437'],
            "series": {
                0: {lineWidth: 3},
                1: {lineWidth: 3}
            },
            "defaultColors": ['#4285f4', '#00b36b', '#db4437'],
			"height": 350,
            "isStacked": "false",
            "fill": 100,
            "displayExactValues": true,
            "curveType": "function",
            "tooltip": {isHtml: true},
            "focusTarget": 'category',

            "vAxis": {
                "title": "",
				"color": 'red',
				"textStyle": {
                                "color": 'transparent'
                            },

            }
        };
        $scope.timeMetricslineChartObject.view = {
            columns: [0, 1, 2]
        };




        $scope.hideTimeToFirstResponseSeries = function (selectedItem) {
            var col = selectedItem.column;
            if (selectedItem.row === null) {
                if ($scope.timeMetricslineChartObject.view.columns[col] == col) {
                    $scope.timeMetricslineChartObject.view.columns[col] = {
                        label: $scope.timeMetricslineChartObject.data.cols[col].label,
                        type: $scope.timeMetricslineChartObject.data.cols[col].type,
                        calc: function () {
                            return null;
                        }
                    };
                    $scope.timeMetricslineChartObject.options.colors[col - 1] = '#CCCCCC';
                } else {
                    $scope.timeMetricslineChartObject.view.columns[col] = col;
                    $scope.timeMetricslineChartObject.options.colors[col - 1] = $scope.timeMetricslineChartObject.options.defaultColors[col - 1];
                }
            }
        }







		
		        $scope.getTimeMetricsChart = function () {
            $http({
                method: 'GET',
                url: ticketChartsContainer.jzURL('TicketChartsController.getTimeMetrics')+ "&spaceId=" + $scope.currentSpace +"&period=" + $scope.timeMetricslinePeriod  + "&startDate=" + $scope.startDate + "&endDate=" + $scope.endDate + "&internal="+$scope.internal
            }).then(function successCallback(data) {
                $scope.statTimeMetrics = data.data;
                var TimeMetricsArray = [];
                for (var i = 0; i < $scope.statTimeMetrics.length; i++) {
                    var obj = $scope.statTimeMetrics[i];
                    TimeMetricsArray.push({c: [{v: obj.timeMetricsDate},
					 {v: obj.timeToFirstResponse, f:  " "+convertMS(obj.timeToFirstResponse).day + ":" +convertMS(obj.timeToFirstResponse).hour + ":" +convertMS(obj.timeToFirstResponse).minute},
					 {v: obj.timeToResolution, f:  " "+convertMS(obj.timeToResolution).day + ":" +convertMS(obj.timeToResolution).hour + ":" +convertMS(obj.timeToResolution).minute}

					 ]});
			   }


                $scope.timeMetricslineChartObject.data = {
                    "cols": [{
                            id: "day",
                            label: "Day",
                            type: "string"
                        }, {
                            id: "ttfr-id",
                            label: "timeToFirstResponse",
                            type: "number"
                        }, {
                            id: "ttr-id",
                            label: "timeToResolution",
                            type: "number"
                        }],
                    "rows": TimeMetricsArray
                };
                deferred.resolve(data);
                //                $scope.setResultMessage(data, "success");
            }, function errorCallback(data) {
                $scope.setResultMessage($scope.i18n.defaultError, "error");
            });
        }
				
		

		
/* ========================= End Tickets by status Time Chart ======================================== */		
		
/* ========================= Begin Satisfaction Time Chart ======================================== */


/* **** Satisfaction Time Chart Init *** */



        $scope.cSatlineChartObject = {};
        $scope.cSatlineChartObject.type = "LineChart";
        $scope.cSatlineChartObject.displayed = false;


        $scope.cSatlineChartObject.options = {
            "colors": ['#4285f4', '#00b36b', '#db4437'],
            "series": {
                0: {lineWidth: 3},
                1: {lineWidth: 3}
            },
            "defaultColors": ['#4285f4', '#00b36b', '#db4437'],
			"height": 350,
            "isStacked": "false",
            "fill": 100,
            "displayExactValues": true,
            "curveType": "function",
            "tooltip": {isHtml: true},
            "focusTarget": 'category'
        };
        $scope.cSatlineChartObject.view = {
            columns: [0, 1, 2]
        };




        $scope.hideSatisfactionSeries = function (selectedItem) {
            var col = selectedItem.column;
            if (selectedItem.row === null) {
                if ($scope.cSatlineChartObject.view.columns[col] == col) {
                    $scope.cSatlineChartObject.view.columns[col] = {
                        label: $scope.cSatlineChartObject.data.cols[col].label,
                        type: $scope.cSatlineChartObject.data.cols[col].type,
                        calc: function () {
                            return null;
                        }
                    };
                    $scope.cSatlineChartObject.options.colors[col - 1] = '#CCCCCC';
                } else {
                    $scope.cSatlineChartObject.view.columns[col] = col;
                    $scope.cSatlineChartObject.options.colors[col - 1] = $scope.cSatlineChartObject.options.defaultColors[col - 1];
                }
            }
        }


		/* **** Time metrics Chart data *** */
		

        $scope.getSatisfactionChart = function () {
            $http({
                method: 'GET',
                url: ticketChartsContainer.jzURL('TicketChartsController.getSatisfactionChartData') + "&spaceId=" + $scope.currentSpace +"&period=" + $scope.satisfactionLinePeriod  + "&startDate=" + $scope.startDate + "&endDate=" + $scope.endDate + "&internal="+$scope.internal
            }).then(function successCallback(data) {
                $scope.satsfactionStat = data.data;
                var satisfactionArray = [];
                for (var i = 0; i < $scope.satsfactionStat.length; i++) {
                    var obj = $scope.satsfactionStat[i];
                    satisfactionArray.push({c: [{v: obj.satisfactionDate},
					 {v: obj.customerSatisfactionPrc, f:  " "+obj.customerSatisfactionPrc+" %"},
					 {v: obj.customerTotalVotes, f:  " "+obj.customerTotalVotes+" votes"}

					 ]});
			   }


                $scope.cSatlineChartObject.data = {
                    "cols": [{
                            id: "date",
                            label: "Date",
                            type: "string"
                        }, {
                            id: "cSat-id",
                            label: "customerSatisfactionPrc",
                            type: "number"
                        }, {
                            id: "tot-id",
                            label: "totalVotes",
                            type: "number"
                        }],
                    "rows": satisfactionArray
                };
                deferred.resolve(data);
                //                $scope.setResultMessage(data, "success");
            }, function errorCallback(data) {
                $scope.setResultMessage($scope.i18n.defaultError, "error");
            });
        }
				

		
/* ========================= End Satisfaction Time  Chart ======================================== */	




        $scope.loadAssignees = function() {
           $http({
              method: 'GET',
              url : ticketChartsContainer.jzURL('TicketChartsController.getSupportUsernames')
           }).then(function successCallback(data) {
               $scope.assignees = data.data;
			   if($scope.assigneeUrl!=""){
				   $scope.selectedAssignee=$scope.getAssigneeByUserName($scope.assigneeUrl);
			   }
               $timeout(function() {
                 //   $scope.setResultMessage("", "info")
               }, 3000);
           },function errorCallback(data) {
               $scope.setResultMessage(data, "error");
           });
        }





        $scope.pieChartByAssigneeObject = {};
        $scope.pieChartByAssigneeObject.options = {
            pieHole: 0.3,
            title: 'Tickets by Assignee',
            width:817,height:500
        };
        $scope.pieChartByAssigneeObject.type = "PieChart";
		
		$scope.getTicketsFilteredByAssignee = function (selectedItem) {
            var col = selectedItem.column;
            var row = selectedItem.row;
			var assignee=$scope.pieChartByAssigneeObject.data.rows[selectedItem.row].c[0].v;
			var adminLink=$scope.getAdminLink(); 
			window.open( adminLink+"?spaceId="+$scope.currentSpace+"&assignee="+assignee+"&internal="+$scope.internal, '_blank');
		
        }
		
		


        $scope.pieChartBySeverityObject = {};
        $scope.pieChartBySeverityObject.options = {
            pieHole: 0.3,
            title: 'Tickets by Severity',
            width:817,height:500
        };
        $scope.pieChartBySeverityObject.type = "PieChart";



        $scope.pieChartBySpaceObject = {};
        $scope.pieChartBySpaceObject.options = {
            pieHole: 0.3,
            title: 'Tickets by space',
            width:817,height:500
        };
        $scope.pieChartBySpaceObject.type = "PieChart";
		
		$scope.getTicketsFilteredBySpace = function (selectedItem) {
            var col = selectedItem.column;
            var row = selectedItem.row;
			var space=$scope.pieChartBySpaceObject.data.rows[selectedItem.row].c[0].v;
			var adminLink=$scope.getAdminLink(); 
			window.open( adminLink+"?spaceId="+space, '_blank');
			
        }
		
		

        $scope.pieChartByOwnerObject = {};
        $scope.pieChartByOwnerObject.options = {
            pieHole: 0.3,
            title: 'Tickets by third party',
            width:817,height:500
        };
        $scope.pieChartByOwnerObject.type = "PieChart";
		
		$scope.getTicketsFilteredByOwner = function (selectedItem) {
            var col = selectedItem.column;
            var row = selectedItem.row;
			var thirdParty=$scope.pieChartByOwnerObject.data.rows[selectedItem.row].c[0].v;
			var adminLink=$scope.getAdminLink(); 
			window.open( adminLink+"?spaceId="+$scope.currentSpace+"&thirdParty="+thirdParty+"&internal="+$scope.internal, '_blank');
			
        }

		$scope.getTicketsFilteredBySeverity = function (selectedItem) {
            var col = selectedItem.column;
            var row = selectedItem.row;
			var severity=$scope.pieChartBySeverityObject.data.rows[selectedItem.row].c[0].v;
			var adminLink=$scope.getAdminLink(); 
			window.open( adminLink+"?spaceId="+$scope.currentSpace+"&severity="+severity+"&internal="+$scope.internal, '_blank');
			
        }
		

        $scope.pieChartByStatusObject = {};
        $scope.pieChartByStatusObject.options = {
            pieHole: 0.3,
			width:817,
			height:500,
            title: 'Tickets by status'
        };
        $scope.pieChartByStatusObject.type = "PieChart";
		
		$scope.getTicketsFilteredByStatus = function (selectedItem) {
            var col = selectedItem.column;
            var row = selectedItem.row;
			var ticketStatus=$scope.pieChartByStatusObject.data.rows[selectedItem.row].c[0].v;
			var adminLink=$scope.getAdminLink(); 
			window.open( adminLink+"?spaceId="+$scope.currentSpace+"&status="+ticketStatus+"&internal="+$scope.internal, '_blank');
			
        }
		


        $scope.pieChartClosedVsOpenedObject = {};
        $scope.pieChartClosedVsOpenedObject.options = {
            pieHole: 0.3,
            title: 'Closed VS Opened tickets',
            width:817,height:500
        };
        $scope.pieChartClosedVsOpenedObject.type = "PieChart";
		
		$scope.getClosedVsOpened = function (selectedItem) {
            var col = selectedItem.column;
            var row = selectedItem.row;
			var ticketStatus=$scope.pieChartClosedVsOpenedObject.data.rows[selectedItem.row].c[0].v;
			var adminLink=$scope.getAdminLink(); 
			window.open( adminLink+"?spaceId="+$scope.currentSpace+"&opvsclStatus="+ticketStatus+"&internal="+$scope.internal, '_blank');
			
        }
		


        $scope.setResultMessage = function (text, type) {
            $scope.resultMessageClass = "alert-" + type;
            $scope.resultMessageClassExt = "uiIcon" + type.charAt(0).toUpperCase()+ type.slice(1);
            $scope.showAlert = true;
            $scope.resultMessage = text;
        }


        $scope.loadBundle = function () {
            $http({
                method: 'GET',
                url: ticketChartsContainer.jzURL('TicketChartsController.getBundle') + "&locale=" + eXo.env.portal.language
            }).then(function successCallback(data) {
                $scope.i18n = data.data;
                deferred.resolve(data);
                /*$scope.setResultMessage(data, "success");*/
                $scope.showAlert = false;
            }, function errorCallback(data) {
                $scope.setResultMessage($scope.i18n.defaultError, "error");
            });
        }





                 $scope.getOpenVsClosedTicketsByDates = function () {
                     $http({
                         method: 'GET',
                         url: ticketChartsContainer.jzURL('TicketChartsController.getOpenVsClosedTicketsByDates')+ "&startDate=" + $scope.startDate + "&endDate=" + $scope.endDate + "&internal="+$scope.internal
                     }).then(function successCallback(data) {
                         $scope.ticketsNumberClosedVsOpenedList = data.data;

                               var ticketsArray = [];
                                 for(var i = 0; i < $scope.ticketsNumberClosedVsOpenedList.length; i++) {
                                      var obj = $scope.ticketsNumberClosedVsOpenedList[i];
                                               ticketsArray.push({ c: [{v: obj.status}, {v: obj.ticketNumber}]});
                                          }
                             $scope.pieChartClosedVsOpenedObject.data = {"cols": [
                                 {id: "t", label: "Status", type: "string"},
                                 {id: "s", label: "Tickets", type: "number"}
                             ], "rows":  ticketsArray
                             };

                         deferred.resolve(data);
                     }, function errorCallback(data) {
                         $scope.setResultMessage($scope.i18n.defaultError, "error");
                     });
                 }




                $scope.getTicketsByStatusAndDatesChartData = function () {
                    $http({
                        method: 'GET',
                        url: ticketChartsContainer.jzURL('TicketChartsController.getTicketsGroupdByStatusAndDates')+ "&startDate=" + $scope.startDate + "&endDate=" + $scope.endDate + "&internal="+$scope.internal
                    }).then(function successCallback(data) {
                        $scope.ticketsNumberByStatusList = data.data;

                              var ticketsArray = [];
                                for(var i = 0; i < $scope.ticketsNumberByStatusList.length; i++) {
                                     var obj = $scope.ticketsNumberByStatusList[i];
                                              ticketsArray.push({ c: [{v: $scope.i18n[obj.status]}, {v: obj.ticketNumber , f:  "eeeeeeeeeeeee"}]});
                                         }
                            $scope.pieChartByStatusObject.data = {"cols": [
                                {id: "t", label: "Status", type: "string"},
                                {id: "s", label: "Tickets", type: "number"}
                            ], "rows":  ticketsArray
                            };

                        deferred.resolve(data);
                    }, function errorCallback(data) {
                        $scope.setResultMessage($scope.i18n.defaultError, "error");
                    });
                }




                $scope.loadData = function () {
        			if ($scope.showGetAll==false){
        				$scope.startDate=0;
        			}
                    $http({
                        method: 'GET',
                        url: ticketChartsContainer.jzURL('TicketChartsController.getData')+ "&currentSpace=" + $scope.currentSpace + "&internal="+$scope.internal+ "&startDate=" + $scope.startDate + "&endDate=" + $scope.endDate
                    }).then(function successCallback(data) {
                        d = data.data;

                        if(d.currentSpace==""){
						 $scope.currentSpace="";
                         $scope.loadSpaces();
                         $scope.showSpaces = true;
                         $scope.showSpaceCharts = false;
                         $scope.showAllCustomerCharts = true;



                        }else{
						$scope.currentSpace=d.currentSpace; 	
						 $scope.customerTotalVotes = d.customerTotalVotes ;
						 $scope.showSpaceCharts = true;
						 $scope.showAllCustomerCharts = false;
														 
                        }
						 $scope.customerTotalVotes = d.customerTotalVotes ;
                         $scope.customerSatisfactionPrc = d.customerSatisfactionPrc ;
                         $scope.firstTimeResponceAverage = convertMS(d.firstTimeResponceAverage);
                         $scope.timeToResolutionAverage = convertMS(d.timeToResolutionAverage);
						 $scope.getOpenVSClosedLineChartData();
        				 $scope.getLogbyStatusChartData();
						 $scope.getTimeMetricsChart();
						 $scope.getSatisfactionChart();
						 $scope.getTicketsBySpaceChartData();
                         $scope.getTicketsByOwnerChartData();
                         $scope.getTicketsByStatusChartData();
                         $scope.getOpenVsClosedTickets();
						 $scope.getTicketsByAssigneeChartData();
						 $scope.getTicketsBySeverityChartData();
                        deferred.resolve(data);
                    }, function errorCallback(data) {
                        $scope.setResultMessage($scope.i18n.defaultError, "error");
                    });
                }

		 $scope.getAll = function() {
			$scope.pickerModel = {
              selectedTemplateName:'',
            };
            $scope.showGetAll=false;
        	$scope.startDate=0;
        	$scope.endDate=(new Date()).getTime();
            $scope.loadData();
        };


		 $scope.getDateText = function() {
			 var dateStart = new Date();
			 var dateEnd = new Date();
			 dateStart.setTime($scope.startDate);
			 dateEnd.setTime($scope.endDate);
			 if (getDateDiff(dateStart, dateEnd) === 0) {
				 return $filter('date')(dateStart, 'dd MMM yyyy');
			 } else {
				 return $filter('date')(dateStart, 'dd' + (dateStart.getMonth() !== dateEnd.getMonth() || dateStart.getFullYear() !== dateEnd.getFullYear() ? ' MMM' :
					 '') + (dateStart.getFullYear() !== dateEnd.getFullYear() ? ' yyyy' : '')) + ' - ' + $filter('date')(dateEnd, 'dd MMM yyyy');
			 }
		 }

		 function getDateDiff(date1, date2) {
			 if (!date1 || !date2) return;
			 var _d1 = new Date(date1.getFullYear(), date1.getMonth(),
					 date1.getDate()),
				 _d2 = new Date(date2.getFullYear(), date2.getMonth(), date2.getDate());
			 return _d2 - _d1;
		 }

        function convertMS( milliseconds ) {
            var day, hour, minute, seconds;
            seconds = Math.floor(milliseconds / 1000);
            minute = Math.floor(seconds / 60);
            seconds = seconds % 60;
            hour = Math.floor(minute / 60);
            minute = minute % 60;
            day = Math.floor(hour / 24);
            hour = hour % 24;
            return {
                day: day,
                hour: hour,
                minute: minute,
                seconds: seconds
            };
        }

        $scope.loadSpaces = function () {
            $http({
                method: 'GET',
                url: ticketChartsContainer.jzURL('TicketChartsController.getSpaces')
            }).then(function successCallback(data) {
                $scope.spaces = data.data;
                $scope.spaces.push($scope.allSpaces);

                $scope.showAlert = false;
            }, function errorCallback(data) {
                $scope.setResultMessage($scope.i18n.defaultError, "error");
            });

        };


        $scope.getSpaceData = function (currentSpace) {
                 if(currentSpace==="all"){
				 $scope.currentSpace="";
				 $scope.showSpaceCharts = false;
                 $scope.showAllCustomerCharts = true;
				 }else{
                 $scope.showSpaceCharts = true;
                 $scope.showAllCustomerCharts = false;
				 $scope.currentSpace=currentSpace;               
				 }
				 $scope.loadData();

        }
        $scope.getAdminLink = function () {
			var  adminLink="";
			var locationHref = window.location.href;
			var indexOfSemiColon = locationHref.lastIndexOf(":spaces:");
			if(indexOfSemiColon <0){
				adminLink = "/portal/g/:platform:administrators/csmgmt/csticketmgmt"
			}else{
				
			var indexOfSlash = locationHref.indexOf("/", indexOfSemiColon+1);
			if(indexOfSlash <0) indexOfSlash =  locationHref.length
			var spacePrettyName = eXo.env.portal.selectedNodeUri;
			var indexSlashPrettyName = spacePrettyName.indexOf('/');
			if(indexSlashPrettyName > 0) {
					spacePrettyName = spacePrettyName.substring(0, indexSlashPrettyName);
			}
			adminLink = locationHref.substring(0, indexOfSlash) + "/" + spacePrettyName + "/tickets-list";
			}
			return adminLink;
        }


        $scope.loadBundle();
        $scope.setDates(); 
        $scope.loadAssignees();


        $('#ticketCharts').css('visibility', 'visible');
        $(".csLoadingBar").remove();

    };
        return ticketChartsCtrl;

});
