﻿'use strict';
angular.module('companyAnalytics', ['ngSanitize'])
	.controller('companyAnalyticsSideBarCtrl', ['$scope', '$http', '$q', '$window', '$timeout', '$filter', function ($scope, $http, $q, $window, $timeout, $filter) {
		$scope.aname = aname;
		$scope.isBubbleChartAnalysis = aname === "marketvaluation" || aname === 'customizablechart' || aname === 'marketvaluationscreener' ? true : false;
		$scope.isAramcoIndicators = aname === "indicatorsaramco" ? true : false;
		$scope.sideBarURLs = {
			marketValuationURL: '/companyanalytics/marketvaluation',
			customizableChartURL: '',
			marketValuationScreenerURL: '/companyanalytics/marketvaluationscreener'
		};
		$http({
			url: siteRoot + "indicatorsaramco",
			data: { flag: 0 },
			method: "POST"
		}).then((res) => {
			$scope.indHeadings = res.data;
			$scope.$emit('analyticsData', res.data);
		});

	}])
	.controller('marketValuationCtrl', ['$global', '$timeout', '$filter', '$scope', '$http', '$q', '$interval', function ($global, $timeout, $filter, $scope, $http, $q, $interval) {
		let self = this,
			dataTable = undefined,
			dataColumns = [];
		$scope.mvData = [];
		$scope.chartData = [];
		$scope.filteredRatios = [];
		$scope.selectedRatios = [];
		$scope.ratios = {};
		$scope.PaginatedData = [];
		$scope.sectors = [];
		$scope.gbSectors = [];
		$scope.currencies = [];
		$scope.chartData = [];
		$scope.mvSwitchM = undefined;
		$timeout(function () {
			var elems = document.querySelectorAll('.mv-switch');
			elems.forEach(function (elem) {
				var switchery = new Switchery(elem, { color: '#7BAEBF', secondaryColor: '#567A86', jackColor: '#fff', jackSecondaryColor: '#eee', size: 'small' });
			});
		});
		$scope.stockMarkets = [];
		$scope.selectElems = {
			stockMarketId: '-2',
			sectorId: '-2',
			currencyId: '1'
		};
		$scope.stockMarketId = "-1";
		$scope.sectorId = "-1";
		blockUI('marketValuation');
		$http({
			url: siteRoot + "common/GetGCCMarkets",
			method: "POST"
		}).then(function (data) {
			$scope.stockMarkets = data.data;
		}).finally(function () {
			unblockUI('marketValuation');
		});

		$scope.$watch('selectElems.stockMarketId', function (n, o) {
			if (n === o) return;
			$timeout(() => {
				$scope.selectElems.sectorId = n === '-1' ? "-2" : '-1';
				if (n === "-1") $scope.sectors = $scope.gbSectors.map(function (elem) {
					return { SectorID: elem.ID, Sector: elem.Sector };
				}); else $scope.sectors = [];
				self.loadData();
			});
		});
		$scope.$watch('selectElems.sectorId', function (n, o) {
			if (n === o) return;
			$timeout(() => {
				self.loadData();
			});

		});
		$scope.$watch('selectElems.currencyId', function (n, o) {
			if (n === o) return;
			self.loadData();
		});
		$scope.$watch('mvSwitchM', function (n, o) {
			$scope.chartData.length > 0 && $timeout(function () {
				self.initChart();
			});
		});
		$scope.init = function (initData) {
			$scope.chartData = initData.valuationData;
			$scope.mvData = initData.valuationData;
			$scope.gbSectors = initData.gbSectors;
			$scope.sectors = initData.gbSectors.map(function (elem) {
				return { SectorID: elem.ID, Sector: elem.Sector };
			});
			$scope.currencies = initData.currencies;
			$scope.ratios = initData.ratios;
			$scope.ratioTitles = $.map(initData.ratios, (elem) => { return { Title: elem.Title, TitleOrder: elem.TitleOrder }; }).uniqueArray('Title').sort(sortBy('TitleOrder'));
			self.createMarketDrillDownChart();
			$timeout(function () {
				$(".table-fixedHeader").stickyTableHeaders({ fixedOffset: 65 });
			});
		};
		this.loadData = function () {
			blockUI('marketValuation');
			resetRatios();
			$http({
				url: siteRoot + "companyanalytics/marketvaluation",
				method: "POST",
				data: { smid: $scope.selectElems.stockMarketId === "-1" ? 0 : $scope.selectElems.stockMarketId, sid: $scope.selectElems.sectorId === "-1" ? 0 : $scope.selectElems.sectorId, isGbSectors: $scope.selectElems.sectorId === "-3" ? true : false, cid: $scope.selectElems.currencyId }
			}).then(function (data) {
				$scope.chartData = data.data.model;
				$scope.mvData = data.data.model;
				self.createMarketDrillDownChart();
				if (Number($scope.selectElems.stockMarketId) > 0 && Number($scope.selectElems.sectorId) < 0) $scope.sectors = $filter('unique')($.map(data.data.model, function (el) {
					return { SectorID: el.SectorID, Sector: el.Sector };
				}).clean());
			}).finally(function () {
				unblockUI('marketValuation');
				$('.table-fixedHeader').stickyTableHeaders('destroy');
				$timeout(function () {
					$(".table-fixedHeader").stickyTableHeaders({ fixedOffset: 65 });
				});
			});
		};
		this.createMarketDrillDownChart = function () {
			$scope.chartData = $.map($scope.mvData, function (v, i) {
				return {
					x: v.PB,
					y: v.PE,
					z: v.MarketCap,
					ID: v.CompanyID > 0 ? v.CompanyID : v.SectorID > 0 ? v.SectorID : v.StockMarketID,
					Ticker: v.UTicker,
					Company: v.Company,
					CompanyID: v.CompanyID,
					MarketCap: v.MarketCap,
					URL: v.CompanyID === 0 ? null : v.profile_URL
				};
			}).clean();
			self.initChart();
		};
		this.initChart = function () {
			var currency = $scope.mvData.firstOrDefault().Currency;
			let tempChartData = $.map($scope.chartData, function (v, i) {
				if (!$scope.mvSwitchM && (v.y <= 0 || v.y > 100 || v.x <= 0 || v.x > 100)) return;
				return {
					x: v.x,
					y: v.y,
					z: v.z,
					ID: v.ID,
					Ticker: v.Ticker,
					Company: v.Company,
					CompanyID: v.CompanyID,
					MarketCap: v.MarketCap,
					URL: v.URL
				};
			}).clean();

			$('#chartMarketValuation').highcharts({
				chart: {
					type: 'bubble',
					backgroundColor: '#000',
					borderColor: '#3a3a3a',
					plotBorderWidth: 1,
					zoomType: 'xy',
					padding: [0, 0, 30, 0]
				},
				legend: {
					enabled: false
				},
				title: {
					useHTML: true,
					text: ""
				},
				subtitle: {
					text: ''
				},
				xAxis: {
					gridLineColor: '#ddd',
					lineColor: '#444',
					lineWidth: 1,
					gridLineWidth: 1,
					title: {
						text: $global.getResources("lblPriceBook") + ' (x)',
						style: {
							color: '#ADADAD'
						}
					},
					labels: {
						formatter: function () { return $filter('WNOrDec')(this.value); },
						style: {
							color: '#ADADAD'
						}
					}
				},
				yAxis: {
					gridLineColor: '#3a3a3a',
					lineColor: '#3a3a3a',
					lineWidth: 1,
					gridLineWidth: 1,
					title: {
						text: $global.getResources("lblPriceEarning") + ' (x)',
						style: {
							color: '#ADADAD'
						}
					},
					labels: {
						//format: '{value}',
						formatter: function () { return $filter('WNOrDec')(this.value); },
						style: {
							color: '#ADADAD'
						}
					},
					maxPadding: 0.2
				},
				tooltip: {
					useHTML: true,
					formatter: function formatter() {
						return `<div class="custom-tooltip defualt-color"><p class="text-left"><b>${this.point.Ticker} </b></p> 
                      <p class="text-left"><b> ${$filter('getLabel')("lblPriceBook")}: </b> 
                      ${WNOrDecimal(this.x)} </p><p class="text-left"><b>${$filter('getLabel')("lblPriceEarning")}: </b> 
                      ${WNOrDecimal(this.y)} </p> <p class="text-left"><b>${$filter('getLabel')("lblMarketCap")}: </b><span>
                      ${$filter('Abbr')(this.point.MarketCap * 1000, 2)} ${currency} </span></p></div>`;
					},
					style: { fontSize: '11px', "fontWeight": "normal", color: '#ADADAD' },
					borderColor: '#3a3a3a'
				},
				plotOptions: {
					series: {
						events: {
							click: function click(e) {

								if (e.point.CompanyID === 0) {
									$timeout(() => {
										if (Number($scope.selectElems.sectorId) === -3)
											$scope.selectElems.sectorId = e.point.ID.toString();
										else if (Number($scope.selectElems.stockMarketId) > 0 && Number($scope.selectElems.sectorId) < 0)
											$scope.selectElems.sectorId = e.point.ID.toString();
										else if (Number($scope.selectElems.stockMarketId) < 0 && e.point.ID === 0)
											$scope.selectElems.stockMarketId = "-1";
										else if (Number($scope.selectElems.stockMarketId) < 0 && e.point.ID > 0)
											$scope.selectElems.stockMarketId = e.point.ID.toString();
									});
								} else if (e.point.CompanyID > 0 && e.point.URL !== null) {
									var url = $filter('getURL')(e.point.URL);
									window.open(url, '_blank');
								}
							}
						},
						dataLabels: {
							enabled: true,
							useHTML: true,
							formatter: function () {
								return '<p>' + this.point.Ticker + '<p/>';
							},
							style: {
								'direction': 'ltr',
								'color': '#ADADAD',
								'fontWeight': 'normal',
								'fontSize': '9px'
							}
						},
						cursor: 'pointer',
						colorByPoint: true,
					}
				},
				series: [{
					enableMouseTracking: !0,
					data: tempChartData
				}]
			}, () => {
				createSorter(); $timeout(function () {
					$(".table-fixedHeader").stickyTableHeaders({ fixedOffset: 65 });
				});
			});

		};
		$scope.filterChange = function ($event, ratio, removeOnly) {
			if (!$($event.currentTarget).prop('checked')) {
				$scope.filteredRatios = $.grep($scope.filteredRatios, (elem) => { if (elem.GBFactID !== ratio.GBFactID) return elem; }).clean();
				$scope.selectedRatios = $.grep($scope.selectedRatios, (elem) => { if (elem.GBFactID !== ratio.GBFactID) return elem; }).clean();
			}
			else if (removeOnly === undefined) {
				blockUI('marketValuation');
				$http({
					url: siteRoot + "companyanalytics/getfactdetail",
					method: "POST",
					data: { fid: ratio.GBFactID, smid: $scope.selectElems.stockMarketId, sid: $scope.selectElems.sectorId === "-1" ? 0 : $scope.selectElems.sectorId, isGbSectors: $scope.selectElems.sectorId === "-3" ? true : false, cid: $scope.selectElems.currencyId }
				}).then(function (data) {
					let gbDetail = data.data;
					if (gbDetail.length === 0) {
						$.notifyDefaults({
							url_target: "_self"
						});
						$.notify({
							message: "<h5>No data found for <b>" + ratio.GBFACT + "</b></h5>",
						});
						$($event.currentTarget).prop('checked', false);
						return;
					}
					angular.forEach(gbDetail, (mvelem) => {
						$scope.filteredRatios.push({
							CompanyID: mvelem.CompanyID,
							Value: mvelem.Value,
							ValueType: mvelem.ValueType,
							GBFACT: ratio.GBFACT,
							GBFactID: ratio.GBFactID,
							Ratio: ratio.Ratio,
							RatioOrder: ratio.RationOrder,
							TitleOrder: ratio.TitleOrder,
							Visible: ratio.Visible,
							ValueType: mvelem.ValueType
						});
						if ($.grep($scope.selectedRatios, (elem) => { if (elem.GBFactID === mvelem.GBFactID) return elem; }).length === 0)
							$scope.selectedRatios.push({ Ratio: mvelem.Ratio, GBFactID: mvelem.GBFactID, ValueType: mvelem.ValueType });
					});
				}).finally(() => {
					unblockUI('marketValuation');
					$("#tblDrillDownCompany").trigger("destroy");
					createSorter();
				});


			} else {
				$.notify("<h3>You have selected maximum.</h3>", {
					animate: {
						enter: 'animated zoomInDown',
						exit: 'animated zoomOutUp'
					}
				}, {
						type: 'warning'
					});
				$($event.currentTarget).prop('checked', false);
			}

		};
		//mv pagination
		$scope.itemsPerPage = '25';
		$scope.totalItems = $scope.mvData.length;
		$scope.currentPage = 1;
		$scope.maxSize = 5; //Number of pager buttons to show
		$scope.wSort = {
			column: 'MarketCap',
			descending: true
		};

		$scope.wClass = function (column) {
			return column === $scope.wSort.column ? $scope.wSort.descending ? "sorting_asc" : "sorting_desc" : 'sorting';
		};
		$scope.wChange = function (column) {

			if ($scope.wSort.column === column) {
				$scope.wSort.descending = !$scope.wSort.descending;
			} else {
				$scope.wSort.column = column;
				$scope.wSort.descending = false;
			}
		};

		$scope.setPage = function (pageNo) {
			$scope.currentPage = pageNo;
		};
		$scope.setItemsPerPage = function (num) {
			$scope.itemsPerPage = num;
			$scope.currentPage = 1; //reset to first paghe
		};

		$scope.pagerInfo = function () {
			var pagerHtml = '';
			var startOfRecord = ($scope.currentPage - 1) * $scope.itemsPerPage + 1;
			var endOfRecord = $scope.currentPage * $scope.itemsPerPage;
			endOfRecord = endOfRecord > $scope.mvData.length ? $scope.mvData.length : endOfRecord;
			return $filter('getLabel')('lblShowing') + ': ' + startOfRecord + ' ' + $filter('getLabel')('lblTo') + ' ' + endOfRecord + ' ' + $filter('getLabel')('lblof') + ' ' + $scope.mvData.length;
		};

		$scope.exportData = function () {
			if ($scope.mvData[0].CompanyID > 0) {
				var $table = $('table.table-tablesorter');
				$table.trigger('outputTable');
			}
			else {
				$('.table-fixedHeader').stickyTableHeaders('destroy');
				let blob = new Blob([document.getElementById('tblDirllDown').innerHTML], {
					type: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8"
				});
				saveAs(blob, "Report.xls");
				$timeout(function () {
					$(".table-fixedHeader").stickyTableHeaders({ fixedOffset: 65 });
				});
			}
		};

		function createSorter() {
			if ($scope.mvData[0].CompanyID === 0) return;
			$("#tblDrillDownCompany").trigger("destroy");
			$timeout(() => {
				$("#tblDrillDownCompany").tablesorter({
					textExtraction: function (node) {
						var attr = $(node).attr('data-order');
						if (typeof attr !== 'undefined' && attr !== false) {
							return attr;
						}
						return $(node).text();
					},
					theme: 'blue',
					widgets: ['zebra', 'output'],
					widgetOptions: {
						output_delivery: 'd',
						output_separator: ',',
						output_saveFileName: 'marketvaluation.csv'
					},
					sortList: [[3, 1]]
				});
			});
		};

		function resetRatios() {
			$("#tblDrillDownCompany").trigger("destroy");
			$scope.filteredRatios = [];
			$scope.selectedRatios = [];
			$('ul.dynamic-colum-select li input:checked').each((i, elem) => {
				$(elem).prop('checked', false);
			});
		};
	}])
	.controller('marketValuationScreenerCtrl', ['$global', '$timeout', '$filter', '$scope', '$http', '$q', '$interval', function ($global, $timeout, $filter, $scope, $http, $q, $interval) {
		let self = this, mySwitch = undefined,
			$table = $('table#tblDrillDown'), $pager = $('.tablesorter-pager');
		$scope.mvData = [];
		$scope.viewData = [];
		$scope.currencies = [];
		$scope.chartData = [];
		$scope.filteredRatios = [];
		$scope.selectedRatios = [];
		$scope.mvSwitchM = false;
		$scope.currency = 'USD';
		$scope.chart = undefined;
		$scope.filterType = undefined;
		$scope.PaginatedData = {};
		$timeout(function () {
			var elems = document.querySelectorAll('.mv-switch');
			elems.forEach(function (elem) {
				mySwitch = new Switchery(elem, { color: '#7BAEBF', secondaryColor: '#567A86', jackColor: '#fff', jackSecondaryColor: '#eee', size: 'small' });
			});
		});

		$scope.stockMarkets = [];
		$scope.selectElems = {
			stockMarketId: '-1',
			currencyId: '1'
		};

		$scope.stockMarketId = "-1";
		$scope.selObj = undefined;
		$scope.callback = function ($item) {
			if ($item !== undefined && $item !== 'undefined') {
				$scope.selObj = $item.originalObject;
				$scope.processCapFilter('', undefined);
			}
		};
		$scope.clearSearch = function () {
			$scope.selObj = undefined;
			$scope.processCapFilter('', undefined);
		};
		$scope.focusOut = function () {
			$scope.$broadcast('angucomplete-alt:clearInput', 'drp-market-valuation');
		};
		function clearText() {
			$scope.$broadcast('angucomplete-alt:clearInput', 'drp-market-valuation');
		}

		$scope.$watch('selectElems.stockMarketId', function (n, o) {
			$('.marketdataval .btn-primary').removeClass('btn-primary');
			if (n === o) return;
			self.loadData();
		});
		$scope.$watch('selectElems.currencyId', function (n, o) {
			$('.marketdataval .btn-primary').removeClass('btn-primary');
			if (n === o) return;
			$scope.currency = $.grep($scope.currencies, function (elem) {
				if (elem.CurrencyID === parseInt($scope.selectElems.currencyId)) return elem;
			}).firstOrDefault().Currency;
			self.loadData();
		});

		$scope.init = function (retModel) {
			$scope.stockMarkets = retModel.gccMarkets;
			$scope.currencies = retModel.currencies;
			$scope.ratios = retModel.ratios;
			$scope.ratioTitles = $.map(retModel.ratios, (elem) => { return { Title: elem.Title, TitleOrder: elem.TitleOrder }; }).uniqueArray('Title').sort(sortBy('TitleOrder'));
			$scope.currency = $scope.currencies.firstOrDefault().Currency;
			self.loadData();
		};

		this.loadData = function () {
			$scope.chart = undefined;
			//$scope.PaginatedData = {};
			Resetfilters();
			blockUI('marketValuation');
			$http({
				url: siteRoot + "companyanalytics/marketvaluationscreener",
				method: "POST",
				data: { smid: $scope.selectElems.stockMarketId === "-1" ? 0 : $scope.selectElems.stockMarketId, cid: $scope.selectElems.currencyId }
			}).then(function (data) {
				$scope.mvData = data.data.model;
				$scope.processCapFilter('', undefined);
			}).finally(function () {

			});
		};

		this.createScreenerChart = function () {

			$('#chartMarketValuationScreener').highcharts({
				chart: {
					type: 'bubble',
					plotBorderWidth: 1,
					zoomType: 'xy',
					padding: [0, 0, 30, 0],
					backgroundColor: '#000',
					borderColor: '#3a3a3a',
				},
				legend: {
					enabled: false
				},
				title: {
					useHTML: true,
					text: ""
				},
				subtitle: {
					text: ''
				},
				xAxis: {
					gridLineColor: '#3a3a3a',
					lineColor: '#3a3a3a',
					lineWidth: 1,
					gridLineWidth: 1,
					title: {
						text: $global.getResources("lblPriceBook") + ' (x)',
						style: {
							color: '#ADADAD'
						}
					},
					labels: {
						format: '{value}',
						style: {
							color: '#ADADAD'
						}
					}
				},

				yAxis: {
					gridLineColor: '#3a3a3a',
					lineColor: '#3a3a3a',
					lineWidth: 1,
					gridLineWidth: 1,
					title: {
						text: $global.getResources("lblPriceEarning") + ' (x)',
						style: {
							color: '#ADADAD'
						}
					},
					labels: {
						format: '{value}',
						style: {
							color: '#ADADAD'
						}
					},
					maxPadding: 0.2
				},

				tooltip: {
					useHTML: true,
					formatter: function formatter() {

						return `<div class="custom-tooltip no-padding ltr opacity-1 defualt-color"><p class="text-left"><b>${this.point.Ticker}</b></p> 
                <p class="text-left"><b>${$filter('getLabel')("lblPriceBook")}: </b>${WNOrDecimal(this.x)}</p>
                <p class="text-left"><b>${$filter('getLabel')("lblPriceEarning")}: </b>${WNOrDecimal(this.y)}</p>
                <p class="text-left"><b>${$filter('getLabel')("lblMarketCap")}: </b><span>${$filter('Abbr')(this.point.z, 0)} ${$scope.currency}</span></p></div>`;
					},
					style: { fontSize: '11px', "fontWeight": "normal", 'opacity': 1.0, color: '#ADADAD' },
					borderColor: '#3a3a3a'
				},

				plotOptions: {
					series: {
						events: {
							click: function click(e) {
								if (e.point.ID > 0 && e.point.URL !== null) {
									var url = $filter('getURL')(e.point.URL);
									window.open(url, '_blank');
								}
							}
						},
						cursor: 'pointer',
						colorByPoint: true,
						dataLabels: {
							enabled: true,
							//format: '{point.Ticker}',
							formatter: function () {
								return '<p>' + this.point.Ticker + '<p/>';
							},
							useHTML: true,
							style: {
								//direction: 'ltr',
								'color': '#ADADAD',
								'fontWeight': 'normal',
								'fontSize': '11px'
							}
						}
					}
				},

				series: [{
					enableMouseTracking: !0,
					data: $scope.chartData
				}]

			}, function (chart) {

				$scope.chart = chart;
				unblockUI('marketValuation');
				createSorter();

			});
		};

		$scope.marketFtr = {
			largeCap: true,
			medCap: true,
			smallCap: true,
			microCap: true,
			csFrom: null,
			csTo: null,

			peLessThan0: false,
			pe0To10: true,
			pe10To15: true,
			pe15To25: true,
			pe25To50: true,
			pe50To100: true,
			peGreaterThen100: false,
			peFrom: null,
			peTo: null,

			pbLessThan0: false,
			pb0To1: true,
			pb1To2: true,
			pb2To3: true,
			pb3To5: true,
			pb5To10: true,
			pbGreaterThen10: false,
			pbFrom: null,
			pbTo: null
		};

		$scope.checkAll = true;

		$scope.setCheckAll = function (obj) {
			$scope.checkAll = !$scope.checkAll;
			for (var property in $scope.marketFtr) {
				if ($scope.marketFtr.hasOwnProperty(property)) {
					if (['csFrom', 'csTo', 'peFrom', 'peTo', 'pbFrom', 'pbTo'].indexOf(property) !== -1) $scope.marketFtr[property] = null; else $scope.marketFtr[property] = $scope.checkAll;
				}
			}
			blockUI('marketValuation');
			$timeout(function () {
				$scope.processCapFilter();
				unblockUI('marketValuation');
			});
		};

		$scope.processCapFilter = function (capId, type, $event) {
			$scope.filterType = type;
			var retArray = [];
			blockUI('marketValuation');
			//market cap
			if (capId === 'csid1') $scope.marketFtr.largeCap = !$scope.marketFtr.largeCap;
			if (capId === 'csid2') $scope.marketFtr.medCap = !$scope.marketFtr.medCap;
			if (capId === 'csid3') $scope.marketFtr.smallCap = !$scope.marketFtr.smallCap;
			if (capId === 'csid4') $scope.marketFtr.microCap = !$scope.marketFtr.microCap;

			// priceToEarning
			if (capId === 'peLessThan0') $scope.marketFtr.peLessThan0 = !$scope.marketFtr.peLessThan0;
			if (capId === 'pe0To10') $scope.marketFtr.pe0To10 = !$scope.marketFtr.pe0To10;
			if (capId === 'pe10To15') $scope.marketFtr.pe10To15 = !$scope.marketFtr.pe10To15;
			if (capId === 'pe15To25') $scope.marketFtr.pe15To25 = !$scope.marketFtr.pe15To25;
			if (capId === 'pe25To50') $scope.marketFtr.pe25To50 = !$scope.marketFtr.pe25To50;
			if (capId === 'pe50To100') $scope.marketFtr.pe50To100 = !$scope.marketFtr.pe50To100;
			if (capId === 'peGreaterThen100') $scope.marketFtr.peGreaterThen100 = !$scope.marketFtr.peGreaterThen100;

			//priceToBook
			if (capId === 'pbLessThan0') $scope.marketFtr.pbLessThan0 = !$scope.marketFtr.pbLessThan0;
			if (capId === 'pb0To1') $scope.marketFtr.pb0To1 = !$scope.marketFtr.pb0To1;
			if (capId === 'pb1To2') $scope.marketFtr.pb1To2 = !$scope.marketFtr.pb1To2;
			if (capId === 'pb2To3') $scope.marketFtr.pb2To3 = !$scope.marketFtr.pb2To3;
			if (capId === 'pb3To5') $scope.marketFtr.pb3To5 = !$scope.marketFtr.pb3To5;
			if (capId === 'pb5To10') $scope.marketFtr.pb5To10 = !$scope.marketFtr.pb5To10;
			if (capId === 'pbGreaterThen10') $scope.marketFtr.pbGreaterThen10 = !$scope.marketFtr.pbGreaterThen10;

			var filteredData = $.map($scope.mvData, function (v, i) {
				let color = undefined,
					rank = 5,
					opacity = 1.0;
				if ($scope.selObj !== undefined && Number($scope.selObj.ID > 0)) {
					color = v.CompanyID === Number($scope.selObj.ID) ? 'rgba(255,0,0,1)' : 'rgba(255, 255, 255,0)';
					rank = 1000;
					opacity = v.CompanyID === Number($scope.selObj.ID) ? 1.0 : 0.0;
				} else {
					color = utility.getRandomColor();
				}

				return {
					x: v.PB,
					y: v.PE,
					z: v.MarketCap,
					labelrank: rank,
					ID: v.CompanyID,
					CSID: v.CapSizeID,
					Ticker: v.Ticker,
					Company: v.Company,
					Currency: v.Currency,
					URL: v.CompanyID === 0 ? null : v.profile_URL,
					color: color,
					marker: {
						fillOpacity: opacity
					}
				};
			}).clean();
			var expression = '';
			var andCondition = ' && ';
			var orCondition = ' || ';

			if ($scope.marketFtr.largeCap) {
				expression += ' (elem.CSID === 1) ' + orCondition;
			}
			if ($scope.marketFtr.medCap) {
				expression += ' (elem.CSID === 2) ' + orCondition;
			}
			if ($scope.marketFtr.smallCap) {
				expression += ' (elem.CSID === 3) ' + orCondition;
			}
			if ($scope.marketFtr.microCap) {
				expression += ' (elem.CSID === 4) ' + orCondition;
			}

			expression = $.trim(expression);
			expression = expression.endsWith($.trim(orCondition)) ? $.trim(expression).slice(0, expression.length - 2) : expression;
			expression = $.trim(expression);
			expression = expression.length > 0 ? "(" + expression + ') ' + andCondition : expression;

			//price to Earning
			var peExpression = '';
			if ($scope.marketFtr.peLessThan0) {
				peExpression += ' (elem.y <0) ' + orCondition;
			}
			if ($scope.marketFtr.pe0To10) {
				peExpression += ' (elem.y >0 && elem.y<=10) ' + orCondition;
			}
			if ($scope.marketFtr.pe10To15) {
				peExpression += ' (elem.y >10 && elem.y<=15) ' + orCondition;
			}
			if ($scope.marketFtr.pe15To25) {
				peExpression += ' (elem.y >15 && elem.y<=25) ' + orCondition;
			}
			if ($scope.marketFtr.pe25To50) {
				peExpression += ' (elem.y >25 && elem.y<=50) ' + orCondition;
			}
			if ($scope.marketFtr.pe50To100) {
				peExpression += ' (elem.y >50 && elem.y<=100) ' + orCondition;
			}
			if ($scope.marketFtr.peGreaterThen100) {
				peExpression += ' (elem.y >100) ' + orCondition;
			}
			if ($scope.marketFtr.peFrom !== null && !isNaN($scope.marketFtr.peFrom) || $scope.marketFtr.peTo !== null && !isNaN($scope.marketFtr.peTo)) {
				var _limitFrom = parseFloat($scope.marketFtr.peFrom);
				var _limitTo = parseFloat($scope.marketFtr.peTo);
				if (!isNaN(_limitFrom) && !isNaN(_limitTo)) {
					peExpression += ' (elem.y > ' + _limitFrom + '&& elem.y < ' + _limitTo + ')' + orCondition;
				} else if (!isNaN(_limitFrom) && isNaN(_limitTo)) {
					peExpression += ' (elem.y > ' + _limitFrom + ')' + orCondition;
				} else if (isNaN(_limitFrom) && !isNaN(_limitTo)) {
					peExpression += ' (elem.y < ' + _limitTo + ')' + orCondition;
				}
			}
			peExpression = $.trim(peExpression);
			peExpression = peExpression.endsWith($.trim(orCondition)) ? $.trim(peExpression).slice(0, peExpression.length - 2) : peExpression;
			peExpression = $.trim(peExpression);
			peExpression = peExpression.length > 0 ? "(" + peExpression + ') ' + andCondition : peExpression;

			expression += peExpression;
			//price To Book
			var pbExpression = '';
			if ($scope.marketFtr.pbLessThan0) {
				pbExpression += ' (elem.x <0) ' + orCondition;
			}
			if ($scope.marketFtr.pb0To1) {
				pbExpression += ' (elem.x > 0 && elem.x <= 1) ' + orCondition;
			}
			if ($scope.marketFtr.pb1To2) {
				pbExpression += ' (elem.x > 1 && elem.x <= 2) ' + orCondition;
			}
			if ($scope.marketFtr.pb2To3) {
				pbExpression += ' (elem.x > 2 && elem.x <= 3) ' + orCondition;
			}
			if ($scope.marketFtr.pb3To5) {
				pbExpression += ' (elem.x > 3 && elem.x <= 5) ' + orCondition;
			}
			if ($scope.marketFtr.pb5To10) {
				pbExpression += ' (elem.x > 5 && elem.x <= 10) ' + orCondition;
			}
			if ($scope.marketFtr.pbGreaterThen10) {
				pbExpression += ' (elem.x > 10) ' + orCondition;
			}
			if ($scope.marketFtr.pbFrom !== null && !isNaN($scope.marketFtr.pbFrom) || $scope.marketFtr.pbTo !== null && !isNaN($scope.marketFtr.pbTo)) {
				var _limitFrom2 = parseFloat($scope.marketFtr.pbFrom);
				var _limitTo2 = parseFloat($scope.marketFtr.pbTo);
				if (!isNaN(_limitFrom2) && !isNaN(_limitTo2)) {
					pbExpression += ' (elem.x > ' + _limitFrom2 + '&& elem.x< ' + _limitTo2 + ')' + orCondition;
				} else if (!isNaN(_limitFrom2) && isNaN(_limitTo2)) {
					pbExpression += ' (elem.x > ' + _limitFrom2 + ')' + orCondition;
				} else if (isNaN(_limitFrom2) && !isNaN(_limitTo2)) {
					pbExpression += ' (elem.x < ' + _limitTo2 + ')' + orCondition;
				}
			}
			pbExpression = $.trim(pbExpression);
			pbExpression = pbExpression.endsWith($.trim(orCondition)) ? $.trim(pbExpression).slice(0, pbExpression.length - 2) : pbExpression;
			pbExpression = $.trim(pbExpression);
			pbExpression = pbExpression.length > 0 ? "(" + pbExpression + ') ' + andCondition : pbExpression;

			expression += pbExpression;
			expression = $.trim(expression);
			expression = expression.endsWith($.trim(andCondition)) ? $.trim(expression).slice(0, expression.length - 2) : expression;
			if (expression.length) {
				expression = '$.grep(filteredData, function (elem) { return ' + expression + '; })';
				$scope.chartData = eval(expression);
			} else $scope.chartData = filteredData;

			if ($scope.chart === undefined) {
				self.createScreenerChart();
			} else {
				$scope.chart.series[0].update({ data: $scope.chartData });
				if ($scope.selObj !== undefined) {
					var index = $scope.chartData.findIndex(function (elem, index, array) {
						if (elem.ID === Number($scope.selObj.ID)) return index;
					});
					if ($scope.chart !== undefined && Number(index) > 0) {
						$scope.chart.series[0].data[index].graphic.toFront();
					}
				}
				unblockUI('marketValuation');
			}
			createSorter();
		};

		$scope.filterChange = function ($event, ratio, removeOnly) {
			if (!$($event.currentTarget).prop('checked')) {
				$scope.filteredRatios = $.grep($scope.filteredRatios, (elem) => { if (elem.GBFactID !== ratio.GBFactID) return elem; }).clean();
				$scope.selectedRatios = $.grep($scope.selectedRatios, (elem) => { if (elem.GBFactID !== ratio.GBFactID) return elem; }).clean();
			}
			else if (removeOnly === undefined) {
				blockUI('marketValuation');
				$http({
					url: siteRoot + "companyanalytics/getfactdetail",
					method: "POST",
					data: { fid: ratio.GBFactID, smid: $scope.selectElems.stockMarketId, sid: $scope.selectElems.sectorId === "-1" ? 0 : $scope.selectElems.sectorId, isGbSectors: $scope.selectElems.sectorId === "-3" ? true : false, cid: $scope.selectElems.currencyId }
				}).then(function (data) {
					let gbDetail = data.data;
					if (gbDetail.length === 0) {
						$.notifyDefaults({
							url_target: "_self"
						});
						$.notify({
							message: "<h5>No data found for <b>" + ratio.GBFACT + "</b></h5>",
						});
						$($event.currentTarget).prop('checked', false);
						return;
					}
					angular.forEach(gbDetail, (mvelem) => {
						$scope.filteredRatios.push({
							CompanyID: mvelem.CompanyID,
							Value: mvelem.Value,
							ValueType: mvelem.ValueType,
							GBFACT: ratio.GBFACT,
							GBFactID: ratio.GBFactID,
							Ratio: ratio.Ratio,
							RatioOrder: ratio.RationOrder,
							TitleOrder: ratio.TitleOrder,
							ValueType: mvelem.ValueType
						});
						if ($.grep($scope.selectedRatios, (elem) => { if (elem.GBFactID === mvelem.GBFactID) return elem; }).length === 0)
							$scope.selectedRatios.push({ Ratio: mvelem.Ratio, GBFactID: mvelem.GBFactID, ValueType: mvelem.ValueType });
					});
				}).finally(() => {
					unblockUI('marketValuation');
					createSorter();
				});


			} else {
				$.notify("<h3>You have selected maximum.</h3>", {
					animate: {
						enter: 'animated zoomInDown',
						exit: 'animated zoomOutUp'
					}
				}, {
						type: 'warning'
					});
				$($event.currentTarget).prop('checked', false);
			}

		};

		function createSorter() {
			$table.trigger('destroyPager');
			$table.trigger("destroy");
			$timeout(() => {
				$table.tablesorter({
					textExtraction: function (node) {
						var attr = $(node).attr('data-order');
						if (typeof attr !== 'undefined' && attr !== false) {
							return attr;
						}
						return $(node).text();
					},
					theme: 'blue',
					widgets: ['zebra', 'output'],
					widgetOptions: {
						output_delivery: 'd',
						output_separator: ',',
						output_saveFileName: 'marketvaluation.csv',
						pager_updateArrows: true,
						pager_savePages: false,
						pager_fixedHeight: false,
						pager_removeRows: false,
					},
					sortList: [[1, 1]]
				}).tablesorterPager({
					container: $pager,
					size: 30,
					output: 'showing: {startRow} to {endRow} of ({filteredRows})'
				});

			});
		};
		function Resetfilters() {
			$scope.filteredRatios = [];
			$scope.selectedRatios = [];
			$('ul.dynamic-colum-select li input:checked').each((i, elem) => {
				$(elem).prop('checked', false);
			});
		};

		$scope.exportData = function () {
			$table.trigger('outputTable');
		};
	}])
	.controller('aramcoAnalyticsCtrl', ['$global', '$timeout', '$filter', '$scope', '$http', '$q', '$interval', function ($global, $timeout, $filter, $scope, $http, $q, $interval) {
		let self = this,
			factDetailData = {};
		$scope.parentFacts = [];
		$scope.$on('analyticsData', function (evnt, data) {
			$scope.parentFacts = data.headings;
		});
		$scope.ratioId = undefined;
		$scope.init = (ratioId) => {
			$scope.ratioId = ratioId;
			loadIndicators(ratioId);
		};


		$scope.loadAramcoIndicator = ($event, ratioId) => {
			$event.preventDefault();
			$scope.ratioId = ratioId;
			loadIndicators(ratioId);
		};
		function loadIndicators(ratioId) {
			$('.chart-holder').html('');
			blockUI('collapseTwo');
			$http({
				method: 'POST',
				url: siteRoot + 'indicatorsaramco/' + ratioId
			}).then((res) => {
				factDetailData = res.data.detail;

				if ([4025, 4032, 4041, 4050, 4052].indexOf(ratioId) !== -1)
					processExtraCharts(res.data.detail);

				processData(res.data.detail);
				unblockUI('collapseTwo');
			});
		}
		function processExtraCharts(detailData) {
			let years = detailData.map((el) => { return el.Year; }).sortUnique();
			let maxYear = years.max();
			let facts = detailData.map((el) => { return el.ESDFactID; }).sortUnique();
			let pieData = [],
				stackedSeries = [];
			let pieDiv = `pie${$scope.ratioId}`;

			facts.forEach((factId) => {
				if ([4030, 4037, 4049, 4056, 4058].indexOf(factId) === -1) {
					let tempFact = detailData.map((el) => { if (el.ESDFactID === factId&& el.Year===maxYear) return el; }).clean().firstOrDefault();
					pieData.push({
						name: tempFact.ESDFact,
						y: tempFact.Value
					});
					stackedSeries.push({
						name: tempFact.ESDFact,
						data: detailData.sort(sortBy('Year', false)).map((el) => { if (el.ESDFactID === factId ) return el.Value; }).clean()
					});
				}
			});
			$('.chart-holder').append(`
        <div class="col-md-6 margin-bottom-30">
           <div class="comany-analytics-chart const-ltr" id="${pieDiv}"></div>                        
        </div>
      `);
			let title = $filter('getLabel')(`lblPie${$scope.ratioId}`);
			title = title.replace('{0}', maxYear);
			createPieChart(title, pieDiv, pieData, '%');

			let stackedId = `stacked${$scope.ratioId}`;

			$('.chart-holder').append(`
        <div class="col-md-6 margin-bottom-30">
           <div class="comany-analytics-chart const-ltr" id="${stackedId}"></div>                        
        </div>
      `);
			title = $filter('getLabel')(`lblStacked${$scope.ratioId}`);
			title = title.replace('{0}', maxYear);
			let measurementUnit = detailData.map((el) => { if (el.Year === maxYear) return el; }).clean().firstOrDefault().Unit.capitalize();
			createStackedChart(title, stackedId, years, stackedSeries, measurementUnit)
		}
		function createPieChart(chartTitle, chartDiv, seriesData, measurementUnit) {

			Highcharts.chart(chartDiv, {
				chart: {
					backgroundColor: '#000',
					borderColor: '#3a3a3a',
					borderRadius: 4,
					borderWidth: 1,
					type: 'pie',
					options3d: {
						enabled: true,
						alpha: 45,
						beta: 0
					}
				},
				watermark: {
					yAxis: 290
				},
				title: {
					text: chartTitle,
					style: {
						color: '#ADADAD'
					}
				},
				tooltip: {
					formatter: function () {
						return `<strong>${this.key}</strong>:<span class="span-label defualt-color"> ${$filter('number')(this.percentage, 2)}%</span>`;
					},
					useHTML: true,
					style: {
						color: '#ADADAD'
					}
				},
				plotOptions: {
					pie: {
						allowPointSelect: true,
						cursor: 'pointer',
						depth: 35,
						dataLabels: {
							enabled: true,
							formatter: function () {
								return `<strong>${this.key}</strong>:<span class="span-label"> ${$filter('number')(this.percentage, 2)}%</span>`;
							},
							useHTML: true
						},

					}
				},
				series: [{
					type: 'pie',
					name: 'Pie Chart',
					data: seriesData
				}]
			});
		}
		function createStackedChart(chartTitle, chartDiv, categories, chartSeries, measurementUnit) {			
			Highcharts.chart(chartDiv, {
				chart: {
					backgroundColor: '#000',
					borderColor: '#3a3a3a',
					borderRadius: 4,
					borderWidth: 1,
					type: 'column'
				},
				watermark: {
					yAxis: 290
				},
				title: {
					text: chartTitle,
					style: {
						color: '#ADADAD'
					}
				},
				xAxis: {
					categories: categories
				},
				yAxis: {
					min: 0,
					lineWidth: 1,
					title: {
						text: measurementUnit
					},
					stackLabels: {
						enabled: false,
						style: {
							fontWeight: 'bold',
							color: (Highcharts.theme && Highcharts.theme.textColor) || 'gray'
						}
					}
				},
				legend: {
					align: 'center',
					x: +33,
					verticalAlign: 'top',
					y: 25,
					floating: true,
					backgroundColor: (Highcharts.theme && Highcharts.theme.background2) || 'white',
					borderColor: '#3a3a3a',
					borderWidth: 1,
					shadow: false
				},
				tooltip: {
					formatter: function () {
						return `
									<p><strong class="defualt-color"> ${$filter('getLabel')('lblYear')}</strong >: <span class="span-label defualt-color">${this.x}</span> </p>
									<p><strong class="defualt-color"> ${$filter('getLabel')('lblValue')}</strong >: <span class="span-label defualt-color">${$filter('AbbrOrWNOrDec')(this.y, 2)} ${measurementUnit}</span> </p>
									`;
					},
					style: {
						color: '#ADADAD'
					},
					useHTML:true
				},
				plotOptions: {
					column: {
						stacking: 'normal',
						dataLabels: {
							enabled: false,
							color: (Highcharts.theme && Highcharts.theme.dataLabelsColor) || 'white'
						}
					}
				},
				series: chartSeries
			});
		}

		function processData(detailData) {			
			let factsIds = detailData.map((el) => { return el.ESDFactID; }).sortUnique();
			factsIds.forEach((factId) => {
				let years = detailData.map((el) => { if (el.ESDFactID === factId && parseFloat(el.Value)>0) return el.Year; }).clean().sortUnique();
				let seriesData = [];
				let tempFact = detailData.map((el) => { if (el.ESDFactID === factId) return el; }).clean().firstOrDefault();
				let chartDiv = `analytics${tempFact.ESDFactID}`;

				seriesData.push({
					name: tempFact.ESDFact,
					type: tempFact.chartType,
					data: detailData.sort(sortBy('Year', false)).map((el) => { if (el.ESDFactID === factId && parseFloat(el.Value) > 0) return el.Value; }).clean(),
					fillColor: {
						linearGradient: [0, 0, 0, 300],
						stops: [
							[0, Highcharts.getOptions().colors[0]],
							[1, Highcharts.Color(Highcharts.getOptions().colors[0]).setOpacity(0).get('rgba')]
						]
					},
					fillOpacity: 0.3
				});

				$('.chart-holder').append(`
					<div class="col-md-6 margin-bottom-30">
					   <div class="comany-analytics-chart const-ltr" id="${chartDiv}"></div>                        
					</div>
				  `);
				createAreaChart(tempFact.ESDFact, chartDiv, years, seriesData, tempFact.Unit.capitalize(), tempFact.chartType);
			});
		}
		function createAreaChart(chartTitle, chartDiv, chartCategories, seriesData, measurementUnit,chartType) {
			Highcharts.chart(chartDiv, {
				chart: {
					backgroundColor: '#000',
					borderColor: '#3a3a3a',
					borderRadius: 4,
					borderWidth: 1
				},
				title: {
					text: chartTitle,
					style: {
						color: '#ADADAD'
					}

				},
				legend: {
					enabled: false
				},
				watermark: {
					yAxis: 290
				},
				xAxis: {
					categories: chartCategories,
					gridLineColor: '#3a3a3a',
					lineColor: '#3a3a3a',
					labels: {
						style: {
							color: '#ADADAD'
						}
					},
				},
				yAxis: {
					min: chartType === 'area' ? seriesData[0].data.map((el) => { return el; }).min():  parseFloat(seriesData[0].data.map((el) => { return el; }).min()) - parseFloat(seriesData[0].data.map((el) => { return el; }).min())/20,
					lineWidth: 1,
					title: {
						text: measurementUnit.capitalize()
					},
					gridLineColor: '#3a3a3a',
					lineColor: '#3a3a3a',
					labels: {
						style: {
							color: '#ADADAD'
						}
					},
				},
				tooltip: {
					shared: true,
					formatter: function () {
						return `<strong class="defualt-color">${$filter('getLabel')('lblYear')}</strong> : <span class="span-label defualt-color">${this.x} </span><br/>
                    <strong class="defualt-color">${$filter('getLabel')('lblValue')}</strong> : <span class="span-label defualt-color">${$filter('AbbrOrWNOrDec')(this.y, 2)} ${measurementUnit}</span>`;
					},
					style: {
						color: '#ADADAD'
					},
					useHTML: true
				},
				credits: {
					enabled: false
				},
				plotOptions: {
					area: {
						fillOpacity: 0.3
					}
				},
				series: seriesData
			});
		}



	}])


	;
