﻿/// <reference path="D:\VS2015\GB_Site\Web\Scripts/angular.js" />

angular.module('ngFundApp', ['ngSanitize'])
    .controller("SearchMutualFunds", ['$scope', '$http', '$q', "$filter", function ($scope, $http, $q, $filter) {
        blockUI('DivNewsDetail');
        $scope.init = function (data) {
            $scope.CountryList = $("#CountryList").data('countries');
            $scope.CategoryList = data.Types;
            $scope.ClassificationList = data.Classification;
            $scope.RiskList = data.Risk;
            $scope.InceptionList = data.Inception;
            $scope.Country = $filter('unique')($scope.CountryList.map(function (v) { return v.CountryID.toString(); }));
            $scope.InceptionFrom = $scope.InceptionList[0];
            $scope.InceptionTo = $scope.InceptionList[$scope.InceptionList.length - 1];
            $scope.ManagementFeeList = [{ Value: 0, Text: "Any" }, { Value: 1, Text: "0-1" }, { Value: 2, Text: "1-2" }, { Value: 3, Text: "2.1" }];
            $scope.ManagementFee = $scope.ManagementFeeList[0].Value;
            $scope.Classification = ["-1"];
            $scope.Risk = ["-1"];
            $scope.Category = ["-1"];
            $scope.fundManagers = ["-1"];

            $http({
                method: 'POST',
                url: siteRoot + 'MutualFund/GetCountryFundManagers/',
            }).then(function (res) {
                $scope.fundManagersList = res.data;
							}, (error) => { unblockUI('DivNewsDetail'); console.log(error.data); }).then(function () {
                unblockUI('DivNewsDetail');
            });
        }
          
        $scope.fundManagersUpdate = function (values) {
            $http({
                method: 'POST',
                url: siteRoot + 'MutualFund/GetCountryFundManagers/',
                params: { Countries: values.join() }
            }).then(function (res) {
                $scope.fundManagersList = res.data;
							}, (error) => { unblockUI('DivNewsDetail'); console.log(error.data); }).then(function () {
                unblockUI('DivNewsDetail');
            });
        }

        $scope.SearchFunds = function () {
            blockUI('divFundSearch');
            $http({
                method: 'POST',
                url: siteRoot + 'MutualFund/SearchFund/',
                params: {
                    Countries: $scope.Country.join(),
                    InceptionFrom: $scope.InceptionFrom.YearOfInc,
                    InceptionTo: $scope.InceptionTo.YearOfInc,
                    ShariahCompliant: $scope.ShariahCompliant,
                    FundManagers: $scope.fundManagers.join(),
                    Category: $scope.Category.join(),
                    Classification: $scope.Classification.join(),
                    Risk: $scope.Risk.join(),
                    OneMonthValue: $scope.OneMonthValue,
                    SixMonthValue: $scope.SixMonthValue,
                    OneYearValue: $scope.OneYearValue,
                    ThreeYearValue: $scope.ThreeYearValue,
                }
            }).then(function (res) {
                $scope.SearchResult = res.data;
							}, (error) => { unblockUI('divFundSearch'); console.log(error.data); }).then(function () {
                unblockUI('divFundSearch');
            });
        }
    }])
	.controller("fundDetailCtrl", ['$http','$scope', '$q', "$filter", "$timeout", function ($http,$scope, $q, $filter, $timeout) {
		$scope.fundId = 0;
		$scope.model = {},
			$scope.model1 = {},
			$scope.model3 = {},
			$scope.currentTab=1;
			$scope.init = ((model) => {
				$scope.fundId = model.FundID;
				$scope.model = model;
				blockUI('accordion1');
				$http({
					url: siteRoot + 'mutualfund/funddetail',
					data: { id: $scope.fundId, flag: 1 },
					method: 'POST'
				}).then((res) => {
					$scope.model1 = res.data;
					CreateFundPriceChart($scope.model1.Charts);
					CreateGeoDiversificationChart($scope.model1.geoDiversification);
					CreateSectorDiversificationChart($scope.model1.sectorDiversification);
					CreateAssetsChart($scope.model1.Assets);
					}).finally(() => { unblockUI('accordion1'); });

			});
			function CreateFundPriceChart(funds) {
				var fundsData = [];
				$(funds).each(function (i, v) {
					fundsData.push([parseInt(v.Date.slice(6, -2)), v.Price]);
				});

				new Highcharts.stockChart("fundsChart", {
					chart: {
						type: 'line',
						borderColor: '#FAFAFA',
						borderWidth: 0,
						plotBackgroundColor: '',
						padding: 5,
						panning: false
					},
					watermark: {
						yAxis: 140
					},
					rangeSelector: {
						allButtonsEnabled: false,
						selected: 5,
						inputEnabled: true,
						inputBoxBorderColor: "#cccccc",
						inputBoxHeight: 17,
						inputBoxStyle: undefined,
						inputBoxWidth: 90,
						inputDateFormat: "%b %e %Y,",
						inputDateParser: null,
						inputEditDateFormat: "%Y-%m-%d",
						inputEnabled: undefined,
						inputPosition: { align: "right" },
						inputStyle: undefined,
						labelStyle: undefined,
						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'
									}
								}
							}
						}
					},
					exporting: {
						enabled: !1
					},
					title: {
						text: '',
					},
					subtitle: {
						text: '',
					},
					xAxis: {
						tickInterval: 500,
						min: 0,
						max: null,
						type: 'datetime',
						labels: {
							formatter: function () {
								return Highcharts.dateFormat('%d/%m/%y', this.value);
							}
						}
					},
					plotOptions: {
						line: {
							marker: {
								enabled: false
							}
						}
					},
					yAxis: {
						title: {
							text: null
						},
						gridLineColor: '#ececec',
						lineColor: '#ccc',
						lineWidth: 1,
						className: 'ltr',
						height: 110,
						labels: {
							align: 'left',
							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;
						},
					},
					tooltip: {
						formatter: function () {
							return '<b>Date: </b>' + Highcharts.dateFormat('%d/%m/%y', this.x) + '<br/><b>Closing: </b>' + Highcharts.numberFormat(this.y, 2) + ' <b> ';
						}
					},
					legend: {
						layout: 'vertical',
						align: 'right',
						verticalAlign: 'middle',
						borderWidth: 0,
						enabled: false
					},
					series: [{
						data: fundsData
					}]
				});
			}
			function CreateGeoDiversificationChart(geoDiv) {
				if (!geoDiv.length > 0) return;
				var geoDivdata = [];

				$(geoDiv).each(function (i, v) {
					geoDivdata.push({ "name": v.Name, "y": v.Value });
				});

				geoDivdata[0] = {
					"name": geoDiv[0].Name,
					"y": geoDiv[0].Value,
					sliced: true,
					selected: true
				};
				$('#geoDiversification').highcharts({
				chart: {
					plotBackgroundColor: null,
					plotBorderWidth: null,
					plotShadow: false,
					type: 'pie',
					options3d: {
						enabled: true,
						alpha: 45,
						beta: 0
					}
				},
				title: null,
				color: 'white',
				tooltip: {
					pointFormat: '<b>{point.percentage:.2f}%</b>'
				},
				plotOptions: {
					pie: {
						allowPointSelect: true,
						cursor: 'pointer',
						dataLabels: {
							enabled: true,
							format: '{point.percentage:.2f}%',
							style: {
								color: (Highcharts.theme && Highcharts.theme.contrastTextColor) || 'black'
							}
						},
						showInLegend: true,
					}
				},
				credits: {
					enabled: false
				},
				legend: {
					enabled: false
				},
				series: [{
					type: 'pie',
					colorByPoint: true,
					data: geoDivdata
				}]
			});
			}
			function CreateSectorDiversificationChart(secDiv) {
				if (!secDiv.length > 0) return;
				var secDivdata = [];

				$(secDiv).each(function (i, v) {
					secDivdata.push({ "name": v.Name, "y": v.Value });
				});

				secDivdata[0] = {
					"name": secDiv[0].Name,
					"y": secDiv[0].Value,
					sliced: true,
					selected: true
				};
				$('#secDiversification').highcharts({
					chart: {
						plotBackgroundColor: null,
						plotBorderWidth: null,
						plotShadow: false,
						type: 'pie',
						options3d: {
							enabled: true,
							alpha: 45,
							beta: 0
						}
					},
					title: null,
					color: 'white',
					tooltip: {
						pointFormat: '<b>{point.percentage:.2f}%</b>'
					},
					plotOptions: {
						pie: {
							allowPointSelect: true,
							cursor: 'pointer',
							dataLabels: {
								enabled: true,
								format: '{point.percentage:.2f}%',
								style: {
									color: (Highcharts.theme && Highcharts.theme.contrastTextColor) || 'black'
								}
							},
							showInLegend: true,
						}
					},
					credits: {
						enabled: false
					},
					legend: {
						enabled: false
					},
					series: [{
						type: 'pie',
						colorByPoint: true,
						data: secDivdata
					}]
				});
			}
			function CreateAssetsChart(asset) {
				if (!asset.length > 0) return;
					let assetData = [];
							$(asset).each(function (i, v) {
								assetData.push({ "name": v.Name, "y": v.Value });
							});
							assetData[0] = {
								"name": asset[0].Name,
								"y": asset[0].Value,
								sliced: true,
								selected: true
							};

							$('#assetAllocation').highcharts({
								chart: {
									plotBackgroundColor: null,
									plotBorderWidth: null,
									plotShadow: false,
									type: 'pie',
									options3d: {
										enabled: true,
										alpha: 45,
										beta: 0
									}
								},
								title: null,
								distance: -30,
								color: 'white',
								tooltip: {
									pointFormat: '<b>{point.percentage:.2f}%</b>'
								},
								plotOptions: {
									pie: {
										allowPointSelect: true,
										cursor: 'pointer',
										dataLabels: {
											enabled: true,
											format: '{point.percentage:.2f}%',
											style: {
												color: (Highcharts.theme && Highcharts.theme.contrastTextColor) || 'black'
											}
										},
										showInLegend: true,
									}
								},
								credits: {
									enabled: false
								},
								series: [{
									colorByPoint: true,
									data: assetData
								}]
							});
			}

			$scope.loadFundManagedByDate = (($event) => {
				if (!$filter('empty')($scope.model3)) return;
				blockUI('accordion1');
				$http({
					url: siteRoot + 'mutualfund/funddetail',
					data: { id: $scope.fundId, flag: 2 },
					method: 'POST'
				}).then((res) => {
					$scope.model3 = res.data;
					$timeout(() => { CreateFundsCharts(); });
					}).finally(() => {
						unblockUI('accordion1');
					});
			});

      function CreateFundsCharts() {
                Highcharts.SparkLine = function (a, b, c) {
                    var hasRenderToArg = typeof a === 'string' || a.nodeName,
                        options = arguments[hasRenderToArg ? 1 : 0],
                        defaultOptions = {
                            chart: {
                                backgroundColor: null,
                                renderTo: (options.chart && options.chart.renderTo) || this,
                                borderWidth: 0,
                                type: 'area',
                                margin: [2, 2, 2, 0],
                                style: {
                                    overflow: 'visible'
                                },

                                skipClone: true
                          },
                            watermark: {
                              text: ''
                            },
                            title: {
                                text: ''
                            },
                            credits: {
                                enabled: false
                            },
                            xAxis: {
                                type: 'datetime',
                                labels: {
                                    enabled: false
                                },
                                title: {
                                    text: null
                                },
                                startOnTick: false,
                                endOnTick: false,
                                tickPositions: []
                            },
                            yAxis: {
                                endOnTick: false,
                                startOnTick: false,
                                labels: {
                                    enabled: false
                                },
                                title: {
                                    text: null
                                },
                                tickPositions: [0]
                            },
                            legend: {
                                enabled: false
                            },
                            tooltip: {
                                backgroundColor: null,
                                borderWidth: 0,
                                shadow: false,
                                useHTML: true,
                                hideDelay: 0,
                                shared: true,
                                padding: 0,
                                positioner: function (w, h, point) {
                                    return { x: point.plotX - w / 2, y: point.plotY - h };
                                },
                                formatter: function () {
                                    return '<div class="highchart-tooltip-cus"><b>' + Highcharts.dateFormat('%b %e, %Y', new Date(this.x)) + ' :</b>' + ' ' + Highcharts.numberFormat(this.y, 2, '.', ',') + "</div>";
                                }
                            },
                            plotOptions: {
                                area: {
                                    fillColor: {
                                        linearGradient: {
                                            x1: 0,
                                            y1: 0,
                                            x2: 0,
                                            y2: 1
                                        },
                                        stops: [
                                            [0, '#fac503'],
                                            [1, '#fac503']
                                        ]
                                    },
                                },
                                series: {
                                    animation: false,
                                    lineWidth: 1,
                                    shadow: false,
                                    states: {
                                        hover: {
                                            lineWidth: 1
                                        }
                                    },

                                    marker: {
                                        radius: 1,
                                        states: {
                                            hover: {
                                                radius: 2
                                            }
                                        }
                                    },
                                    fillOpacity: 0.25
                                },
                            }
                        };

                    options = Highcharts.merge(defaultOptions, options);

                    return hasRenderToArg ?
                        new Highcharts.Chart(a, options, c) :
                        new Highcharts.Chart(options, b);
                };

								let start = +new Date(),
                    $tds = $('.otherFundChart'),
                    fullLen = $tds.length,
                    n = 0;

                function doChunk() {
									let time = +new Date(),
                        i,
                        len = $tds.length,
                        $td,
                        stringdata,
                        arr,
                        data,
                        chart;

                    for (i = 0; i < len; i += 1) {
											$td = $($tds[i]);
											let mfundId = parseInt($td.data('mfundid')),
											stringdata = $.map($scope.model3.ChartByFunds, (elem) => { if (elem.MFundID === mfundId) return elem; }),
                      chart = {};

                        let chartData = [];
                        angular.forEach(stringdata, function (v) {
                            chartData.push([parseInt(v.Date.slice(6, -2)), v.Price]);
                        });
                        let minVal = Math.min.apply(null, stringdata.map(i => i.Price)),
                            maxVal = Math.max.apply(null, stringdata.map(i => i.Price));

                        $td.highcharts('SparkLine', {
                            yAxis: {
                                min: minVal,
                                max: maxVal,
                          },
                            watermark: {
                              text: ''
                            },
                            series: [{
                                data: chartData,
                                color: {
                                    linearGradient: { x1: 0, x2: 0, y1: 0, y2: 1 },
                                    stops: [
                                        [0, '#e69140'],
                                        [1, '#e69140']
                                    ]
                                }
                            }],
                            chart: chart
                        });
                        n += 1;
                        if (new Date() - time > 500) {
                            $tds.splice(0, i + 1);
                            setTimeout(doChunk, 0);
                            break;
                        }
                    }
                }
                doChunk();
			};

			
	}])
	.controller('fundPerformanceCtrl', ['$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.singleLineAnalysis = false;
		$scope.lang = Number(lang);
		$scope.SelectedList = [];
		$scope.RecentFunds = [];
		var cur, expireDate, cookie;
		expireDate = new Date();
		expireDate.setDate(expireDate.getDate() + 1);
		$scope.init = function (detailModel) {
			$scope.detailModel = detailModel;
			$scope.PriceChartCall(detailModel.FundID, 0, 0, 0, 6);
		}
		
		$scope.searchSelectionCallback = function ($item) {
			if ($item !== undefined && $item !== 'undefined') {

				$scope.PriceChartCall($item.originalObject.MFundID,0, 0,  0, 6, $item.originalObject.ShortName);
				var recTicker = undefined;
				if ($scope.RecentFunds !== undefined)
					recTicker = $filter('filter')($scope.RecentFunds, { Ticker: $item.originalObject.ShortName })[0];

				if ($cookies.getObject('RecentFunds') && recTicker === undefined) {
					cur = $cookies.getObject('RecentFunds');
					cookie = {
						'Id': $item.originalObject.MFundID,
						'Ticker': $item.originalObject.ShortName,
						'ETicker': $item.originalObject.EngShortName,
						'lang': $scope.lang
					}

					cur.push(cookie)
					$cookies.putObject('RecentFunds', cur, { 'expires': expireDate });
					$scope.RecentFunds = $cookies.getObject('RecentFunds');

					$timeout(function () {
						$scope.$apply($scope.RecentFunds);
					});
				}
			}
		}

		perfChart = Highcharts.stockChart('fundPerformanceChart', {
			chart: {
				borderColor: '#FAFAFA',
				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: 7,
				inputEnabled: true,
				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')
				}, {
					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); }
					}
				}
			},
			yAxis: {
				gridLineColor: '#ececec',
				lineColor: '#ccc',
				lineWidth: 1,
				labels: {
					x: -5,
					y: -7,
					formatter: function () {
						return $filter('WNOrDec')(this.value, 2) + '%';
					}
				},
				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"><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\"><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\"><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 + 'mutualfund/fundperformance',
				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('RecentFunds')) {
					$scope.RecentFunds = $cookies.getObject('RecentFunds');
				}
				if ($scope.RecentFunds !== undefined) {
					var recTicker = $filter('filter')($scope.RecentFunds, {
						Ticker: res.data[0].EngTicker
					})[0];
				}
				if (recTicker === undefined && TypeID===6) {

					if (!$cookies.getObject('RecentFunds')) {
						cookie = [{
							'Id': parseInt(MarketID),
							'Ticker': res.data[0].Ticker,
							'ETicker': res.data[0].EngTicker,
							'lang': $scope.lang
						}];
						$cookies.putObject('RecentFunds', cookie, { 'expires': expireDate });
					} else {
						cur = $cookies.getObject('RecentFunds');
						data = {
							'Id': parseInt(MarketID),
							'Ticker': res.data[0].Ticker,
							'ETicker': res.data[0].EngTicker,
							'lang': $scope.lang
						}
						cur.push(data)
						$cookies.putObject('RecentFunds', cur, { 'expires': expireDate });
					}
				}

				$scope.RecentFunds = $cookies.getObject('RecentFunds');
				$timeout(function () {
					$scope.$apply($scope.RecentFunds);
				});
				

				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 ($('.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();
		};

		
		////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();
			}
		}

	}])
	;