﻿angular.module('toolsApp', ['rzModule', 'ngSanitize'])
	.controller('marketWatchCtrl', ['$global', '$scope', '$http', '$q', '$location', '$filter', '$uibModal', '$timeout', function ($global, $scope, $http, $q, $location, $filter, $uibModal, $timeout) {
		var self = this;
		$scope.auth = undefined;
		$scope.markets = [];
		$scope.marketData = [];
		$scope.mapData = [];
		$scope.init = function (data, auth) {
			$scope.auth = Number(auth);
			$scope.AllData = data;
			$scope.markets = data.stockMarkets;
			$scope.marketData = data.marketData;
      $scope.marketSummary = data.marketSummary;
      $scope.loadWatchIndexData();
			var sectors = $filter('unique')($scope.marketData.map(function (elem) { return elem.Sector; }).clean());
			$filter('unique')(sectors.map(function (sector) {
				$scope.mapData.push({
					Text: $.grep($scope.marketData, function (s) { if (s.Sector === sector) return s.SectorAbbr; }).firstOrDefault().SectorAbbr,
					Value: $scope.marketData.map(function (x) { if (x.Sector === sector) return x.MarketCap; }).clean().sum()
				});
			})
			);

			$timeout(function () {
				self.createMarketCapsTreeMap($scope.mapData);
				self.createTopMarketCapChart();
				self.createMarketSummaryCharts($scope.marketSummary);
				$('#collapseOne').collapse("hide");
				$('#collapseTwo').collapse("hide");
        $(".table-fixedHeader").stickyTableHeaders({ fixedOffset: 65 });
       
			});
		}
		$scope.loadWatchIndexData = (() => {
			if (!$filter('empty')($scope.marketWatchIndexModel)) return;
			blockUI('accordion3');
			$http({
				url: siteRoot + 'tools/marketwatch',
				data: { marketId: $scope.marketData[0].StockMarketID, market: $scope.marketData[0].EngStockMarket },
				method: 'POST'
			}).then((res) => {
				$scope.marketWatchIndexModel = res.data;
			}, (error) => { unblockUI('accordion3'); console.log(error.data); })
				.finally(() => {
					unblockUI('accordion3');
				});
		});
		this.createMarketCapsTreeMap = function (data) {
			var mapData = [];
			var colors = Highcharts.getOptions().colors;
			var i = 0;
			data.map(function (v) {
				if (v !== undefined && parseFloat(v.Value) > 0) {
					mapData.push({
						id: v.Text,
						name: v.Text,
						value: v.Value,
						color: colors[i]
					});
					i++;
				}
				if (i > colors.length)
					i = 0;
			});

			new Highcharts.chart({
				chart: {
					renderTo: 'mcTreeMap',
					backgroundColor: '#000',
					borderColor: '#3a3a3a',
				},
				tooltip: {
					formatter: function () {
						return '<b>' + this.point.options.name + '</b> (<small>' + $global.getResources("lblMarketCap") + '</small>): ' + $filter('Abbr')(parseFloat(this.point.options.value));
					},
					style: {
						"fontSize": "12px",
						color: '#ADADAD'
					}
				},
				plotOptions: {
					series: {
						cursor: 'pointer'
					},
					treemap: {
						dataLabels: {
							align: 'center',
							enabled: true,
							style: {
								"fontSize": "9px"
							},
							verticalAlign: "middle",
						},
						events: {
							click: function (event) {
								self.showCompanyHM(event.point.name);
							}
						}
					}
				},
				series: [{
					type: "treemap",
					layoutAlgorithm: 'squarified',
					data: mapData
				}],
				title: {
					text: ''
				}
			});
		}
		this.createTopMarketCapChart = function () {
			var data = $filter('limitTo')($filter('orderBy')($scope.marketData, 'MarketCap', true, true), 5, 0);
			var xdata = [], ydata = [], i = 20;
			data.map(function (elem) {
				xdata.push(
					elem.CompanyTicker
				);
				ydata.push({ y: elem.MarketCap, color: LightenDarkenColor('#000FB3', i) });
				i = i + 20;

			});
			new Highcharts.chart({
				chart: {
					renderTo: 'topmarketCh',
					type: 'column',
					margin: [60, 0, 10, 10],
					backgroundColor: '#000',
					borderColor: '#3a3a3a',
					borderRadius: 0,
					borderWidth: 1,
					backgroundColor: Highcharts.getOptions().backgroundColor
				},
				title: {
					text: 'Top Market Cap',
					style: {
						fontSize: '12px'
					}
				},
				subtitle: {
					text: ''
				},
				xAxis: {
					opposite: !0,
					categories: xdata,
					labels: {
						distance: 0,
						style: {
							'fontSize': '8px',
							color: '#ADADAD'
						}
					}
				},
				yAxis: {
					min: 0,
					title: {
						text: ''
					},
					labels: {
						style: {
							'fontSize': '9px'
						},
						x: -5,
						style: {
							color:'#ADADAD'
                        },
						enabled: !1

					},
					gridLineWidth: 0,
					lineWidth: 1,
				},
				tooltip: {
					shared: true,
					useHTML: true,
					formatter: function () {
						var html = this.x + ': ' + $filter('Abbr')(this.y);
						html += '<br/>' + $global.getResources("lblClickToView") + '<b> ' + this.x + '</b> ' + $global.getResources("lblProfile");
						return html;
					},
					style: {
						color: '#000'
					}
				},
				plotOptions: {
					series: {
						cursor: 'pointer',
						borderWidth: 0,
						dataLabels: {
							enabled: true,
							overflow: 'justify',
							allowOverlap: true,
							//formatter: function () {
							//  return '<div style="text-align:right"> <span>' + $filter('Abbr')(this.point.y) + '</span><span style="font-weight: bold">' + " " + '</span> </div>';
							//},
							style: {
								direction: 'ltr'
							},
							rotation: 0,
							crop: false,
						},
						events: {
							click: function (event) {
								var point = event.point.category;
								var url = $.grep($scope.marketData, function (elem) { return elem.CompanyTicker === point; }).firstOrDefault().CompanyURL;
								if (url !== undefined)
									window.open($filter('getURL')(url), '_blank');
							}
						}

					},
					column: {
						pointWidth: 40,
						pointPadding: 0,
						borderWidth: 0,
						dataLabels: {
							enabled: true,
							formatter: function () {
								return $filter('Abbr')(this.y);
							},
							style: {
								fontSize: '9px',
								fontWeight: 'normal'
							}
						}
					},

				},
				legend: {
					enabled: false,
				},
				colorAxis: {
					minColor: '#FFFFFF',
					maxColor: Highcharts.getOptions().colors[0]
				},
				series: [{
					name: 'Top Market Caps',
					data: ydata
				}]
			});

		}
		this.createMarketSummaryCharts = function (data) {
			var summary = ['Gainners', 'Decliners', 'Active'];
			summary.forEach(function (type) {
				var marketSummary = data.map(function (v) { if (v.Type === type) return v; }).clean();
				var xdata = [], i = 0, ydata = [];
				marketSummary.map(function (elem) {
					xdata.push(elem.Ticker);
					ydata.push({ y: type === "Active" ? elem.TradingVolume : elem.ChangePer, color: type === 'Gainners' ? '#90ed7d' : type === "Decliners" ? '#FF2A2A' : LightenDarkenColor('#E45400', i) })
					i += 25;
				});
				var title = type === 'Decliners' ? 'Losers' : (type === 'Active' ? 'Most Active' : type === 'Gainners' ? 'Gainers' : '');

				new Highcharts.chart({
					chart: {
						renderTo: type,
						type: 'column',
						margin: [70, 20, 10, 20],
						backgroundColor: '#000',
						borderColor: '#3a3a3a',
						borderRadius: 0,
						borderWidth: 1,
						backgroundColor: Highcharts.getOptions().backgroundColor
					},
					title: {
						text: title,
						style: {
							"fontSize": "13px",
							color:'#ADADAD'
						}
					},
					legend: {
						enabled: false
					},

					xAxis: {
						opposite: !0,
						labels: {
							style: {
								color: '#ADADAD',
								width: '100px',
								textOverflow: 'none',
								fontSize: '8px'
							},
							formatter: function () {
								return WNOrDecimal(this.value);
							},
							enabled: true

						},
						useHTML: true,
						categories: xdata,
					},
					yAxis: {
						title: '',
						labels: {
							style: {
								width: '80px',
								color: '#ADADAD',
								textOverflow: 'none'
							},
							formatter: function () {
								return this.value;
							},
							enabled: !1,
							x: -5,
							y: 0
						},
						gridLineWidth: 0,
						lineWidth: 1,

					},
					tooltip: {
						style: {
							fontSize: '11px',
							color: '#ADADAD',
							fontWeight: 'normal'
						},
						formatter: function () {
							var html = '';
							if (type === 'Active')
								html = '<b>' + this.x + '</b>: ' + $filter('Abbr')(this.y);
							else
								html = '<b>' + this.x + '</b>: ' + (this.y) + '%';
							html += '<br/> Click to view <b>' + this.point.category + '</b> profile.';
							return html;
						},
						style: {
							color: '#000'
						}
					},
					plotOptions: {
						column: {
							pointWidth: 40,
							pointPadding: 0,
							borderWidth: 0,
						},
						series: {
							cursor: 'pointer',
							dataLabels: {
								enabled: true,
								overflow: 'justify',
								allowOverlap: true,
								formatter: function () {
									if (type === 'Active')
										return $filter('Abbr')(this.y);
									else
										return WNOrDecimal(this.y) + '%';
								},
								style: {
									direction: 'ltr'
								},
								rotation: 0,
								crop: false,
							},
							events: {
								click: function (event) {
									var point = event.point.category;
									var url = $.grep(data, function (elem) { return elem.Ticker === point; }).firstOrDefault().CompanyURL;
									if (url !== undefined)
										window.open($filter('getURL')(url), '_blank');
								}
							}
						}
					},
					credits: {
						enabled: false
					},
					series: [{
						name: '',
						data: ydata
					}]
				});
			});
		}

		this.showCompanyHM = function (sector) {
			var modalInstance = $uibModal.open({
				template: `<div style="width:520px;"><div class="modal-body"><div ng-if="auth>1" id="popupchart" style="width:100%; height:420px;"></div><div> <a title="{{'lblPremiumOnly'|getLabel}}" ng-if="auth<2" ng-href="{{auth|authLink}}"><img style="width:100%; height:420px;" src="/Content/Theme/images/lockimages/heatmap.png" /></a> </di></div><div class="modal-footer"><button class="btn btn-primary btn-sm" ng-click="Close()">Close</button></div></div>`,
				controller: 'HeatMapPopupCtrl',
				scope: $scope,
				windowClass: 'app-modal-window',
				resolve: {
					'data': { s: sector, d: $scope.marketData, auth: $scope.auth }
				}
			});
		}


		/**Sorting*/
		//companies view sorting
		$scope.cVwSort = {
			column: 'CompanyTicker',
			descending: false
		};

		$scope.CVClass = function (column) {
			return column == $scope.cVwSort.column ? $scope.cVwSort.descending ? "sorting_asc" : "sorting_desc" : 'sorting';
		};
		$scope.cVwChange = function (column) {

			if ($scope.cVwSort.column == column) {
				$scope.cVwSort.descending = !$scope.cVwSort.descending;
			} else {
				$scope.cVwSort.column = column;
				$scope.cVwSort.descending = false;
			}
		};
		//End companies Sorting

		//sectors view sorting
		$scope.sVwSort = {
			column: 'SortOrder',
			descending: false
		};

		$scope.sVClass = function (column) {
			return column == $scope.sVwSort.column ? $scope.sVwSort.descending ? "sorting_asc" : "sorting_desc" : 'sorting';
		};
		$scope.sVwChange = function (column) {

			if ($scope.sVwSort.column == column) {
				$scope.sVwSort.descending = !$scope.sVwSort.descending;
			} else {
				$scope.sVwSort.column = column;
				$scope.sVwSort.descending = false;
			}
		};
		//End companies Sorting
	}])
	.controller('HeatMapPopupCtrl', ['$global', '$scope', '$uibModalInstance', '$filter', 'data', function ($global, $scope, $uibModalInstance, $filter, data) {
		var self = this;

		$uibModalInstance.rendered.then(() => {
			var d = data.d;
			var s = data.s;
			$scope.s = s;
			$scope.auth = data.auth;
			$scope.auth > 1 && self.createHMap(s, d);
		});
		$scope.Close = function () {
			$uibModalInstance.close();
		};
		this.createHMap = function (sector, data) {
			var mapData = [];
			var colors = Highcharts.getOptions().colors;
			data = data.map(function (o) { if (o.SectorAbbr === sector) return o; }).clean();
			$scope.s = data[0].Sector;
			var i = 0;
			data.map(function (v) {
				if (v !== undefined && parseFloat(v.MarketCap) > 0) {
					mapData.push({
						id: v.CompanyTicker,
						name: v.CompanyTicker,
						value: v.MarketCap,
						color: colors[i]
					});
				}
				i++;
				if (i > colors.length)
					i = 0;
			});
			new Highcharts.chart({
				chart: {
					renderTo: 'popupchart',
					backgroundColor: '#000',
					borderColor: '#3a3a3a',
				},
				title: {
					text: sector,
					style: {
						'fontSize': '13px',
						color:'#ADADAD'
					}
				},
				tooltip: {
					formatter: function () {
						var html = '<b>' + this.point.options.name + '</b> (<small>' + $global.getResources("lblMarketCap") + '</small>): ' + $filter('Abbr')(parseFloat(this.point.options.value));
						html += '<br/>' + $global.getResources("lblClickToView") + '<b> ' + this.point.name + ' </b> ' + $global.getResources("lblProfile");

						return html;
					},
					style: {
						"fontSize": "12px",
						color: '#ADADAD'
					}
				},
				plotOptions: {
					series: {
						cursor: 'pointer'
					},
					treemap: {
						dataLabels: {
							align: 'center',
							enabled: true,
							style: {
								"fontSize": "11px"
							},
							verticalAlign: "middle",
						},
						events: {
							click: function (event) {
								var point = event.point.name;
								var url = data !== undefined && data.length && $.grep(data, function (elem) { return elem.CompanyTicker === point; }) !== undefined && $.grep(data, function (elem) { return elem.CompanyTicker === point; }).length ? $.grep(data, function (elem) { return elem.CompanyTicker === point; }).firstOrDefault().CompanyURL : undefined;
								if (url !== undefined)
									window.open($filter('getURL')(url), '_blank');

							}
						}
					}
				},
				series: [{
					type: "treemap",
					layoutAlgorithm: 'squarified',
					data: mapData
				}],

			});


		}

	}])
	.controller('toolsMarketIndexCtrl', ['$global', '$scope', '$http', '$q', '$location', '$filter', '$timeout', '$log', function ($global, $scope, $http, $q, $location, $filter, $timeout, $log) {
		var self = this;
		$scope.stockMarketID = 0;
		$scope.model = {};
		$scope.chartConst = {
			is50DayMA: false,
			is200DayMA: false,
			isTrendLine: false
		};
		$scope.chart = undefined;
		$scope.auth = undefined;
		$scope.init = function (model, auth) {
			$scope.model = model;
			$scope.stockMarketID = model.StockMarketID;
			$scope.auth = Number(auth);
		}
		$scope.$watchCollection('chartConst', function (newValues, oldValues) {
			if ($scope.chart === undefined) return;
			var s50Obj = $.grep($scope.chart.series, (elem) => { return elem.name === '50-day SMA'; }).firstOrDefault();
			if (!angular.isFunction(s50Obj)) {
				if ($scope.chartConst.is50DayMA) {
					$scope.chart.series[s50Obj.index].update({
						visible: true
					});
				}
				else {
					$scope.chart.series[s50Obj.index].update({
						visible: false
					});
				}
			}
			var s200Obj = $.grep($scope.chart.series, (elem) => { return elem.name === '200-day SMA'; }).firstOrDefault();
			if (!angular.isFunction(s200Obj)) {
				if ($scope.chartConst.is200DayMA) {
					$scope.chart.series[s200Obj.index].update({
						visible: true
					});
				}
				else {
					$scope.chart.series[s200Obj.index].update({
						visible: false
					});
				}
			}
			var trendLine = $.grep($scope.chart.series, (elem) => { return elem.name === 'Linear Trendline'; }).firstOrDefault();
			if (!angular.isFunction(trendLine)) {
				if ($scope.chartConst.isTrendLine) {
					$scope.chart.series[trendLine.index].update({
						visible: true
					});
				}
				else {
					$scope.chart.series[trendLine.index].update({
						visible: false
					});
				}
			}
		});

		var drpMarkets = document.getElementById("drpMarkets");
		$scope.market = drpMarkets.options[drpMarkets.selectedIndex].text;
		$scope.stockMarketID = drpMarkets.value;
		$timeout(() => {
			angular.element(document.getElementsByClassName('official-index-section')[0]).trigger('click');
		});
		$scope.detail = [];
		$scope.$on('hotNewsFinish', function (hotNewsFinishEvent) {
			$(".hot-news").ticker({
				start_item: 1,
				transition_interval: 7000,
				pause_on_hover: true
			});

		});
		let prevTitle = '';
		$scope.loadData = function (stockMarketId, sectorId, title, capsize, $event) {

			if (prevTitle === title) {
				$scope.chartConst.isTrendLine = !$scope.chartConst.isTrendLine;
				return;
			}
			if (title !== undefined) {
				$scope.market = title;
				prevTitle = title;
			}

			if ($event !== undefined) {
				$('.market-active').removeClass('market-active');
				$($event.currentTarget).addClass('market-active');
			}
			blockUI('secIndices');
			$http({
				url: siteRoot + 'tools/officialindices',
				method: 'post',
				data: { marketId: stockMarketId, sid: sectorId, capsize: capsize }
			}).then(function (res) {
				self.createChart(res.data.officialIndices, res.data.detail);
				$scope.detail = res.data.detail;

			}, (error) => { unblockUI('secIndices'); console.log(error.data); }).then(function () {
				unblockUI('secIndices');
			});
		}
		this.createChart = function (chartData, detail) {
			var pdata = [], vdata = [];
			var url = chartData[0].URL;
			chartData.map(function (e) {
				pdata.push([parseInt(e.Date.slice(6, -2)), parseFloat(e.Closing)]);
				vdata.push([parseInt(e.Date.slice(6, -2)), parseInt(e.Volume)]);
			});
			$scope.market = chartData[0].SectorID === 0 ? detail.StockMarket : $scope.market;

			let min = Number(chartData[0].MinDate.slice(6, -2));
			let max = Number(chartData[0].MaxDate.slice(6, -2));
			let linTrendData = $.grep(pdata, (elem) => { return elem[0] >= min && elem[0] <= max; })
			$scope.IndexDetail = $filter('getURL')(detail.IndexDetail);
			// Create the chart
			new Highcharts.stockChart('officialIndicechart', {
				chart: {
					borderColor: '#3a3a3a',
					borderWidth: 0,
					plotBackgroundColor: '',
					backgroundColor: '#000',
					panning: false
				},
				watermark: {
					yAxis: 150
				},
				title: {
					text: '',
					align: Highcharts.getOptions().direction,
					x: 0,
					style: {
						color: '#222'
					},
					useHTML: !0
				},
				yAxis: [{
					gridLineColor: '#3a3a3a',
					lineColor: '#3a3a3a',
					lineWidth: 1,
					className: 'ltr',
					labels: {
						align: 'left',
						formatter: function () {
							return $filter('WNOrDec')(this.value, 0);
						},
						x: 5,
						style: {
							color: '#ADADAD',
						}
					},
					height: 150,
					tickPositioner: function () {
						var positions = [],
							tick = Math.floor(this.dataMin),
							increment = Math.ceil((this.dataMax - this.dataMin) / 4);

						if (this.dataMax !== null && this.dataMin !== null) {
							for (tick; tick - increment <= this.dataMax; tick += increment) {
								positions.push(tick);
							}
						}
						return positions;
					},
					plotLines: [{
						color: Highcharts.getOptions().horizontalLineColor,
						dashStyle: Highcharts.getOptions().horizontalLineStyle,
						width: 1,
						value: chartData[0].Average,
						label: {
							text: '',
							x: -10
						},
						zIndex: 3
					}]
				},
				{
					gridLineColor: '#3a3a3a',
					alternateGridColor: '#3a3a3a',
					lineColor: '#3a3a3a',
					lineWidth: 1,
					opposite: true,
					labels: {
						align: 'left',
						formatter: function () {
							return '<span class="ltr text-normal">' + $filter('Abbr')(this.value, 0) + '</span>';
						},
						x: 5,
						style: {
							color: '#ADADAD',
						},
						useHTML: true
					},
					top: 170,
					height: 90,
					offset: 0,
					tickPositioner: function () {
						var positions = [],
							tick = Math.floor(this.dataMin),
							increment = Math.ceil((this.dataMax - this.dataMin) / 3);

						if (this.dataMax !== null && this.dataMin !== null) {
							for (tick; tick - increment <= this.dataMax; tick += increment) {
								positions.push(tick);
							}
						}
						return positions;
					}
				}],
				legend: {
					enabled: false
				},
				xAxis: {
					gridLineColor: '#3a3a3a',
					lineColor: '#3a3a3a',
					min: parseInt(chartData[0].MinDate.slice(6, -2)),
					labels: {
						formatter: function () {
							return Highcharts.dateFormat('%d/%m  ', this.value);
						},
						style: {
							color: '#ADADAD'
						}
					}
				},
				scrollbar: {
					enabled: false
				},
				rangeSelector: {
					enabled: false
				},
				navigator: {
					enabled: false
				},
				exporting: {
					enabled: false
				},
				tooltip: {
					formatter: function () {
						var tooltipHtml = '';
						try {
							tooltipHtml = '<div class="col-md-12 padding-5 ltr defualt-color"><p><b>' + $filter('getLabel')('lblDate') + ': </b> ' + Highcharts.dateFormat('%b %e, %Y', new Date(this.points[0].x)) + ' </p>';
							var primary = $.grep(this.points, function (elem) { return elem.series.name === 'primary'; }).firstOrDefault();
							if (!angular.isFunction(primary)) {
								tooltipHtml += '<b><p style="color:' + primary.series.color + '">' + $filter('getLabel')('lblClosing') + ': </b>' + $filter('AbbrOrWNOrDec')(primary.y, 2) + "</p>";
							}
							var smas = $.grep(this.points, function (elem) { return elem.series.name.indexOf('SMA') !== -1; });
							if (smas.length > 0) {
								angular.forEach(smas, function (sm) {
									tooltipHtml += '<b><p style="color:' + sm.series.color + '">' + sm.series.options.dname + ': </b>' + $filter('AbbrOrWNOrDec')(sm.y, 2) + "</p>";
								});
							}
							var vol = $.grep(this.points, function (elem) { return elem.series.name === 'Volume'; }).firstOrDefault();
							if (vol !== undefined)
								tooltipHtml += '<b><p style="color:' + vol.series.color + '">' + $filter('getLabel')('lblVolume') + ': </b> ' + $filter('AbbrOrWNOrDec')(vol.y, 2) + '</p>' + "</div>";

						} catch (e) {

						}
						return tooltipHtml;
					}
				},
				series: [{
					name: 'primary',
					dname: $scope.market,
					id: 'primary',
					data: pdata,
					color: '#18A97E',
					type: 'line',
					threshold: null,
					dataGrouping: {
						forced: true,
						units: [['day', [1]]]
					}
				},
				{
					id: 'SMA-1',
					name: '50-day SMA',
					dname: '50-' + $filter('getLabel')('lbldaySMA'),
					linkedTo: 'primary',
					showInLegend: true,
					type: 'trendline',
					lineWidth: 2,
					algorithm: 'SMA',
					color: '#FF8000',
					periods: 50,
					visible: $scope.chartConst.is50DayMA,
					dataGrouping: {
						forced: true,
						units: [['day', [1]]]
					}
				},
				{
					id: 'SMA-2',
					name: '200-day SMA',
					dname: '200-' + $filter('getLabel')('lbldaySMA'),
					linkedTo: 'primary',
					showInLegend: true,
					type: 'trendline',
					lineWidth: 2,
					algorithm: 'SMA',
					color: '#FF5500',
					periods: 200,
					visible: $scope.chartConst.is200DayMA,
					dataGrouping: {
						forced: true,
						units: [['day', [1]]]
					}
				},
				{
					name: 'Linear Trendline',
					id: 'ltrLine',
					dname: $filter('getLabel')('lblLinearTrendline'),
					color: '#666',
					defaultSeriesType: 'spline',
					lineWidth: 2,
					threshold: null,
					visible: $scope.chartConst.isTrendLine,
					enableMouseTracking: false,
					data: (function () {
						return fitData(linTrendData).data.map((elem, i, arr) => { if (i === 0 || i === arr.length - 1) return elem; }).clean();
					})(),
					dataGrouping: {
						forced: true,
						units: [['month', [1]]]
					}
				},
				{
					type: 'column',
					id: 'volume',
					name: 'Volume',
					color: '#ADADAD',
					data: vdata,
					yAxis: 1,
					dataGrouping: {
						forced: true,
						units: [['day', [1]]]
					}
				}]
			}, function (chart) {
				$scope.chart = chart;
			});
		}
		$scope.loadActiveGainersDecliners = (($inview) => {
			if (!$inview || !$filter('empty')($scope.activeGainersDecliners)) return;
			blockUI('gainerlosers');
			$http({
				url: siteRoot + 'tools/officialindices/',
				method: 'post',
				data: { marketId: $scope.stockMarketID, agd: true },

			}).then(function (resp) {
				$scope.activeGainersDecliners = resp.data;
			}, (error) => { unblockUI('gainerlosers'); console.log(error.data); })
				.finally(function () {
					unblockUI('gainerlosers');
				});




		});




		$scope.loadRecommendations = (($inview) => {
			if (!$inview || !$filter('empty')($scope.recommendations)) return;
			//get news
			blockUI('accordion7');
			$http({
				url: siteRoot + 'tools/officialindices/',
				method: 'post',
				data: { marketId: $scope.stockMarketID, news: true },

			}).then(function (resp) {
				$scope.recommendations = resp.data.recommendations;
				$timeout(function () {
					CreateRecommendationCharts()
				});
			}, (error) => { unblockUI('accordion7'); console.log(error.data); })
				.finally(function () {
					unblockUI('accordion7');
				});
		});
		function CreateRecommendationCharts() {
			var align = parseInt(lang) === 1 ? "right" : "left";
			var margin = parseInt(lang) === 1 ? [15, 15, 25, 110] : [15, 15, 25, 70];
			$('.recommendationCharts').each(function (d) {
				var r = $(this).data('val');
				new Highcharts.chart({
					chart: {
						renderTo: this,
						type: 'bar',
						backgroundColor: '#000',
						borderColor: '#3a3a3a',
						plotBackgroundColor: '',
						margin: margin,
						panning: false
					},
					watermark: {
						text: ''
					},
					title: {
						text: ''
					},
					legend: {
						enabled: false
					},
					xAxis: {
						labels: {
							style: {
								width: '100px',
								textOverflow: 'none',
								color: '#ADADAD'
							},
							formatter: function () {
								return WNOrDecimal(this.value);
							},
							align: align,
							enabled: true
						},
						useHTML: true,
						categories: [$global.getResources("lblCPrice"), $global.getResources("lblPriceRecommendationDate"), $global.getResources("lblFairValue")]
					},
					yAxis: {
						title: '',
						gridLineWidth: 0,
						lineWidth: 1,
						labels: {
							style: {
								color: '#ADADAD'
							}
						}
					},
					tooltip: {
						formatter: function () {
							return '<b>' + this.x + '</b>: ' + WNOrDecimal(this.y);
						},
						style: {
							color: '#ADADAD'
						}
					},
					plotOptions: {
						series: {
							dataLabels: {
								align: 'left',
								enabled: true,
								formatter: function () {
									return WNOrDecimal(this.y);
								}
							}
						}
					},
					credits: {
						enabled: false
					},
					exporting: {
						enabled: false
					},
					series: [{
						name: '',
						data: [{
							color: '#4d83c5',
							y: r.CurrentPrice,
						},
						{
							color: '#ee9e1f',
							y: r.MarketPrice,
						},
						{
							color: '#eb564e',
							y: r.FairValue,
						}]
					}],
				});

			});
		}

	}])
	.controller('toolsOfficialIndexDetailCtrl', ['$global', '$scope', '$http', '$q', '$location', '$filter', '$timeout', '$log', function ($global, $scope, $http, $q, $location, $filter, $timeout, $log) {
		var self = this;
		$scope.chartConst = {
			is50DayMA: false,
			is200DayMA: false,
			isTrendLine: false
		};
		$scope.trendLineData = [];
		$scope.min = undefined,
			$scope.max = undefined;
		$scope.chart = undefined;
		$scope.auth = undefined;
		$scope.marketInfo = null;
		$scope.momentum = [];
		$scope.indicesChart = [];

		$scope.$watchCollection('chartConst', function (newValues, oldValues) {
			if ($scope.chart === undefined) return;
			var s50Obj = $.grep($scope.chart.series, (elem) => { return elem.name === '50-day SMA'; }).firstOrDefault();
			if (!angular.isFunction(s50Obj)) {
				if ($scope.chartConst.is50DayMA) {
					$scope.chart.series[s50Obj.index].update({
						visible: true
					});
				}
				else {
					$scope.chart.series[s50Obj.index].update({
						visible: false
					});
				}
			}
			var s200Obj = $.grep($scope.chart.series, (elem) => { return elem.name === '200-day SMA'; }).firstOrDefault();
			if (!angular.isFunction(s200Obj)) {
				if ($scope.chartConst.is200DayMA) {
					$scope.chart.series[s200Obj.index].update({
						visible: true
					});
				}
				else {
					$scope.chart.series[s200Obj.index].update({
						visible: false
					});
				}
			}
			var trendLine = $.grep($scope.chart.series, (elem) => { return elem.name === 'Linear Trendline'; }).firstOrDefault();
			if (!angular.isFunction(trendLine)) {
				if ($scope.chartConst.isTrendLine) {
					$scope.chart.series[trendLine.index].update({
						visible: true,
						data: (function () {
							return fitData($scope.trendLineData).data.map((elem, i, arr) => { if (i === 0 || i === arr.length - 1) return elem; }).clean();
						})(),
					});
				}
				else {
					$scope.chart.series[trendLine.index].update({
						visible: false
					});
				}
			}
		});

		$scope.init = function (model, auth) {
			$scope.model = model;
			$scope.auth = Number(auth);
			blockUI('toolsOfficialIndexDetailCtrl');
			$http({
				url: siteRoot + 'tools/officialindexdetail/',
				method: 'post',
				data: { stockMarketID: model.StockMarketID, sectorId: model.SectorID, IsCapsize: model.IsCapsize, flag: 1 }

			}).then(function (resp) {
				$scope.indicesChart.push(resp.data.indicesChart);
				self.createChart(resp.data.indicesChart);
				$scope.momentum = resp.data.momentum;

			}, (error) => { unblockUI('toolsOfficialIndexDetailCtrl'); console.log(error.data); })
				.finally(function () {
					unblockUI('toolsOfficialIndexDetailCtrl');
				});

		}

		this.createChart = function (chartData) {
			var data = [], chart, cdata = [], price = [];
			chartData !== null && chartData.map(function (elem) {
				var date = parseInt(elem.Date.slice(6, -2));
				var value = parseFloat(elem.Closing);
				var volume = parseInt(elem.Volume);;
				data.push([date, value]);
				cdata.push([date, volume]);
			});
			$scope.min = parseInt(chartData[0].MinDate.slice(6, -2));
			$scope.max = parseInt(chartData[0].MaxDate.slice(6, -2));

			$scope.trendLineData = $.grep(data, (elem) => { return elem[0] >= $scope.min && elem[0] <= $scope.max; });

			new Highcharts.stockChart({
				chart: {
					renderTo: 'indexDetailChart',
					borderColor: '#FAFAFA',
					borderWidth: 1,
					plotBackgroundColor: '',
					margin: [5, 75, 25, 5],
					panning: false
				},
				watermark: {
					yAxis: 230
				},
				navigator: {
					xAxis: {
						//min: parseInt(chartData[0].MinDate.slice(6, -2)),
						type: 'datetime',
						labels: {
							formatter: function () {
								return Highcharts.dateFormat('%d/%m/%y', this.value);
							},
							style: {
								color: '#222'
							},
							x: -3
						},
					},
				},
				rangeSelector: {
					allButtonsEnabled: true,
					selected: 4,
					inputEnabled: false,
					inputBoxBorderColor: "#cccccc",
					inputBoxHeight: 17,
					inputBoxWidth: 90,
					inputDateFormat: "%b %e %Y,",
					inputDateParser: null,
					inputEditDateFormat: "%Y-%m-%d",
					inputPosition: { align: "right" },
					buttonTheme: {
						useHTML: true,

						fill: 'none',
						stroke: 'none',
						'stroke-width': 0,
						r: 8,
						style: {
							color: '#039',
							fontWeight: 'bold',
							direction: 'ltr'
						},
						states: {
							hover: {
							},
							select: {
								style: {
									color: 'black'
								}
							}
						}
					},
					buttons: [{
						type: 'month',
						count: 1,
						text: $filter('getLabel')('lbl1m')
					}, {
						type: 'month',
						count: 3,
						text: $filter('getLabel')('lbl3m')
					}, {
						type: 'month',
						count: 6,
						text: $filter('getLabel')('lbl6m')
					}, {
						type: 'ytd',
						text: $filter('getLabel')('lblytd')
					}, {
						type: 'year',
						count: 1,
						text: $filter('getLabel')('lbl1y')
					}]
				},
				exporting: {
					enabled: !1
				},
				scrollbar: {
					barBackgroundColor: 'gray',
					barBorderRadius: 7,
					barBorderWidth: 0,
					buttonBackgroundColor: 'gray',
					buttonBorderWidth: 0,
					buttonBorderRadius: 7,
					trackBackgroundColor: 'none',
					trackBorderWidth: 1,
					trackBorderRadius: 8,
					trackBorderColor: '#CCC'
				},
				title: {
					text: '',
					x: -20 //center
				},
				subtitle: {
					text: '',
					x: -20
				},
				xAxis: {
					min: parseInt(chartData[0].MinDate.slice(6, -2)),
					tickInterval: 10,
					min: 0,
					max: null,
					type: 'datetime',
					labels: {
						formatter: function () {
							return Highcharts.dateFormat('%d/%m/%y', this.value);
						},
						style: {
							color: '#222'
						},
						x: -3
					},
					events: {
						afterSetExtremes: function (event) {
							let tchart = this.chart;
							$scope.min = event.min;
							$scope.max = event.max;
							let tempData = [];
							$timeout(function () {
								//plot line update
								chartData.map(function (elem, i) {
									let date = parseInt(elem.Date.slice(6, -2));
									if (date > $scope.min && date < $scope.max) {
										tempData.push(parseFloat(elem.Closing));
									}
								});
								if (tempData.length > 0) {
									tchart.yAxis[0].removePlotLine('pltLine');
									tchart.yAxis[0].addPlotLine({
										id: 'pltLine',
										color: Highcharts.getOptions().horizontalLineColor,
										dashStyle: Highcharts.getOptions().horizontalLineStyle,
										width: 1,
										value: tempData.sum() / tempData.length,
										label: {
											text: '',
											x: -10
										},
										zIndex: 3
									});
								}

								// trendline update
								$scope.trendLineData = $.grep(data, (elem) => { return elem[0] >= $scope.min && elem[0] <= $scope.max; });
								var trendLine = $.grep($scope.chart.series, (elem) => { return elem.name === 'Linear Trendline'; }).firstOrDefault();
								if (!angular.isFunction(trendLine)) {
									$scope.chart.series[trendLine.index].update({
										data: (function () {
											return fitData($scope.trendLineData).data.map((elem, i, arr) => { if (i === 0 || i === arr.length - 1) return elem; }).clean();
										})()
									});
								}
							});
						}
					}
				},
				plotOptions: {
					line: {
						marker: {
							enabled: false
						}
					}
				},
				yAxis: [{
					gridLineColor: '#ececec',
					//alternateGridColor: '#FeFeFe',
					lineColor: '#ccc',
					lineWidth: 1,
					className: 'ltr',
					labels: {
						align: 'left',
						formatter: function () {
							return $filter('WNOrDec')(this.value, 0);
						},
						x: 5,
						style: {
							color: '#222',
						}
					},
					height: 200,
					tickPositioner: function () {
						var positions = [],
							tick = Math.floor(this.dataMin),
							increment = Math.ceil((this.dataMax - this.dataMin) / 6);

						if (this.dataMax !== null && this.dataMin !== null) {
							for (tick; tick - increment <= this.dataMax; tick += increment) {
								positions.push(tick);
							}
						}
						return positions;
					},
					plotLines: [{
						id: 'pltLine',
						color: Highcharts.getOptions().horizontalLineColor,
						dashStyle: Highcharts.getOptions().horizontalLineStyle,
						width: 1,
						value: chartData[0].Average,
						label: {
							text: '',
							x: -10
						},
						zIndex: 3
					}]
				},
				{
					gridLineColor: '#ececec',
					alternateGridColor: '#FeFeFe',
					lineColor: '#ccc',
					lineWidth: 1,
					opposite: true,
					labels: {
						align: 'left',
						formatter: function () {
							return '<label class="ltr text-normal">' + $filter('Abbr')(this.value, 0) + '</label>';
						},
						x: 5,
						style: {
							color: '#222',
						},
						useHTML: true
					},
					top: 250,
					height: 120,
					offset: 0,
					tickPositioner: function () {
						var positions = [],
							tick = Math.floor(this.dataMin),
							increment = Math.ceil((this.dataMax - this.dataMin) / 3);

						if (this.dataMax !== null && this.dataMin !== null) {
							for (tick; tick - increment <= this.dataMax; tick += increment) {
								positions.push(tick);
							}
						}
						return positions;
					}
				}],

				credits: {
					enabled: false
				},
				legend: {
					layout: 'vertical',
					align: 'right',
					verticalAlign: 'middle',
					borderWidth: 0,
					enabled: false
				},
				tooltip: {
					headerFormat: '',
					useHTML: true,
					formatter: function () {
						var tooltipHtml = '';
						try {
							tooltipHtml = '<div class="col-md-12 padding-5 ltr defualt-color"><p><b>' + $filter('getLabel')('lblDate') + ': </b> ' + Highcharts.dateFormat('%b %e, %Y', new Date(this.points[0].x)) + ' </p>';
							var primary = $.grep(this.points, function (elem) { return elem.series.name === 'primary'; }).firstOrDefault();
							if (!angular.isFunction(primary)) {
								tooltipHtml += '<b><p style="color:' + primary.series.color + '">' + $filter('getLabel')('lblClosing') + ': </b>' + $filter('AbbrOrWNOrDec')(primary.y, 2) + "</p>";
							}
							var smas = $.grep(this.points, function (elem) { return elem.series.name.indexOf('SMA') !== -1; });
							if (smas.length > 0) {
								angular.forEach(smas, function (sm) {
									tooltipHtml += '<b><p style="color:' + sm.series.color + '">' + sm.series.options.dname + ': </b>' + $filter('AbbrOrWNOrDec')(sm.y, 2) + "</p>";
								});
							}
							var vol = $.grep(this.points, function (elem) { return elem.series.name === 'Volume'; }).firstOrDefault();
							if (vol !== undefined)
								tooltipHtml += '<b><p style="color:' + vol.series.color + '">' + $filter('getLabel')('lblVolume') + ': </b> ' + $filter('AbbrOrWNOrDec')(vol.y, 2) + '</p>' + "</div>";

						} catch (e) {
							console.log(e);
						}
						return tooltipHtml;
					}
				},
				series: [{
					name: 'primary',
					id: 'primary',
					data: data,
					dname: $scope.MarketName,
					color: '#52658f',
					type: 'line',
					threshold: null,
					fillColor: {
						linearGradient: {
							x1: 0,
							y1: 0,
							x2: 0,
							y2: 1
						},
						stops: [
							[0, 'rgb(100,119,161)'],
							[1, 'rgb(100,119,161)']
						]
					},
					dataGrouping: {
						forced: true,
						units: [['day', [1]]]
					}
				},
				{
					id: 'SMA-1',
					name: '50-day SMA',
					dname: '50-' + $filter('getLabel')('lbldaySMA'),
					linkedTo: 'primary',
					showInLegend: true,
					type: 'trendline',
					lineWidth: 2,
					algorithm: 'SMA',
					color: '#FF8000',
					periods: 50,
					visible: false,
					dataGrouping: {
						forced: true,
						units: [['day', [1]]]
					}
				},
				{
					id: 'SMA-2',
					name: '200-day SMA',
					dname: '200-' + $filter('getLabel')('lbldaySMA'),
					linkedTo: 'primary',
					showInLegend: true,
					type: 'trendline',
					lineWidth: 2,
					algorithm: 'SMA',
					color: '#FF5500',
					periods: 200,
					visible: false,
					dataGrouping: {
						forced: true,
						units: [['day', [1]]]
					}
				},
				{
					name: 'Linear Trendline',
					id: 'ltrLine',
					dname: $filter('getLabel')('lblLinearTrendline'),
					color: '#666',
					defaultSeriesType: 'spline',
					lineWidth: 2,
					threshold: null,
					visible: false,
					enableMouseTracking: false,
					data: (function () {
						return fitData($scope.trendLineData).data.map((elem, i, arr) => { if (i === 0 || i === arr.length - 1) return elem; }).clean();
					})(),
					dataGrouping: {
						forced: true,
						units: [['month', [1]]]
					}
				},
				{
					type: 'column',
					id: 'volume',
					name: 'Volume',
					color: '#333a56',
					data: cdata,
					yAxis: 1,
					dataGrouping: {
						forced: true,
						units: [['day', [1]]]
					}

				}]
			}, function (chart) {
				$scope.chart = chart;
			});
		}
	}])
	.controller('toolsGCCIndexDetailCtrl', ['$global', '$scope', '$http', '$q', '$location', '$filter', '$timeout', '$log', function ($global, $scope, $http, $q, $location, $filter, $timeout, $log) {
		var self = this;
		$scope.chartConst = {
			is50DayMA: false,
			is200DayMA: false,
			isTrendLine: false
		};
		$scope.trendLineData = [];
		$scope.min = undefined,
			$scope.max = undefined;
		$scope.chart = undefined;

		$scope.auth = undefined;
		$scope.marketInfo = null;
		$scope.momentum = [];
		$scope.indicesChart = [];
		$scope.$watchCollection('chartConst', function (newValues, oldValues) {
			if ($scope.chart === undefined) return;
			var s50Obj = $.grep($scope.chart.series, (elem) => { return elem.name === '50-day SMA'; }).firstOrDefault();
			if (!angular.isFunction(s50Obj)) {
				if ($scope.chartConst.is50DayMA) {
					$scope.chart.series[s50Obj.index].update({
						visible: true
					});
				}
				else {
					$scope.chart.series[s50Obj.index].update({
						visible: false
					});
				}
			}
			var s200Obj = $.grep($scope.chart.series, (elem) => { return elem.name === '200-day SMA'; }).firstOrDefault();
			if (!angular.isFunction(s200Obj)) {
				if ($scope.chartConst.is200DayMA) {
					$scope.chart.series[s200Obj.index].update({
						visible: true
					});
				}
				else {
					$scope.chart.series[s200Obj.index].update({
						visible: false
					});
				}
			}
			var trendLine = $.grep($scope.chart.series, (elem) => { return elem.name === 'Linear Trendline'; }).firstOrDefault();
			if (!angular.isFunction(trendLine)) {
				if ($scope.chartConst.isTrendLine) {
					$scope.chart.series[trendLine.index].update({
						visible: true,
						data: (function () {
							return fitData($scope.trendLineData).data.map((elem, i, arr) => { if (i === 0 || i === arr.length - 1) return elem; }).clean();
						})(),
					});
				}
				else {
					$scope.chart.series[trendLine.index].update({
						visible: false
					});
				}
			}
		});
		$scope.init = function (model, auth) {
			$scope.auth = Number(auth);
			$scope.model = model;
			blockUI('toolsGCCIndexDetailCtrl');
			$http({
				url: siteRoot + 'tools/gccindexdetail/',
				method: 'post',
				data: { iscapsize: model.IsCapsize, gccsectorId: model.SectorID, flag: 2 },
			}).then(function (resp) {
				$scope.indicesChart.push(resp.data.indicesChart);
				$scope.min = parseInt(resp.data.indicesChart[0].MinDate.slice(6, -2));
				$scope.max = parseInt(resp.data.indicesChart[0].MaxDate.slice(6, -2));
				self.createChart(resp.data.indicesChart);
				$scope.momentum = resp.data.momentum;
			}, (error) => { unblockUI('toolsGCCIndexDetailCtrl'); console.log(error.data); })
				.finally(function () {
					unblockUI('toolsGCCIndexDetailCtrl');
				});
		}

		this.createChart = function (chartData) {
			let data = [], chart, cdata = [], price = [];
			chartData !== null && chartData.map(function (elem) {
				var date = parseInt(elem.Date.slice(6, -2));
				var value = parseFloat(elem.Closing);
				var volume = parseInt(elem.Volume);;
				data.push([date, value]);
				cdata.push([date, volume]);
			});

			$scope.trendLineData = $.grep(data, (elem) => { return elem[0] >= $scope.min && elem[0] <= $scope.max; });

			var align = parseInt(lang) === 1 ? "right" : "left";

			new Highcharts.stockChart({
				chart: {
					renderTo: 'indexDetailChart',
					borderColor: '#FAFAFA',
					borderWidth: 0,
					plotBackgroundColor: '',
					panning: false
				},
				watermark: {
					yAxis: 230
				},
				navigator: {
					xAxis: {
						min: parseInt(chartData[0].MinDate.slice(6, -2)),
						labels: {
							style: {
								color: '#222',
								fontWeight: 'bold'
							}
						}
					},
				},
				rangeSelector: {
					allButtonsEnabled: true,
					selected: 4,
					inputEnabled: false,
					inputBoxBorderColor: "#cccccc",
					inputBoxHeight: 17,
					inputBoxWidth: 90,
					inputDateFormat: "%b %e %Y,",
					inputDateParser: null,
					inputEditDateFormat: "%Y-%m-%d",
					inputPosition: { align: "right" },
					buttonTheme: {
						useHTML: true,

						fill: 'none',
						stroke: 'none',
						'stroke-width': 0,
						r: 8,
						style: {
							color: '#039',
							fontWeight: 'bold',
							direction: 'ltr'
						},
						states: {
							hover: {
							},
							select: {
								style: {
									color: 'black'
								}
							}
						}
					},
					buttons: [{
						type: 'month',
						count: 1,
						text: $filter('getLabel')('lbl1m')
					}, {
						type: 'month',
						count: 3,
						text: $filter('getLabel')('lbl3m')
					}, {
						type: 'month',
						count: 6,
						text: $filter('getLabel')('lbl6m')
					}, {
						type: 'ytd',
						text: $filter('getLabel')('lblytd')
					}, {
						type: 'year',
						count: 1,
						text: $filter('getLabel')('lbl1y')
					}]
				},
				exporting: {
					enabled: !1
				},
				scrollbar: {
					barBackgroundColor: 'gray',
					barBorderRadius: 7,
					barBorderWidth: 0,
					buttonBackgroundColor: 'gray',
					buttonBorderWidth: 0,
					buttonBorderRadius: 7,
					trackBackgroundColor: 'none',
					trackBorderWidth: 1,
					trackBorderRadius: 8,
					trackBorderColor: '#CCC'
				},
				title: {
					text: '',
					x: -20 //center
				},
				subtitle: {
					text: '',
					x: -20
				},
				xAxis: {
					min: parseInt(chartData[0].MinDate.slice(6, -2)),
					tickInterval: 10,
					min: 0,
					max: null,
					type: 'datetime',
					labels: {
						formatter: function () {
							return Highcharts.dateFormat('%d/%m/%y', this.value);
						},
						style: {
							color: '#222'
						},
						x: -3
					},
					events: {
						afterSetExtremes: function (event) {
							let tchart = this.chart;
							$scope.min = event.min;
							$scope.max = event.max;
							let tempData = [];
							$timeout(function () {
								//plot line update
								chartData.map(function (elem, i) {
									let date = parseInt(elem.Date.slice(6, -2));
									if (date > $scope.min && date < $scope.max) {
										tempData.push(parseFloat(elem.Closing));
									}
								});
								if (tempData.length > 0) {
									tchart.yAxis[0].removePlotLine('pltLine');
									tchart.yAxis[0].addPlotLine({
										id: 'pltLine',
										color: Highcharts.getOptions().horizontalLineColor,
										dashStyle: Highcharts.getOptions().horizontalLineStyle,
										width: 1,
										value: tempData.sum() / tempData.length,
										label: {
											text: '',
											x: -10
										},
										zIndex: 3
									});
								}

								// trendline update
								$scope.trendLineData = $.grep(data, (elem) => { return elem[0] >= $scope.min && elem[0] <= $scope.max; });

								var trendLine = $.grep($scope.chart.series, (elem) => { return elem.name === 'Linear Trendline'; }).firstOrDefault();
								if (!angular.isFunction(trendLine)) {
									$scope.chart.series[trendLine.index].update({
										data: (function () {
											return fitData($scope.trendLineData).data.map((elem, i, arr) => { if (i === 0 || i === arr.length - 1) return elem; }).clean();
										})()
									});
								}
							});
						}
					}
				},
				plotOptions: {
					line: {
						marker: {
							enabled: false
						}
					}
				},
				yAxis: [{
					gridLineColor: '#ececec',
					lineColor: '#ccc',
					lineWidth: 1,
					className: 'ltr',
					labels: {
						align: 'left',
						formatter: function () {
							return $filter('WNOrDec')(this.value, 0);
						},
						x: 5,
						style: {
							color: '#222',
						}
					},
					height: 200,
					tickPositioner: function () {
						var positions = [],
							tick = Math.floor(this.dataMin),
							increment = Math.ceil((this.dataMax - this.dataMin) / 6);
						if (this.dataMax !== null && this.dataMin !== null) {
							for (tick; tick - increment <= this.dataMax; tick += increment) {
								positions.push(tick);
							}
						}
						return positions;
					},
					plotLines: [{
						id: 'pltLine',
						color: Highcharts.getOptions().horizontalLineColor,
						dashStyle: Highcharts.getOptions().horizontalLineStyle,
						width: 1,
						value: chartData[0].Average,
						label: {
							text: '',
							x: -10
						},
						zIndex: 3
					}]
				},
				{
					gridLineColor: '#ececec',
					alternateGridColor: '#FeFeFe',
					lineColor: '#ccc',
					lineWidth: 1,
					opposite: true,
					labels: {
						align: 'left',
						formatter: function () {
							return '<label class="ltr text-normal">' + $filter('Abbr')(this.value, 0) + '</label>';
						},
						x: 5,
						style: {
							color: '#222',
						},
						useHTML: true
					},
					top: 250,
					height: 100,
					offset: 0,
					tickPositioner: function () {
						var positions = [],
							tick = Math.floor(this.dataMin),
							increment = Math.ceil((this.dataMax - this.dataMin) / 3);

						if (this.dataMax !== null && this.dataMin !== null) {
							for (tick; tick - increment <= this.dataMax; tick += increment) {
								positions.push(tick);
							}
						}
						return positions;
					}
				}],

				credits: {
					enabled: false
				},
				legend: {
					layout: 'vertical',
					align: 'right',
					verticalAlign: 'middle',
					borderWidth: 0,
					enabled: false
				},
				tooltip: {
					headerFormat: '',
					useHTML: true,
					formatter: function () {
						var tooltipHtml = '';
						try {
							tooltipHtml = '<div class="col-md-12 padding-5 ltr defualt-color"><p><b>' + $filter('getLabel')('lblDate') + ': </b> ' + Highcharts.dateFormat('%b %e, %Y', new Date(this.points[0].x)) + ' </p>';
							var primary = $.grep(this.points, function (elem) { return elem.series.name === 'primary'; }).firstOrDefault();
							if (!angular.isFunction(primary)) {
								tooltipHtml += '<b><p style="color:' + primary.series.color + '">' + $filter('getLabel')('lblClosing') + ': </b>' + $filter('AbbrOrWNOrDec')(primary.y, 2) + "</p>";
							}


							var smas = $.grep(this.points, function (elem) { return elem.series.name.indexOf('SMA') !== -1; });
							if (smas.length > 0) {
								angular.forEach(smas, function (sm) {
									tooltipHtml += '<b><p style="color:' + sm.series.color + '">' + sm.series.options.dname + ': </b>' + $filter('AbbrOrWNOrDec')(sm.y, 2) + "</p>";
								});
							}
							var vol = $.grep(this.points, function (elem) { return elem.series.name === 'Volume'; }).firstOrDefault();
							if (vol !== undefined)
								tooltipHtml += '<b><p style="color:' + vol.series.color + '">' + $filter('getLabel')('lblVolume') + ': </b> ' + $filter('AbbrOrWNOrDec')(vol.y, 2) + '</p>' + "</div>";

						} catch (e) {
							console.log(e);
						}
						return tooltipHtml;
					}
				},
				series: [{
					name: 'primary',
					id: 'primary',
					data: data,
					dname: $scope.MarketName,
					color: '#52658f',
					type: 'line',
					threshold: null,
					fillColor: {
						linearGradient: {
							x1: 0,
							y1: 0,
							x2: 0,
							y2: 1
						},
						stops: [
							[0, 'rgb(100,119,161)'],
							[1, 'rgb(100,119,161)']
						]
					},
					dataGrouping: {
						forced: true,
						units: [['day', [1]]]
					}
				},
				{
					id: 'SMA-1',
					name: '50-day SMA',
					dname: '50-' + $filter('getLabel')('lbldaySMA'),
					linkedTo: 'primary',
					showInLegend: true,
					type: 'trendline',
					lineWidth: 2,
					algorithm: 'SMA',
					color: '#FF8000',
					periods: 50,
					visible: false,
					dataGrouping: {
						forced: true,
						units: [['day', [1]]]
					}
				},
				{
					id: 'SMA-2',
					name: '200-day SMA',
					dname: '200-' + $filter('getLabel')('lbldaySMA'),
					linkedTo: 'primary',
					showInLegend: true,
					type: 'trendline',
					lineWidth: 2,
					algorithm: 'SMA',
					color: '#FF5500',
					periods: 200,
					visible: false,
					dataGrouping: {
						forced: true,
						units: [['day', [1]]]
					}
				},
				{
					name: 'Linear Trendline',
					id: 'ltrLine',
					dname: $filter('getLabel')('lblLinearTrendline'),
					color: '#666',
					defaultSeriesType: 'spline',
					lineWidth: 2,
					threshold: null,
					visible: false,
					enableMouseTracking: false,
					data: (function () {
						return fitData($scope.trendLineData).data.map((elem, i, arr) => { if (i === 0 || i === arr.length - 1) return elem; }).clean();
					})(),
					dataGrouping: {
						forced: true,
						units: [['month', [1]]]
					}
				},
				{
					type: 'column',
					id: 'volume',
					name: 'Volume',
					color: '#333a56',
					data: cdata,
					yAxis: 1,
					dataGrouping: {
						forced: true,
						units: [['day', [1]]]
					}

				}]
			}, function (chart) {
				$scope.chart = chart;

			});
		}



	}])
	.controller('toolsGlobalIndicesCtrl', ['$scope', '$http', '$q', '$location', '$filter', '$timeout', '$log', function ($scope, $http, $q, $location, $filter, $timeout, $log) {
		var self = this;
		$scope.model = [];
        $scope.init = function (data) {
            $scope.model = data;
		}
		$scope.username = 'lblGBIndicesHeading';

	}])
	.controller('toolsGlobalIndexDetailCtrl', ['$global', '$scope', '$http', '$q', '$location', '$filter', '$timeout', '$log', function ($global, $scope, $http, $q, $location, $filter, $timeout, $log) {
		var self = this;
		$scope.model = [];
		$scope.chartConst = {
			is50DayMA: false,
			is200DayMA: false,
			isTrendLine: false
		};
		$scope.trendLineData = [];

		$scope.min = undefined,
			$scope.max = undefined;
		$scope.chart = undefined;
		$scope.newsData = {};
		$scope.$watchCollection('chartConst', function (newValues, oldValues) {
			if ($scope.chart === undefined) return;
			var s50Obj = $.grep($scope.chart.series, (elem) => { return elem.name === '50-day SMA'; }).firstOrDefault();
			if (!angular.isFunction(s50Obj)) {
				if ($scope.chartConst.is50DayMA) {
					$scope.chart.series[s50Obj.index].update({
						visible: true
					});
				}
				else {
					$scope.chart.series[s50Obj.index].update({
						visible: false
					});
				}
			}
			var s200Obj = $.grep($scope.chart.series, (elem) => { return elem.name === '200-day SMA'; }).firstOrDefault();
			if (!angular.isFunction(s200Obj)) {
				if ($scope.chartConst.is200DayMA) {
					$scope.chart.series[s200Obj.index].update({
						visible: true
					});
				}
				else {
					$scope.chart.series[s200Obj.index].update({
						visible: false
					});
				}
			}
			var trendLine = $.grep($scope.chart.series, (elem) => { return elem.name === 'Linear Trendline'; }).firstOrDefault();
			if (!angular.isFunction(trendLine)) {
				if ($scope.chartConst.isTrendLine) {
					$scope.chart.series[trendLine.index].update({
						visible: true,
						pdata: {
							xData: $scope.trendLineXData,
							yData: $scope.trendLineYData
						}
					});
				}
				else {
					$scope.chart.series[trendLine.index].update({
						visible: false
					});
				}
			}
		});
		$scope.init = function (data) {
			$scope.model = data;
			self.createChart(data.indicesChart);


			$http({
				url: siteRoot + 'tools/globalindexdetail/0',
				method: 'post'
			}).then(function (res) {
				$scope.newsData = res.data.globalNews;
			}, (error) => { console.log(error.data); });
		}

		this.createChart = function (chartData) {
			var data = [], chart, price = [];
			chartData !== null && chartData.map(function (elem) {
				var date = parseInt(elem.Date.slice(6, -2));
				var value = parseFloat(elem.Closing);
				var volume = parseInt(elem.Volume);;
				data.push([date, value]);
			});
			$scope.min = parseInt(chartData[0].MinDate.slice(6, -2));
			$scope.max = parseInt(chartData[0].MaxDate.slice(6, -2));
			$scope.trendLineData = $.grep(data, (elem) => { return elem[0] >= $scope.min && elem[0] <= $scope.max; });

			new Highcharts.stockChart({
				chart: {
					renderTo: 'indexDetailChart',
					borderColor: '#FAFAFA',
					borderWidth: 0,
					plotBackgroundColor: '',
					panning: false
					//margin: [5, 75, 25, 5]
				},
				navigator: {
					xAxis: {
						min: parseInt(chartData[0].MinDate.slice(6, -2)),
						labels: {
							style: {
								color: '#222',
								fontWeight: 'bold'
							}
						}
					},
				},
				rangeSelector: {
					allButtonsEnabled: true,
					selected: 4,
					inputEnabled: false,
					inputBoxBorderColor: "#cccccc",
					inputBoxHeight: 17,
					inputBoxWidth: 90,
					inputDateFormat: "%b %e %Y,",
					inputDateParser: null,
					inputEditDateFormat: "%Y-%m-%d",
					inputPosition: { align: "right" },
					buttonTheme: {
						useHTML: true,

						fill: 'none',
						stroke: 'none',
						'stroke-width': 0,
						r: 8,
						style: {
							color: '#039',
							fontWeight: 'bold',
							direction: 'ltr'
						},
						states: {
							hover: {
							},
							select: {
								style: {
									color: 'black'
								}
							}
						}
					},
					buttons: [{
						type: 'month',
						count: 1,
						text: $filter('getLabel')('lbl1m')
					}, {
						type: 'month',
						count: 3,
						text: $filter('getLabel')('lbl3m')
					}, {
						type: 'month',
						count: 6,
						text: $filter('getLabel')('lbl6m')
					}, {
						type: 'ytd',
						text: $filter('getLabel')('lblytd')
					}, {
						type: 'year',
						count: 1,
						text: $filter('getLabel')('lbl1y')
					}]
				},
				exporting: {
					enabled: !1
				},
				scrollbar: {
					barBackgroundColor: 'gray',
					barBorderRadius: 7,
					barBorderWidth: 0,
					buttonBackgroundColor: 'gray',
					buttonBorderWidth: 0,
					buttonBorderRadius: 7,
					trackBackgroundColor: 'none',
					trackBorderWidth: 1,
					trackBorderRadius: 8,
					trackBorderColor: '#CCC'
				},
				title: {
					text: '',
					x: -20 //center
				},
				subtitle: {
					text: '',
					x: -20
				},
				xAxis: {
					min: Number(chartData[0].MinDate.slice(6, -2)),
					labels: {
						formatter: function () {
							return Highcharts.dateFormat('%d/%m  ', this.value);
						},
						style: {
							color: '#222'
						}
					},
					events: {
						afterSetExtremes: function (event) {
							let tchart = this.chart;
							$scope.min = event.min;
							$scope.max = event.max;
							let tempData = [];
							$timeout(function () {
								//plot line update
								chartData.map(function (elem, i) {
									let date = parseInt(elem.Date.slice(6, -2));
									if (date > $scope.min && date < $scope.max) {
										tempData.push(parseFloat(elem.Closing));
									}
								});
								if (tempData.length > 0) {
									tchart.yAxis[0].removePlotLine('pltLine');
									tchart.yAxis[0].addPlotLine({
										id: 'pltLine',
										color: Highcharts.getOptions().horizontalLineColor,
										dashStyle: Highcharts.getOptions().horizontalLineStyle,
										width: 1,
										value: tempData.sum() / tempData.length,
										label: {
											text: '',
											x: -10
										},
										zIndex: 3
									});
								}

								// trendline update
								$scope.trendLineData = $.grep(data, (elem) => { return elem[0] >= $scope.min && elem[0] <= $scope.max; });

								var trendLine = $.grep($scope.chart.series, (elem) => { return elem.name === 'Linear Trendline'; }).firstOrDefault();
								if (!angular.isFunction(trendLine)) {
									$scope.chart.series[trendLine.index].update({
										data: (function () {
											return fitData($scope.trendLineData).data.map((elem, i, arr) => { if (i === 0 || i === arr.length - 1) return elem; }).clean();
										})()
									});
								}
							});

						}
					}
				},
				plotOptions: {
					line: {
						marker: {
							enabled: false
						}
					}
				},
				yAxis: [{
					gridLineColor: '#ececec',
					//alternateGridColor: '#FeFeFe',
					lineColor: '#ccc',
					lineWidth: 1,
					className: 'ltr',
					//title: {
					//	text: $global.getResources("lblIndex"),
					//	style: {
					//		color: '#222',
					//		fontWeight: 'bold',
					//		fontSize: '12px'
					//	},
					//},
					labels: {
						align: 'left',
						formatter: function () {
							return $filter('WNOrDec')(this.value, 0);
						},
						x: 5,
						style: {
							color: '#222',
						}
					},
					tickPositioner: function () {
						var positions = [],
							tick = Math.floor(this.dataMin),
							increment = Math.ceil((this.dataMax - this.dataMin) / 4);

						if (this.dataMax !== null && this.dataMin !== null) {
							for (tick; tick - increment <= this.dataMax; tick += increment) {
								positions.push(tick);
							}
						}
						return positions;
					},
					plotLines: [{
						id: 'pltLine',
						color: Highcharts.getOptions().horizontalLineColor,
						dashStyle: Highcharts.getOptions().horizontalLineStyle,
						width: 1,
						value: chartData[0].Average,
						label: {
							text: '',
							x: -10
						},
						zIndex: 3
					}]
				}],
				tooltip: {
					formatter: function () {
						var tooltipHtml = '';
						try {
							tooltipHtml = '<div class="col-md-12 padding-5 ltr defualt-color"><p><b>' + $filter('getLabel')('lblDate') + ': </b> ' + Highcharts.dateFormat('%b %e, %Y', new Date(this.points[0].x)) + ' </p>';
							var primary = $.grep(this.points, function (elem) { return elem.series.name === 'primary'; }).firstOrDefault();
							if (!angular.isFunction(primary)) {
								tooltipHtml += '<b><p style="color:' + primary.series.color + '">' + $filter('getLabel')('lblClosing') + ': </b>' + $filter('AbbrOrWNOrDec')(primary.y, 2) + "</p>";
							}

							var smas = $.grep(this.points, function (elem) { return elem.series.name.indexOf('SMA') !== -1; });
							if (smas.length > 0) {
								angular.forEach(smas, function (sm) {
									tooltipHtml += '<b><p style="color:' + sm.series.color + '">' + sm.series.options.dname + ': </b>' + $filter('AbbrOrWNOrDec')(sm.y, 2) + "</p>";
								});
							}

						} catch (e) { }
						return tooltipHtml;
					}
				},
				credits: {
					enabled: false
				},
				legend: {
					layout: 'vertical',
					align: 'right',
					verticalAlign: 'middle',
					borderWidth: 0,
					enabled: false
				},
				series: [{
					name: 'primary',
					id: 'primary',
					data: data,
					dname: '',
					color: '#52658f',
					type: 'line',
					lineWidth: 2,
					threshold: null,
					dataGrouping: {
						forced: true,
						units: [['day', [1]]]
					}
				},
				{
					id: 'SMA-1',
					name: '50-day SMA',
					dname: '50-' + $filter('getLabel')('lbldaySMA'),
					linkedTo: 'primary',
					showInLegend: true,
					type: 'trendline',
					lineWidth: 2,
					algorithm: 'SMA',
					color: '#FF8000',
					periods: 50,
					visible: $scope.is50DayMA,
					dataGrouping: {
						forced: true,
						units: [['day', [1]]]
					}
				},
				{
					id: 'SMA-2',
					name: '200-day SMA',
					dname: '200-' + $filter('getLabel')('lbldaySMA'),
					linkedTo: 'primary',
					showInLegend: true,
					type: 'trendline',
					lineWidth: 2,
					algorithm: 'SMA',
					color: '#FF5500',
					periods: 200,
					visible: $scope.is200DayMA,
					dataGrouping: {
						forced: true,
						units: [['day', [1]]]
					}
				},
				{
					name: 'Linear Trendline',
					id: 'ltrLine',
					dname: $filter('getLabel')('lblLinearTrendline'),
					color: '#666',
					defaultSeriesType: 'spline',
					lineWidth: 2,
					threshold: null,
					visible: $scope.chartConst.isTrendLine,
					enableMouseTracking: false,
					data: (function () {
						return fitData($scope.trendLineData).data.map((elem, i, arr) => { if (i === 0 || i === arr.length - 1) return elem; }).clean();
					})(),
					dataGrouping: {
						forced: true,
						units: [['month', [1]]]
					}
				}]
			}, function (chart) {
				$scope.chart = chart;
			});
		}

	}])
	.controller('toolsCommoditiesCtrl', ['$scope', '$http', '$q', '$location', '$filter', '$timeout', '$log', function ($scope, $http, $q, $location, $filter, $timeout, $log) {
		var self = this;
		$scope.model = {};
		$scope.newsData = {};
		$scope.showNewsDiv = false;
		$scope.init = function (data) {
			$scope.model = data;
		}

	}])
	.controller('toolsCommodityDetailCtrl', ['$global', '$scope', '$http', '$q', '$location', '$filter', '$timeout', '$log', function ($global, $scope, $http, $q, $location, $filter, $timeout, $log) {
		var self = this;
		$scope.auth = undefined;
		$scope.model = {};
		$scope.marketInfo = null;
		$scope.momentum = [];
		$scope.indicesChart = [];
		$scope.init = function (data, auth) {
			$scope.auth = Number(auth);
			$scope.model = data;
			self.createChart(data.commodityChart);

			blockUI('toolsCommodityDetailCtrl');
			$http({
				url: siteRoot + 'tools/commoditydetail/',
				method: 'post',
				data: { catId: data.commodityDetail.MaterialID },
			}).then(function (resp) {
				$scope.newsData = resp.data.commodityNews;
			}, (error) => { unblockUI('toolsCommodityDetailCtrl'); console.log(error.data); })
				.finally(function () {
					unblockUI('toolsCommodityDetailCtrl');
				});
		}

		this.createChart = function (chartData) {
			var data = [], chart, price = [];
			chartData !== null && chartData.map(function (elem) {
				var date = parseInt(elem.Date.slice(6, -2));
				var value = parseFloat(elem.Close);
				var volume = parseInt(elem.Volume);;
				data.push([date, value]);
			});
			Highcharts.setOptions({
				lang: {
					rangeSelectorZoom: '',
					style: { direction: 'ltr' },
				}
			});
			new Highcharts.stockChart({
				chart: {

					renderTo: 'commodityDetailChart',
					borderColor: '#FAFAFA',
					borderWidth: 1,
					plotBackgroundColor: '',
					panning: false
				},
				navigator: {
					xAxis: {
						labels: {
							style: {
								color: '#222',
								fontWeight: 'bold'
							}
						}
					},
				},
				rangeSelector: {
					allButtonsEnabled: false,
					inputEnabled: !1,
					selected: 1,
					inputBoxBorderColor: "#cccccc",
					inputBoxHeight: 17,
					inputBoxStyle: undefined,
					inputBoxWidth: 90,
					inputDateFormat: "%b %e %Y,",
					inputDateParser: null,
					inputEditDateFormat: "%Y-%m-%d",
					inputPosition: { align: "right" },
					buttons: [{
						type: 'month',
						count: 1,
						text: '1m'
					}, {
						type: 'month',
						count: 3,
						text: '3m'
					},
					{
						type: 'month',
						count: 6,
						text: '6m'
					},
					{
						type: 'ytd',
						text: 'YTD'
					}
						, {
						type: 'all',
						count: 1,
						text: '1y'
					}
					],
					buttonTheme: { // styles for the buttons
						fill: 'none',
						stroke: 'none',
						'stroke-width': 0,
						r: 8,
						style: {
							color: '#039',
							fontWeight: 'bold'
						},
						states: {
							hover: {
							},
							select: {
								fill: '#039',
								style: {
									color: 'white'
								}
							}
							// disabled: { ... }
						}
					},
					labelStyle: {
						color: '#fff',
						fontWeight: 'bold'
					},
				},
				exporting: {
					enabled: !1
				},
				scrollbar: {
					barBackgroundColor: 'gray',
					barBorderRadius: 7,
					barBorderWidth: 0,
					buttonBackgroundColor: 'gray',
					buttonBorderWidth: 0,
					buttonBorderRadius: 7,
					trackBackgroundColor: 'none',
					trackBorderWidth: 1,
					trackBorderRadius: 8,
					trackBorderColor: '#CCC'
				},
				title: {
					text: '',
					x: -20 //center
				},
				subtitle: {
					text: '',
					x: -20
				},
				xAxis: {
					tickInterval: 10,
					min: 0,
					max: null,
					type: 'datetime',
					labels: {
						formatter: function () {
							return Highcharts.dateFormat('%d/%m/%y', this.value);
						},
						style: {
							color: '#222'
						},
						x: -15
					}
				},
				plotOptions: {
					line: {
						marker: {
							enabled: false
						}
					}
				},
				yAxis: [{
					gridLineColor: '#ececec',
					//alternateGridColor: '#FeFeFe',
					labels: {
						formatter: function () {
							return $filter('WNOrDec')(this.value, 0);
						},
						style: {
							color: '#222'
						},
						x: -5,
						y: -3
					},
					title: {
						text: $global.getResources('lblClosing'),
						style: {
							color: '#222'
						}
					},
					lineWidth: 2,
					tickPositioner: function () {
						var positions = [],
							tick = Math.floor(this.dataMin),
							increment = Math.ceil((this.dataMax - this.dataMin) / 4);

						if (this.dataMax !== null && this.dataMin !== null) {
							for (tick; tick - increment <= this.dataMax; tick += increment) {
								positions.push(tick);
							}
						}
						return positions;
					}
				}],
				tooltip: {
					split: false,
					formatter: function () {
						return '<div class="col-md-12 ltr defualt-color"><p><b>' + $global.getResources('lblDate') + ': </b>' + Highcharts.dateFormat('%d/%m/%y', this.x) + '</p><p><b>' + $global.getResources('lblClosing') + ': </b>' + $filter('number')(this.y, 2) + "</p></div>";
					}
				},
				credits: {
					enabled: false
				},
				legend: {
					layout: 'vertical',
					align: 'right',
					verticalAlign: 'middle',
					borderWidth: 0,
					enabled: false
				},
				series: [{
					data: data,
					name: 'Index',
					color: '#52658f',
					type: 'line',
					fillColor: {
						linearGradient: {
							x1: 0,
							y1: 0,
							x2: 0,
							y2: 1
						},
						stops: [
							[0, Highcharts.Color(Highcharts.getOptions().colors[0]).setOpacity(0.4).get('rgba')],
							[1, Highcharts.Color(Highcharts.getOptions().colors[0]).setOpacity(0).get('rgba')]
						]
					},
					fillOpacity: 0.1,
					dataGrouping: {
						forced: true,
						units: [['day', [1]]]
					}
				}]
			});
		}

	}])
	.controller('toolsMyWatchListCtrl', ['$uibModal', '$global', '$scope', '$http', '$q', '$location', '$filter', '$timeout', '$log', '$window', 'ngNotify',
		function ($uibModal, $global, $scope, $http, $q, $location, $filter, $timeout, $log, $window, ngNotify) {
			var self = this;
			$scope.auth = undefined;
			this.table = null;
			$scope.type = 1;
			$scope.RatioValue = "0"
			$scope.watchList = [];
			$scope.topList = [];
			$scope.news = [];
			$scope.gRatios = [];
			$scope.ratioRawData = [];
			$scope.loadingFinished = true;
			$scope.init = function (model, auth) {
				$scope.auth = Number(auth);
				$scope.watchList = model.watchList;
				$scope.topList = model.topList;
				$scope.newsData = model.news;
				ProcessBenchMark(model.benchMark);
			}

			$scope.$watch('RatioValue', function (n, o) {
				if (o !== n) {
					if (n > 0)
						LoadRatios();
				}
			});
			$scope.$watch('ratioRawData', function (n, o) {
				ProcessRatios();
			});
			$scope.searchSelectionCallback = function ($item) {
				$http({
					url: siteRoot + 'tools/mywatchlist',
					method: 'POST',
					data: { addComapny: $item.originalObject.ID }
				}).then(function (res) {
					if (res.data.results > 0) {
						utility.alert($global.getResources('lblSuccess'), '<span style="float:left; margin:0 7px 50px 0;"><i class="fa fa-check-square-o"></i></span>' + $global.getResources("lblCompanySuccessfullyAddedToWatchList"), $global.getResources('lblOK'));
						initLoad();
					} else {
						utility.alert($global.getResources('lblInfo'), '<span style="float:left; margin:0 7px 50px 0;"><i class="fa fa-info-circle"></i></span>' + $global.getResources("lblYouAlreadyHveThisCompanyInWatchList"), $global.getResources('lblOK'));
					}
					$timeout(function () {
						clearText();
					}, 400);

				}, (error) => { console.log(error.data); });

			}
			$scope.focusOut = function () {
				clearText();
			}
			function clearText() {
				$scope.$broadcast('angucomplete-alt:clearInput', 'input-watchlist-search');
			}
			function initLoad() {

				blockUI('toolsMyWatchListCtrl');
				$scope.loadingFinished = false;
				$http({
					url: siteRoot + 'tools/mywatchlist',
					method: 'POST',
					data: { typeId: $scope.RatioValue, init: true }
				}).then(function (res) {
					$scope.watchList = res.data.watchList;
					$scope.topList = res.data.topList;
					$scope.newsData = res.data.news;
					ProcessBenchMark(res.data.benchMark)
				}, (error) => { unblockUI('toolsMyWatchListCtrl'); console.log(error.data); }).then(function () {
					$scope.loadingFinished = true;
					unblockUI('toolsMyWatchListCtrl');
				}).finally(function () { LoadRatios(); });

			}
			$scope.removeCompany = function (companyId) {
				var utility = new Utility();
				$.when(utility.confirm($global.getResources('lblConfirmation'), '<span style="float:left; margin:0 7px 50px 0;"><i class="fa fa-trash"></i></span>' + $global.getResources("lblAreYouSureToRemoveThisCompanyFromWatchlist"), $global.getResources("lblOK"), $global.getResources("lblCancel"))).then(
					function (status) {
						if (status == "No") return;
						$http({
							method: 'POST',
							url: siteRoot + 'tools/mywatchlist',
							data: { removeCompany: companyId }
						}).then(function (res) {
							if (res.data.results > 0) {
                utility.alert($global.getResources('lblSuccess'), '<span style="float:left; margin:0 7px 50px 0;"><i class="fa fa-check-square-o"></i></span>' + $global.getResources("lblCompanySuccessfullyRemovedFromWatchList"), $global.getResources("lblOK"));
								initLoad();
							} else {
								utility.alert($global.getResources('lblError'), '<span style="float:left; margin:0 7px 50px 0;"><i class="fa fa-check-square-o"></i></span>' + $global.getResources("lblErrorOccured"), $global.getResources("lblOK"));
							}
						}, (error) => { console.log(error.data); });
					}
				);

			}
			function LoadRatios() {
				if ($scope.RatioValue < 0) return;
				blockUI('ratiosSection');
				$http({
					method: 'POST',
					url: siteRoot + "tools/MyWatchList",
					data: { typeId: $scope.RatioValue }
				})
					.then(function (res) {
						$scope.fields = [];
						$scope.ratioRawData = res.data.ratios;
					}, function (error) { unblockUI('ratiosSection'); utility.alert($global.getResources("lblError"), $global.getResources("lblErrorOccured"), $global.getResources("lblOK")); unblockUI('ratiosSection'); }).finally(function () {
						$scope.loaded = true;
						unblockUI('ratiosSection');
					});
			}
			function ProcessBenchMark(benchMarkData) {
				if (benchMarkData === null) return;
				$scope.benchMarkTitles = $filter('unique')($.grep(benchMarkData, function (elem) { return elem.SectorID === 0; }));
				$scope.benchMark = benchMarkData;

			}

			function ProcessRatios() {
				if ($scope.ratioRawData === undefined) return;
				$scope.gRatios = [];
				var tempfields = $filter('unique')($scope.ratioRawData.map(function (elem) { return elem.FName; }));
				tempfields.forEach(function (field) {
					if ($.grep($scope.ratioRawData, function (elem) { return elem.FName === field && elem.Value > 0; }).length > 0) {
						var record = $.grep($scope.ratioRawData, function (elem) { return elem.FName === field }).firstOrDefault();
						$scope.fields.push({ FieldName: record.FieldName, FName: record.FName, GBFact: record.GBFact });
					}
				});
				$scope.companies = $filter('unique')($scope.ratioRawData.map(function (elem) { return elem.CompanyID; }));
				PopulateRatios();

			}
			function PopulateRatios() {
				$scope.companies.forEach(function (cid) {
					var values = [];
					$scope.fields.forEach(function (field) {
						var record = $.grep($scope.ratioRawData, function (elem) { return elem.FName === field.FName && elem.CompanyID === cid; }).firstOrDefault();
						if (typeof (record) === 'function') return;
						values.push({
							FieldName: record.FName,
							Value: record.Value,
							Title: record.Title,
							Transaction_Detail_URL: record.Transaction_Detail_URL,
						});
					});
					$scope.gRatios.push({
						CompanyID: cid,
						CompanyTicker: $.grep($scope.ratioRawData, function (elem) { return elem.CompanyID === cid; }).firstOrDefault().CompanyTicker,
						Company_URL: $.grep($scope.ratioRawData, function (elem) { return elem.CompanyID === cid; }).firstOrDefault().Company_URL,
						values: values
					});
				});
			}
			/**Sorting*/
			//basic sorting
			$scope.basicViewSort = {
				column: 'CompanyTicker',
				descending: false
			};

			$scope.basicSelectedCls = function (column) {
				return column == $scope.basicViewSort.column ? $scope.basicViewSort.descending ? "sorting_asc" : "sorting_desc" : 'sorting';
			};
			$scope.basicChangeSorting = function (column) {

				if ($scope.basicViewSort.column == column) {
					$scope.basicViewSort.descending = !$scope.basicViewSort.descending;
				} else {
					$scope.basicViewSort.column = column;
					$scope.basicViewSort.descending = false;
				}
			};
			//End Basic Sorting

			//Ratio sorting
			$timeout(function () {
				$scope.ratioViewSort = {
					column: '',
					descending: false
				};

				$scope.ratioSelectedCls = function (column) {
					return column == $scope.ratioViewSort.column ? $scope.ratioViewSort.descending ? "sorting_asc" : "sorting_desc" : 'sorting';
				};
				$scope.ratioChangeSorting = function (column) {

					if ($scope.ratioViewSort.column == column) {
						$scope.ratioViewSort.descending = !$scope.ratioViewSort.descending;
					} else {
						$scope.ratioViewSort.column = column;
						$scope.ratioViewSort.descending = false;
					}
					if ($scope.ratioViewSort.column === "CompanyTicker")
						$scope.gRatios = $scope.gRatios.sort(sortBy($scope.ratioViewSort.column, $scope.ratioViewSort.descending));
					else {
						var tempCompanies = [];
						$scope.companies.forEach(function (elem) {
							tempCompanies.push({
								cid: elem,
								value: $.grep($scope.ratioRawData, function (r) { return r.CompanyID === elem && r.FName === $scope.ratioViewSort.column; }).firstOrDefault().Value
							});
						});
						tempCompanies = tempCompanies.sort(sortBy("value", $scope.ratioViewSort.descending));
						$scope.companies = tempCompanies.map(function (c) { return c.cid; });
						$scope.gRatios = [];
						PopulateRatios();
					}
					//   $filter('orderBy')($scope.gRatios, $scope.ratioViewSort.column, $scope.basicViewSort.descending);
				};
			});
			//Ratio Sorting

			//add company to portfolio   
			$scope.addToPortfolio = function (content) {
				var modalInstance = $uibModal.open({
					templateUrl: '/content/theme/ng/partials/addportfoliopopup.html',
					//template: '<div style="min-width:300px;">'
					//  + '<div class="popup-header">'
					//  + '<a title="Close" class="popup-close" href="javascript:;" ng-click="Close();"><i class="fa fa-times"></i></a>'
					//  + '<div class="popup-header-content">'
					//  + '<h5 class="search-h5" style="padding:5px;">Add ({{companyData.CompanyName}})</h5></div></div><div class="space-5"></div>'
					//  + '<div id="portfolioBody" class="modal-body" style="min-height:200px;padding-top:0;">'
					//  + '<div id="portfolioHistoryData" style="min-width:100%; height:auto;text-align:center;"></div>'
					//  + '<div id="portfolio-history" style="min-height:100px;" ng-bind-html="historyData"></div>'
					//  + '</div></div></div>',
					controller: 'addToPortfolioPopupCtrl',
					scope: $scope,
					windowClass: 'app-modal-window',
					resolve: {
						'data': { data: content }
					}
				});
			}
		}])
	.controller('addToPortfolioPopupCtrl', ['$global', '$http', '$scope', '$compile', '$uibModalInstance', '$filter', 'data', '$timeout',
		function ($global, $http, $scope, $compile, $uibModalInstance, $filter, data, $timeout) {
			var self = this;
			$scope.currentTab = 1;
			$scope.success = false;
			$scope.error = false;
			$scope.info = false;
			$scope.infoMessage = "";
			$scope.working = false;
			$scope.PortfolioID = 0;
			$scope.TransactionTypeID = 0;
			$scope.companyData = {};
			$scope.company = {
				Quantity: '',
				SharePrice: '',
				Commission: '',
				portfolioDate: ''
			};
			$uibModalInstance.rendered.then(function () {
				$timeout(() => {
					$scope.$apply();
				});

				$scope.companyData = data.data;
				initFunc();
			});
			$scope.Close = function () {
				$uibModalInstance.close();
			};

			$scope.addCompany = function (company) {
				Reset();
				$("form[name=companyForm] :input").prop("disabled", true);
				$scope.working = true;
				$http({
					url: siteRoot + 'tools/SavePortfolio',
					method: 'POST',
					data: {
						PortfolioID: $scope.PortfolioID,
						CompanyID: $scope.companyData.CompanyID,
						SymbolTicker: $scope.companyData.CompanyTicker,
						Quantity: company.Quantity,
						SharePrice: company.SharePrice,
						Commision: company.Commission,
						BuyDate: company.portfolioDate,
						Note: company.Notes,
						Transaction: $scope.TransactionTypeID
					}
				}).then(function (resp) {
					if (resp.data === '0') {
						$scope.success = true;
						$timeout(function () {
							$uibModalInstance.close();
						}, 1500);
					} else if (resp.data === '-2') {
						$scope.info = true;
						$scope.infoMessage = $global.getResources('lblCompanyAlreadyExistInfPortfolio');
						$timeout(function () {
							$scope.info = false;
							$scope.infoMessage = '';
						}, 6000);
					}
				}, function () {
					$scope.error = true;
					$timeout(function () {
						$scope.error = false;
					}, 1500);
				}).finally(function () {
					$("form[name=companyForm] :input").prop("disabled", false);
					$scope.working = false;
				});
			}
			function initFunc() {
				$http({
					url: siteRoot + 'home/GSAddCompanyToPortfolio',
					method: 'POST'
				}).then(function (resp) {
					$scope.portfolioOptions = resp.data.options;
					$scope.actionTypes = resp.data.actionTypes;
					$timeout(function () {
						$scope.PortfolioID = $scope.portfolioOptions.firstOrDefault().Id;
						$scope.TransactionTypeID = $scope.actionTypes.firstOrDefault().TransactionTypeID.toString();
						$timeout(function () {
							$("#datepicker").datepicker({
								changeMonth: true,
								dateFormat: 'dd/mm/yy',
								changeYear: true
							});
							$('#datepicker').datepicker('setDate', 'now');
							$scope.company.portfolioDate = $.datepicker.formatDate("dd/mm/yy", $("#datepicker").datepicker("getDate"));
						});
					});
				}, (error) => { console.log(error.data); });
			}
			function Reset() {
				$scope.success = false;
				$scope.error = false;
				$scope.info = false;
				$scope.infoMessage = "";
				$scope.working = false;
				$("form[name=companyForm] :input").prop("disabled", false);
			}
		}])
	.controller('toolsEarningWatchCtrl', ['$scope', '$http', '$q', '$location', '$filter', '$timeout', '$log', '$window', function ($scope, $http, $q, $location, $filter, $timeout, $log, $window) {
		var self = this;
		$scope.auth = undefined;
		$scope.watchData = {};
		$scope.init = function (data, auth) {
			$scope.auth = Number(auth);
			$scope.AllData = data;
			$scope.watchData = data.earningWatch;
			$scope.sectors = $filter('unique')($scope.watchData.map(function (elem) { return elem.Sector; }));
			$scope.sectorData = [];
			$scope.cols = data.QuarterID === 4 ? 1 : 2;
			angular.forEach($scope.sectors, function (v) {
				$scope.sectorData.push({
					sectorId: v,
					sector: ($scope.watchData.map(function (elem) { if (elem.Sector === v) return elem.Sector; }).clean().sortUnique()).firstOrDefault(),
					sectorURL: $.grep($scope.watchData, function (elem) { return elem.Sector === v; }).firstOrDefault().SectorUrl,
					total: $scope.watchData.map(function (elem) { if (elem.Sector === v) return elem; }).clean().length,
					sumPrevYear: $scope.watchData.map(function (elem) { if (elem.Sector === v && elem.CPreviousNP !== "" && elem.Remarks !== 'Not Announced') return elem.CPreviousNP; }).clean().sum(),
					sumCurrYear: $scope.watchData.map(function (elem) { if (elem.Sector === v && elem.CNetProfit !== "" && elem.Remarks !== 'Not Announced') return elem.CNetProfit; }).clean().sum(),
					announced: $scope.watchData.map(function (elem) { if (elem.Sector === v && elem.Remarks !== 'Not Announced') return elem.NetProfit; }).clean().length,
					gain: $scope.watchData.map(function (elem) { if (elem.Sector === v && elem.CNetProfit > 0 && elem.Remarks !== 'Not Announced') return elem.CNetProfit; }).clean().length,
					lose: $scope.watchData.map(function (elem) { if (elem.Sector === v && elem.CNetProfit < 0 && elem.Remarks !== 'Not Announced') return elem.CNetProfit; }).clean().length
				});

			});

			$scope.sectorData.push({
				sectorId: $scope.watchData.firstOrDefault().StockMarketID,
				sector: $scope.watchData.firstOrDefault().StockMarket,
				sectorURL: $scope.watchData.firstOrDefault().StockMarketUrl,
				total: $scope.watchData.map(function (elem) { return elem.CompanyID; }).clean().length,
				sumPrevYear: $scope.watchData.map(function (elem) { if (elem.PreviousNP !== "" && elem.Remarks !== 'Not Announced') return elem.PreviousNP; }).clean().sum(),
				sumCurrYear: $scope.watchData.map(function (elem) { if (elem.NetProfit !== "" && elem.Remarks !== 'Not Announced') return elem.NetProfit; }).clean().sum(),
				announced: $scope.watchData.map(function (elem) { if (elem.Remarks !== 'Not Announced') return elem.NetProfit; }).clean().length,
				gain: $scope.watchData.map(function (elem) { if (elem.NetProfit > 0 && elem.Remarks !== 'Not Announced') return elem.NetProfit; }).clean().length,
				lose: $scope.watchData.map(function (elem) { if (elem.NetProfit < 0 && elem.Remarks !== 'Not Announced') return elem.NetProfit; }).clean().length
			});

		}
		$timeout(() => {
			$(".table-fixedHeader").stickyTableHeaders({ fixedOffset: 65 });
		});
	}])
	.controller('gccLeadersCtrl', ['$global', '$scope', '$http', '$q', '$location', '$filter', '$timeout', '$log', '$window', '$uibModal', function ($global, $scope, $http, $q, $location, $filter, $timeout, $log, $window, $uibModal) {
		var self = this;
		$scope.selectedSector = 0;
		$scope.auth = undefined;
		$scope.hmData = {};
		$scope.sectors = {};
		$scope.sectorsInfo = [];
		$scope.category = 'MarketCap';
		$scope.currentSector = null;
		$scope.init = function (data, auth) {
			$scope.auth = Number(auth);
			$scope.sectors = data;
			$scope.currentSector = data.firstOrDefault().SectorID;
			if (Number(auth) > 1)
				self.createGCCHMap($scope.sectors);
		};
		$scope.$watchGroup(['category'], function (newValues, oldValues, scope) {
			if (oldValues[0] !== newValues[0]) {
				self.createGCCHMap($scope.sectors);
			}

		});
		$scope.$watchGroup(['currentSector'], function (newValues, oldValues, scope) {
			blockUI('gccLeadersCtrl');
			$http({
				url: siteRoot + 'tools/sectors',
				method: 'POST',
				data: { id: $scope.currentSector }
			}).then(function (resp) {
				$scope.sectorsInfo = resp.data.sectorsInfo;
			}, (error) => { unblockUI('gccLeadersCtrl'); console.log(error.data); })
				.finally(function () { unblockUI('gccLeadersCtrl'); });
		});
		$scope.loadSectorDetail = function ($event, s) {
			$event.preventDefault();
			$scope.currentSector = s;
		}
		this.createGCCHMap = function (data) {
			var mapData = [];
			var i = 0;
			data.map(function (v) {
				if (v !== undefined && parseFloat(v[$scope.category]) > 0) {
					mapData.push({
						id: v.SectorID,
						name: v.Sector,
						value: v[$scope.category],
						color: Highcharts.getOptions().colors[i]
					});
					i++;
				}
				if (i > 10)
					i = 0;
			});

			Highcharts.chart('mcGCCLeadersTreeMap', {
				chart: {
					animation: false,
					backgroundColor: '#000',
					borderColor: '#3a3a3a',
				},
				tooltip: {
					formatter: function () {
						return '<b>' + this.point.options.name + '</b> (<small>' + $global.getResources('lblMarketCap') + '</small>): ' + $filter('Abbr')(parseFloat(this.point.options.value));
					},
					useHTML: true,
					style: {
						"fontSize": "12px",
						color: '#ADADAD'
					}
				},
				plotOptions: {
					series: {
						cursor: 'pointer',

						events: {

						}
					},
					treemap: {
						dataLabels: {
							align: parseInt(lang) == 1 ? 'center' : 'right',
							enabled: true,
							style: {
								"fontSize": "9px"
							},
							verticalAlign: "middle",
						},
						events: {
							click: function (event) {
								$scope.currentSector = event.point.id;
								$scope.$apply();
							}
						}
					}
				},
				series: [{
					type: "treemap",
					layoutAlgorithm: 'squarified',
					data: mapData,
					animation: false
				}],
				title: {
					text: ''
				}
			});
		}
	}])
	.controller('portfolioToolsCtrl', ['$scope', '$http', '$q', '$location', '$filter', '$timeout', '$log', '$window', 'portfolioData', '$uibModal',
		function ($scope, $http, $q, $location, $filter, $timeout, $log, $window, portfolioData, $uibModal) {
			var self = this;
			$scope.urlAppend = this.urlAppend;
			$scope.data = portfolioData.portfolio;
			$scope.currencies = portfolioData.currencies;
			$scope.reload = function () {
				blockUI('portfolioToolsCtrl');
				$http({
					url: siteRoot + 'tools/Portfolio',
					method: 'POST'
				}).then(function (res) {
					$scope.data = res.data.portfolio;
				}, (error) => { unblockUI('portfolioToolsCtrl'); console.log(error.data); })
					.finally(function () {
						unblockUI('portfolioToolsCtrl');

					});
			}
			$scope.addPorfolio = function ($event) {
				$event.preventDefault();
				var modalInstance = $uibModal.open({
					//templateUrl: '/content/theme/ng/partials/addPortfolio.html',
					template: "<div style=\"width:320px;\"> <div class=\"modal-header\"> <h4 class=\"modal-title txt-left\">{{'lblAddNewPortfolio'|getLabel}}</h4> </div><div class=\"modal-body\"> <div class=\"padding-5\"> <form method=\"POST\" name=\"portfolioForm\" ng-submit=\"portfolioForm.$valid && update(portfolio)\"> <div ng-show=\"success\" class=\"alert alert-success\" role=\"alert\"> <strong>{{'lblSuccess'|getLabel}}!</strong>{{'lblPortfolioSavedSuccessfully'|getLabel}}</div><div ng-show=\"error\" class=\"alert alert-danger\" role=\"alert\"> <strong>Error!</strong>{{'lblErrorOccured'|getLabel}}</div><div class=\"form-group\"> <label for=\"pName\" class=\"control-label pull-left\">{{'lblName'|getLabel}}</label> <input type=\"text\" class=\"form-control\" name=\"pName\" value=\"\" ng-model=\"portfolio.pName\" ng-required=\"true\" title=\"{{'lblPleaseEnterPrortflioName'|getLabel}}\" placeholder=\"{{'lblPortfolioName' | getLabel}}\" ng-pattern=\"\"> <div ng-show=\"portfolioForm.$submitted || portfolioForm.pName.$touched\" class=\"validation-div\"> <span ng-show=\"portfolioForm.pName.$error.required\" class=\"padding-5 alert alert-danger\">{{'lblRequired'|getLabel}}</span> <span ng-show=\"portfolioForm.pName.$error.pattern\" class=\"padding-5 alert alert-danger\">{{'lblInvalidName'|getLabel}}</span> </div></div><div class=\"form-group\"> <label for=\"pCash\" class=\"control-label pull-left\">{{'lblCash'|getLabel}}</label> <input type=\"text\" class=\"form-control\" ng-model=\"portfolio.pCash\" name=\"pCash\" placeholder=\"{{'lblCash'|getLabel}}\" value=\"\" ng-required=\"true\" title=\"{{'lblCashValue'|getLabel}}\" ng-pattern=\"/^[1-9][0-9]*(\.[0-9]+)?|0+\.[0-9]*[1-9][0-9]*$./\"> <div ng-show=\"portfolioForm.$submitted || portfolioForm.pCash.$touched\" class=\"validation-div\"> <span class=\"padding-5 alert alert-danger\" ng-show=\"portfolioForm.pCash.$error.required\">{{'lblRequired'|getLabel}}</span> <span class=\"padding-5 alert alert-danger\" ng-show=\"portfolioForm.pCash.$error.pattern||portfolioForm.pCash.$error.number\">{{'lblInvalidValue'|getLabel}}</span> </div></div><div class=\"form-group\"> <label for=\"pCash\" class=\"control-label pull-left\">{{'lblCurrency'|getLabel}}</label> <select ng-model=\"portfolio.pCurrency\" name=\"pCurrency\" class=\"form-control\"> <option ng-selected=\"c.CurrencyID==1\" ng-repeat=\"c in currencies\" value=\"{{c.CurrencyID}}\">{{c.Currency}}</option> </select> </div><hr class=\"padding-5 no-margin\"/> <div class=\"form-group row\"> <div class=\"col-sm-12 txt-right\"> <button ng-hide=\"saving&&saved\" type=\"submit\" class=\"btn btn-success pull-left\">{{'lblSave'|getLabel}}</button><button ng-hide=\"saving&&saved\" ng-click=\"Close()\" type=\"button\" class=\"btn btn-warning pull-right\">{{'lblCancel'|getLabel}}</button> </div></div></form> </div></div></div>",
					controller: 'addPortfolioPopupCtrl',
					scope: $scope,
					windowClass: 'app-modal-window',
					resolve: {
						'data': { d: $scope.portfolioData, c: $scope.currencies }
					}
				});



			}
		}])
	.controller('addPortfolioPopupCtrl', ['$http', '$timeout', '$scope', '$compile', '$uibModalInstance', '$filter', 'data',
		function ($http, $timeout, $scope, $compile, $uibModalInstance, $filter, data) {
			var self = this;
			$scope.success = false;
			$scope.error = false;
			$scope.saving = false;
			$scope.saved = false;
			$scope.archiveData = {};
			$scope.archiveDate = 1;
			$scope.data = {};
			$uibModalInstance.rendered.then(function () {
				$scope.data = data.d;
				$scope.currencies = data.c;

			});
			$scope.Close = function () {
				$uibModalInstance.close();
			};
			$scope.portfolio = {
				pName: '',
				pCash: '',
				pCurrency: '1'
			};

			$scope.update = function (portfolio) {
				$scope.saving = true;
				utility.toggleFormElements('portfolioForm', true);
				$http({
					url: siteRoot + 'tools/SaveNewPortfolio',
					data: { Name: portfolio.pName, Cash: portfolio.pCash, CurrencyID: portfolio.pCurrency },
					method: 'POST'
				}).then(function (res) {
					if (Number(res.data) > 0) {
						$scope.success = true;
						$scope.saved = true;
						$timeout(() => {
							$scope.$parent.reload();
							$uibModalInstance.close();
						}, 1000);
					} else {
						$scope.saved = false;
					}
				}, function () {
					$scope.error = true;
				}).finally(function () {
					$scope.saving = false;
					utility.toggleFormElements('portfolioForm', false);
				});
			};


		}])
	.controller('toolsAddCompanyCtrl', ['$global', '$scope', '$http', '$q', '$location', '$filter', '$timeout', '$log', '$window', '$uibModal', function ($global, $scope, $http, $q, $location, $filter, $timeout, $log, $window, $uibModal) {
			var self = this;
			var datePicker;
			$scope.model = {};
			$scope.success = false;
			$scope.error = false;
			$scope.info = false;
			$scope.infoMessage = "";
			$scope.loading = false;
			$scope.companyId = 0;
			$scope.transaction = '5';
			$scope.item = {};
			/*click events*/
			$scope.loadCompanies = function () { LoadPortfolioCompany(); }
			$scope.loadCashData = function () { LoadTransactions(); }
			
			$scope.companyModel = {
				Quantity: "",
				SharePrice: "",
				Commission: "",
				Notes: "",
				Date: ""
			};
			var cashEmpty = {
				cashType: '1',
				cash: '',
				cashDate: ''
			};

			$scope.init = function (model) {
				$scope.model = model;
				LoadPortfolioCompany();
			}
			$scope.searchSelectionCallback = function ($item) {
				$scope.companyId = $item === undefined ? 0 : $item.originalObject.ID;
				$scope.itemObject = $item === undefined ? {} : $item.originalObject;
			}
			$scope.focusOut = function () {
				clearText();
			}
			function clearText() {
				$scope.$broadcast("angucomplete-alt:clearInput", "txtCompaniesSearch");
			}

			$timeout(function () {
				datePicker = $("input[name=Date],input[name=cashDate]").datepicker({
					changeMonth: true,
					dateFormat: 'dd/mm/yy',
					changeYear: true
				});
				$(".date-picker").datepicker({
					showOn: 'button',
					buttonImage: '/content/theme/images/x_office_calendar.png',
					buttonImageOnly: true,
					changeMonth: true,
					changeYear: true,
					showAnim: 'slideDown',
					duration: 'fast',
					dateFormat: 'dd/mm/yy'
				});
			});
			$scope.DeletePortfolio = function ($event) {
				if (!$window.confirm($global.getResources("lblPortfolioDeleteConfirm"))) {
					return;
				}
				$http({
					method: 'POST',
					url: siteRoot + "Tools/DeletePortfolio",
					data: { PID: $scope.model.PortfolioID }
				}).then(function (resp) {
					if (parseInt(resp.data) == 1)
						alert($event.currentTarget.attributes["data-error-message"].value);
					else
						$window.location = $event.currentTarget.attributes["data-href"].value;
				}, (error) => { console.log(error.data); })
			}
			$scope.company = {
				Quantity: '',
				SharePrice: '',
				Commission: '',
				Notes: '',
				Date: ''
			};
			$scope.addCompany = function (company) {
				blockUI('fcontent1');
				$http({
					url: siteRoot + 'tools/SavePortfolio',
					data: {
						PortfolioID: $scope.model.PortfolioID,
						CompanyID: $scope.companyId,
						SymbolTicker: $scope.itemObject.Ticker,
						Quantity: company.Quantity,
						SharePrice: company.SharePrice,
						Commision: company.Commission,
						BuyDate: company.Date,
						Note: company.Notes,
						Transaction: $scope.transaction
					},
					method: 'POST'
				}).then(function (resp) {
					if (resp.data === '0') {
						$scope.success = true;
						$timeout(function () {
							ResetFlags();
							LoadPortfolioCompany();
						}, 1500);
					} else if (resp.data === '-2') {
						$scope.info = true;
						$scope.infoMessage = $global.getResources("lblCompanyAlreadyExistInfPortfolio");
						$timeout(function () {
							$scope.info = false;
							$scope.infoMessage = '';
						}, 1500);
					}
				}, function () {
					$scope.error = true;
					$timeout(function () {
						$scope.error = false;
					}, 1500);
				}).finally(function () {
					unblockUI('fcontent1');
				});
			}
			$scope.DeleteCompany = function ($event, rec) {
				$http({
					method: "POST",
					url: siteRoot + "tools/deletecompany",
					data: { PID: rec.PortfolioID, CID: rec.CompanyID, PortfolioCompanyID: rec.PortfolioCompanyID },
				}).then(function (resp) {
					if (resp.data.texist === 0 && resp.data.res == 1)
						LoadPortfolioCompany();
					else if (resp.data.texist === 1 && resp.data.res == 0)
						alert($global.getResources("lblPortfolioTransactionsExist"));
					else
						alert($global.getResources("lblErrorOccured"));

				}, (error) => { console.log(error.data); });
			}

			$scope.reset = function () { ResetFlags(); };
			function ResetFlags() {
				$scope.success = false;
				$scope.error = false;
				$scope.info = false;
				$scope.infoMessage = '';
				$scope.loading = false;
				$scope.companyId = 0;
				$scope.transaction = '5';
				clearText();
				$timeout(function () {
					$scope.company = angular.copy($scope.companyModel);
					$scope.companyForm.$setPristine();
					$scope.companyForm.$setUntouched();

					$scope.cashFormModel = angular.copy(cashEmpty);
					$scope.cashForm.$setPristine();
					$scope.cashForm.$setUntouched();
				});
			}
			function LoadPortfolioCompany() {
				blockUI('collapseOne');
				$http({
					method: "POST",
					url: siteRoot + "tools/getportfoliocompany",
					data: {
						PID: $scope.model.PortfolioID,
						CName: $scope.model.PortfolioName
					}
				}).then(function (resp) {
					$scope.portfolioCompanies = resp.data;
				}, (error) => { unblockUI('collapseOne'); console.log(error.data); })
					.finally(function () { unblockUI('collapseOne'); });
			}

			$scope.cashFormModel = {
				cashType: '1',
				cash: '',
				cashDate: ''
			};
			$scope.addCash = function (cashFormModel) {
				blockUI('fcontent2');
				$http({
					url: siteRoot + 'tools/SaveCash',
					method: 'POST',
					data: {
						PortfolioID: $scope.model.PortfolioID,
						CashTypeID: cashFormModel.cashType,
						Cash: cashFormModel.cash,
						BuyDate: cashFormModel.cashDate
					}
				}).then(function (resp) {
					if (parseInt(resp.data) > 0) {
						$scope.success = true;
						$timeout(function () {
							ResetFlags();
							LoadTransactions();
						}, 1500);
					} else {
						$scope.error = true;
						$timeout(function () {
							$scope.error = false;
						}, 1500);
					}
				}, function () {
					$scope.cashError = true;
					$timeout(function () {
						$scope.cashError = false;
					}, 1500);
				}).finally(function () {
					unblockUI('fcontent2');
				});
			}
			//Load Cash Manage Transactions
			function LoadTransactions() {
				blockUI('collapseOne');
				$http({
					method: "POST",
					url: siteRoot + "tools/cashmanage",
					data: { PID: $scope.model.PortfolioID, PName: $scope.model.PortfolioName }
				}).then(function (resp) {
					$scope.cashModel = resp.data;
				}, (error) => { unblockUI('collapseOne'); console.log(error.data); })
					.finally(function () { unblockUI('collapseOne'); });

		}


		/*Mutual fund section*/
		$scope.fundManagers = [];
		$scope.mutualFunds = [];
		$scope.portfolioFunds = [];
		$scope.fundModel = {
			portfolioId:$scope.model.PortfolioID,
			fundManager: '',
			mFundID:0,
			fundName: '',
			fundTransactionType:"5",
			fundQuantity: "",
			fundUnitPrice: '',
			fundCommission: '',
			fundNotes: '',
			fundDate: ''
		};
		
		$scope.loadFunds = (() => {
			
				loadPortfolioFunds();
				loadFundManagers();
			
		});

		function loadPortfolioFunds() {
			blockUI('collapseOne');
			$http({
				method: "POST",
				url: siteRoot + "tools/loadportfoliofunds",
				data: { portfolioId: $scope.model.PortfolioID }
			})
				.then((res) => {
					$scope.portfolioFunds = res.data;
					$scope.success = false;
					$scope.success = false;
					$scope.success = false;
					unblockUI('collapseOne');
				});
		}

		function loadFundManagers() {
			$('.fundmanager-picker').selectpicker('destroy');
			blockUI('collapseOne');
			$http({
				method: "POST",
				url: siteRoot + "tools/loadfundmanagers",
				data: {}
			}).then(function (resp) {
				$scope.fundManagers = resp.data;
				$scope.fundModel.fundManager = $scope.fundManagers.firstOrDefault().Value;
			}, (error) => { unblockUI('collapseOne'); console.log(error.data); })
				.finally(function () {
					$timeout(() => {
						$('.fundmanager-picker').selectpicker({
							style: 'fundmanager-picker',
							size: 8
						});
						$('.fund-picker').selectpicker({
							style: 'fund-picker',
							size: 8
						});
					});
					unblockUI('collapseOne');
				});
		}

		$scope.$watch('fundModel.fundManager', (n, o) => {
			$scope.mutualFunds = [];
				if (n) {
					loadMutualFundsForManager();
				}
		});
		function loadMutualFundsForManager() {
			blockUI('collapseOne');
			$http({
				method: "POST",
				url: siteRoot + "tools/loadfundmanagers",
				data: { searchText: $scope.fundModel.fundManager }
			}).then(function (resp) {
				$scope.mutualFunds = resp.data;
				$scope.fundModel.fundName = resp.data.firstOrDefault().Value;
			}, (error) => { unblockUI('collapseOne'); console.log(error.data); })
				.finally(function () {
					$timeout(() => {
						$('.fund-picker').selectpicker('refresh');
					});
					unblockUI('collapseOne');
				});
		}



		$scope.addFund = (() => {
			$scope.error = false;
			$scope.success = false;
			$scope.info = false;
			blockUI('collapseOne');
			$scope.fundModel.mFundID = $scope.mutualFunds.map((el) => { if (el.Value === $scope.fundModel.fundName) return el.Id; }).clean().firstOrDefault();
			$scope.fundModel.portfolioId = $scope.model.PortfolioID;
			$http({
				method: "POST",
				url: siteRoot + "tools/savefundsinportfolio",
				data: $scope.fundModel
			}).then(function (resp) {
				if (parseInt(resp.data) > 0) {
					$scope.success = true;
					loadMutualFundsForManager();
						loadPortfolioFunds();
						$scope.fundForm.$setPristine();
						$scope.fundForm.$setUntouched();
						$scope.fundModel = {
							mFundID: 0,
							fundName: '',
							fundTransactionType: "5",
							fundQuantity: "",
							fundUnitPrice: '',
							fundCommission: '',
							fundNotes: '',
							fundDate: ''
					};
					
				//	$('.fundmanager-picker').selectpicker('val', $scope.fundManagers.firstOrDefault().Value);
				//	$scope.fundModel.fundManager = $scope.fundManagers.firstOrDefault().Value;
				}
				else if (parseInt(resp.data) === -1) {
					
						$scope.info = true;
						$scope.infoMessage = $filter('getLabel')('lblFundAlreadyExist');
			
				} else {
					$scope.error = true;
				}
			}, (error) => { unblockUI('collapseOne'); console.log(error.data); })
			.finally(function () {
					unblockUI('collapseOne');
			});
		});

		$scope.DeleteFund = function ($event, rec) {
			blockUI('collapseOne');
			$http({
				method: "POST",
				url: siteRoot + "tools/deletefund",
				data: { portfolioMFundId: rec.PortfolioMFundID },
			}, (error) => { unblockUI('collapseOne'); console.log(error.data); })
				.then(function (resp) {
				//	console.log(resp.data);
					if (resp.data.texist === 0 && resp.data.res == 1)
						loadPortfolioFunds();
					else if (resp.data.texist === 1 && resp.data.res == 0)
						alert($global.getResources("lblPortfolioFundTransactionsExist"));
					else
						alert($global.getResources("lblErrorOccured"));

				}).finally(() => {
					unblockUI('collapseOne');
				});
		}

	}])
	.controller('toolsPortfolioTransactionDetailCtrl', ['$scope', '$http', '$q', '$location', '$filter', '$timeout', '$log', '$window', '$uibModal',
		function ($scope, $http, $q, $location, $filter, $timeout, $log, $window, $uibModal) {
			var self = this;
			$scope.portfolioValue = "0";
			$scope.companyID = 0;
			$scope.action = '';
			$scope.deleteAction = '0';
			$scope.model = {};
			$scope.transactionHistory = [];
			$scope.transactionModel = {
				Quantity: '',
				SharePrice: '',
				Fee: '',
				Note: '',
				BuyDate: '',
				Amount: '',
				Share: '',
				To: '',
				For: '',
			};
			var emptyModel = angular.copy($scope.transactionModel);
			$timeout(function () {
				datePicker = $("input[name=Date],input[name=buyDate]").datepicker({
					changeMonth: true,
					dateFormat: 'dd/mm/yy',
					changeYear: true
				});
			});
			$scope.init = function (model) {
				$scope.model = model;
				$scope.companyID = model.CompanyID.toString();
				LoadPortfolioHistory(model.CompanyID);
			}
			$scope.$watch("companyID", function (o, n) {
				o !== n && LoadPortfolioHistory();
			});
			$scope.$watch("action", function (o, n) {
				if (o !== n) {
					$scope.transactionModel = angular.copy(emptyModel);
					if ($scope.actionForm !== undefined) {
						$scope.actionForm.$setPristine();
						$scope.actionForm.$setUntouched();
					}
				}
			});
			$scope.processAction = function (transactionModel) {
				blockUI('divTransactionDetail');
				$http({
					method: "Post",
					url: siteRoot + "Tools/SaveTransaction",
					data: {
						PortfolioID: $scope.model.PortfolioID,
						CompanyID: $scope.companyID,
						Quantity: transactionModel.Quantity,
						ShareAmount: transactionModel.ShareAmount,
						Amount: transactionModel.Amount,
						SharePrice: transactionModel.SharePrice,
						SplitFrom: transactionModel.For,
						SplitTo: transactionModel.To,
						BuyDate: transactionModel.BuyDate,
						Commision: transactionModel.Fee,
						TransactionTypeID: $scope.action,
						Note: transactionModel.Note
					}
				}).then(function (resp) {
					LoadPortfolioHistory();
					$scope.action = '';
				}, (error) => { unblockUI('divTransactionDetail'); console.log(error.data); })
					.finally(function () {
						unblockUI('divTransactionDetail');
					});
			}
			$scope.DeleteTransactions = function ($event) {
				if (confirm($event.currentTarget.attributes["data-confirmation"].value)) {
					$http({
						method: "POST",
						url: siteRoot + "Tools/DeleteTransactions",
						data: { PID: $scope.model.PortfolioID, CID: $scope.companyID, TID: $scope.deleteAction }
					}).then(function (resp) {
						if (resp.data == "1")
							LoadPortfolioHistory();
					}, (error) => { console.log(error.data); });

					$scope.deleteAction = '0';
				}
			}
			function LoadPortfolioHistory() {
				blockUI('divTransactionDetail');
				$http({
					method: "POST",
					url: siteRoot + "Tools/PortfolioHistory",
					data: { PID: $scope.model.PortfolioID, CID: $scope.companyID }
				}).then(function (resp) {
					$scope.transactionHistory = resp.data;
				}, (error) => { unblockUI('divTransactionDetail'); console.log(error.data); })
					.finally(function () { unblockUI('divTransactionDetail'); });
			}


		}])
	.controller('toolsPortfolioFundTransactionDetailCtrl', ['$scope', '$http', '$q', '$location', '$filter', '$timeout', '$log', '$window', '$uibModal',	function ($scope, $http, $q, $location, $filter, $timeout, $log, $window, $uibModal) {
			var self = this;
			$scope.portfolioValue = "0";
			$scope.fundId = 0;
			$scope.action = '';
			$scope.deleteAction = '0';
			$scope.model = {};
			$scope.transactionHistory = [];
			$scope.transactionModel = {
				Quantity: '',
				SharePrice: '',
				Fee: '',
				Note: '',
				BuyDate: '',
				Amount: '',
				Share: '',
				To: '',
				For: '',
			};
			var emptyModel = angular.copy($scope.transactionModel);
		$timeout(function () {
			$(".date-picker").datepicker({
				showOn: 'button',
				buttonImage: '/content/theme/images/x_office_calendar.png',
				buttonImageOnly: true,
				changeMonth: true,
				changeYear: true,
				showAnim: 'slideDown',
				duration: 'fast',
				dateFormat: 'dd/mm/yy'
			});


				//datePicker = $("input[name=Date]").datepicker({
				//	changeMonth: true,
				//	dateFormat: 'dd/mm/yy',
				//	changeYear: true
				//});
			});
			$scope.init = function (model) {
				$scope.model = model;
				$scope.fundId = model.fundId.toString();
				LoadPortfolioHistory(model.fundId);
			}
			$scope.$watch("fundId", function (o, n) {
				o !== n && LoadPortfolioHistory();
			});
			$scope.$watch("action", function (o, n) {
				if (o !== n) {
					$scope.transactionModel = angular.copy(emptyModel);
					if ($scope.actionForm !== undefined) {
						$scope.actionForm.$setPristine();
						$scope.actionForm.$setUntouched();
					}
				}
			});
		$scope.processAction = function (transactionModel) {
				blockUI('divTransactionDetail');
				$http({
					method: "POST",
					url: siteRoot + "tools/insertportfoliofundhistory",
					data: {
						portfolioId: $scope.model.portfolioId,
						mfundId: $scope.fundId,
						fundQuantity: transactionModel.Quantity,
						fundShareAmount: transactionModel.ShareAmount,
						fundAmount: transactionModel.Amount,
						fundUnitPrice: transactionModel.SharePrice,
						fundSplitFrom: transactionModel.For,
						fundSplitTo: transactionModel.To,
						fundDate: transactionModel.BuyDate,
						fundCommission: transactionModel.Fee,
						fundTransactionType: $scope.action,
						fundNotes: transactionModel.Note
					}
				}).then(function (resp) {
					LoadPortfolioHistory();
					$scope.action = '';
				}, (error) => { unblockUI('divTransactionDetail'); console.log(error.data); })
					.finally(function () {
						unblockUI('divTransactionDetail');
					});
			}
			$scope.DeleteTransactions = function ($event) {
				if (confirm($event.currentTarget.attributes["data-confirmation"].value)) {
					$http({
						method: "POST",
						url: siteRoot + "tools/deletefundtransactions",
						data: { portfolioId: $scope.model.portfolioId, fundId: $scope.fundId, transactionId: $scope.deleteAction }
					}).then(function (resp) {
						if (resp.data == "1")
							LoadPortfolioHistory();
					}, (error) => { console.log(error.data); });

					$scope.deleteAction = '0';
				}
			}
			function LoadPortfolioHistory() {
				blockUI('divTransactionDetail');
				$http({
					method: "POST",
					url: siteRoot + "FundTransactions",
					data: { portfolioId: $scope.model.portfolioId, fundId: $scope.fundId }
				}).then(function (resp) {
					$scope.transactionHistory = resp.data.transactions;
				}, (error) => { unblockUI('divTransactionDetail'); console.log(error.data); })
					.finally(function () { unblockUI('divTransactionDetail'); });
			}
		}])
	.controller('searchPortfolioToolsCtrl', ['$global', '$scope', '$http', '$q', '$location', '$filter', '$timeout', '$log', '$window', '$uibModal', '$interval',
		function ($global, $scope, $http, $q, $location, $filter, $timeout, $log, $window, $uibModal, $interval) {
			var self = this;
			/*New ticker*/
			var pEelemIndex = 0;
			var totalPortfolioNews = 0;
			$scope.allPNews = [];
			$scope.pNews = {};
			$scope.pNewsTitle = "";
			var totalPNews = 0;
			var pCaptionLength = 0;
			var pCharTimeOut = 20;
			var pNewsTimeOut = 7000;
			var pCaption = "";
			var pIntervalID = undefined;
			//news ticker


			$scope.loaded = true;
			$scope.portfolioData = {};
			$scope.marketSummaryModel = [];
			$scope.ratioRawData = [];
			$scope.annoucementModel = [];
			$scope.newsModel = [];
			$scope.PortfolioList = '';
			$scope.auth = undefined;
			$scope.init = function (model, auth) {
				$scope.auth = Number(auth);
				$scope.portfolioData = model;
				$timeout(function () { $scope.PortfolioList = model.PortfolioID; });
			}
			$scope.PortfolioValue = -1;
			$scope.ConfirmNav = function ($event) {
				$event.preventDefault();
				$.when(
					utility.confirm(
						$filter('getLabel')("lblWantToTakePortfolioScreenshort") + '' + ("lblConfirmation"),
						$filter('getLabel')("lblWantToTakePortfolioScreenshort"),
						$filter('getLabel')("lblYes"),
						$filter('getLabel')("lblNo")
					)
				).then(
					function (status) {
						if (status === "Yes") {
							$timeout(() => {
								$scope.saveCurrentPortfolio(undefined);
							});
							return;
						} else {
							window.location.href = $event.currentTarget.attributes.href.value;
						}
					});

			}

			$scope.$watch('PortfolioList', function (o, n) {
				o !== n && $scope.loadView();
			});
			$scope.$watch('ratioRawData', function (n, o) {
				ProcessRatios();
			});
			$scope.loadView = function () {
				$scope.loaded = false;
				$scope.marketSummaryModel = [];
				$scope.gRatios = [];
				if ($scope.PortfolioValue === -1) {
					new searchPortfolioFunctions().LoadTransactionsforPortfolio("PortfolioID", "0");

				}
				if ($scope.PortfolioValue === 0) {
					new searchPortfolioFunctions().LoadMarketSummary();
				}
				if ($scope.PortfolioValue > 0) {
					new searchPortfolioFunctions().LoadGeneralRatios();
				}
			}
			function searchPortfolioFunctions() {
				var pself = this;
				this.LoadNews = function () {
					$http({
						method: 'POST',
						url: siteRoot + "Tools/PortfolioGraphs",
						data: { pid: $scope.PortfolioList }
					}).then(function (res) {
						pself.CreatePortfolioCharts(res.data);
					});
				}
				this.LoadTransactionsforPortfolio = function (sortby, sortDir) {
					blockUI('collapseOne');
					$http({
						method: 'POST',
						url: siteRoot + "tools/cashmanage",
						data: { pid: $scope.PortfolioList, pname: $scope.portfolioData.PortfolioName, sortBy: sortby, sortDir: sortDir }
					}, function () { alert('An error occured while processing your request. Please try again later'); unblockUI('collapseOne'); })
						.then(function (res) {
							$scope.TransactionsforPortfolio = res.data;
							new searchPortfolioFunctions().LoadNews();
						}, (error) => { unblockUI('collapseOne'); console.log(error.data); })
						.finally(function () {
							$scope.loaded = true;
							unblockUI('collapseOne');
						});
				}
				this.LoadMarketSummary = function () {

					blockUI('collapseOne');
					$http({
						method: 'POST',
						url: siteRoot + "tools/MarketSummary",
						data: { pid: $scope.PortfolioList, aid: $scope.PortfolioValue }
					}).then(function (res) {
						$scope.marketSummaryModel = res.data;
						new searchPortfolioFunctions().LoadNews();
					}, function () { alert('An error occured while processing your request. Please try again later'); unblockUI('collapseOne'); })
						.finally(function () {
							$scope.loaded = true;
							unblockUI('collapseOne');
						});
				},
				this.LoadGeneralRatios = function () {
						var portfolioName = $.grep($scope.portfolioData.Portfolios, function (elem) { return elem.Id === parseInt($scope.PortfolioList); }).firstOrDefault().Text;
						blockUI('collapseOne');
						$http({
							method: 'POST',
							url: siteRoot + "tools/generalratios",
							data: { pid: $scope.PortfolioList, pname: portfolioName, flag: $scope.PortfolioValue }
						}, function () { alert('An error occured while processing your request. Please try again later'); unblockUI('collapseOne'); })
							.then(function (res) {
								$scope.titles = [];
								$scope.ratioRawData = res.data.ratioModel;
							}, (error) => { unblockUI('collapseOne'); console.log(error.data); })
							.finally(function () {
								$scope.loaded = true;
								new searchPortfolioFunctions().LoadNews();
								unblockUI('collapseOne');
							});
					},
				this.CreateCharts = function (allData) {
						let assetAllocation = [];
						let countryAllocation = [];
						let capSizeAllocation = [];
						let sectorAllocation = [];

						let assetArray = allData.graphs.slice(0, 9);
						let totalGrand = parseFloat(allData.totalGrand);
						angular.forEach(assetArray, function (elem) {

							//asset Allocation

							let conversionValue = parseInt(elem.ConversionCurrentValue);
							let conversionVal = parseFloat((conversionValue / totalGrand) * 100);
							if (conversionValue > 0)
								assetAllocation.push([
									elem.Ticker, conversionVal
								]);
						});
						if (allData.graphs.length > 10) {
							var otherData = allData.graphs.slice(10);
							var allDataCValue = otherData.map(function (elem) { return elem.ConversionCurrentValue; }).clean().sum();
							var allDataVal = parseFloat((allDataCValue / totalGrand) * 100);
							if (allDataVal > 0)
								assetAllocation.push([
									"Others", allDataVal
								]);
						}
						let cashValue = parseFloat(allData.graphs.firstOrDefault().Cash);
						let cashDivValue = (cashValue / totalGrand) * 100;
						if (Math.abs(cashDivValue) > 0)
							assetAllocation.push(["Cash", cashDivValue]);

						createGraph('chrtAssetAllocation', $global.getResources("lblAssetsAllocation"), assetAllocation);
						//country allocation
						let countries = $filter('unique')(allData.graphs.map(function (abb) { return abb.Abbr; }));
						angular.forEach(countries, function (country) {
							let conversionSum = allData.graphs.map(function (m) { if (m.Abbr === country) return m.ConversionCurrentValue; }).clean().sum();
							let totalConvertion = allData.graphs.map(function (m) { return m.ConversionCurrentValue; }).clean().sum();
							let conversionValue = parseFloat((conversionSum / totalConvertion) * 100);
							if (conversionValue > 0)
								countryAllocation.push([
									country,
									(conversionSum / totalConvertion) * 100
								]);
							createGraph('chrtCountryAllocation', $global.getResources("lblCountryAllocation"), countryAllocation);
						});

						//capsize allocation
						var capsizes = $filter('unique')(allData.graphs.map(function (abb) { return abb.CapSize; }));
						angular.forEach(capsizes, function (capsize) {
							var conversionSum = allData.graphs.map(function (m) { if (m.CapSize === capsize) return m.ConversionCurrentValue; }).clean().sum();
							var totalConvertion = allData.graphs.map(function (m) { return m.ConversionCurrentValue; }).clean().sum();
							var conversionValue = parseFloat((conversionSum / totalConvertion) * 100);
							if (conversionValue > 0)
								capSizeAllocation.push([
									capsize, conversionValue
								]);
							createGraph('chrtMarketCapAllocation', $global.getResources("lblMarketCapAllocation"), capSizeAllocation);
						});

						//sector allocation
						var sectors = $filter('unique')(allData.graphs.map(function (abb) { return abb.Sector; }));
						angular.forEach(sectors, function (sector) {
							var conversionSum = allData.graphs.map(function (m) { if (m.Sector === sector) return m.ConversionCurrentValue; }).clean().sum();
							var totalConvertion = allData.graphs.map(function (m) { return m.ConversionCurrentValue; }).clean().sum();
							var conversionValue = parseFloat((conversionSum / totalConvertion) * 100);
							if (conversionValue > 0)
								sectorAllocation.push([
									sector, conversionValue
								]);
							createGraph('chrtSectorAllocation', $global.getResources("lblSectorsAllocation"), sectorAllocation);
						});
					}
				
				this.CreatePortfolioCharts = function (graphsData) {
					let assetAllocation = [];
					let countryAllocation = [];
					let totalConvertion = graphsData.ca.map(function (m) { return m.Value; }).clean().sum();
					angular.forEach(graphsData.ca, function (v, i) {
						countryAllocation.push({ key: v.Country, y: v.Value,val:v.Value });
					});
					createGraph('chrtCountryAllocation', $global.getResources("lblCountryAllocation"), countryAllocation);

					assetAllocation.push({ key: $filter('getLabel')('lblMutualFundTotal'), y: graphsData.aa.firstOrDefault().MFundTotal});
					assetAllocation.push({ key: $filter('getLabel')('lblEquitiesTotal'), y: graphsData.aa.firstOrDefault().EquitiesTotal });
					assetAllocation.push({ key: $filter('getLabel')('lblCash'), y: graphsData.aa.firstOrDefault().Cash });
					createGraph('chrtAssetAllocation', $global.getResources("lblAssetsAllocation"), assetAllocation);
				}
			}
			function createGraph(chartId, title, chartData) {
				$('#' + chartId).highcharts({
					chart: {
						type: 'pie',
						direction: 'rtl',
						showInLegend: true,
						options3d: {
							enabled: true,
							alpha: 50,
							beta: 0
						},
						watermark: {
							text: ''
						},
						margin: [20, 0, 0, 0],
						spacingTop: 0,
						spacingBottom: 0,
						spacingLeft: 0,
						spacingRight: 0
					},
					title: {
						text: title

					},
					labels: {
						useHTML: true,
						style: {
							color: '#222'
						}
					},
					credits: {
						enabled: false
					},
					tooltip: {
						useHTML: true,
						formatter: function () {
							return `<div class="direction:ltr; defualt-color"><span class="displayInline">${this.point.options.key}: </span><span class="displayInline">${$filter('suffix')($filter('WNOrDec')(this.point.percentage, 2), '%')}</span></div>`;
						}
					},
					plotOptions: {
						pie: {
							allowPointSelect: false,
							cursor: 'pointer',
							depth: 40,
							dataLabels: {
								useHTML: true,
								formatter: function () {
									return `<div class="direction:ltr;"><span class="displayInline">${this.point.options.key}: </span><span class="displayInline">${$filter('suffix')($filter('WNOrDec')(this.point.percentage, 2), '%')}</span></div>`;
								},
								style: {
									color: '#222'
								},
								useHTML: true,
								distance: 5
							}
						}
					},

					series: [{
						type: 'pie',
						data: chartData,
						showInLegend: false,
						dataLabels: {
							enabled: true,
							padding: 0
						}
					}],
					exporting: {
						enabled: false
					}
				});
			}
			function ProcessRatios() {
				$scope.gRatios = [];
				$scope.fields = [];
				var tempfields = $filter('unique')($scope.ratioRawData.map(function (elem) { return elem.FName; }));
				tempfields.forEach(function (field) {
					if ($.grep($scope.ratioRawData, function (elem) { return elem.FName === field && elem.Value > 0; }).length > 0) {
						var record = $.grep($scope.ratioRawData, function (elem) { return elem.FName === field }).firstOrDefault();
						$scope.fields.push({ FieldName: record.FieldName, FName: record.FName, GBFact: record.GBFact, ValueType: record.ValueType });
					}
				});
				$scope.companies = $filter('unique')($scope.ratioRawData.map(function (elem) { return elem.CompanyID; }));
				PopulateRatios();

			}
			function PopulateRatios() {

				$scope.companies.forEach(function (cid) {
					var values = [];
					$scope.fields.forEach(function (field) {

						var record = $.grep($scope.ratioRawData, function (elem) { return elem.FName === field.FName && elem.CompanyID === cid; }).firstOrDefault();
						if (typeof (record) === 'function') return;
						values.push({
							FieldName: record.FName,
							Value: record.Value,
							ValueType: record.ValueType,
							Title: record.Title,

						});
					});

					$scope.gRatios.push({
						CompanyID: cid,
						CompanyTicker: $.grep($scope.ratioRawData, function (elem) { return elem.CompanyID === cid; }).firstOrDefault().CompanyTicker,
						Ticker: $.grep($scope.ratioRawData, function (elem) { return elem.CompanyID === cid; }).firstOrDefault().Ticker,
						Company_URL: $.grep($scope.ratioRawData, function (elem) { return elem.CompanyID === cid; }).firstOrDefault().Company_URL,
						Transaction_Detail_URL: $.grep($scope.ratioRawData, function (elem) { return elem.CompanyID === cid; }).firstOrDefault().Transaction_Detail_URL,
						values: values
					});
				});
			}
			/**Sorting*/
			//basic sorting
			$scope.basicViewSort = {
				column: 'Ticker',
				descending: false
			};
			$scope.basicFundViewSort = {
				column: 'Name',
				descending: false
			};


			$scope.basicSelectedCls = function (column) {
				return column == $scope.basicViewSort.column ? $scope.basicViewSort.descending ? "sorting_asc" : "sorting_desc" : 'sorting';
			};
			$scope.basicFundSelectedCls = function (column) {
				return column == $scope.basicFundViewSort.column ? $scope.basicFundViewSort.descending ? "sorting_asc" : "sorting_desc" : 'sorting';
			};


			$scope.basicChangeSorting = function (column) {

				if ($scope.basicViewSort.column == column) {
					$scope.basicViewSort.descending = !$scope.basicViewSort.descending;
				} else {
					$scope.basicViewSort.column = column;
					$scope.basicViewSort.descending = false;
				}
			};
			$scope.basicFundChangeSorting = function (column) {

				if ($scope.basicFundViewSort.column == column) {
					$scope.basicFundViewSort.descending = !$scope.basicFundViewSort.descending;
				} else {
					$scope.basicFundViewSort.column = column;
					$scope.basicFundViewSort.descending = false;
				}
			};
			//End Basic Sorting

			//Ratio sorting
			$timeout(function () {
				$scope.ratioViewSort = {
					column: '',
					descending: false
				};

				$scope.ratioSelectedCls = function (column) {
					return column == $scope.ratioViewSort.column ? $scope.ratioViewSort.descending ? "sorting_asc" : "sorting_desc" : 'sorting';
				};
				$scope.ratioChangeSorting = function (column) {

					if ($scope.ratioViewSort.column == column) {
						$scope.ratioViewSort.descending = !$scope.ratioViewSort.descending;
					} else {
						$scope.ratioViewSort.column = column;
						$scope.ratioViewSort.descending = false;
					}
					if ($scope.ratioViewSort.column === "CompanyTicker")
						$scope.gRatios = $scope.gRatios.sort(sortBy($scope.ratioViewSort.column, $scope.ratioViewSort.descending));
					else {
						var tempCompanies = [];
						$scope.companies.forEach(function (elem) {
							tempCompanies.push({
								cid: elem,
								value: $.grep($scope.ratioRawData, function (r) { return r.CompanyID === elem && r.FName === $scope.ratioViewSort.column; }).firstOrDefault().Value
							});
						});
						tempCompanies = tempCompanies.sort(sortBy("value", $scope.ratioViewSort.descending));
						$scope.companies = tempCompanies.map(function (c) { return c.cid; });
						$scope.gRatios = [];
						PopulateRatios();
					}
					//   $filter('orderBy')($scope.gRatios, $scope.ratioViewSort.column, $scope.basicViewSort.descending);
				};
			});
			$scope.showPortfolioHistory = function ($event) {
				$event.preventDefault();
				var portfolioName = $.grep($scope.portfolioData.Portfolios, function (elem) { return elem.Id === parseInt($scope.PortfolioList); }).firstOrDefault().Text;
				var modalInstance = $uibModal.open({
					template:`<div style="min-width:620px;">
					<div class="popup-header">
					<a title="Close" class="popup-close" href="javascript:;" ng-click="Close()"><i class="fa fa-times"></i></a>
					<div class="popup-header-content">
					<h5 class="search-h5 color-white" data-h="{{PortflioName}}" style="padding:5px;">${$filter("getLabel")("lblScreenshot")} ({{PortflioName}})</h5></div></div><div class="space-5"></div>
					<div id="portfolioBody" class="modal-body height-400 overflow-auto">
					<div id="portfolioHistoryData" style="min-width:100%; height:auto;text-align:center;"></div>
					<div id="portfolio-history" style="min-height:100px;" ng-bind-html="historyData"><i class="fa fa-spinner fa-cog fa-3x"></i></div>
					</div></div></div>`,
					controller: 'portfolioHistoryPopupCtrl',
					scope: $scope,
					windowClass: 'app-modal-window',
					resolve: {
						'data': { PortfolioId: $scope.PortfolioList, PortfolioName: portfolioName }
					}
				});

			}
			$scope.saveCurrentPortfolio = function ($event) {
				let addCompanyLink;
				if ($event === undefined)
					addCompanyLink = $('#addCompanyLink').attr('href');
				var portfolioName = $.grep($scope.portfolioData.Portfolios, function (elem) { return elem.Id === parseInt($scope.PortfolioList); }).firstOrDefault().Text;
				var modalInstance = $uibModal.open({
					templateUrl: "/content/theme/ng/partials/SavePorfolioScreenshot.html",
					controller: 'savePortfolioPositionPopupCtrl',
					scope: $scope,
					windowClass: 'app-modal-window',
					resolve: {
						'data': { PortfolioId: $scope.PortfolioList, PortfolioName: portfolioName, valuesData: $scope.TransactionsforPortfolio, returnLink: addCompanyLink }
					}
				});
			}

			//portfolio News Section

			$scope.PortfolioPrevNews = function ($event) {
				if (pEelemIndex - 2 >= 0) {
					pEelemIndex = pEelemIndex - 2;
					ResetPInterval();
					pScrollNews();
				}
			}
			$scope.PortfolioNextNews = function ($event) {
				if (totalPortfolioNews > pEelemIndex - 1) {
					ResetPInterval();
					pScrollNews();
				}
			}
			$(".navli:last .child li ul.sub-child").removeClass("sub-child").addClass("menuleft");

			//get the scroll news
			function pScrollNews() {
				$scope.pNewsTitle = "";
				$scope.pNews = $scope.allPNews[pEelemIndex];

				if ($scope.pNews !== undefined) {
					ResetPInterval();
					pCaption = $scope.pNews.Title;
					typePortfolioLetters();
					pEelemIndex = pEelemIndex + 1 > $scope.allPNews.length ? 0 : ++pEelemIndex;
				} else {
					pEelemIndex = pEelemIndex + 1 > $scope.allPNews.length ? 0 : ++pEelemIndex;
					pScrollNews();
				}
			}
			//typing effect javascript
			function typePortfolioLetters() {
				$scope.pNewsTitle = pCaption.substr(0, pCaptionLength++);
				if (pCaptionLength < pCaption.length + 1) {
					$timeout(typePortfolioLetters, pCharTimeOut);
				}
				else {
					pCaptionLength = 0;
					pCaption = "";
				}
			}
			$scope.PortfolioNewsCategoryClass = function (val) {
				var style = "";
				if (val === undefined) return "no-class";
				switch (val.NewsCategoryID) {
					case 1:
						style = "label-home-1";
						break;
					case 2:
						style = "label-home-2";
						break;
					case 3:
						style = "label-home-3";
						break;
					case 7:
						style = "label-home-4";
						break;
					case 4:
						style = "label-home-5";
						break;
					default:
						style = "label-home-6"
				}
				return style;
			}
			$scope.PortfolioNewsUrl = function (val) {
				var url = "";
				switch (val.NewsCategoryID) {
					case 0:
						url = $filter('getURL')(val.Corporate_Ann_URL);
						break;
					case 3:
						url = $filter('getURL')(val.More_Url);
						break;
				}
				return url;
			}

			function ResetPInterval() {
				if ($scope.allPNews.length == 0) return;
				$timeout.cancel(pCharTimeOut);
				if (angular.isDefined(pIntervalID)) {
					$interval.cancel(pIntervalID);
					pIntervalID = undefined;
				}
				if (pIntervalID === undefined)
					pIntervalID = $interval(pScrollNews, pNewsTimeOut);
			}
			$scope.StopInterval = function () {
				$timeout.cancel(pCharTimeOut);
				if (pIntervalID !== undefined) {
					$interval.cancel(pIntervalID);
					pIntervalID = undefined;
				}
			}
			$scope.ResumeInterval = function () {
				if (pIntervalID === undefined) {
					pIntervalID = $interval(pScrollNews, pNewsTimeOut);
				}
			}
			// End portfolio News Section
		}])
	.controller('portfolioHistoryPopupCtrl', ['$global', '$http', '$scope', '$compile', '$uibModalInstance', '$filter', 'data', function ($global, $http, $scope, $compile, $uibModalInstance, $filter, data) {
		var self = this;
		$scope.archiveData = {};
		$scope.archiveDate = 1;
		$scope.data = {};		
		$uibModalInstance.rendered.then(function () {
			
			$scope.data = data.d;
			$scope.PortfolioId = data.PortfolioId;
			$scope.PortflioName = data.PortfolioName;
			$scope.LoadArchiveDate();
		});
		$scope.Close = function () {
			$uibModalInstance.close();
		};
		$scope.init = function (archiveData) {
			$scope.archiveData = archiveData;
			$scope.archiveDate = archiveData[0].ID;
		}
		$scope.loadPortfolioHistory = function ($event) {
			var date = [];
			angular.forEach($scope.archiveData, function (elem) { if (elem.ID === $scope.archiveDate) this.push(elem.ArchiveDate); }, date);
			blockUI('portfolioBody');
			$http({
				method: 'POST',
				url: siteRoot + "Tools/PortfolioHistroyControl",
				data: {
					'PID': $scope.PortfolioId, 'date': date[0]
				},
			}).then(function (res) {
				$scope.historyData = res.data;
				$compile(angular.element($('div.popup-header')));
			}, (error) => { console.log(error.data); })
				.finally(() => { unblockUI('portfolioBody'); });
		}
		$scope.LoadArchiveDate = function () {
			blockUI('portfolioBody');
			$http({
				method: 'POST',
				url: siteRoot + "Tools/PortfolioArchiveDate",
				data: { 'PID': $scope.PortfolioId },
			}).then(function (res) {
				document.getElementById("portfolioHistoryData").innerHTML = res.data;
				$compile(document.getElementById('portfolioHistoryData'))($scope);
				}, (error) => { unblockUI('portfolioBody'); console.log(error.data); })
				.finally(function () {
					unblockUI('portfolioBody');
				});
		}
	}])
	.controller('savePortfolioPositionPopupCtrl', ['$http', '$scope', '$compile', '$uibModalInstance', '$filter', 'data', '$timeout',
		function ($http, $scope, $compile, $uibModalInstance, $filter, data, $timeout) {
			var self = this;
			let returnLink = data.returnLink;
			$scope.archiveData = {};
			$scope.archiveDate = 1;
			$scope.data = {};
			$scope.currentDate = $filter('date')(new Date(), "dd/MM/yyyy hh:mm:ss a");
			$scope.valuesHtml = {};
			$uibModalInstance.rendered.then(function () {
				$scope.data = data;
				$scope.TransactionsforPortfolio = data.valuesData;

			});
			$scope.Close = function () {
				$uibModalInstance.close();
			};
			$scope.SavePortfolioNotes = function ($event) {
				$event.preventDefault();
				$scope.type = "info";
				$scope.saving = true;
				$http({
					method: 'POST',
					url: siteRoot + "Tools/SaveCurrentPortfolio",
					data: { 'pid': $scope.data.PortfolioId, 'note': $scope.portfolioNotes, 'pdate': $scope.currentDate },
				}).then(function (resp) {
					$scope.type = "success";
					$scope.saving = false;
					$scope.saved = true;
					$scope.msg = "Request processed successfully";
					$timeout(function () {
						$uibModalInstance.close();
					});
					if (returnLink !== undefined)
						window.location.href = returnLink;
				}, function () {
					$scope.type = "danger";
					$scope.saving = false;
					$scope.saved = true;
					$scope.msg = "An error occurred while processing your request. Please try again later.";
				}).finally(function () {
					$timeout(function () {
						$scope.type = "info";
						$scope.saving = true;
						$scope.saved = false;
						$scope.msg = "";
					}, 1000);
				});

			}
		}])
	.controller('InvestingIdeasCtrl', ['$global', '$scope', '$http', '$q', '$filter', "$timeout", '$window', function ($global, $scope, $http, $q, $filter, $timeout, $window) {
		blockUI('investingPage');
		$scope.itemsPerPage = 5;
		$scope.maxSize = 5;
		$scope.totalItems = 1;
		$scope.pageId = parseInt($.getQueryString('page'));
		$scope.auth = undefined;
		$scope.init = ((regType) => {
			$scope.auth = regType === null ? 0 : parseInt(regType);
		});


		$timeout(function () {
			$http({
				method: 'POST',
				url: siteRoot + 'tools/investingidea/' + $scope.CountryId,
				data: { page: $scope.pageId }
			})
				.then(function (res) {
					$scope.InvestingItem = res.data;
				}, (error) => { console.log(error.data); })
				.finally(function () {
					$timeout(function () {

						$('.investing_ideas').each(function (d) {
							var cid = $(this).data("cid");

							$scope.filterData = $filter('filter')($scope.InvestingItem.Charts, { CompanyID: cid }, true);
							var Ticker = $filter('filter')($scope.InvestingItem.Tweets, { CompanyID: cid }, true)[0].Ticker;
							var candlestickData = [], lineChartData = [], volumeData = [];

							angular.forEach($scope.filterData, function (v) {
								lineChartData.push([
									parseInt(v.Date.slice(6, -2)),
									v.ClosingPrice
								]);
								candlestickData.push([
									parseInt(v.Date.slice(6, -2)),
									v.OpeningPrice,
									v.HighestPrice,
									v.LowestPrice,
									v.ClosingPrice
								]);
								volumeData.push([parseInt(v.Date.slice(6, -2)), v.Volume]);
							});

							var chartOption = {
								chart: {
									borderColor: '#3a3a3a',
									backgroundColor: "#000",
								},
								xAxis: {
									type: 'datetime',
									gridLineColor: '#3a3a3a',
									lineColor: '#3a3a3a',
								},
								watermark: {
									yAxis: 280
								},
								yAxis: [{
									labels: {
										x: -5,
										y: -3
									},
									gridLineColor: '#3a3a3a',
									lineColor: '#3a3a3a',
									title: {
										text: $global.getResources("lblPrice"),
										y: -10,
										x: -5,
										color: "#ADADAD",
										offset: 15,
									},
									height: 250,
								}, {
									title: {
										text: $global.getResources("lblVolume"),
										y: -10,
										x: -5,
										offset: 15,
									},
									labels: {
										x: -5,
										style: {
											color: "#ADADAD"
                                        },
										y: -3
									},
									top: 300,
									gridLineColor: '#3a3a3a',
									lineColor: '#3a3a3a',
									height: 100,
									offset: 0,
								}],
								tooltip: {
									crosshairs: true,
									shared: true,
									enabledIndicators: true,
									followPointer: false,
									backgroundColor: "white",
									borderWidth: 0,
									borderRadius: 0,
									shape: "square",
									formatter: function () {
										var tooltipHtml = '';
										var tadate = null;
										var primary = $.grep(this.points, function (elem) { return elem.series.name === 'primary' }).firstOrDefault();
										if (!angular.isFunction(primary)) {
											tadate = '<p class="defualt-color"><b>' + $filter('getLabel')('lblDate') + ':</b>' + $filter('date')(primary.x, 'dd/MM/yyyy') + "</p>";
										}
										var cS = $.grep(this.points, function (elem) { return elem.series.name === "candlestick" }).firstOrDefault();
										if (!angular.isFunction(cS)) {
											tooltipHtml += '<p  class="defualt-color"><b>' + $filter('getLabel')('lblOpen') + ':</b>' + $filter('number')(cS.point.open, 2) + "</p>";
											tooltipHtml += '<p class="defualt-color"><b>' + $filter('getLabel')('lblHigh') + ':</b>' + $filter('number')(cS.point.high, 2) + "</p>";
											tooltipHtml += '<p class="defualt-color"><b> ' + $filter('getLabel')('lblLow') + ':</b>' + $filter('number')(cS.point.low, 2) + "</p>";
											tooltipHtml += '<p class="defualt-color"><b> ' + $filter('getLabel')('lblClose') + ':</b>' + $filter('number')(cS.point.close, 2) + "</p>";
										}
										var volume = $.grep(this.points, function (elem) { return elem.series.name === "Volume" }).firstOrDefault();
										if (!angular.isFunction(volume)) {
											tooltipHtml += '<p class="defualt-color"><b>  ' + $filter('getLabel')('lblVolume') + ':</b>' + $filter('number')(volume.y, 0) + "</p>";
										}
										var smas = $.grep(this.points, function (elem) { return elem.series.name.indexOf('SMA') !== -1; });
										if (smas.length > 0) {
											angular.forEach(smas, function (sm) {
												tooltipHtml += '<p class="defualt-color"><label class="direction-ltr margin-left-2 margin-right-2">' + $filter('getLabel')(sm.series.name) + ':</label>' + $filter('number')(sm.y, 2) + "</p>";
											});
										}
										if (tadate === null)
											return;
										else
											return '<div class="col-md-12 padding-5 defualt-color"><div class="indicator-tooltip">' + tadate + ' ' + tooltipHtml + '</div></div>';
									}
								},
								rangeSelector: {
									enabled: true,
									selected: 4,
									buttonTheme: {
										useHTML: true,
										fill: 'none',
										stroke: 'none',
										'stroke-width': 0,
										r: 8,
										style: {
											color: '#ADADAD',
											fontWeight: 'bold',
											direction: 'ltr'
										},
										states: {
											hover: {
												select: {
													//fill: '#fff',
													style: {
														color: 'black'
													}
												}
											},
											select: {
												//fill: '#fff',
												style: {
													color: 'black'
												}
											}
										}
									},
									labels: {
										style: {
											color: "#ADADAD",
										}
									},
									buttons: [{
										type: 'month',
										count: 1,
										text: '1m'
									}, {
										type: 'month',
										count: 3,
										text: '3m'
									}, {
										type: 'month',
										count: 6,
										text: '6m'
									}, {
										type: 'ytd',
										text: 'YTD'
									}, {
										type: 'year',
										count: 1,
										text: '1y'
									}],
									inputEnabled: false,
								},
								navigator: {
									enabled: false
								},
								scrollbar: {
									enabled: false
								},
								legend: {
									enabled: false,
								},
								plotOptions: {
									column: {
										tooltip: {
											followPointer: false
										}
									},
									series: {
										marker: {
											enabled: false,
										},
									}
								},
								series: [{
									name: 'primary',
									id: 'primary',
									data: lineChartData,
									yAxis: 0,
									tooltip: {
										valueDecimals: 2
									},
									color: 'transparent',
									dataGrouping: {
										units: [['day', [1]]]
									}
								}, {
									name: 'candlestick',
									id: 'candlestick',
									type: 'candlestick',
									data: candlestickData,
									color: '#EF070F',
									lineColor: '#EF070F',
									upColor: '#009900',
									upLineColor: '#009900',
									tooltip: {
										valueDecimals: 2
									},
									dataGrouping: {
										units: [['day', [1]]]
									}
								}, {
									data: volumeData,
									name: 'Volume',
									type: 'column',
									yAxis: 1,
									dataGrouping: {
										units: [['day', [1]]]
									}
								}, {
									name: 'lbl50DaySMA',
									linkedTo: 'primary',
									type: 'trendline',
									algorithm: 'SMA',
									periods: 50,
									yAxis: 0,
									dataGrouping: {
										units: [['day', [1]]]
									}
								}, {
									name: 'lbl200DaySMA',
									linkedTo: 'primary',
									type: 'trendline',
									algorithm: 'SMA',
									periods: 200,
									dataGrouping: {
										units: [['day', [1]]]
									}
								}]
							};

							$(this).highcharts('StockChart', chartOption, function () {
								var chart = this;
								// chart.series[0].update({ color: '#fff' });
							});
						});
					});

				}).finally(function () {
					unblockUI('investingPage');
					$scope.totalItems = $scope.InvestingItem.Tweets[0].TotalCount;
					$scope.currentPage = $scope.pageId > 0 ? $scope.pageId : 1;
				});
		});

		$scope.CMomentum = function (cid) {
			return $filter('filter')($scope.InvestingItem.Momentums, { CompanyID: cid }, true);
		}

		$scope.setPage = function (pageNo) {
			$scope.currentPage = pageNo;
		};
		$scope.$watch('currentPage', (n, o) => {
			if (o)
				$window.location.href = siteRoot + 'tools/investingidea/' + $scope.CountryId + "?page=" + n;

		});


		// $scope.selectPage = function (cPno, $event) {
		//if ($scope.currentPage === cPno) return;
		//   $window.location.href = siteRoot + 'tools/investingidea/' + $scope.CountryId + "?page=" + cPno;
		// };
	}])
	.controller('technicalAnalysisIndicesCtrl', ['$global', '$compile', '$scope', '$http', '$filter', '$q', '$timeout', '$uibModal', function ($global, $compile, $scope, $http, $filter, $q, $timeout, $uibModal) {
		var self = this;
		$scope.priceData = {};
		this.xData = [];
		this.volume = [];
		this.ohlc = [];
		this.line = [];
		this.chart = undefined;
		this.yIndex = 1;
		this.yTop = 0;
		this.smaSeries = [];
		this.emaSeries = [];
		this.rsiSeries = [];
		this.atrSeries = [];
		$scope.axisType = 'linear';
		$scope.chartType = 'candlestick';
		$scope.trendLine = false;
		$scope.smaInd = true;
		$scope.emaInd = false;
		$scope.rsiInd = false;
		$scope.atrInd = false;
		$scope.mfiInd = false;
		$scope.macdInd = true;
		$scope.stdInd = false;
		$scope.bbInd = false;
		$scope.sdInd = false;
		$scope.wrInd = false;

		$scope.devEnabled = false;
		$scope.eAnnEnabled = false;


		$scope.init = function (baseModel) {
			blockUI('technicalAnalysis');
			$http({
				url: siteRoot + 'tools/technicalanalysis',
				data: { smid: baseModel.stockMarketID, sid: baseModel.sectorID },
				method: 'POST'

			}).then(function (resp) {
				$scope.marketInfo = resp.data.marketInfo;
				$scope.priceData = resp.data.prices;

				$scope.priceData.map(function (elem) {
					var priceDate = parseInt(elem.PriceDate.slice(6, -2));
					var open = parseFloat(elem.OpeningPrice);
					var high = parseFloat(elem.HighestPrice);
					var low = parseFloat(elem.LowestPrice);
					var close = parseFloat(elem.ClosingPrice);
					var volume = parseInt(elem.TradingVolume);
					self.ohlc.push([priceDate, open, high, low, close]);
					self.line.push([priceDate, close]);
					self.volume.push([priceDate, volume]);
					self.xData.push(priceDate);

				});

			}, (error) => { unblockUI('technicalAnalysis'); console.log(error.data); })
				.then(function () {
					if ($scope.smaInd) {
						self.smaSeries.push({
							id: 'SMA-1',
							name: '50-day SMA',
							linkedTo: 'primary',
							showInLegend: true,
							type: 'trendline',
							algorithm: 'SMA',
							periods: 50
						});
						self.smaSeries.push({
							id: 'SMA-2',
							name: '14-day SMA',
							linkedTo: 'primary',
							showInLegend: true,
							type: 'trendline',
							algorithm: 'SMA',
							periods: 14,
							color: '#ADADAD',
							label: {
								style: {
									color: '#3a3a3a'
                                }
                            }
						});
					}
					new TechnicalAnalysis().createChart();
				}).finally(function () {
					unblockUI('technicalAnalysis');
				});
		}
		function TechnicalAnalysis() {
			var groupUnits = [['day', [1]], ['week', [1]]];

			this.createChart = function () {
				blockUI('technicalAnalysis');
				self.yIndex = 1;
				self.yTop = 0;
				self.backgroundColor = '#000';
				var yAxis = [{
					//alternateGridColor: '#FEFCFC',
					labels: {
						align: 'left',
						x: 0,
						styles: {
							color: '#ADADAD'
						}
						
					},
					label: {
						style: {
							color: '#ADADAD'
						}
                    },
					title: {
						text: $global.getResources("lblIndexClose"),
					},
					height: 250,
					lineWidth: 2,
					backgroundColor: '#000',
					labels: {
						formatter: function () {
							return $filter('number')(this.value, 0);
						},
						x: -5,
						y: -3,

					}
				}, {
					alternateGridColor: '#000',
					title: {
						text: $global.getResources("lblVolume"),

					},
					top: 300,
					height: 120,
					offset: 0,
					backgroundColor: '#000',
					lineWidth: 2,
					tickPositioner: function () {
						var positions = [],
							tick = Math.floor(this.dataMin),
							increment = Math.ceil((this.dataMax - this.dataMin) / 3);

						if (this.dataMax !== null && this.dataMin !== null) {
							for (tick; tick - increment <= this.dataMax; tick += increment) {
								positions.push(tick);
							}
						}
						return positions;
					},
					label:{
					style: {
						color: '#ADADAD'
					}
					},
					labels: {
						formatter: function () {
							return $filter('Abbr')(this.value);
						},
						x: -5,
						y: -3,
						color: '#ADADAD'
					}
				}];
				self.yTop += 430;

				var chartSeries = [{
					type: 'line',
					name: 'primary',
					id: "primary",
					data: self.line,
					backgroundColor: "#000",
					color: $scope.chartType === 'line' ? '#337ab7' : '#fff',
					dataLabels: {
						enabled: false,
						crop: false,
						verticalAlign: 'bottom',
						y: +20,
						useHTML: true,

					},
					dataGrouping: {
						units: groupUnits
					}
				},
				{
					type: 'candlestick',
					borderColor: '#3a3a3a',
					name: 'candleStick',
					id: "candleStick",
					data: self.ohlc,
					color: '#EF070F',
					lineColor: '#EF070F',
					upColor: '#009900',
					upLineColor: '#009900',
					visible: $scope.chartType === 'candlestick' ? true : false,
					dataGrouping: {
						units: groupUnits
					}
				},
				{
					type: 'ohlc',
					name: 'ohlc',
					id: "ohlc",
					data: self.ohlc,
					visible: $scope.chartType === 'ohlc' ? true : false,
					color: '#36368B',
					dataGrouping: {
						units: groupUnits
					}
				},

				{
					type: 'column',
					id: 'volume',
					name: 'Volume',
					data: self.volume,
					yAxis: 1,
					color: '#333A56',
					dataGrouping: {
						units: groupUnits
					}
				}];
				if ($scope.trendLine) {
					chartSeries.push({
						name: 'Linear Trendline',
						linkedTo: 'primary',
						showInLegend: true,
						enableMouseTracking: false,
						type: 'trendline',
						algorithm: 'linear'
					});
				}
				// RSI         
				if ($scope.rsiInd) {
					yAxis.push({
						labels: {
							x: -5,
							y: -3,
						},
						label: {
							style: {
								color:"#3a3a3a"
                            }
                        },
						title: {
							text: 'RSI'
						},
						top: self.yTop,
						height: 110,
						offset: 0,
						lineWidth: 2
					});
					self.yTop += 120;
					self.yIndex += 1;

					chartSeries.push(self.rsiSeries.firstOrDefault());
				}
				//End RSI
				// ATR
				if ($scope.atrInd) {
					yAxis.push({
						labels: {
							x: -5,
							y: -3,
						},
						title: {
							text: 'ATR'
						},
						top: self.yTop,
						height: 110,
						offset: 0,
						lineWidth: 2
					});
					self.yTop += 120;
					self.yIndex += 1;
					chartSeries.push(self.atrSeries.firstOrDefault());
				}
				// End ATR
				//start push macd      
				if ($scope.macdInd) {
					yAxis.push({
						labels: {
							x: -5,
							y: -3,
						},
						title: {
							text: $filter('getLabel')('lblMACD')
						},
						top: self.yTop,
						height: 110,
						offset: 0,
						lineWidth: 2
					});
					self.yTop += 120;
					self.yIndex += 1;
					chartSeries.push({
						name: 'MACD (12,24)',
						linkedTo: 'primary',
						yAxis: self.yIndex,
						showInLegend: true,
						type: 'trendline',
						algorithm: 'MACD',

					},
						{
							name: 'Signal line',
							linkedTo: 'primary',
							yAxis: self.yIndex,
							showInLegend: true,
							type: 'trendline',
							algorithm: 'signalLine'
						},
						{
							name: 'Histogram',
							linkedTo: 'primary',
							yAxis: self.yIndex,
							showInLegend: true,
							type: 'histogram'
						});
				}
				//end push macd


				//sma series addition       
				if (self.smaSeries.length > 0) {
					self.smaSeries.forEach(function (s) {
						chartSeries.push(s);
					});
				}
				//end sma series addition

				//ema series addition       
				if (self.emaSeries.length > 0) {

					self.emaSeries.forEach(function (s) {
						chartSeries.push(s);
					});
				}
				//end ema series addition

				self.chart = $('#technicalAnalysisChart').highcharts('StockChart', {
					showTooltip: false,
					addEvents: true,
					backgroundColor: '#000',
					style: {
						color: '#ADADAD'
					},
					chart: {
						height: self.yTop += 120,
						backgroundColor: '#000',
					},
					watermark: {
						yAxis: 285
					},
					rangeSelector: {
						//inputEnabled: false,
						buttons: [
							//{
							//  type: 'day',
							//  count: 1,
							//  text: '1d'
							//},
							//  {
							//    type: 'week',
							//    count: 1,
							//    text: '1w'
							//  },
							{
								type: 'month',
								count: 1,
								text: '1m'
							}, {
								type: 'month',
								count: 3,
								text: '3m'
							}, {
								type: 'month',
								count: 6,
								text: '6m'
							}, {
								type: 'ytd',
								text: 'YTD'
							}, {
								type: 'year',
								count: 1,
								text: '1y'
							}, {
								type: 'year',
								count: 3,
								text: '3y'
							}, {
								type: 'year',
								count: 5,
								text: '5y'
							}],
						selected: 4
					},
					plotOptions: {
						series: {
							pointInterval: 24 * 3600 * 1000,
							pointIntervalUnit: 'day'
						},
						line: {
							dataGrouping: {
								enabled: false
							},
							turboThreshold: 0

						}
					},
					tooltip: {
						crosshairs: true,
						shared: true,
						enabledIndicators: true,
						followPointer: false,
						backgroundColor: "white",
						borderWidth: 0,
						borderRadius: 0,
						shape: "square",
						useHTML: true,
						backgroundColor: "rgba(255,255,255,1)",
						formatter: function () {
							var tooltipHtml = '';
							var tadate = null;
							var primary = $.grep(this.points, function (elem) { return elem.series.name === "primary" }).firstOrDefault();
							if (!angular.isFunction(primary)) {
								tadate = '<p class="defualt-color">' + $filter('date')(primary.x, 'dd/MM/yyyy') + "</p>";
								if ($scope.chartType === 'line') {
									tooltipHtml += '<p><b> Close:</b>' + $filter('number')(primary.y, 2) + "</p>";
								}
							}
							var cS = $.grep(this.points, function (elem) { return elem.series.name === "candleStick" }).firstOrDefault();
							if (!angular.isFunction(cS)) {
								tooltipHtml += '<p class="defualt-color"><b> Open:</b>' + $filter('number')(cS.point.open, 2) + "</p>";
								tooltipHtml += '<p class="defualt-color"> <b> High:</b>' + $filter('number')(cS.point.high, 2) + "</p>";
								tooltipHtml += '<p class="defualt-color"><b> Low:</b>' + $filter('number')(cS.point.low, 2) + "</p>";
								tooltipHtml += '<p class="defualt-color"><b> Close:</b>' + $filter('number')(cS.point.close, 2) + "</p>";
								tooltipHtml += '<br/>';
							}
							var ohlc = $.grep(this.points, function (elem) { return elem.series.name === "ohlc" }).firstOrDefault();
							if (!angular.isFunction(ohlc)) {
								tooltipHtml += '<p class="defualt-color"><b> ' + $filter('getLabel')('lblOpen') + ':</b>' + $filter('number')(ohlc.point.open, 2) + "</p>";
								tooltipHtml += '<p class="defualt-color"><b> ' + $filter('getLabel')('lblHigh') + ':</b>' + $filter('number')(ohlc.point.high, 2) + "</p>";
								tooltipHtml += '<p class="defualt-color"><b>  ' + $filter('getLabel')('lblLow') + ':</b>' + $filter('number')(ohlc.point.low, 2) + "</p>";
								tooltipHtml += '<p class="defualt-color"><b>  ' + $filter('getLabel')('lblClose') + ':</b>' + $filter('number')(ohlc.point.close, 2) + "</p>";
								tooltipHtml += '';
							}
							var linearTrend = $.grep(this.points, function (elem) { return elem.series.name === "Linear Trendline" }).firstOrDefault();
							if (!angular.isFunction(linearTrend)) {
								tooltipHtml += '<p class="defualt-color"><b> ' + $filter('getLabel')('lblLinearTrendLine') + ':</b>' + $filter('number')(linearTrend.y, 2) + "</p>";

							}
							var smas = $.grep(this.points, function (elem) { return elem.series.name.indexOf('SMA') !== -1; });
							if (smas.length > 0) {
								angular.forEach(smas, function (sm) {
									tooltipHtml += '<p class="defualt-color"><b> ' + sm.series.name + ':</b>' + $filter('number')(sm.y, 2) + "</p>";
								});
							}

							var emas = $.grep(this.points, function (elem) { return elem.series.name.indexOf('EMA') !== -1; });
							if (smas.length > 0) {
								angular.forEach(emas, function (em) {
									tooltipHtml += '<p class="defualt-color"><b> ' + em.series.name + ':</b>' + $filter('number')(em.y, 2) + "</p>";
								});
							}

							var volume = $.grep(this.points, function (elem) { return elem.series.name === "Volume" }).firstOrDefault();
							if (!angular.isFunction(volume)) {
								tooltipHtml += '<p class="defualt-color"><b>  ' + $filter('getLabel')('lblVolume') + ':</b>' + $filter('number')(volume.y, 0) + "</p>";
							}

							var rsi = $.grep(this.points, function (elem) { return elem.series.name.indexOf('RSI') !== -1; }).firstOrDefault();
							if (!angular.isFunction(rsi)) {
								tooltipHtml += '<p class="defualt-color"><b>' + rsi.series.name + ':</b>' + $filter('number')(rsi.y, 2) + "</p>";
							}

							var atr = $.grep(this.points, function (elem) { return elem.series.name.indexOf('ATR') !== -1; }).firstOrDefault();
							if (!angular.isFunction(atr)) {
								tooltipHtml += '<p class="defualt-color"><b>' + atr.series.name + ':</b>' + $filter('number')(atr.y, 2) + "</p>";
							}

							var macd = $.grep(this.points, function (elem) { return elem.series.name.indexOf('MACD') !== -1; }).firstOrDefault();
							if (!angular.isFunction(macd)) {
								tadate = tadate == null ? tadate = '<p>' + $filter('date')(macd.x, 'dd/MM/yyyy') + "</p>" : tadate;
								tooltipHtml += '<p class="defualt-color"><b>' + macd.series.name + ':</b>' + $filter('number')(macd.y, 2) + "</p>";
							}
							var signalLine = $.grep(this.points, function (elem) { return elem.series.name === "Signal line" }).firstOrDefault();
							if (!angular.isFunction(macd)) {
								tadate = tadate == null ? tadate = '<p>' + $filter('date')(signalLine.x, 'dd/MM/yyyy') + "</p>" : tadate;
								tooltipHtml += '<p class="defualt-color"><b> ' + $filter('getLabel')('lblSignalLine') + ':</b>' + $filter('number')(signalLine.y, 2) + "</p>";
							}

							var histogram = $.grep(this.points, function (elem) { return elem.series.name === "Histogram" }).firstOrDefault();
							if (!angular.isFunction(histogram)) {
								tadate = tadate == null ? tadate = '<p>' + $filter('date')(histogram.x, 'dd/MM/yyyy') + "</p>" : tadate;
								tooltipHtml += '<p class="defualt-color"><b> ' + $filter('getLabel')('lblHistogram') + ':</b>' + $filter('number')(histogram.y, 2) + "</p>";
							}
							return '<div class="row"><div class="col-md-12"><div class="indicator-tooltip defualt-color">' + tadate + ' ' + tooltipHtml + '</div> </div></div>';
						}

					},
					exporting: {
						enabled: false
					},
					navigator: {
						xAxis: {
							plotBands: [{
								color: "#fff",
								from: -Infinity,
								to: Infinity
							}]
						}
					},
					plotOptions: {
						candlestick: {
							color: 'blue',
							upColor: 'red'
						}
					},
					title: {
						text: ''
					},
					xAxis: {
						type: 'datetime',
						label: {
							style: {
								color: '#ADADAD'
							}
                        }

					},
					yAxis: yAxis,
					series: chartSeries
				}, function (chart) {
					unblockUI('technicalAnalysis');
				});
			}


			$scope.saveChart = function ($obj, chartType) {
				$obj.preventDefault();
				if (self.chart.selector === undefined) return;
				try {
					var chart = $('#technicalAnalysisChart').highcharts();
					$timeout(function () {
						$('#technicalAnalysisChart').highcharts().exportChartLocal({
							type: chartType,
							filename: 'Technical Indicators'
						});
					});
				} catch (e) {
				}
			}
		}


		$scope.changeAxisType = function (type) {
			$scope.axisType = type;
			switch (type) {
				case 'log':
					if (self.chart !== undefined)
						$(self.chart.selector).highcharts().yAxis[0].update({ type: 'logarithmic' });
					break;
				case 'linear':
					if (self.chart !== undefined)
						$(self.chart.selector).highcharts().yAxis[0].update({ type: 'linear' });
					break;
			}
		}

		$scope.changeChartType = function (type) {
			$scope.chartType = type;
			var series = $(self.chart.selector).highcharts().series;
			switch (type) {

				case 'line':
					$(self.chart.selector).highcharts().series[0].update({ color: '#337ab7' });
					$(self.chart.selector).highcharts().series[1].hide(); // candle stick
					$(self.chart.selector).highcharts().series[2].hide(); // ohlc chart
					SetVisible(series);
					break;

				case 'candlestick':
					$(self.chart.selector).highcharts().series[0].update({ color: '#fff' });
					$(self.chart.selector).highcharts().series[1].show();
					$(self.chart.selector).highcharts().series[2].hide();
					SetVisible(series);
					break;

				case 'hloc':
					$(self.chart.selector).highcharts().series[0].update({ color: '#fff' });
					$(self.chart.selector).highcharts().series[1].hide();
					$(self.chart.selector).highcharts().series[2].show();
					SetVisible(series);
					break;
			}
			function SetVisible(series) {
				angular.forEach(series, function (v, i) {
					if (v.name.indexOf('RSI') !== -1 || v.name.indexOf('ATR') !== -1) {
						$(self.chart.selector).highcharts().series[i].show();
					}
				});
			}
		}

		$scope.technicalInd = function (type) {
			switch (type) {
				case 'sma':
				case 'ema':
					var modalInstance = $uibModal.open({
						templateUrl: '/content/theme/ng/partials/EMAIndicatorPopup.html',
						//template: "<div style=\"width:300px;\"><div class=\"modal-header\"><h5 class=\"modal-title\">{{title}}</h5></div><form method=\"POST\" name=\"emaForm\" ng-submit=\"emaForm.$valid && submitForm($event,line)\"><div class=\"modal-body\"><div class=\"form-group table\"><label class=\"col-md-3 padding-top-10 txt-right no-padding-left\">Line 1</label><div class=\"col-md-4 no-padding-left no-padding-right\"><input type=\"text\" name=\"line1\" class=\"form-control\" ng-model=\"line.line1\" placeholder=\"\" ng-required=\"true\" ng-pattern=\"/^\d+$/\"></div><div ng-show=\"emaForm.$submitted || emaForm.line1.$touched\" class=\"validation-div padding-top-10 padding-bottom-10 col-md-4 no-padding-left no-padding-right\"><span ng-show=\"emaForm.line1.$error.required\" class=\"padding-5 alert alert-danger\">{{'lblRequired'|getLabel}}</span><span class=\"padding-5 alert alert-danger\" ng-show=\"emaForm.line1.$error.pattern||emaForm.line1.$error.number\">{{'lblInvalidValue'|getLabel}}</span></div></div><div class=\"space-5\"></div><div class=\"form-group table\"><label class=\"col-md-3 padding-top-10 txt-right no-padding-left\">Line 2</label><div class=\"col-md-4 no-padding-left no-padding-right\"><input type=\"text\" name=\"line2\" class=\"form-control\" ng-model=\"line.line2\" placeholder=\"(optional)\" ng-required=\"false\" ng-pattern=\"/^\d+$/\"></div><div ng-show=\"emaForm.$submitted || emaForm.line2.$touched\" class=\"validation-div padding-top-10 padding-bottom-10 col-md-4 no-padding-left no-padding-right\"><span class=\"padding-5 alert alert-danger\" ng-show=\"emaForm.line2.$error.pattern||emaForm.line2.$error.number\">{{'lblInvalidValue'|getLabel}}</span></div></div><div class=\"space-5\"></div><div class=\"form-group table\"><label class=\"col-md-3 padding-10 txt-right\">Line 3</label><div class=\"col-md-4 no-padding-left no-padding-right\"><input type=\"text\" name=\"line3\" class=\"form-control\" ng-model=\"line.line3\" placeholder=\"(optional)\" ng-required=\"false\" ng-pattern=\"/^\d+$/\"></div><div ng-show=\"emaForm.$submitted || emaForm.line3.$touched\" class=\"validation-div padding-top-10 padding-bottom-10 col-md-4 no-padding-left no-padding-right\"><span class=\"padding-5 alert alert-danger\" ng-show=\"emaForm.line3.$error.pattern||emaForm.line3.$error.number\">{{'lblInvalidValue'|getLabel}}</span></div></div></div><div class=\"space-10\"></div><div class=\"modal-footer\"><div class=\"form-group row\"><div class=\"col-sm-12 txt-right\"><button type=\"submit\" data-name=\"submit\" ng-click=\"action='add'\" class=\"btn btn-default pull-left\">{{'lblOK'|getLabel}}</button><button type=\"submit\" data-name=\"remove\" ng-click=\"action='remove'\" class=\"btn btn-default pull-left\">{{'lblRemove'|getLabel}}</button><button ng-click=\"Close()\" type=\"button\" class=\"btn btn-default pull-right\">{{'lblCancel'|getLabel}}</button></div></div></div></form></div>",
						controller: 'smaPopupCtrl',
						scope: $scope,
						windowClass: 'app-modal-window',
						resolve: {
							'type': function () { return type; },
							'data': { sma: self.smaSeries, ema: self.emaSeries }
						}
					});

					break;
				case 'trendLine':

					$scope.trendLine = $scope.trendLine ? false : true;
					new TechnicalAnalysis().createChart();
					break;
				case 'rsi':
				case 'atr':
					var modalInstance = $uibModal.open({
						templateUrl: '/content/theme/ng/partials/RSIPopup.html',
						controller: 'rsiPopupCtrl',
						scope: $scope,
						windowClass: 'app-modal-window',
						resolve: {
							'type': function () { return type; },
							'data': { rsi: self.rsiSeries, atr: self.atrSeries }
						}
					});
					break;
				case 'mfi':

					break;
				case 'macd':
					var modalInstance = $uibModal.open({
						templateUrl: '/content/theme/ng/partials/MACDIndicatorPopup.html',
						//template: "<div style=\"width:300px;\"><div class=\"modal-header\"><h5 class=\"modal-title\">{{title}}</h5></div><form method=\"POST\" name=\"emaForm\" ng-submit=\"emaForm.$valid && submitForm($event,line)\"><div class=\"modal-body\"><div class=\"form-group table\"><label class=\"col-md-3 padding-top-10 txt-right no-padding-left\">Line 1</label><div class=\"col-md-4 no-padding-left no-padding-right\"><input type=\"text\" name=\"line1\" class=\"form-control\" ng-model=\"line.line1\" placeholder=\"\" ng-required=\"true\" ng-pattern=\"/^\d+$/\"></div><div ng-show=\"emaForm.$submitted || emaForm.line1.$touched\" class=\"validation-div padding-top-10 padding-bottom-10 col-md-4 no-padding-left no-padding-right\"><span ng-show=\"emaForm.line1.$error.required\" class=\"padding-5 alert alert-danger\">{{'lblRequired'|getLabel}}</span><span class=\"padding-5 alert alert-danger\" ng-show=\"emaForm.line1.$error.pattern||emaForm.line1.$error.number\">{{'lblInvalidValue'|getLabel}}</span></div></div><div class=\"space-5\"></div><div class=\"form-group table\"><label class=\"col-md-3 padding-top-10 txt-right no-padding-left\">Line 2</label><div class=\"col-md-4 no-padding-left no-padding-right\"><input type=\"text\" name=\"line2\" class=\"form-control\" ng-model=\"line.line2\" placeholder=\"(optional)\" ng-required=\"false\" ng-pattern=\"/^\d+$/\"></div><div ng-show=\"emaForm.$submitted || emaForm.line2.$touched\" class=\"validation-div padding-top-10 padding-bottom-10 col-md-4 no-padding-left no-padding-right\"><span class=\"padding-5 alert alert-danger\" ng-show=\"emaForm.line2.$error.pattern||emaForm.line2.$error.number\">{{'lblInvalidValue'|getLabel}}</span></div></div><div class=\"space-5\"></div><div class=\"form-group table\"><label class=\"col-md-3 padding-10 txt-right\">Line 3</label><div class=\"col-md-4 no-padding-left no-padding-right\"><input type=\"text\" name=\"line3\" class=\"form-control\" ng-model=\"line.line3\" placeholder=\"(optional)\" ng-required=\"false\" ng-pattern=\"/^\d+$/\"></div><div ng-show=\"emaForm.$submitted || emaForm.line3.$touched\" class=\"validation-div padding-top-10 padding-bottom-10 col-md-4 no-padding-left no-padding-right\"><span class=\"padding-5 alert alert-danger\" ng-show=\"emaForm.line3.$error.pattern||emaForm.line3.$error.number\">{{'lblInvalidValue'|getLabel}}</span></div></div></div><div class=\"space-10\"></div><div class=\"modal-footer\"><div class=\"form-group row\"><div class=\"col-sm-12 txt-right\"><button type=\"submit\" data-name=\"submit\" ng-click=\"action='add'\" class=\"btn btn-default pull-left\">{{'lblOK'|getLabel}}</button><button type=\"submit\" data-name=\"remove\" ng-click=\"action='remove'\" class=\"btn btn-default pull-left\">{{'lblRemove'|getLabel}}</button><button ng-click=\"Close()\" type=\"button\" class=\"btn btn-default pull-right\">{{'lblCancel'|getLabel}}</button></div></div></div></form></div>",
						controller: 'macdPopupCtrl',
						scope: $scope,
						windowClass: 'app-modal-window',
						resolve: {
							'type': function () { return type; },
							'data': { type }
						}
					});
					break;
				case 'std':

					break;
				case 'bb':

					break;
				case 'st':

					break;
				case 'wr':

					break;
			}
		}

		$scope.addSMAOrEMASeries = function (lineData, action, type) {

			var chart = $(self.chart.selector).highcharts();
			var indicatorSuffix = type === 'ema' ? '-day EMA' : '-day SMA';
			var algorithm = type === 'ema' ? 'EMA' : 'SMA';
			if (action === 'add') {
				if (!isNaN(lineData.line1) && Number(lineData.line1) > 0) {
					var seriesName = Number(lineData.line1) + indicatorSuffix;

					if (type === 'sma') {
						self.smaSeries = $.grep(self.smaSeries, (elem) => { return elem.id !== 'SMA-1'; });
						self.smaSeries.push({
							id: 'SMA-1',
							name: seriesName,
							linkedTo: 'primary',
							showInLegend: true,
							type: 'trendline',
							algorithm: algorithm,
							periods: Number(lineData.line1)
						});

					} else {
						self.emaSeries = $.grep(self.emaSeries, (elem) => { return elem.id !== 'EMA-1'; });
						self.emaSeries.push({
							id: 'EMA-1',
							name: seriesName,
							linkedTo: 'primary',
							showInLegend: true,
							type: 'trendline',
							algorithm: algorithm,
							periods: Number(lineData.line1)
						});

					}
				}

				if (!isNaN(lineData.line2) && Number(lineData.line2) > 0) {
					var seriesName = Number(lineData.line2) + indicatorSuffix;

					if (type === 'sma') {
						self.smaSeries = $.grep(self.smaSeries, (elem) => { return elem.id !== 'SMA-2'; });

						self.smaSeries.push({
							id: 'SMA-2',
							name: seriesName,
							linkedTo: 'primary',
							showInLegend: true,
							type: 'trendline',
							algorithm: algorithm,
							periods: Number(lineData.line2)
						});
					}
					else {
						self.emaSeries = $.grep(self.emaSeries, (elem) => { return elem.id !== 'EMA-2'; });
						self.emaSeries.push({
							id: 'EMA-2',
							name: seriesName,
							linkedTo: 'primary',
							showInLegend: true,
							type: 'trendline',
							algorithm: algorithm,
							periods: Number(lineData.line2)
						});
					}
				}

				if (!isNaN(lineData.line3) && Number(lineData.line3) > 0) {
					var seriesName = Number(lineData.line3) + indicatorSuffix;

					if (type === 'sma') {
						self.smaSeries = $.grep(self.smaSeries, (elem) => { return elem.id !== 'SMA-3'; });

						self.smaSeries.push({
							id: 'SMA-3',
							name: seriesName,
							linkedTo: 'primary',
							showInLegend: true,
							type: 'trendline',
							algorithm: algorithm,
							periods: Number(lineData.line3)
						});
					}

					else {
						self.emaSeries = $.grep(self.emaSeries, (elem) => { return elem.id !== 'EMA-3'; });
						self.emaSeries.push({
							id: 'EMA-3',
							name: seriesName,
							linkedTo: 'primary',
							showInLegend: true,
							type: 'trendline',
							algorithm: algorithm,
							periods: Number(lineData.line3)
						});
					}
				}

			}
			else {
				if (!isNaN(lineData.line1) && Number(lineData.line1) > 0) {
					var seriesName = Number(lineData.line1) + indicatorSuffix;
					if (type === 'sma') {
						self.smaSeries = $.grep(self.smaSeries, (elem) => { return elem.id !== 'SMA-1'; });
					} else
						self.emaSeries = $.grep(self.emaSeries, (elem) => { return elem.id !== 'EMA-1'; });
				}
				if (!isNaN(lineData.line2) && Number(lineData.line2) > 0) {
					var seriesName = Number(lineData.line2) + indicatorSuffix;
					if (type === 'sma') {
						self.smaSeries = $.grep(self.smaSeries, (elem) => { return elem.id !== 'SMA-2'; });
					} else
						self.emaSeries = $.grep(self.emaSeries, (elem) => { return elem.id !== 'EMA-2'; });
				}
				if (!isNaN(lineData.line3) && Number(lineData.line3) > 0) {
					var seriesName = Number(lineData.line3) + indicatorSuffix;
					if (type === 'sma') {
						self.smaSeries = $.grep(self.smaSeries, (elem) => { return elem.id !== 'SMA-3'; });
					} else
						self.emaSeries = $.grep(self.emaSeries, (elem) => { return elem.id !== 'EMA-3'; });
				}
			}

			$scope.smaInd = self.smaSeries.length > 0 ? true : false;
			$scope.emaInd = self.emaSeries.length > 0 ? true : false;
			new TechnicalAnalysis().createChart();
		}

		$scope.addRemoveMACD = function (periodData, action) {
			var chart = $(self.chart.selector).highcharts();
			if (action === 'add') {
				$scope.macdInd = true;
			} else {
				$scope.macdInd = false;
			}
			new TechnicalAnalysis().createChart();
		}

		$scope.addRemoveRSI = function (lineData, action, type) {

			var chart = $(self.chart.selector).highcharts();
			if (action === 'add') {
				if (!isNaN(lineData.line1) && Number(lineData.line1) > 0) {
					if (type === 'rsi') {
						var seriesName = 'RSI (' + Number(lineData.line1) + ')';
						self.rsiSeries = $.grep(self.rsiSeries, (elem) => { return elem.id !== 'RSI'; });
						self.rsiSeries.push({
							name: seriesName,
							id: 'RSI',
							linkedTo: 'candleStick',
							yAxis: self.yIndex,
							showInLegend: true,
							type: 'trendline',
							algorithm: 'RSI',
							periods: {
								period: Number(lineData.line1),
								overbought: 70,
								oversold: 30,
								decimals: 4
							},
							visible: true,
							color: '#FF0051'
						});
						$scope.rsiInd = true;
					} else if (type === 'atr') {
						var seriesName = 'ATR (' + Number(lineData.line1) + ')';
						self.atrSeries = $.grep(self.atrSeries, (elem) => { return elem.id !== 'RSI'; });
						self.atrSeries.push({
							name: seriesName,
							id: 'ATR',
							linkedTo: 'candleStick',
							yAxis: self.yIndex,
							showInLegend: true,
							type: 'trendline',
							algorithm: 'ATR',
							periods: {
								period: Number(lineData.line1)
							},
							visible: true,
							color: '#471C1C'
						});
						$scope.atrInd = true;
					}
				}
			}
			else {
				if (!isNaN(lineData.line1) && Number(lineData.line1) > 0) {
					if (type === 'rsi') {
						self.rsiSeries = $.grep(self.rsiSeries, (elem) => { return $.trim(elem.id) !== 'RSI'; });
						$scope.rsiInd = false;
					}
					else if (type === 'atr') {
						self.atrSeries = $.grep(self.rsiSeries, (elem) => { return $.trim(elem.id) !== 'ATR'; });
						$scope.atrInd = false;
					}
				}

			}
			new TechnicalAnalysis().createChart();
		}
	}])
	.controller('smaPopupCtrl', ['$global', '$scope', '$uibModalInstance', 'type', 'data', function ($global, $scope, $uibModalInstance, type, data) {
		$scope.title = "";
		$scope.action = 'add';
		$scope.line = {
			line1: 50,
			line2: undefined,
			line3: undefined
		};
		$uibModalInstance.rendered.then(function () {
			switch (type) {
				case 'sma':
					$scope.title = "Simple Moving Average";
					var series = data.sma;
					$scope.line.line1 = parseInt($.grep(series, (elem) => { return elem.id === 'SMA-1'; }).firstOrDefault().name.replace(/[^\d.]/g, ''));
					$scope.line.line2 = parseInt($.grep(series, (elem) => { return elem.id === 'SMA-2'; }).firstOrDefault().name.replace(/[^\d.]/g, ''));
					$scope.line.line3 = parseInt($.grep(series, (elem) => { return elem.id === 'SMA-3'; }).firstOrDefault().name.replace(/[^\d.]/g, ''));
					$scope.line.line1 = parseInt($scope.line.line1) > 0 ? $scope.line.line1 : 50;
					break;
				case 'ema':
					$scope.title = "Exponential Moving Average";
					var series = data.ema;
					$scope.line.line1 = parseInt($.grep(series, (elem) => { return elem.id === 'EMA-1'; }).firstOrDefault().name.replace(/[^\d.]/g, ''));
					$scope.line.line2 = parseInt($.grep(series, (elem) => { return elem.id === 'EMA-2'; }).firstOrDefault().name.replace(/[^\d.]/g, ''));
					$scope.line.line3 = parseInt($.grep(series, (elem) => { return elem.id === 'EMA-3'; }).firstOrDefault().name.replace(/[^\d.]/g, ''));
					$scope.line.line1 = parseInt($scope.line.line1) > 0 ? $scope.line.line1 : 50;
					break;
			}



		});
		$scope.Close = function () {
			$uibModalInstance.close();
		};
		$scope.cancel = function () {
			$uibModalInstance.dismiss('cancel');
		};
		$scope.submitForm = function ($event, line) {
			$scope.$parent.addSMAOrEMASeries(line, $scope.action, type);
			$uibModalInstance.close();
		}
	}])
	.controller('macdPopupCtrl', ['$global', '$scope', '$uibModalInstance', 'type', 'data', function ($global, $scope, $uibModalInstance, type, data) {
		$scope.title = "Moving Average Convergence Divergence";
		$scope.action = 'add';
		$scope.period = {
			period1: 12,
			period2: 24
		};
		$uibModalInstance.rendered.then(function () {

			$scope.title = "Moving Average Convergence Divergence";
		});
		$scope.Close = function () {
			$uibModalInstance.close();
		};
		$scope.cancel = function () {
			$uibModalInstance.dismiss('cancel');
		};
		$scope.submitForm = function ($event, period) {
			$scope.$parent.addRemoveMACD(period, $scope.action, type);
			$uibModalInstance.close();
		}
	}])
	.controller('rsiPopupCtrl', ['$global', '$scope', '$uibModalInstance', 'type', 'data', function ($global, $scope, $uibModalInstance, type, data) {
		$scope.title = "";
		$scope.action = 'add';
		$scope.line = {
			line1: 14
		};
		$uibModalInstance.rendered.then(function () {
			$scope.title = type === 'rsi' ? "Relative Strength Index" : 'Average True Range';
			var series = type === 'rsi' ? data.rsi : data.atr;
			$scope.line.line1 = parseInt($.grep(series, (elem) => { return $.trim(elem.id) === 'RSI'; }).firstOrDefault().name.replace(/[^\d.]/g, ''));
			$scope.line.line1 = parseInt($scope.line.line1) > 0 ? $scope.line.line1 : 14;
		});
		$scope.Close = function () {
			$uibModalInstance.close();
		};
		$scope.cancel = function () {
			$uibModalInstance.dismiss('cancel');
		};
		$scope.submitForm = function ($event, line) {
			$scope.$parent.addRemoveRSI(line, $scope.action, type);
			$uibModalInstance.close();
		}
	}])
	.controller('pricePerformanceCtrl', ['$global', '$scope', '$http', '$filter', '$q', '$timeout', '$cookies', function ($global, $scope, $http, $filter, $q, $timeout, $cookies) {
		let perfChart = undefined;
		var groupUnits = [['day', [1]]];
		let savedSeries = [],
			singleLineSeriesID = 'singleline';
		$scope.info = null;
		$scope.isMarket = undefined;
		$scope.isSector = undefined;
		$scope.isGBSector = undefined;
		$scope.isCapSize = undefined;
		$scope.isMarketcap = undefined;
		$scope.isGCCIndex = undefined;
		$scope.singleLineAnalysis = false;
		$scope.lang = Number(lang);
		$scope.SelectedList = [];
		$scope.RecentCompanies = [];
		var cur, expireDate, cookie;
		expireDate = new Date();
		expireDate.setDate(expireDate.getDate() + 1);
		$scope.init = function (obj) {
			$scope.info = obj;
			$scope.marketID = obj.StockMarketID;
			$scope.sectorID = obj.SectorID;
			$scope.CapSize = obj.CapsizeID;
			$scope.TypeId = obj.Type;
			switch (obj.selType) {
				case 'market':
					$scope.isMarket = true;
					break;
				case 'sector':
					$scope.isSector = true;
					break;
				case 'market':
					$scope.isMarket = true;
					break;
				case 'gbsector':
					$scope.isGBSector = true;
					break;
				case 'capsize':
					$scope.isCapSize = true;
					break;
				case 'marketcap':
					$scope.isMarketcap = true;
					break;
				case 'gccindex':
					$scope.isGCCIndex = true;
					break;
			}
		}

		$scope.searchSelectionCallback = function ($item) {
			if ($item !== undefined && $item !== 'undefined') {

				$scope.PriceChartCall(0, 0, $item.originalObject.ID, 0, 5, $item.originalObject.Ticker);
				var recTicker = undefined;
				if ($scope.RecentCompanies !== undefined)
					recTicker = $filter('filter')($scope.RecentCompanies, { Ticker: $item.originalObject.Ticker })[0];

				if ($cookies.getObject('RecentCompanies') && recTicker === undefined) {
					cur = $cookies.getObject('RecentCompanies');
					cookie = {
						'Id': $item.originalObject.ID,
						'Ticker': $item.originalObject.Ticker,
						'lang': $scope.lang
					}

					cur.push(cookie)
					$cookies.putObject('RecentCompanies', cur, { 'expires': expireDate });
					$scope.RecentCompanies = $cookies.getObject('RecentCompanies');

					$timeout(function () {
						$scope.$apply($scope.RecentCompanies);
					});
				}
			}
		}

		perfChart = Highcharts.stockChart('pricePermanceChart', {
			chart: {
				borderColor: '#3a3a3a',
				backgroundColor: '#000',
				borderWidth: 1,
				plotBackgroundColor: '',
				panning: false,
				events: {
					render: function () {
						if ($('input.highcharts-range-selector').length) {
							$('#' + this.renderTo.attributes['id'].value + ' input.highcharts-range-selector').datepicker();
						}
					}
				}
			},
			scrollbar: {
				enabled: true
			},
			navigator: {
				enabled: true
			},

			rangeSelector: {
				allButtonsEnabled: true,
				selected: 4,
				inputEnabled: true,
				inputBoxBorderColor: "#3a3a3a",
				inputBoxHeight: 17,
				inputBoxWidth: 90,
				inputDateFormat: "%b %e %Y,",
				inputDateParser: null,
				inputEditDateFormat: "%Y-%m-%d",
				inputPosition: { align: "right" },
				buttonTheme: {
					useHTML: true,
					fill: 'none',
					stroke: 'none',
					'stroke-width': 0,
					r: 8,
					style: {
						color: '#039',
						fontWeight: 'bold',
						direction: 'ltr'
					},
					states: {
						hover: {
						},
						select: {
							style: {
								color: 'black'
							}
						}
					}
				},
				buttons: [{
					type: 'month',
					count: 1,
					text: $filter('getLabel')('lbl1m')
				}, {
					type: 'month',
					count: 3,
					text: $filter('getLabel')('lbl3m')
				}, {
					type: 'month',
					count: 6,
					text: $filter('getLabel')('lbl6m')
				}, {
					type: 'ytd',
					text: $filter('getLabel')('lblytd')
				}, {
					type: 'year',
					count: 1,
					text: $filter('getLabel')('lbl1y')
				}, {
					type: 'year',
					count: 3,
					text: $filter('getLabel')('lbl3y')
				}, {
					type: 'year',
					count: 5,
					text: $filter('getLabel')('lbl5y')
				}, {
					type: 'all',
					text: $filter('getLabel')('lblAll')
				}]
			},
			xAxis: {
				type: 'datetime',
				events: {
					afterSetExtremes: function (hEvent) {
						let tempLineData = [], seriesName,
							sLineSeries = perfChart.get(singleLineSeriesID);
						// single line analysis
						try {
							if ($scope.singleLineAnalysis && savedSeries.length === 2 && sLineSeries !== undefined) {
								let min = hEvent.dataMin,
									max = hEvent.dataMax,
									series1 = savedSeries[0].data,
									series2 = savedSeries[1].data,
									commonXData = savedSeries[0].xData.intersect(savedSeries[1].xData).sortAsc(),
									x1XDataDate = $.map(series1, (elem) => { return elem.x; }).getClosestNum(hEvent.min, commonXData),
									x2XDataDate = $.map(series2, (elem) => { return elem.x; }).getClosestNum(hEvent.min, commonXData),
									y1Val = $.grep(series1, (elem) => { if (elem.x === x1XDataDate) return elem; }).clean().firstOrDefault().y,
									y2Val = $.grep(series2, (elem) => { return elem.x === x2XDataDate; }).clean().firstOrDefault().y,
									firstChange = y1Val / y2Val;
								seriesName = savedSeries[0].aname + ' vs. ' + savedSeries[1].aname + ' ' + $filter('getLabel')('lblSingleLineAnalysis');

								$.each(commonXData, function (indx, xpoint) {
									let t1Val = $.grep(series1, (elem) => { if (elem.x === xpoint) return elem; }).clean().firstOrDefault();
									let t2Val = $.grep(series2, (elem) => { if (elem.x === xpoint) return elem; }).clean().firstOrDefault()
									let change = t1Val.y / t2Val.y;
									let changePer = (change / firstChange - 1) * 100;
									tempLineData.push({ x: xpoint, y: changePer, z: change, 'ename': seriesName, TDate: $filter('date')(xpoint, 'dd/MM/yyyy'), a: t1Val.y, b: t2Val.y });
								});

								let singleLineSeries = perfChart.get(singleLineSeriesID);
								perfChart.series[singleLineSeries.index].update({ data: tempLineData });
								perfChart.redraw();
							}
						} catch (e) { console.log(e); }
					}
				},
				labels: {
					style: {
						color: "#ADADAD"
					}
                }
			},
			yAxis: {
				gridLineColor: '#3a3a3a',
				lineColor: '#3a3a3a',
				lineWidth: 1,
				labels: {
					x: -5,
					y: -7,
					formatter: function () {
						return $filter('WNOrDec')(this.value, 2) + '%';
					},
					style: {
						color:"#ADADAD"
                    }
				},
				plotLines: [{
					value: 0,
					width: 2,
					color: 'silver'
				}],
				events: {
					afterSetExtremes: function (e) {
						let thisEvent = e;
						var name = "", start = 0, end = 1, indexof;

						for (var i = 0; i < e.target.series.length; ++i) {
							name = e.target.series[i].name,
								start = e.target.series[i].processedYData[1];

							for (var b = 0; b < 8; ++b) {
								end = e.target.series[i].processedYData[e.target.series[i].processedYData.length - b];
								if (end !== undefined && end !== 'undefined') break;
							}

							indexof = $scope.SelectedList.findIndex(obj => obj['name'] === name);
							if (indexof > -1) {
								$scope.SelectedList[indexof].first = start;
								$scope.SelectedList[indexof].last = end;
								$scope.SelectedList[indexof].ChangePer = (parseFloat(end) / parseFloat(start) - 1) * 100;
							}
						}

						$timeout(function () {
							thisEvent.target.chart.scroller.scrollbar.mouseUpHandler(thisEvent);
							$scope.$apply($scope.SelectedList);
						});

					}
				}
			},
			tooltip: {
				formatter: function () {
					var tooltipHtml = '<ul class="highcharts-gb-tooltip defualt-color"><li class="text-bold text-capitalize">' + $filter('getLabel')('lblDate') + ': </li><li>' + $filter('date')(this.points[0].x, 'dd/MM/yyyy') + "</li></ul>";
					for (var i = 0; i < this.points.length; i++) {
						var point = this.points[i];
						if (!$scope.singleLineAnalysis)
							tooltipHtml += "<ul class=\"highcharts-gb-tooltip defualt-color\"><li style='color:" + point.color + ";'  class=\"text-bold text-capitalize\">" + point.series.options.aname + ":</li><li>" + $filter('WNOrDec')(point.y, 2) + "</li><li class='" + $filter('successclass')(point.point.change) + "'> (" + $filter("WNOrDec")(point.point.change, 2) + " %)</li></ul>";
						else
							tooltipHtml += "<ul class=\"highcharts-gb-tooltip defualt-color\"><li style='color:" + point.color + ";'  class=\"text-bold text-capitalize\">" + point.series.options.cname + ":</li><li class='" + $filter('successclass')(point.y) + "'>" + $filter("WNOrDec")(point.y, 2) + "%</li></ul>";
					}
					return tooltipHtml;
				},
				backgroundColor: {
					linearGradient: [0, 0, 500, 500],
					stops: [
						[0, 'rgb(255, 255, 255)'],
						[1, 'rgb(200, 200, 255)']
					]
				},
				borderWidth: 0,
				shadow: false,
				useHTML: true,
				style: {
					padding: 0,
					opacity: 1
				}
			},
		}, function (chart) {
			$.datepicker.setDefaults({
				dateFormat: 'yy-mm-dd',
				onSelect: function (dateText) {
					chart.xAxis[0].setExtremes($('input.highcharts-range-selector:eq(0)').datepicker("getDate").getTime(), $('input.highcharts-range-selector:eq(1)').datepicker("getDate").getTime());
					//this.onchange();
					this.onblur();
				}
			});
		});

		$scope.PriceChartCall = function (MarketID, SectorID, CompanyID, CapSize, TypeID, Ticker) {
			$scope.msgShow = false;
			$scope.$broadcast('angucomplete-alt:clearInput', 'txtCompaniesSearch');

			if (Ticker !== undefined) {
				var reqTicker = $.grep($scope.SelectedList, (el) => { return el.ename === Ticker; });
				if (reqTicker.length) {
					utility.alert($filter('getLabel')('lblInfo'), '<span style="float:left; margin:0 7px 50px 0;"><i class="fa fa-info-circle"></i></span>' + $filter('getLabel')('lblTickerAlreadyExist'));
					return;
				}
				if ($scope.SelectedList.length >= 10) {
					utility.alert($filter('getLabel')('lblInfo'), '<span style="float:left; margin:0 7px 50px 0;"><i class="fa fa-info-circle"></i></span>' + $filter('getLabel')('lblYouHaveSelectMaximusItems'));
					return;
				}
			}
			blockUI('chartheader');
			$http({
				url: siteRoot + 'tools/priceperformance',
				method: "POST",
				data: { smid: MarketID, sid: SectorID, capid: CapSize, cid: CompanyID, type: TypeID }
			}).then(function (res) {
				$scope.data = [];

				angular.forEach(res.data, function (item) {
					$scope.data.push({ x: parseInt(item.PriceDate.slice(6, -2)), y: item.ClosingPrice, 'ename': item.Ticker });
				});
				if (res.data.length === 0) return;
				perfChart.addSeries({
					id: res.data[0].EngTicker,
					name: res.data[0].EngTicker,
					aname: res.data[0].Ticker,
					data: $scope.data,
					turboThreshold: 0,
					compare: 'percent',
					showInNavigator: true,
					dataGrouping: {
						forced: true,
						units: [['day', [1]]]
					}
				}, true);
				var seriesT = perfChart.get(res.data[0].EngTicker),
					start = seriesT.processedYData[1], end = undefined;

				for (var b = 2; b < 8; ++b) {
					end = seriesT.processedYData[seriesT.processedYData.length - b];
					if (end !== undefined && end !== 'undefined') break;
				}

				$scope.SelectedList.push({
					name: res.data[0].Ticker,
					ename: res.data[0].EngTicker,
					first: start,
					last: end,
					ChangePer: (parseFloat(end) / parseFloat(start) - 1) * 100,
					color: seriesT.color,
					IsSelected: true
				});
				if ($cookies.getObject('RecentCompanies')) {
					$scope.RecentCompanies = $cookies.getObject('RecentCompanies');
				}
				if ($scope.RecentCompanies !== undefined) {
					var recTicker = $filter('filter')($scope.RecentCompanies, {
						Ticker: res.data[0].EngTicker
					})[0];
				}
				if (recTicker === undefined && CompanyID > 0) {

					if (!$cookies.getObject('RecentCompanies')) {
						cookie = [{
							'Id': parseInt(CompanyID),
							'Ticker': res.data[0].EngTicker,
							'lang': $scope.lang
						}];
						$cookies.putObject('RecentCompanies', cookie, { 'expires': expireDate });
					} else {
						cur = $cookies.getObject('RecentCompanies');
						data = {
							'Id': parseInt($scope.CompanyID),
							'Ticker': res.data[0].EngTicker,
							'lang': $scope.lang
						}
						cur.push(data)
						$cookies.putObject('RecentCompanies', cur, { 'expires': expireDate });
					}
				}

				$scope.RecentCompanies = $cookies.getObject('RecentCompanies');
				$timeout(function () {
					$scope.$apply($scope.RecentCompanies);
				});
				if ($.grep($scope.SelectedList, (el) => el.ename === $scope.info.EngStockMarketAbbr).length)
					$scope.isMarket = true;

				if ($.grep($scope.SelectedList, (el) => el.ename === $scope.info.SectorTitle).length)
					$scope.isSector = true;

				if ($.grep($scope.SelectedList, (el) => el.ename === $scope.info.EngGBSector).length)
					$scope.isGBSector = true;

				if ($.grep($scope.SelectedList, (el) => el.ename === $scope.info.CapsizeTitle).length)
					$scope.isCapSize = true;

				if ($.grep($scope.SelectedList, (el) => el.ename === $scope.info.MarketcapTitle).length)
					$scope.isMarketcap = true;

				if ($.grep($scope.SelectedList, (el) => el.ename === $scope.info.EngGCCIndex).length)
					$scope.isGCCIndex = true;

				if ($('.company-sector-market li label[data-title="' + Ticker + '"] input').length) {
					if ($.grep($scope.SelectedList, (elems) => { return elems.ename === Ticker; }).length > 0) {
						$('.company-sector-market li label[data-title="' + Ticker + '"] input').attr('checked', true);
					} else {
						$('.company-sector-market li label[data-title="' + Ticker + '"] input').attr('checked', false);
					}
				}

			}, (error) => { unblockUI('chartheader'); console.log(error.data); })
				.finally(function (res) {
					unblockUI('chartheader');
					if ($scope.SelectedList.length > 2) {
						RemoveSeries('average');
					}
				});
		}

		$scope.ListControl = function (name) {

			var series = perfChart.get(name);

			if ($scope.info !== null && name === $scope.info.EngStockMarketAbbr) {
				$scope.isMarket = false;
			}
			else if ($scope.info !== null && name === $scope.info.SectorTitle) {
				$scope.isSector = false;
			}
			else if ($scope.info !== null && name === $scope.info.EngGBSector) {
				$scope.isGBSector = false;
			}
			else if ($scope.info !== null && name === $scope.info.CapSizeTitle) {
				$scope.isCapSize = false;
			}
			else if ($scope.info !== null && name === $scope.info.MarketcapTitle) {
				$scope.isMarketcap = false;
			}
			else if ($scope.info !== null && name === $scope.info.EngGCCIndex) {
				$scope.isGCCIndex = false;
			}
			else {
				if ($('.company-sector-market li label[data-title="' + name + '"]').length) {
					if ($.grep($scope.SelectedList, (elems) => { return elems.ename === name; }).length > 0)
						$('.company-sector-market li label[data-title="' + name + '"] input').attr('checked', false);
				}
			}
			series !== undefined && series.remove();
			if (savedSeries.length) {
				savedSeries = $.grep(savedSeries, (elem) => { return elem.aname !== name || elem.name !== name; });
			}

			$scope.SelectedList = $.grep($scope.SelectedList, (elem) => { return elem.ename !== name; });
			if ($scope.SelectedList.length < 2)
				RemoveSeries();
		};

		$timeout(function () {
			$scope.PriceChartCall($scope.marketID, $scope.sectorID, 0, $scope.CapSize, $scope.TypeId);
		});

		////smid, sid,companyid,iscapsize,flag,title, obj
		$scope.ProcessSectorMarket = function (isObj, sid, cid, iscapsize, flag, title, cobject) {

			switch (isObj) {
				case 'sector':
					if ($scope.isSector) {
						var exist = $.grep($scope.SelectedList, (elems) => { return elems.ename === $scope.info.SectorTitle; });
						if (!exist.length) {
							$scope.PriceChartCall($scope.info.StockMarketID, $scope.info.SectorID, 0, 0, 1, $scope.info.SectorTitle);
						}
					}
					else {
						var obj = $('table.table-selected-list tbody tr td label.list-control-input[data-name="' + $scope.info.SectorTitle + '"] input');
						if (obj.length > 0) {
							$timeout(() => {
								angular.element(obj).trigger("click");
							});
						}
					}
					break;
				case 'market':
					if ($scope.isMarket) {
						var exist = $.grep($scope.SelectedList, (elems) => { return elems.ename === $scope.info.EngStockMarketAbbr; });
						if (!exist.length) {
							$scope.PriceChartCall($scope.info.StockMarketID, 0, 0, 0, 1, $scope.info.EngStockMarketAbbr);
						}
						else {
							var obj = $('table.table-selected-list tbody tr td label.list-control-input[data-name="' + $scope.info.EngStockMarketAbbr + '"] input');
							if (obj.length > 0) {
								$timeout(() => {
									angular.element(obj).trigger("click");
								});
							}
						}
					}
					break;
				case 'gbsector':
					if ($scope.isGBSector) {
						var exist = $.grep($scope.SelectedList, (elems) => { return elems.ename === $scope.info.GBSector; });
						if (!exist.length) {
							$scope.PriceChartCall(0, $scope.info.GBSectorID, 0, 0, 2, $scope.info.GBSectorTitle);
						}
					}
					else {
						var obj = $('table.table-selected-list tbody tr td label.list-control-input[data-name="' + $scope.info.EngGBSector + '"] input');
						if (obj.length > 0) {
							$timeout(() => {
								angular.element(obj).trigger("click");
							});
						}
					}
					break;
				case 'capsize':
					if ($scope.isCapSize) {
						var exist = $.grep($scope.SelectedList, (elems) => { return elems.ename === $scope.info.CapSizeTitle; });
						if (!exist.length) {
							$scope.PriceChartCall($scope.info.StockMarketID, $scope.info.CapSizeID, 0, $scope.info.CapSizeID, 2, $scope.info.CapSizeTitle);
						}
					}
					else {
						var obj = $('table.table-selected-list tbody tr td label.list-control-input[data-name="' + $scope.info.CapSizeTitle + '"] input');
						if (obj.length > 0) {
							$timeout(() => {
								angular.element(obj).trigger("click");
							});
						}
					}
					break;
				case 'marketcap':
					if ($scope.isMarketcap) {
						var exist = $.grep($scope.SelectedList, (elems) => { return elems.ename === $scope.info.MarketcapTitle; });
						if (!exist.length) {
							$scope.PriceChartCall($scope.info.StockMarketID, $scope.info.SectorID, 0, $scope.info.CapSizeID, 2, $scope.info.MarketcapTitle)
						}
					}
					else {
						var obj = $('table.table-selected-list tbody tr td label.list-control-input[data-name="' + $scope.info.MarketcapTitle + '"] input');
						if (obj.length > 0) {
							$timeout(() => {
								angular.element(obj).trigger("click");
							});
						}
					}
					break;
				case 'gccindex':
					if ($scope.isGCCIndex) {
						var exist = $.grep($scope.SelectedList, (elems) => { return elems.ename === $scope.info.EngGCCIndex; });
						if (!exist.length) {
							$scope.PriceChartCall(0, $scope.info.GCCSectorID, 0, 0, 2, $scope.info.GCCIndexTitle);
						}
					}
					else {
						var obj = $('table.table-selected-list tbody tr td label.list-control-input[data-name="' + $scope.info.EngGCCIndex + '"] input');
						if (obj.length > 0) {
							$timeout(() => {
								angular.element(obj).trigger("click");
							});
						}
					}
					break;
				default:
					if (cobject !== undefined) {
						if ($.grep($scope.SelectedList, (elems) => { return elems.ename === title; }).length > 0) {
							var obj = $('table.table-selected-list tbody tr td label.list-control-input[data-name="' + title + '"] input');
							if (obj.length > 0) {
								$timeout(() => {
									angular.element(obj).trigger("click");
								});

								$(cobject.currentTarget).next('span').removeClass('fa-check-square-o').addClass('fa-square-o');
							}
						} else {
							$scope.PriceChartCall(isObj, sid, cid, iscapsize, flag, title);
							$(cobject.currentTarget).next('span').removeClass('fa-square-o').addClass('fa-check-square-o');
						}
					}

					break;
			}
		}
		$scope.toggleSingleAnalysis = function ($event) {

			if ($scope.SelectedList.length === 2)
				$scope.singleLineAnalysis = !$scope.singleLineAnalysis;
			else {
				$scope.singleLineAnalysis = false;
				return;
			}

			if ($scope.singleLineAnalysis) {
				let series = perfChart.series;
				let series1 = series[0];
				let series2 = series[1];
				let singleLineData = [];
				var commonXData = series1.xData.intersect(series2.xData).sortAsc();
				let minPoint = commonXData.getClosestNum(series1.processedXData[0], commonXData);
				let firstChange = series1.yData[series1.xData.indexOf(minPoint)] / series2.yData[series2.xData.indexOf(minPoint)];

				let seriesName = series1.options.aname + ' vs. ' + series2.options.aname + ' ' + $filter('getLabel')('lblSingleLineAnalysis');
				$.each(commonXData, function (indx, xpoint) {
					try {
						let s1yData = series1.yData[series1.xData.indexOf(xpoint)];
						let s2yData = series2.yData[series2.xData.indexOf(xpoint)];
						let change = s1yData / s2yData;
						let changePer = (change / firstChange - 1) * 100;
						singleLineData.push({ x: xpoint, y: changePer, z: change, 'ename': seriesName });
					} catch (e) { }
				});
				if (singleLineData.length === 0) return;
				RemoveSeries();
				perfChart.addSeries({
					id: singleLineSeriesID,
					type: 'line',
					name: 'Single Line',
					aname: $filter('getLabel')('lblSingleLineAnalysis'),
					cname: seriesName,
					data: singleLineData,
					color: '#000',
					turboThreshold: 0,
					lineWidth: 1,
					dataGrouping: {
						units: groupUnits
					}
				}, true);
				perfChart.xAxis[0].setExtremes(perfChart.series[0].processedXData[0], perfChart.series[0].processedXData[perfChart.series[0].processedXData.length - 1]);
				perfChart.xAxis[0].update();

			} else {
				RemoveSeries();
			}
		}
		function RemoveSeries() {
			var averageSeries = perfChart.get(singleLineSeriesID);
			if (averageSeries !== undefined && averageSeries.index !== undefined) {
				perfChart.series[averageSeries.index].remove();
				$scope.singleLineAnalysis = false;
			}
			showHideSeries();
		}
		function showHideSeries() {
			var chart = perfChart;
			var series = chart.series[0];
			if ($scope.singleLineAnalysis) {
				$(chart.series).each(function () {
					if (this.index !== undefined) {
						savedSeries.push({
							id: this.options.id,
							name: this.name,
							aname: this.options.aname,
							data: this.options.data,
							turboThreshold: 0,
							compare: this.options.compare,
							showInNavigator: true,
							dataGrouping: this.options.dataGrouping,
							points: this.points,
							xData: this.xData,
							yData: this.yData
						});
						chart.series[this.index].remove();
					}
				});
				chart.redraw();
			} else {
				$(savedSeries).each(function () {
					chart.addSeries(this);
				});
				savedSeries = [];
				chart.redraw();
			}
		}

	}])
	.controller('toolsRecommendationCtrl', ['$global', '$scope', '$http', '$filter', '$q', '$timeout', '$cookies', function ($global, $scope, $http, $filter, $q, $timeout, $cookies) {
		$scope.countryId = 0;
		$scope.noRecordsToView = 20;
		let rowFrom = 1;
		let rowTo = $scope.noRecordsToView;
		$scope.wSort = {
			column: 'PRD.DateOfRec',
			descending: true
		};
		$scope.sortClass = function (column) {
			return column === $scope.wSort.column ? $scope.wSort.descending ? "sorting_asc" : "sorting_desc" : 'sorting';
		};
		$scope.recData = [];
		$scope.currentPage = 1;
		$scope.maxSize = 5;
		$scope.paginationMaxSize = 5;

		$scope.init = (countryId) => {
			$scope.countryId = countryId;
			LoadData();
		}
		function LoadData() {
			blockUI('divRecommendation');
			$http({
				url: siteRoot + 'tools/recommendation',
				method: 'POST',
				data: { id: $scope.countryId, rowFrom: rowFrom, rowTo: rowTo, orderBy: $scope.wSort.column, sortDir: $scope.wSort.descending ? 'Desc' : 'Asc' }
			}).then((res) => {
				$scope.recData = res.data;
			}, (error) => { console.log(error.data); unblockUI('divRecommendation'); })
				.finally(() => {
					unblockUI('divRecommendation');

					$scope.totalItems = $scope.recData[0].TotalRecomendation;
					$scope.itemsPerPage = $scope.noRecordsToView;

					$scope.pagerInfo = function () {
						let pagerHtml = '';
						let startOfRecord = (($scope.currentPage - 1) * $scope.itemsPerPage) + 1;
						let endOfRecord = ($scope.currentPage) * $scope.itemsPerPage;
						endOfRecord = endOfRecord > $scope.totalItems ? $scope.totalItems : endOfRecord;
						return startOfRecord + ' ' + $filter('getLabel')('lblTo') + ' ' + endOfRecord + ' ' + $filter('getLabel')('lblof') + ' ' + $scope.totalItems;
					}
				});
			$scope.getData = ((currentPage) => {
				rowFrom = ((currentPage * $scope.itemsPerPage) - $scope.itemsPerPage) + 1;
				rowTo = (currentPage * $scope.itemsPerPage);
				LoadData();
			});

			$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.getData($scope.currentPage);
			};
		}

	}])
	.controller('toolsRecommendationsCtrl', ['$global', '$scope', '$http', '$filter', '$q', '$timeout', '$cookies', function ($global, $scope, $http, $filter, $q, $timeout, $cookies) {
		$scope.countryId = 0;
		$scope.noRecordsToView = 10;
		let self = this;
		let rowFrom = 1;
		let rowTo = $scope.noRecordsToView;
		$scope.wSort = {
			column: 'PRD.DateOfRec',
			descending: true
		};
		$scope.sortClass = function (column) {
			return column === $scope.wSort.column ? $scope.wSort.descending ? "sorting_asc" : "sorting_desc" : 'sorting';
		};
		$scope.recData = [];
		$scope.currentPage = 1;
		$scope.maxSize = 5;
		$scope.paginationMaxSize = 5;

		$scope.init = (countryId) => {
			$scope.countryId = countryId;
			LoadData();
		}
		function LoadData() {
			blockUI('divRecommendations');
			$http({
				url: siteRoot + 'tools/recommendations',
				method: 'POST',
				data: { id: $scope.countryId, rowFrom: rowFrom, rowTo: rowTo, orderBy: $scope.wSort.column, sortDir: $scope.wSort.descending ? 'Desc' : 'Asc' }
			}).then((res) => {
				$scope.recData = res.data;
			}, (error) => { console.log(error.data); unblockUI('divRecommendations'); }).finally(() => {
				unblockUI('divRecommendations');

				$scope.totalItems = $scope.recData[0].TotalRecomendation;
				$scope.itemsPerPage = $scope.noRecordsToView;

				$scope.pagerInfo = function () {
					let pagerHtml = '';
					let startOfRecord = (($scope.currentPage - 1) * $scope.itemsPerPage) + 1;
					let endOfRecord = ($scope.currentPage) * $scope.itemsPerPage;
					endOfRecord = endOfRecord > $scope.totalItems ? $scope.totalItems : endOfRecord;
					return startOfRecord + ' ' + $filter('getLabel')('lblTo') + ' ' + endOfRecord + ' ' + $filter('getLabel')('lblof') + ' ' + $scope.totalItems;
				}
				$timeout(() => {
					angular.forEach(document.getElementsByClassName('recomm-chart'), (elem) => {
						let rowIndex = elem.attributes['data-rowid'].value;
						let elemId = elem.attributes['id'].value;
						let elemArr = $.grep($scope.recData, (el) => { if (el.RowIndex === parseInt(rowIndex)) return el; }).firstOrDefault();
						CreateCharts(elemArr, elemId);
					});
				});
			});
			$scope.getData = ((currentPage) => {
				rowFrom = ((currentPage * $scope.itemsPerPage) - $scope.itemsPerPage) + 1;
				rowTo = (currentPage * $scope.itemsPerPage);
				LoadData();
			});

			let CreateCharts = ((rec, elemId) => {

				new Highcharts.chart({
					chart: {
						renderTo: elemId,
						type: 'bar',
						backgroundColor: '#000',
						borderColor: '#3a3a3a',
						plotBackgroundColor: '',
					},
					title: {
						text: ''
					},
					legend: {
						enabled: false
					},
					xAxis: {
						labels: {
							style: {
								width: '50px',
								color: '#ADADAD'
							},
							step: 1,
							//formatter: function () {
							//  return this.value.replace(/ /g, '<br />');
							//},
							enabled: true
						},
						maxStaggerLines: 1,
						useHTML: true,
						categories: [$global.getResources("lblCPrice"), $global.getResources("lblPriceRecommendationDate"), $global.getResources("lblFairValue")]
					},
					yAxis: {
						title: '',
						gridLineWidth: 0,
						lineWidth: 1,
						labels: {
							style: {
								color: '#ADADAD'
							}
						}
					},
					tooltip: {
						formatter: function () {
							return '<b>' + this.x + '</b>: ' + WNOrDecimal(this.y);
						},
						style: {
							color: '#ADADAD'
                        }
					},
					plotOptions: {
						series: {
							dataLabels: {
								align: 'left',
								enabled: true,
								formatter: function () {
									return WNOrDecimal(this.y);
								}
							}
						}
					},
					credits: {
						enabled: false
					},
					exporting: {
						enabled: false
					},
					series: [{
						name: '',
						data: [{
							color: '#4d83c5',
							y: rec.Price,
						},
						{
							color: '#ee9e1f',
							y: rec.MarketPrice,
						},
						{
							color: '#eb564e',
							y: rec.FairValue,
						}]
					}],
				});
			});
		}
	}])
	.controller('toolsMarketComparisonCtrl', ['$scope', '$http', '$filter', '$q', "$timeout", function ($scope, $http, $filter, $q, $timeout) {
		$scope.data = undefined;
		var chartPieValue = [],
			chartPieCap = [],
			marketCapCat = [],
			chartColDailyPerf = [],
			columnOneMonth = [],
			columnThreeMonth = [],
			columnOneYear = [],
			columnDailyVolumn = [],
			marketPerfAbbr = [],
			columnAvgVolumn10 = [],
			columnDailyIndex52 = [],
			columnIndex50Day = [],
			columnIndexVS100Day = [];

		$scope.init = function (obj) {
			$.map(obj.capComparison, function (elem) {
				if (elem.TradingValue > 0)
					chartPieValue.push({ "name": elem.Abbr, "y": elem.TradingValue, tv: elem.TradingValueUSMil, suffix: $filter('getLabel')('lblUSMil'), url: $filter('getURL')(elem.URL) });
				if (elem.MarketCap > 0)
					chartPieCap.push({ "name": elem.Abbr, "y": elem.MarketCap, mc: elem.MarketCapUSMil, suffix: $filter('getLabel')('lblUSMil'), url: $filter('getURL')(elem.URL) });
			});

			$.map(obj.marketComparison, function (elem) {
				//marketCapCat.push(elem.Abbr);
				chartColDailyPerf.push([elem.Abbr, elem.DailyChange]);
				columnOneMonth.push([elem.Abbr, elem.OneMonthChange]);
				columnThreeMonth.push([elem.Abbr, elem.ThreeMonthChange]);
				columnOneYear.push([elem.Abbr, elem.OneYearChange]);
				columnDailyVolumn.push([elem.Abbr, elem.DailyVolumeChange]);
			});

			$scope.createPieChart("#pieValue", "Market Value", chartPieValue);
			$scope.createPieChart("#pieCap", "Market Cap", chartPieCap);

			$scope.createColumnChart("columnDailyPerf", marketCapCat, chartColDailyPerf);
			$scope.createColumnChart("columnOneMonth", marketCapCat, columnOneMonth);
			$scope.createColumnChart("columnThreeMonth", marketCapCat, columnThreeMonth);
			$scope.createColumnChart("columnOneYear", marketCapCat, columnOneYear);
			$scope.createColumnChart("columnDailyVolumn", marketCapCat, columnDailyVolumn);
		}

		$http({
			method: 'POST',
			url: siteRoot + "tools/marketcomparison",
		}).then(function (res) {
			$.map(res.data.capPerformance, function (elem) {
				//marketPerfAbbr.push(elem.Abbr);
				columnAvgVolumn10.push([elem.Abbr, elem.AvgVolume]);
				columnDailyIndex52.push([elem.Abbr, elem.Week52High]);
				columnIndex50Day.push([elem.Abbr, elem.MovingAvg50]);
				columnIndexVS100Day.push([elem.Abbr, elem.MovingAvg200]);
			});
		}, (error) => { console.log(error.data); })
			.finally(function () {
				$scope.createColumnChart("columnAvgVolumn10", marketPerfAbbr, columnAvgVolumn10);
				$scope.createColumnChart("columnDailyIndex52", marketPerfAbbr, columnDailyIndex52);
				$scope.createColumnChart("columnIndex50Day", marketPerfAbbr, columnIndex50Day);
				$scope.createColumnChart("columnIndexVS100Day", marketPerfAbbr, columnIndexVS100Day);
			});

		$scope.createPieChart = function (rederedID, chartTitle, chartData) {


			var dataForChart = $filter('orderBy')(chartData, 'y', true);

			chartTitle = 'lbl' + chartTitle.replaceAll(' ', '');
			$(rederedID).highcharts({
				chart: {
					plotBackgroundColor: null,
					plotBorderWidth: null,
					backgroundColor: '#000',
					borderColor: '#3a3a3a',
					color: '#ADADAD',
					plotShadow: false,
					type: 'pie',
					options3d: {
						enabled: true,
						alpha: 45,
						beta: 0
					}
				},
				title: {
					text: null
				},
				color: '#ADADAD',
				tooltip: {
					formatter: function () {
						if (this.point.options.mc) {
							return `<div class="custom-tooltip defualt-color"><p><b>${this.point.name}:</b> <span>${this.point.options.mc} ${this.point.options.suffix} </span></p>${$filter('getLabel')('lblClickToView')} <b>${this.point.name} </b>${$filter('getLabel')('lblDetail')}</div>`;
						} else {
							return `<div class="custom-tooltip defualt-color"><p><b>${this.point.name}:</b> <span>${this.point.options.tv} ${this.point.options.suffix} </span></p>${$filter('getLabel')('lblClickToView')} <b>${this.point.name} </b>${$filter('getLabel')('lblDetail')}</div>`;
						}
						return html;
					}
				},
				plotOptions: {
					pie: {
						allowPointSelect: true,
						cursor: 'pointer',
						dataLabels: {
							enabled: true,
							distance: 20,
							formatter: function () {
								return `<p><b>${this.point.name}</b> : <label class="text-normal">${$filter('number')(this.point.percentage, 2)}%</label></p>`;
							},
							style: {
								color: '#ADADAD',
								fontWeight: 'normal'
							},
							useHTML: true
						},
						showInLegend: true,
						animation: false,
						point: {
							events: {
								click: function (event) {
									if (this.options.url)
										window.open(this.options.url, '_blank');
								}
							}
						}
					}
				},
				credits: {
					enabled: false
				},
				legend: {
					enabled: false
				},
				series: [{
					type: 'pie',
					colorByPoint: true,
					data: dataForChart,

				}]
			});
		}

		$scope.createColumnChart = function (rederedID, chartCategory, chartData) {
			chartData.sort((function (index) {
				return function (a, b) {
					return (a[1] === b[1] ? -1 : (a[1] < b[1] ? 1 : 0));
				};
			})(2));

			Highcharts.chart({
				chart: {
					renderTo: rederedID,
					type: 'column',
					backgroundColor: '#000',
					//backgroundColor: {
					//	linearGradient: { x1: 0, y1: 0, x2: 1, y2: 1 },
					//	stops: [
					//		[0, 'rgb(255, 255, 255)'],
					//		[1, 'rgb(240, 240, 255)']
					//	]
					//},
					borderColor: "#3a3a3a"
				},
				title: {
					text: ''
				},
				xAxis: {
					type: 'category',
					labels: {
						style: {
							'color': '#ADADAD',
							'fontSize': '10px'
						},
						useHTML: true
					}
				},
				credits: {
					enabled: false
				},
				yAxis: {
					title: '',
					labels: {
						formatter: function () {
							return `<label class="text-normal">${this.axis.defaultLabelFormatter.call(this)}%</label>`;
						},
						style: {
							'color': '#ADADAD',
							'fontSize': '10px'
						},
						useHTML: true
					},
					lineColor: "#3a3a3a",
					lineWidth: 1,
				},
				plotOptions: {
					series: {
						cursor: 'pointer',
						borderWidth: 0,
						dataLabels: {
							enabled: true,
							overflow: 'justify',
							formatter: function () {
								return `<label class="text-normal">${$filter('WNOrDec')(this.point.y, 2)}%</label>`;
							},
							crop: false
						},
					}
				},
				tooltip: {
					enabled: true,
					useHTML: true,
					formatter: function () {
						return `<div class="custom-tooltip defualt-color"><p><b>${this.key}</b> :<span class="text-normal defualt-color"> ${Highcharts.numberFormat(this.y, 2, '.', ',')}%</span></p></div>`;
					}
				},
				series: [{
					showInLegend: false,
					name: '',
					data: chartData,
					color: '#00B050',
					displayNegative: true,
					negativeColor: '#FF0000',
				}]
			});
		}
	}])
	;


