﻿
angular.module('ngHomeApp', ['ngSanitize'])
    .controller('homeIndexCtrl', ['$global', '$uibModal', '$timeout', '$filter', '$scope', '$http', '$q', '$interval', '$window', function ($global, $uibModal, $timeout, $filter, $scope, $http, $q, $interval, $window) {
        let self = this,
            globalIndicesLoaded = false;

        $(window).scrollTop(0, 0);

        $scope.chartConst = {
            is50DayMA: false,
            is200DayMA: false,
            isTrendLine: false
        };

        $scope.widgets = [];
        $scope.chartData = [];

        $scope.addWidget = function (id, name, parentId, widgetKey) {
            
            var errFlag = false;
            
            if ($scope.portfolioId == "") {
                alert("Please select any Portfolio");
                errFlag =true
                return;
            }
            if ($scope.dashboardId == "") {
                alert("Please select any Dashboard");
                errFlag = true;
                return;
            }

            var widget = $scope.widgets.find(f => f.PortfolioId == $scope.portfolioId && f.DashboardId == $scope.dashboardId && f.WidgetId == id);
            if (widget != null) {
                alert("This widget Already exist in this dashboard");
                errFlag = true;
                return;
            }

            if (!errFlag) {
                //$scope.widgets.push({
                //    'Id': id,
                //    'Name': name,
                //    'ParentId': parentId,
                //    'WidgetKey': widgetKey,
                //});

                $http({
                    url: siteRoot + 'home/SaveUpdatePortfolioWidgetDashboard',
                    method: 'POST',
                    data: {
                        WidgetId: id,
                        PortfolioId: $scope.portfolioId,
                        DashboardId: $scope.dashboardId,
                    }
                }, function (error) {
                    $scope.error = true;
                    $timeout(function () {
                        $scope.error = false;
                    }, 1500);
                }).then(function (resp) {
                    if (resp.data === 0) {
                        $scope.success = true;
                        $timeout(function () {
                            var obj = { WidgetId: id, PortfolioId: $scope.portfolioId, DashboardId: $scope.dashboardId, Name: name, WidgetKey: widgetKey }
                            $scope.widgets.push(obj);
                            $scope.loadWidgetsData(obj);

                        }, 1500);
                    }
                }).finally(function () {
                    $scope.working = false;
                });


                
            }
            
        }

        /**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

        function getTransactionsforPortfolioTotals(data) {
            
            $scope.SumCurrentValue = 0;
            $scope.SumTotalCost = 0;
            $scope.SumTodayGain = 0;
            $scope.SumOverAllGain = 0;
            $scope.SumGainPercent = 0;
            for (var i = 0; i < data.length; i++) {
                $scope.currency = data[0].Currency;
                $scope.SumCurrentValue = $scope.SumCurrentValue + data[i].Current_Value;
                $scope.SumTotalCost = $scope.SumTotalCost + data[i].TotalCost;
                $scope.SumTodayGain = $scope.SumTodayGain + data[i].Today_Gain;
                $scope.SumOverAllGain = $scope.SumOverAllGain + data[i].OverallGain;
                $scope.SumGainPercent = $scope.SumGainPercent + data[i].OverallGainPer;
            }
        }

        $scope.loadDashboardPieChart = function (title) {
            Highcharts.chart(title, {
                chart: {
                    type: 'pie',
                    plotBackgroundColor: null,
                    plotBorderWidth: null,
                    backgroundColor: '#000',
                    borderColor: null,
                    borderWidth: 0,
                    color: '#ADADAD',
                    plotShadow: false,
                },
                color: '#ADADAD',
                title: {
                    text: null
                },
                tooltip: {
                    pointFormat: '{point.name}: <b>{point.percentage:.2f}%</b>',
                    style: {
                        fontSize: '1.2em',
                        color: '#ADADAD',
                        textOutline: 'none',
                        opacity: 0.7
                    },
                },
                plotOptions: {
                    pie: {
                        allowPointSelect: true,
                        cursor: 'pointer',
                        dataLabels: {
                            enabled: true,
                            format: '<b>{point.name}</b>: {point.percentage:.1f} %',
                            style: {
                                color: '#ADADAD'
                            }
                        }
                    },
                    //series: {
                    //    allowPointSelect: true,
                    //    cursor: 'pointer',
                    //    dataLabels: [{
                    //        enabled: true,
                    //        distance: 20
                    //    }, {
                    //        enabled: true,
                    //        distance: -40,
                    //        format: '{point.percentage:.1f}%',
                    //        style: {
                    //            fontSize: '1.2em',
                    //            color: '#ADADAD',
                    //            textOutline: 'none',
                    //            opacity: 0.7
                    //        },
                    //        filter: {
                    //            operator: '>',
                    //            property: 'percentage',
                    //            value: 10
                    //        }
                    //    }]
                    //}
                },
                series: [
                    {
                        //name: 'Percentage',
                        //colorByPoint: true,
                        data: $scope.chartData
                    }
                ]
            });
        }

        $scope.loadDashboardColumnChart = function (title) {
            Highcharts.chart(title, {
                chart: {
                    type: 'column',
                    plotBackgroundColor: null,
                    plotBorderWidth: null,
                    backgroundColor: '#000',
                    borderColor: null,
                    borderWidth: 0,
                    color: '#ADADAD',
                    plotShadow: false,
                },
                color: '#ADADAD',
                title: {
                    text: null
                },
                xAxis: {
                    categories: $scope.sectors,
                    labels: {
                        style: {
                            width: '100px',
                            textOverflow: 'none',
                            color: '#ADADAD'
                        },
                        formatter: function () {
                            return WNOrDecimal(this.value);
                        },
                        enabled: true
                    },
                    crosshair: true
                },
                yAxis: {
                    min: 0,
                    labels: {
                        style: {
                            color: '#ADADAD'
                        }
                    },
                    title: {
                        text: null
                    }
                },
                tooltip: {
                    headerFormat: '<span style="font-size:10px">{point.key}</span><table>',
                    pointFormat: '<tr><td style="color:{series.color};padding:0">{series.name}: </td>' +
                        '<td style="padding:0"><b>{point.y:.1f} %</b></td></tr>',
                    footerFormat: '</table>',
                    shared: true,
                    style: {
                        color: '#ADADAD'
                    },
                    useHTML: true
                },

                series: [{
                    name: title == "Fundamentalanalysis" ? "Portfolio" : "Current",
                    data: $scope.sectorRatios

                }, {
                    name: title == "Fundamentalanalysis" ? "TASI" : "Cost",
                    data: title == "Fundamentalanalysis" ? $scope.tasiWeightings : $scope.sumtotalCosts

                }]
            });
        }

        $scope.loadDashboardBarChart = function (title) {
            Highcharts.chart(title, {
                chart: {
                    type: 'column',
                    plotBackgroundColor: null,
                    plotBorderWidth: null,
                    backgroundColor: '#000',
                    borderColor: null,
                    borderWidth: 0,
                    color: '#ADADAD',
                    plotShadow: false,
                },
                color: '#ADADAD',
                title: {
                    text: null
                },
                xAxis: {
                    categories: $scope.companies,
                    labels: {
                        style: {
                            width: '100px',
                            textOverflow: 'none',
                            color: '#ADADAD'
                        },
                        formatter: function () {
                            return WNOrDecimal(this.value);
                        },
                        enabled: true
                    },
                    crosshair: true
                },
                yAxis: {
                    min: 0,
                    labels: {
                        style: {
                            color: '#ADADAD'
                        }
                    },
                    title: {
                        text: null
                    }
                },
                tooltip: {
                    headerFormat: '<span style="font-size:10px">{point.key}</span><table>',
                    pointFormat: '<tr><td style="color:{series.color};padding:0">{series.name}: </td>' +
                        '<td style="padding:0"><b>{point.y:.1f} %</b></td></tr>',
                    footerFormat: '</table>',
                    shared: true,
                    style: {
                        color: '#ADADAD'
                    },
                    useHTML: true
                },

                series: [{
                    name: title,
                    data: $scope.barValues

                }]
            });
        }

        $scope.loadDashboardBubbleChart = function (title) {
            Highcharts.chart(title, {
                chart: {
                    type: 'bubble',
                    zoomType: 'xy',
                    plotBackgroundColor: null,
                    plotBorderWidth: null,
                    backgroundColor: '#000',
                    borderColor: null,
                    borderWidth: 0,
                    color: '#ADADAD',
                    plotShadow: false,
                },
                color: '#ADADAD',
                legend: {
                    enabled: false
                },
                credits: {
                    enabled: false
                },
                title: {
                    text: null//'Sugar and fat intake per country'
                },

                subtitle: {
                    text: null// 'Source: <a href="http://www.euromonitor.com/">Euromonitor</a> and <a href="https://data.oecd.org/">OECD</a>'
                },
                xAxis: {
                    gridLineWidth: 1,
                    title: {
                        text: title == "XYBubble" ? 'Price to Earning (P/E)' : 'Return on Assets (RoA)',
                        style: {
                            color: '#ADADAD',
                        },
                    },

                    labels: {
                        format: '{value}',
                        style: {
                            color: '#ADADAD',
                        },
                    },
                    plotLines: [{
                        color: '#ADADAD',
                        dashStyle: 'dot',
                        width: 2,
                        value: 65,
                        label: {
                            rotation: 0,
                            y: 15,
                            style: {
                                fontStyle: 'italic',
                                color: '#ADADAD',
                            },
                            text: null
                        },
                        zIndex: 3
                    }]
                },
                yAxis: {
                    startOnTick: false,
                    endOnTick: false,
                    title: {
                        text: title == "XYBubble" ? 'Price to Book (P/B)' : "Return on Equity (RoE)",
                        style: {
                            color: '#ADADAD',
                        },
                    },
                    labels: {
                        format: '{value}',
                        style: {
                            color: '#ADADAD',
                        },
                    },
                    maxPadding: 0.2,
                    plotLines: [{
                        color: '#ADADAD',
                        dashStyle: 'dot',
                        width: 2,
                        value: 50,
                        label: {
                            align: 'right',
                            style: {
                                fontStyle: 'italic',
                                color: '#ADADAD',
                            },
                            text: null,
                            x: -10
                        },
                        zIndex: 3
                    }]
                },
                tooltip: {
                    headerFormat: '<table>',
                    pointFormat: '<tr><th colspan="2"><h3>{point.name}</h3></th></tr>' +
                        '<tr><th>P/E:</th><td>{point.x}%</td></tr>' +
                        '<tr><th>P/B:</th><td>{point.y}%</td></tr>' +
                        '<tr><th>Current Value:</th><td>{point.z}</td></tr>',
                    footerFormat: '</table>',
                    shared: true,
                    style: {
                        color: '#ADADAD'
                    },
                    useHTML: true
                },

                plotOptions: {
                series: {
                    dataLabels: {
                        enabled: true,
                        format: '{point.name}'
                    }
                }
            },

            series: [{
                data: title == "XYBubble" ? $scope.fundPEPBBubbleChartData : $scope.fundROAROEBubbleChartData
                //data: [
                //    { x: 12.5, y: 12.8, z: 13444, name: 'RIBL' },
                //     { x: 9.5, y: 7.5, z: 763344, name: 'SABIC' },

                //]
            }]
            });
        }

        $scope.loadRecomendations = function ($inview) {
            $http({
                method: 'POST',
                url: siteRoot + 'home/index',
                data: { type: 'recommendations' }
            })
                .then((res) => {
                    $scope.recommendations = res.data.recommendations;
                }, (error) => { console.log(error.data); })
                .finally(() => {
                    $timeout(function () {
                        CreateRecommendationCharts()
                    });
                });

            //if (!$inview || !$filter('empty')($scope.recommendations)) return;
            //blockUI('accordion3');
            //$http({
            //    method: 'POST',
            //    url: siteRoot + 'home/index',
            //    data: { type: 'recommendations' }
            //})
            //    .then((res) => {
            //        $scope.recommendations = res.data.recommendations;
            //    }, (error) => { unblockUI('accordion3'); console.log(error.data); })
            //    .finally(() => {
            //        unblockUI('accordion3');
            //        $timeout(function () {
            //            CreateRecommendationCharts()
            //        });
            //    });
        }

        $scope.removeWidget = function (productIndex,item) {
            $scope.widgets.splice(productIndex, 1);
            $scope.deleteDashboardWidgets(item.WidgetId);
        }

        $scope.portofolios = [];
        $scope.portfolioId = "";
        $scope.getPortofolios = function () {
            
            $http({
                method: 'GET',
                url: siteRoot + 'home/GetPortofolios',
                //data: { portfolioId: $scope.portfolioId, langID: 1, type: title }
            })
                .then((res) => {
                    
                    $scope.portofolios = res.data;
                }, (error) => { console.log(error.data); })
                .finally(() => {
                });
        }

        $scope.dashboards = [];
        $scope.dashboardId = "";
        $scope.getDashboards = function () {
            
            $scope.dashboardId = "";
            $scope.widgets = [];
            $http({
                method: 'GET',
                url: siteRoot + 'home/GetDashboardByPortofolioId?portofolioId=' + $scope.portfolioId,
                //data: { portofolioId: $scope.portfolioId }
            })
                .then((res) => {
                    
                    $scope.dashboards = res.data;
                }, (error) => { console.log(error.data); })
                .finally(() => {
                });
        }

        $scope.addDashboard = function () {
            
            var modalInstance = $uibModal.open({
                templateUrl: '/content/theme/ng/partials/addDashboard.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: 'addToWidgetDashboardCtrl',
                scope: $scope,
                windowClass: 'app-modal-window',
                resolve: {
                    'data': { portofolioId: $scope.portfolioId}
                }
            });
            modalInstance.result.then(function (result) {
                
                if (result == 0) {
                    $scope.getDashboards();
                }
            });
        }

        $scope.widgets = [];
        $scope.widgetId = "";
        $scope.getDashboardWidgets = function () {
            
            $http({
                method: 'GET',
                url: siteRoot + 'home/GetDashboardWidgets?portofolioId=' + $scope.portfolioId + '&dashboardId=' + $scope.dashboardId,
                //data: { portofolioId: $scope.portfolioId }
            })
                .then((res) => {
                    
                    $scope.widgets = res.data;
                    angular.forEach($scope.widgets, function (value, key) {
                        $scope.loadWidgetsData(value);                        
                    });
                    
                    
                }, (error) => { console.log(error.data); })
                .finally(() => {
                });
        }

        $scope.deleteDashboardWidgets = function (id) {
            
            $http({
                method: 'GET',
                url: siteRoot + 'home/DeletePortofolioWidgetDashBoard?portofolioId=' + $scope.portfolioId + '&dashboardId=' + $scope.dashboardId + '&widgetId=' + id,
                //data: { portofolioId: $scope.portfolioId }
            })
                .then((res) => {
                    
                    alert(res.data)


                }, (error) => { console.log(error.data); })
                .finally(() => {
                });
        }

        $scope.loadWidgetsData = function (value) {
            if (
                value.WidgetKey == 'AssetAllocation' || value.WidgetKey == 'SectorAllocation' || value.WidgetKey == 'MarketCap' ||
                value.WidgetKey == 'P/BExposure' || value.WidgetKey == 'P/EExposure' || value.WidgetKey == 'PEGExposure' ||
                value.WidgetKey == 'RoAExposure' || value.WidgetKey == 'RoEExposure' || value.WidgetKey == '1-YearPrice' ||
                value.WidgetKey == 'DividendYield' || value.WidgetKey == 'IncomeGrowth' || value.WidgetKey == 'RevenueGrowth' || value.WidgetKey == 'RelativeValuation'
            ) {
                $scope.chartData = [];
                $http({
                    method: 'POST',
                    url: siteRoot + 'home/GetPortfoioDashBoardData',
                    data: { portfolioId: $scope.portfolioId, langID: 1, type: value.WidgetKey }
                })
                    .then((res) => {
                        $scope.chartData = res.data.ChartData;
                    }, (error) => { console.log(error.data); })
                    .finally(() => {
                        $scope.loadDashboardPieChart(value.WidgetKey);
                    });


            }
            else if (value.WidgetKey == "Fundamentalanalysis" || value.WidgetKey == "StatisticalAnalysis") {
                $scope.chartData = [];
                $http({
                    method: 'POST',
                    url: siteRoot + 'home/GetPortfoioDashBoardData',
                    data: { portfolioId: $scope.portfolioId, langID: 1, type: value.WidgetKey }
                })
                    .then((res) => {
                        $scope.chartData = res.data.ChartData;
                        $scope.sectors = [];
                        $scope.sectorRatios = [];
                        $scope.tasiWeightings = [];
                        $scope.sumtotalCosts = [];
                        angular.forEach(res.data.ChartData, function (value, key) {
                            $scope.sectors.push(value.name);
                            $scope.sectorRatios.push(value.y);
                            $scope.tasiWeightings.push(value.weighting);
                            $scope.sumtotalCosts.push(value.sumtotalCost);
                        });
                    }, (error) => { console.log(error.data); })
                    .finally(() => {
                        $scope.loadDashboardColumnChart(value.WidgetKey);
                    });
            }
            else if (value.WidgetKey == "XYBubble" || value.WidgetKey == "XYBubbleROA") {
                $scope.chartData = [];
                $http({
                    method: 'POST',
                    url: siteRoot + 'home/GetPortfoioDashBoardData',
                    data: { portfolioId: $scope.portfolioId, langID: 1, type: value.WidgetKey }
                })
                    .then((res) => {
                        
                        $scope.chartData = res.data.ChartData;
                        $scope.fundPEPBBubbleChartData = [];
                        $scope.fundROAROEBubbleChartData = [];
                        angular.forEach(res.data.ChartData, function (value, key) {
                            $scope.fundPEPBBubbleChartData.push({ x: value.x, y: value.y, z: value.z, name: value.name });
                            $scope.fundROAROEBubbleChartData.push({ x: value.x, y: value.y, z: value.z, name: value.name });
                        });
                    }, (error) => { console.log(error.data); })
                    .finally(() => {
                        $scope.loadDashboardBubbleChart(value.WidgetKey);
                    });
            }
            else if (value.WidgetKey == "MyPortfolio") {
                $scope.transactionsforPortfolio = [];
                $http({
                    method: 'POST',
                    url: siteRoot + 'home/GetPortfoioDashBoardData',
                    data: { portfolioId: $scope.portfolioId, langID: 1, type: value.WidgetKey }
                })
                    .then((res) => {
                        
                        $scope.transactionsforPortfolio = res.data.ChartData;
                        getTransactionsforPortfolioTotals($scope.transactionsforPortfolio);
                    }, (error) => { console.log(error.data); })
                    .finally(() => {
                    });
            }
            else if (value.WidgetKey == "UnrealizedGain" || value.WidgetKey == "ComparativeAnalysisPrice" || value.WidgetKey == "ComparativeAnalysisEarning)" || value.WidgetKey == "ComparativeBook") {
                $scope.chartData = [];
                $http({
                    method: 'POST',
                    url: siteRoot + 'home/GetPortfoioDashBoardData',
                    data: { portfolioId: $scope.portfolioId, langID: 1, type: value.WidgetKey }
                })
                    .then((res) => {
                        $scope.chartData = res.data.ChartData;
                        $scope.companies = [];
                        $scope.barValues = [];
                        angular.forEach(res.data.ChartData, function (value, key) {
                            $scope.companies.push(value.name);
                            $scope.barValues.push(value.y);
                        });
                    }, (error) => { console.log(error.data); })
                    .finally(() => {
                        console.log($scope.barValues);
                        $scope.loadDashboardBarChart(value.WidgetKey);
                    });
            }
        }

        $scope.menus;
        $scope.subMenus;
        $scope.getWidgets = function () {
            
            $http({
                method: 'GET',
                url: siteRoot + 'home/GetgbWidget',
                //data: { portofolioId: $scope.portfolioId }
            })
                .then((res) => {
                    $scope.menus = res.data.filter(f => f.ParentId == 0);
                    $scope.subMenus = res.data.filter(f => f.ParentId != 0 && f.ParentId != 1 && f.ParentId != 3);
                    $scope.subMenus1 = res.data.filter(f => f.ParentId == 1);
                    $scope.subMenus3 = res.data.filter(f => f.ParentId == 3);

                    
                }, (error) => { console.log(error.data); })
                .finally(() => {
                });
        }

        $scope.addDashboardWidget = function () {
            
            var modalInstance = $uibModal.open({
                templateUrl: '/content/theme/ng/partials/addDashboardWidget.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: 'addToPortfolioWidgetDashboardCtrl',
                scope: $scope,
                windowClass: 'app-modal-window',
                resolve: {
                    'data': { portofolioId: $scope.portfolioId, dashboardId: $scope.dashboardId }
                }
            });
            modalInstance.result.then(function (result) {
                
                if (result == 0) {
                    $scope.getDashboardWidgets();
                }
            });
        }

        $scope.dashboard = {};

        $scope.addWidgetDashboard = function () {
            $http({
                method: 'POST',
                url: siteRoot + 'home/InsertWidgetDashboard',
                data: { model: $scope.dashboard }
            })
                .then((res) => {
                    
                    $scope.dashboards = res.data;
                }, (error) => { console.log(error.data); })
                .finally(() => {
                });
        }

        loadGlobalIndices();

        $scope.customFilter = function (item) {

            return $scope.subMenus.filter(f => f.ParentId == item);
        };

        $scope.init = function () {
            $scope.getPortofolios();
            $scope.getWidgets();

            //jQuery.noConflict();

            //$("#list1").dragsort({
            //    dragSelector: "div",
            //    dragBetween: true,
            //    dragEnd: saveOrder,
            //    placeHolderTemplate: "<li class='placeHolder'><div></div></li>",
            //    cursor: "move"
            //});




        }
        //$scope.init();
        
        $scope.chart = undefined;
        let pdata = [],
            vdata = [];
        $scope.marketName = undefined,
            $scope.stockMarketID = undefined,
            $scope.stockMarketURL = undefined;
        $scope.initChart = function () {
            $timeout(() => {
                angular.element($('div.gccstockmarket .market-div').first().find('ul')).trigger('click');
            });
        };

        $scope.mydragg = function () {
            return {
                move: function (divid, xpos, ypos) {
                    divid.style.left = xpos + 'px';
                    divid.style.top = ypos + 'px';
                },
                startMoving: function (divid, container, evt) {
                    evt = evt || window.event;
                    divid = document.getElementById(divid);
                    var posX = evt.clientX,
                        posY = evt.clientY,
                        divTop = divid.style.top,
                        divLeft = divid.style.left,
                        eWi = parseInt(divid.style.width),
                        eHe = parseInt(divid.style.height),
                        cWi = parseInt(document.getElementById(container).style.width),
                        cHe = parseInt(document.getElementById(container).style.height);
                    document.getElementById(container).style.cursor = 'move';
                    divTop = divTop.replace('px', '');
                    divLeft = divLeft.replace('px', '');
                    var diffX = posX - divLeft,
                        diffY = posY - divTop;
                    document.onmousemove = function (evt) {
                        evt = evt || window.event;
                        var posX = evt.clientX,
                            posY = evt.clientY,
                            aX = posX - diffX,
                            aY = posY - diffY;
                        if (aX < 0) aX = 0;
                        if (aY < 0) aY = 0;
                        if (aX + eWi > cWi) aX = cWi - eWi;
                        if (aY + eHe > cHe) aY = cHe - eHe;
                        $scope.mydragg.move(divid, aX, aY);
                    }
                },
                stopMoving: function (container) {
                    var a = document.createElement('script');
                    document.getElementById(container).style.cursor = 'default';
                    document.onmousemove = function () { }
                },
            }
        }();

        $scope.closePopup = function (divid) {
            
            document.getElementById(divid).style.display = 'none';
        }

        $scope.openPopup = function (divid) {
            
            document.getElementById(divid).style.display = 'block';
        }

        $scope.stockInfo = function (id) {
            if (id === $scope.stockMarketID) {
                $scope.chartConst.isTrendLine = !$scope.chartConst.isTrendLine;
                return;
            }


            $scope.data = {};
            $scope.stockMarketID = id,
                blockUI('StockMarketData');
            $http({
                method: 'GET',
                url: siteRoot + 'Home/StockMarket/' + id,
            }).then(function (res) {
                $scope.data = res.data;

                self.stockMarket = res.data.ListCompanyStock;
                createChart();
            }, (error) => { unblockUI('StockMarketData'); console.log(error.data); })
                .then(function () {
                    unblockUI('StockMarketData');
                });
        }

        $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
                    });
                }
            }

        });

        function maxValue(data) {
            return Math.max.apply(Math, data.map(function (val) { return Math.abs(val.ChangePer); }));
        }
        function createChart() {
            pdata = [];
            vdata = [];

            self.stockMarket.map(function (elem) {
                let IndexDate = parseInt(elem.IndexDate.slice(6, -2));
                pdata.push([IndexDate, parseFloat(elem.Closing)]);
                vdata.push([IndexDate, parseInt(elem.Volume)]);
            });
            let
                min = Number($scope.data.MinDate.slice(6, -2)),
                max = Number($scope.data.MaxDate.slice(6, -2)),
                linXData = [], linYData = [];

            pdata.map(function (elem, i) {
                let date = parseInt(elem[0]);
                if (date >= min && date <= max) {
                    linXData.push([elem[0], elem[1]]);
                    //linYData.push(elem[1]);
                }
            });
            // Create the chart
            new Highcharts.stockChart('StockMarketChart', {
                chart: {
                    borderColor: '#3a3a3a',
                    borderWidth: 0,
                    plotBackgroundColor: '',
                    backgroundColor: '#000',
                    padding: 5,
                    panning: false
                },
                watermark: {
                    yAxis: 120
                },
                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: 120,
                    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: $scope.data.Average,
                        label: {
                            text: '',
                            x: -10
                        },
                        zIndex: 3
                    }]
                },
                {
                    gridLineColor: '#3a3a3a',
                    alternateGridColor: '#',
                    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: 135,
                    height: 60,
                    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',
                    range: 12 * 30 * 24 * 3600 * 1000,
                    labels: {
                        formatter: function () {
                            return Highcharts.dateFormat('%d/%m  ', this.value);
                        },
                        style: {
                            color: '#ADADAD'
                        }
                    }
                },
                title: {
                    text: ''
                },
                scrollbar: {
                    enabled: false
                },
                rangeSelector: {
                    enabled: false
                },
                navigator: {
                    enabled: false
                },
                exporting: {
                    enabled: false
                },
                tooltip: {
                    style: {
                        opacity: '1.0'
                    },
                    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 += '<p style="color:' + primary.series.color + '"><b>' + $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 += '<p style="color:' + sm.series.color + '"><b>' + 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 += '<p style="color:' + vol.series.color + '"><b>' + $filter('getLabel')('lblVolume') + ': </b> ' + $filter('AbbrOrWNOrDec')(vol.y, 2) + '</p>' + "</div>";

                        } catch (e) { }
                        return tooltipHtml;
                    }
                },
                series: [{
                    name: 'primary',
                    id: 'primary',
                    data: pdata,
                    dname: $scope.MarketName,
                    color: '#18A97E',
                    type: 'line',
                    lineWidth: 1,
                    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: 1,
                    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: 1,
                    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: '#18A97E',
                    defaultSeriesType: 'spline',
                    lineWidth: 1,
                    threshold: null,
                    visible: $scope.chartConst.isTrendLine,
                    enableMouseTracking: false,
                    data: (function () {
                        return fitData(linXData).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: '#18A97E',
                    borderColor: '#3a3a3a',
                    data: vdata,
                    yAxis: 1,
                    dataGrouping: {
                        forced: true,
                        units: [['day', [1]]]
                    }
                }]
            }, function (chart) {
                $scope.chart = chart;
            });
        }

        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',
                        plotBackgroundColor: '',
                        margin: margin,
                        width: 350
                    },
                    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,
                        }]
                    }],
                });

            });
        }

        $scope.loadRecomendations = function ($inview) {
            $http({
                method: 'POST',
                url: siteRoot + 'home/index',
                data: { type: 'recommendations' }
            })
                .then((res) => {
                    $scope.recommendations = res.data.recommendations;
                }, (error) => { console.log(error.data); })
                .finally(() => {
                    $timeout(function () {
                        CreateRecommendationCharts()
                    });
                });

            //if (!$inview || !$filter('empty')($scope.recommendations)) return;
            //blockUI('accordion3');
            //$http({
            //    method: 'POST',
            //    url: siteRoot + 'home/index',
            //    data: { type: 'recommendations' }
            //})
            //    .then((res) => {
            //        $scope.recommendations = res.data.recommendations;
            //    }, (error) => { unblockUI('accordion3'); console.log(error.data); })
            //    .finally(() => {
            //        unblockUI('accordion3');
            //        $timeout(function () {
            //            CreateRecommendationCharts()
            //        });
            //    });
        }
        /*global indices*/
        function loadGlobalIndices() {

            $http({
                url: siteRoot + 'home/index',
                data: { type: 'globalindices' },
                method: 'POST'
            }).then((res) => {

                $scope.globalIndicesData = res.data.globalIndices;
                $scope.gblAsia = $filter('filter')($scope.globalIndicesData, { CountryGroupID: 46 });
                $scope.gblEurope = $filter('filter')($scope.globalIndicesData, { CountryGroupID: 45 });
                $scope.gblAmerica = $filter('filter')($scope.globalIndicesData, { CountryGroupID: 47 });

                $scope.gblAsiaMax = maxValue($scope.gblAsia);
                $scope.gblEuropeMax = maxValue($scope.gblEurope);
                $scope.gblAmericaMax = maxValue($scope.gblAmerica);
            }, (error) => { unblockUI('accordion4'); console.log(error.data); }).finally(() => {
                unblockUI('accordion4');
                globalIndicesLoaded = true;
            });
        }

        function saveOrder() {
            var data = $("#list1 li").map(function () {
                return $(this).children().html();
            }).get();
            $("input[name=list1SortOrder]").val(data.join("|"));
        }

        
    }])
    .controller('homeNewIndexCtrl', ['$global', '$uibModal', '$timeout', '$filter', '$scope', '$http', '$q', '$interval', '$window', function ($global, $uibModal, $timeout, $filter, $scope, $http, $q, $interval, $window) {
        let self = this,
            globalIndicesLoaded = false;

        $(window).scrollTop(0, 0);

        $scope.chartConst = {
            is50DayMA: false,
            is200DayMA: false,
            isTrendLine: false
        };

        $scope.widgets = [];
        $scope.chartData = [];

        $scope.addWidget = function (id, name, parentId, widgetKey) {

            var errFlag = false;

            if ($scope.portfolioId == "") {
                alert("Please select any Portfolio");
                errFlag = true
                return;
            }
            if ($scope.dashboardId == "") {
                alert("Please select any Dashboard");
                errFlag = true;
                return;
            }

            var widget = $scope.widgets.find(f => f.PortfolioId == $scope.portfolioId && f.DashboardId == $scope.dashboardId && f.WidgetId == id);
            if (widget != null) {
                alert("This widget Already exist in this dashboard");
                errFlag = true;
                return;
            }

            if (!errFlag) {
                //$scope.widgets.push({
                //    'Id': id,
                //    'Name': name,
                //    'ParentId': parentId,
                //    'WidgetKey': widgetKey,
                //});
                $(".dropdown").removeClass("open");
                $(".dropdown-submenu").removeClass("open");
                blockUI();
                $http({
                    url: siteRoot + 'home/SaveUpdatePortfolioWidgetDashboard',
                    method: 'POST',
                    data: {
                        WidgetId: id,
                        PortfolioId: $scope.portfolioId,
                        DashboardId: $scope.dashboardId,
                    }
                }, function (error) {
                    $scope.error = true;
                    unblockUI();
                    $timeout(function () {
                        $scope.error = false;
                    }, 1500);
                }).then(function (resp) {
                    if (resp.data === 0) {
                        $scope.success = true;
                        $timeout(function () {
                            var obj = { WidgetId: id, PortfolioId: $scope.portfolioId, DashboardId: $scope.dashboardId, Name: name, WidgetKey: widgetKey }
                            $scope.widgets.push(obj);
                            $timeout(function () {
                                $('html, body').animate({
                                    scrollTop: $('#' + widgetKey).offset().top - 250
                                }, 2000);
                            }, 1000);
                            $scope.loadWidgetsData(obj);
                        }, 1000);
                    }
                }).finally(function () {
                    $scope.working = false;
                });



            }

        }

        /**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

        function getTransactionsforPortfolioTotals(data) {

            $scope.SumCurrentValue = 0;
            $scope.SumTotalCost = 0;
            $scope.SumTodayGain = 0;
            $scope.SumOverAllGain = 0;
            $scope.SumGainPercent = 0;
            for (var i = 0; i < data.length; i++) {
                $scope.currency = data[0].Currency;
                $scope.SumCurrentValue = $scope.SumCurrentValue + data[i].Current_Value;
                $scope.SumTotalCost = $scope.SumTotalCost + data[i].TotalCost;
                $scope.SumTodayGain = $scope.SumTodayGain + data[i].Today_Gain;
                $scope.SumOverAllGain = $scope.SumOverAllGain + data[i].OverallGain;
                $scope.SumGainPercent = $scope.SumGainPercent + data[i].OverallGainPer;
            }
        }

        $scope.loadDashboardPieChart = function (title) {
            Highcharts.chart(title, {
                chart: {
                    type: 'pie',
                    plotBackgroundColor: null,
                    plotBorderWidth: null,
                    backgroundColor: '#000',
                    borderColor: null,
                    borderWidth: 0,
                    color: '#ADADAD',
                    plotShadow: false,
                },
                color: '#ADADAD',
                title: {
                    text: null
                },
                tooltip: {
                    pointFormat: '{point.name}: <b>{point.percentage:.2f}%</b>',
                    style: {
                        fontSize: '1.2em',
                        color: '#ADADAD',
                        textOutline: 'none',
                        opacity: 0.7
                    },
                },
                plotOptions: {
                    pie: {
                        allowPointSelect: true,
                        cursor: 'pointer',
                        dataLabels: {
                            enabled: true,
                            format: '<b>{point.name}</b>: {point.percentage:.1f} %',
                            style: {
                                color: '#ADADAD'
                            }
                        }
                    },
                    //series: {
                    //    allowPointSelect: true,
                    //    cursor: 'pointer',
                    //    dataLabels: [{
                    //        enabled: true,
                    //        distance: 20
                    //    }, {
                    //        enabled: true,
                    //        distance: -40,
                    //        format: '{point.percentage:.1f}%',
                    //        style: {
                    //            fontSize: '1.2em',
                    //            color: '#ADADAD',
                    //            textOutline: 'none',
                    //            opacity: 0.7
                    //        },
                    //        filter: {
                    //            operator: '>',
                    //            property: 'percentage',
                    //            value: 10
                    //        }
                    //    }]
                    //}
                },
                series: [
                    {
                        //name: 'Percentage',
                        //colorByPoint: true,
                        data: $scope.chartData
                    }
                ]
            });
        }

        $scope.loadDashboardColumnChart = function (title) {
            Highcharts.chart(title, {
                chart: {
                    type: 'column',
                    plotBackgroundColor: null,
                    plotBorderWidth: null,
                    backgroundColor: '#000',
                    borderColor: null,
                    borderWidth: 0,
                    color: '#ADADAD',
                    plotShadow: false,
                },
                color: '#ADADAD',
                title: {
                    text: null
                },
                xAxis: {
                    categories: $scope.sectors,
                    labels: {
                        style: {
                            width: '100px',
                            textOverflow: 'none',
                            color: '#ADADAD'
                        },
                        formatter: function () {
                            return WNOrDecimal(this.value);
                        },
                        enabled: true
                    },
                    crosshair: true
                },
                yAxis: {
                    min: 0,
                    labels: {
                        style: {
                            color: '#ADADAD'
                        }
                    },
                    title: {
                        text: null
                    }
                },
                tooltip: {
                    headerFormat: '<span style="font-size:10px">{point.key}</span><table>',
                    pointFormat: '<tr><td style="color:{series.color};padding:0">{series.name}: </td>' +
                        '<td style="padding:0"><b>{point.y:.1f} %</b></td></tr>',
                    footerFormat: '</table>',
                    shared: true,
                    style: {
                        color: '#ADADAD'
                    },
                    useHTML: true
                },

                series: [{
                    name: title == "Fundamentalanalysis" ? "Portfolio" : "Current",
                    data: $scope.sectorRatios

                }, {
                    name: title == "Fundamentalanalysis" ? "TASI" : "Cost",
                    data: title == "Fundamentalanalysis" ? $scope.tasiWeightings : $scope.sumtotalCosts

                }]
            });
        }

        $scope.loadDashboardBarChart = function (title) {
            Highcharts.chart(title, {
                chart: {
                    type: 'column',
                    plotBackgroundColor: null,
                    plotBorderWidth: null,
                    backgroundColor: '#000',
                    borderColor: null,
                    borderWidth: 0,
                    color: '#ADADAD',
                    plotShadow: false,
                },
                color: '#ADADAD',
                title: {
                    text: null
                },
                xAxis: {
                    categories: $scope.companies,
                    labels: {
                        style: {
                            width: '100px',
                            textOverflow: 'none',
                            color: '#ADADAD'
                        },
                        formatter: function () {
                            return WNOrDecimal(this.value);
                        },
                        enabled: true
                    },
                    crosshair: true
                },
                yAxis: {
                    min: 0,
                    labels: {
                        style: {
                            color: '#ADADAD'
                        }
                    },
                    title: {
                        text: null
                    }
                },
                tooltip: {
                    headerFormat: '<span style="font-size:10px">{point.key}</span><table>',
                    pointFormat: '<tr><td style="color:{series.color};padding:0">{series.name}: </td>' +
                        '<td style="padding:0"><b>{point.y:.1f} %</b></td></tr>',
                    footerFormat: '</table>',
                    shared: true,
                    style: {
                        color: '#ADADAD'
                    },
                    useHTML: true
                },

                series: [{
                    name: title,
                    data: $scope.barValues

                }]
            });
        }

        $scope.loadDashboardBubbleChart = function (title) {
            Highcharts.chart(title, {
                chart: {
                    type: 'bubble',
                    zoomType: 'xy',
                    plotBackgroundColor: null,
                    plotBorderWidth: null,
                    backgroundColor: '#000',
                    borderColor: null,
                    borderWidth: 0,
                    color: '#ADADAD',
                    plotShadow: false,
                },
                color: '#ADADAD',
                legend: {
                    enabled: false
                },
                credits: {
                    enabled: false
                },
                title: {
                    text: null//'Sugar and fat intake per country'
                },

                subtitle: {
                    text: null// 'Source: <a href="http://www.euromonitor.com/">Euromonitor</a> and <a href="https://data.oecd.org/">OECD</a>'
                },
                xAxis: {
                    gridLineWidth: 1,
                    title: {
                        text: title == "XYBubble" ? 'Price to Earning (P/E)' : 'Return on Assets (RoA)',
                        style: {
                            color: '#ADADAD',
                        },
                    },

                    labels: {
                        format: '{value}',
                        style: {
                            color: '#ADADAD',
                        },
                    },
                    plotLines: [{
                        color: '#ADADAD',
                        dashStyle: 'dot',
                        width: 2,
                        value: 65,
                        label: {
                            rotation: 0,
                            y: 15,
                            style: {
                                fontStyle: 'italic',
                                color: '#ADADAD',
                            },
                            text: null
                        },
                        zIndex: 3
                    }]
                },
                yAxis: {
                    startOnTick: false,
                    endOnTick: false,
                    title: {
                        text: title == "XYBubble" ? 'Price to Book (P/B)' : "Return on Equity (RoE)",
                        style: {
                            color: '#ADADAD',
                        },
                    },
                    labels: {
                        format: '{value}',
                        style: {
                            color: '#ADADAD',
                        },
                    },
                    maxPadding: 0.2,
                    plotLines: [{
                        color: '#ADADAD',
                        dashStyle: 'dot',
                        width: 2,
                        value: 50,
                        label: {
                            align: 'right',
                            style: {
                                fontStyle: 'italic',
                                color: '#ADADAD',
                            },
                            text: null,
                            x: -10
                        },
                        zIndex: 3
                    }]
                },
                tooltip: {
                    headerFormat: '<table>',
                    pointFormat: '<tr><th colspan="2"><h3>{point.name}</h3></th></tr>' +
                        '<tr><th>P/E:</th><td>{point.x}%</td></tr>' +
                        '<tr><th>P/B:</th><td>{point.y}%</td></tr>' +
                        '<tr><th>Current Value:</th><td>{point.z}</td></tr>',
                    footerFormat: '</table>',
                    shared: true,
                    style: {
                        color: '#ADADAD'
                    },
                    useHTML: true
                },

                plotOptions: {
                    series: {
                        dataLabels: {
                            enabled: true,
                            format: '{point.name}'
                        }
                    }
                },

                series: [{
                    data: title == "XYBubble" ? $scope.fundPEPBBubbleChartData : $scope.fundROAROEBubbleChartData
                    //data: [
                    //    { x: 12.5, y: 12.8, z: 13444, name: 'RIBL' },
                    //     { x: 9.5, y: 7.5, z: 763344, name: 'SABIC' },

                    //]
                }]
            });
        }

        $scope.loadRecomendations = function ($inview) {
            $http({
                method: 'POST',
                url: siteRoot + 'home/index',
                data: { type: 'recommendations' }
            })
                .then((res) => {
                    $scope.recommendations = res.data.recommendations;
                }, (error) => { console.log(error.data); })
                .finally(() => {
                    $timeout(function () {
                        CreateRecommendationCharts()
                    });
                });

            //if (!$inview || !$filter('empty')($scope.recommendations)) return;
            //blockUI('accordion3');
            //$http({
            //    method: 'POST',
            //    url: siteRoot + 'home/index',
            //    data: { type: 'recommendations' }
            //})
            //    .then((res) => {
            //        $scope.recommendations = res.data.recommendations;
            //    }, (error) => { unblockUI('accordion3'); console.log(error.data); })
            //    .finally(() => {
            //        unblockUI('accordion3');
            //        $timeout(function () {
            //            CreateRecommendationCharts()
            //        });
            //    });
        }

        $scope.removeWidget = function (productIndex, item) {
            $scope.widgets.splice(productIndex, 1);
            $scope.deleteDashboardWidgets(item.WidgetId);
        }

        $scope.portofolios = [];
        $scope.portfolioId = "";
        $scope.getPortofolios = function () {
            blockUI();
            $http({
                method: 'GET',
                url: siteRoot + 'home/GetPortofolios',
                //data: { portfolioId: $scope.portfolioId, langID: 1, type: title }
            })
                .then((res) => {

                    $scope.portofolios = res.data;
                }, (error) => { console.log(error.data); })
                .finally(() => {
                    unblockUI();
                });
        }

        $scope.dashboards = [];
        $scope.dashboardId = "";
        $scope.getDashboards = function () {
            blockUI();
            $scope.dashboardId = "";
            $scope.widgets = [];
            $http({
                method: 'GET',
                url: siteRoot + 'home/GetDashboardByPortofolioId?portofolioId=' + $scope.portfolioId,
                //data: { portofolioId: $scope.portfolioId }
            })
                .then((res) => {

                    $scope.dashboards = res.data;
                }, (error) => { console.log(error.data); })
                .finally(() => {
                    unblockUI();
                });
        }

        $scope.addDashboard = function () {

            var modalInstance = $uibModal.open({
                templateUrl: '/content/theme/ng/partials/addDashboard.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: 'addToWidgetDashboardCtrl',
                scope: $scope,
                windowClass: 'app-modal-window',
                resolve: {
                    'data': { portofolioId: $scope.portfolioId }
                }
            });
            modalInstance.result.then(function (result) {

                if (result == 0) {
                    $scope.getDashboards();
                }
            });
        }

        $scope.widgets = [];
        $scope.widgetId = "";
        $scope.getDashboardWidgets = function () {
            blockUI();
            $http({
                method: 'GET',
                url: siteRoot + 'home/GetDashboardWidgets?portofolioId=' + $scope.portfolioId + '&dashboardId=' + $scope.dashboardId,
                //data: { portofolioId: $scope.portfolioId }
            })
                .then((res) => {

                    $scope.widgets = res.data;
                    angular.forEach($scope.widgets, function (value, key) {
                        $scope.loadWidgetsData(value);
                    });


                }, (error) => { console.log(error.data); })
                .finally(() => {
                    unblockUI();
                });
        }

        $scope.deleteDashboardWidgets = function (id) {
            blockUI();
            $http({
                method: 'GET',
                url: siteRoot + 'home/DeletePortofolioWidgetDashBoard?portofolioId=' + $scope.portfolioId + '&dashboardId=' + $scope.dashboardId + '&widgetId=' + id,
                //data: { portofolioId: $scope.portfolioId }
            })
                .then((res) => {

                    unblockUI();


                }, (error) => { console.log(error.data); })
                .finally(() => {
                    unblockUI();
                });
        }

        $scope.loadWidgetsData = function (value) {
            if (
                value.WidgetKey == 'AssetAllocationByCurrency' || value.WidgetKey == 'AssetAllocationByCash' || value.WidgetKey == 'SectorAllocation' || value.WidgetKey == 'MarketCap' ||
                value.WidgetKey == 'P/BExposure' || value.WidgetKey == 'P/EExposure' || value.WidgetKey == 'PEGExposure' ||
                value.WidgetKey == 'RoAExposure' || value.WidgetKey == 'RoEExposure' || value.WidgetKey == '1-YearPrice' ||
                value.WidgetKey == 'DividendYield' || value.WidgetKey == 'IncomeGrowth' || value.WidgetKey == 'RevenueGrowth' || value.WidgetKey == 'RelativeValuation'
            ) {
                $scope.chartData = [];
                blockUI();
                $http({
                    method: 'POST',
                    url: siteRoot + 'home/GetPortfoioDashBoardData',
                    data: { portfolioId: $scope.portfolioId, langID: 1, type: value.WidgetKey }
                })
                    .then((res) => {
                        $scope.chartData = res.data.ChartData;
                    }, (error) => { console.log(error.data); })
                    .finally(() => {
                        $scope.loadDashboardPieChart(value.WidgetKey);
                        unblockUI();
                    });


            }
            else if (value.WidgetKey == "Fundamentalanalysis" || value.WidgetKey == "StatisticalAnalysis") {
                $scope.chartData = [];
                blockUI();
                $http({
                    method: 'POST',
                    url: siteRoot + 'home/GetPortfoioDashBoardData',
                    data: { portfolioId: $scope.portfolioId, langID: 1, type: value.WidgetKey }
                })
                    .then((res) => {
                        $scope.chartData = res.data.ChartData;
                        $scope.sectors = [];
                        $scope.sectorRatios = [];
                        $scope.tasiWeightings = [];
                        $scope.sumtotalCosts = [];
                        angular.forEach(res.data.ChartData, function (value, key) {
                            $scope.sectors.push(value.name);
                            $scope.sectorRatios.push(value.y);
                            $scope.tasiWeightings.push(value.weighting);
                            $scope.sumtotalCosts.push(value.sumtotalCost);
                        });
                    }, (error) => { console.log(error.data); })
                    .finally(() => {
                        $scope.loadDashboardColumnChart(value.WidgetKey);
                        unblockUI();
                    });
            }
            else if (value.WidgetKey == "XYBubble" || value.WidgetKey == "XYBubbleROA") {
                $scope.chartData = [];
                blockUI();
                $http({
                    method: 'POST',
                    url: siteRoot + 'home/GetPortfoioDashBoardData',
                    data: { portfolioId: $scope.portfolioId, langID: 1, type: value.WidgetKey }
                })
                    .then((res) => {

                        $scope.chartData = res.data.ChartData;
                        $scope.fundPEPBBubbleChartData = [];
                        $scope.fundROAROEBubbleChartData = [];
                        angular.forEach(res.data.ChartData, function (value, key) {
                            $scope.fundPEPBBubbleChartData.push({ x: value.x, y: value.y, z: value.z, name: value.name });
                            $scope.fundROAROEBubbleChartData.push({ x: value.x, y: value.y, z: value.z, name: value.name });
                        });
                    }, (error) => { console.log(error.data); })
                    .finally(() => {
                        $scope.loadDashboardBubbleChart(value.WidgetKey);
                        unblockUI();
                    });
            }
            else if (value.WidgetKey == "MyPortfolio") {
                $scope.transactionsforPortfolio = [];
                blockUI();
                $http({
                    method: 'POST',
                    url: siteRoot + 'home/GetPortfoioDashBoardData',
                    data: { portfolioId: $scope.portfolioId, langID: 1, type: value.WidgetKey }
                })
                    .then((res) => {

                        $scope.transactionsforPortfolio = res.data.ChartData;
                        getTransactionsforPortfolioTotals($scope.transactionsforPortfolio);
                    }, (error) => { console.log(error.data); })
                    .finally(() => {
                        unblockUI();
                    });
            }
            else if (value.WidgetKey == "UnrealizedGain" || value.WidgetKey == "ComparativeAnalysisPrice" ||
                value.WidgetKey == "Comparative(Dividend" || value.WidgetKey == "ComparativeEquity" || value.WidgetKey == "ComparativeAssets" ||
                value.WidgetKey == "ComparativeAnalysisEarning)" || value.WidgetKey == "ComparativeBook") {
                $scope.chartData = [];
                blockUI();
                $http({
                    method: 'POST',
                    url: siteRoot + 'home/GetPortfoioDashBoardData',
                    data: { portfolioId: $scope.portfolioId, langID: 1, type: value.WidgetKey }
                })
                    .then((res) => {
                        $scope.chartData = res.data.ChartData;
                        $scope.companies = [];
                        $scope.barValues = [];
                        angular.forEach(res.data.ChartData, function (value, key) {
                            $scope.companies.push(value.name);
                            $scope.barValues.push(value.y);
                        });
                    }, (error) => { console.log(error.data); })
                    .finally(() => {
                        console.log($scope.barValues);
                        $scope.loadDashboardBarChart(value.WidgetKey);
                        unblockUI();
                    });
            }
            else {
                unblockUI();
            }
        }

        $scope.menus;
        $scope.subMenus;
        $scope.getWidgets = function () {
            blockUI();
            $http({
                method: 'GET',
                url: siteRoot + 'home/GetgbWidget',
                //data: { portofolioId: $scope.portfolioId }
            })
                .then((res) => {
                    $scope.menus = res.data.filter(f => f.ParentId == 0);
                    $scope.subMenus = res.data.filter(f => f.ParentId != 0 && f.ParentId != 1 && f.ParentId != 3);
                    $scope.subMenus1 = res.data.filter(f => f.ParentId == 1);
                    $scope.subMenus3 = res.data.filter(f => f.ParentId == 3);


                }, (error) => { console.log(error.data); })
                .finally(() => {
                    unblockUI();
                });
        }

        $scope.addDashboardWidget = function () {

            var modalInstance = $uibModal.open({
                templateUrl: '/content/theme/ng/partials/addDashboardWidget.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: 'addToPortfolioWidgetDashboardCtrl',
                scope: $scope,
                windowClass: 'app-modal-window',
                resolve: {
                    'data': { portofolioId: $scope.portfolioId, dashboardId: $scope.dashboardId }
                }
            });
            modalInstance.result.then(function (result) {

                if (result == 0) {
                    $scope.getDashboardWidgets();
                }
            });
        }

        $scope.dashboard = {};

        $scope.addWidgetDashboard = function () {
            blockUI();
            $http({
                method: 'POST',
                url: siteRoot + 'home/InsertWidgetDashboard',
                data: { model: $scope.dashboard }
            })
                .then((res) => {

                    $scope.dashboards = res.data;
                }, (error) => { console.log(error.data); })
                .finally(() => {
                    unblockUI();
                });
        }

        loadGlobalIndices();

        $scope.customFilter = function (item) {

            return $scope.subMenus.filter(f => f.ParentId == item);
        };

        $scope.init = function () {
            jQuery.noConflict();
            $scope.getPortofolios();
            $scope.getWidgets();

            

            $("#list1").dragsort({
                dragSelector: "div",
                dragBetween: true,
                dragEnd: saveOrder,
                placeHolderTemplate: "<li class='placeHolder'><div></div></li>",
                cursor: "move"
            });




        }
        $scope.init();

        $scope.chart = undefined;
        let pdata = [],
            vdata = [];
        $scope.marketName = undefined,
            $scope.stockMarketID = undefined,
            $scope.stockMarketURL = undefined;
        $scope.initChart = function () {
            $timeout(() => {
                angular.element($('div.gccstockmarket .market-div').first().find('ul')).trigger('click');
            });
        };

        $scope.mydragg = function () {
            return {
                move: function (divid, xpos, ypos) {
                    divid.style.left = xpos + 'px';
                    divid.style.top = ypos + 'px';
                },
                startMoving: function (divid, container, evt) {
                    evt = evt || window.event;
                    divid = document.getElementById(divid);
                    var posX = evt.clientX,
                        posY = evt.clientY,
                        divTop = divid.style.top,
                        divLeft = divid.style.left,
                        eWi = parseInt(divid.style.width),
                        eHe = parseInt(divid.style.height),
                        cWi = parseInt(document.getElementById(container).style.width),
                        cHe = parseInt(document.getElementById(container).style.height);
                    document.getElementById(container).style.cursor = 'move';
                    divTop = divTop.replace('px', '');
                    divLeft = divLeft.replace('px', '');
                    var diffX = posX - divLeft,
                        diffY = posY - divTop;
                    document.onmousemove = function (evt) {
                        evt = evt || window.event;
                        var posX = evt.clientX,
                            posY = evt.clientY,
                            aX = posX - diffX,
                            aY = posY - diffY;
                        if (aX < 0) aX = 0;
                        if (aY < 0) aY = 0;
                        if (aX + eWi > cWi) aX = cWi - eWi;
                        if (aY + eHe > cHe) aY = cHe - eHe;
                        $scope.mydragg.move(divid, aX, aY);
                    }
                },
                stopMoving: function (container) {
                    var a = document.createElement('script');
                    document.getElementById(container).style.cursor = 'default';
                    document.onmousemove = function () { }
                },
            }
        }();

        $scope.closePopup = function (divid) {

            document.getElementById(divid).style.display = 'none';
        }

        $scope.openPopup = function (divid) {

            document.getElementById(divid).style.display = 'block';
        }

        $scope.stockInfo = function (id) {
            if (id === $scope.stockMarketID) {
                $scope.chartConst.isTrendLine = !$scope.chartConst.isTrendLine;
                return;
            }


            $scope.data = {};
            $scope.stockMarketID = id,
                blockUI('StockMarketData');
            $http({
                method: 'GET',
                url: siteRoot + 'Home/StockMarket/' + id,
            }).then(function (res) {
                $scope.data = res.data;

                self.stockMarket = res.data.ListCompanyStock;
                createChart();
            }, (error) => { unblockUI('StockMarketData'); console.log(error.data); })
                .then(function () {
                    unblockUI('StockMarketData');
                });
        }

        $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
                    });
                }
            }

        });

        function maxValue(data) {
            return Math.max.apply(Math, data.map(function (val) { return Math.abs(val.ChangePer); }));
        }
        function createChart() {
            pdata = [];
            vdata = [];

            self.stockMarket.map(function (elem) {
                let IndexDate = parseInt(elem.IndexDate.slice(6, -2));
                pdata.push([IndexDate, parseFloat(elem.Closing)]);
                vdata.push([IndexDate, parseInt(elem.Volume)]);
            });
            let
                min = Number($scope.data.MinDate.slice(6, -2)),
                max = Number($scope.data.MaxDate.slice(6, -2)),
                linXData = [], linYData = [];

            pdata.map(function (elem, i) {
                let date = parseInt(elem[0]);
                if (date >= min && date <= max) {
                    linXData.push([elem[0], elem[1]]);
                    //linYData.push(elem[1]);
                }
            });
            // Create the chart
            new Highcharts.stockChart('StockMarketChart', {
                chart: {
                    borderColor: '#3a3a3a',
                    borderWidth: 0,
                    plotBackgroundColor: '',
                    backgroundColor: '#000',
                    padding: 5,
                    panning: false
                },
                watermark: {
                    yAxis: 120
                },
                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: 120,
                    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: $scope.data.Average,
                        label: {
                            text: '',
                            x: -10
                        },
                        zIndex: 3
                    }]
                },
                {
                    gridLineColor: '#3a3a3a',
                    alternateGridColor: '#',
                    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: 135,
                    height: 60,
                    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',
                    range: 12 * 30 * 24 * 3600 * 1000,
                    labels: {
                        formatter: function () {
                            return Highcharts.dateFormat('%d/%m  ', this.value);
                        },
                        style: {
                            color: '#ADADAD'
                        }
                    }
                },
                title: {
                    text: ''
                },
                scrollbar: {
                    enabled: false
                },
                rangeSelector: {
                    enabled: false
                },
                navigator: {
                    enabled: false
                },
                exporting: {
                    enabled: false
                },
                tooltip: {
                    style: {
                        opacity: '1.0'
                    },
                    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 += '<p style="color:' + primary.series.color + '"><b>' + $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 += '<p style="color:' + sm.series.color + '"><b>' + 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 += '<p style="color:' + vol.series.color + '"><b>' + $filter('getLabel')('lblVolume') + ': </b> ' + $filter('AbbrOrWNOrDec')(vol.y, 2) + '</p>' + "</div>";

                        } catch (e) { }
                        return tooltipHtml;
                    }
                },
                series: [{
                    name: 'primary',
                    id: 'primary',
                    data: pdata,
                    dname: $scope.MarketName,
                    color: '#18A97E',
                    type: 'line',
                    lineWidth: 1,
                    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: 1,
                    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: 1,
                    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: '#18A97E',
                    defaultSeriesType: 'spline',
                    lineWidth: 1,
                    threshold: null,
                    visible: $scope.chartConst.isTrendLine,
                    enableMouseTracking: false,
                    data: (function () {
                        return fitData(linXData).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: '#18A97E',
                    borderColor: '#3a3a3a',
                    data: vdata,
                    yAxis: 1,
                    dataGrouping: {
                        forced: true,
                        units: [['day', [1]]]
                    }
                }]
            }, function (chart) {
                $scope.chart = chart;
            });
        }

        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',
                        plotBackgroundColor: '',
                        margin: margin,
                        width: 350
                    },
                    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,
                        }]
                    }],
                });

            });
        }

        $scope.loadRecomendations = function ($inview) {
            $http({
                method: 'POST',
                url: siteRoot + 'home/index',
                data: { type: 'recommendations' }
            })
                .then((res) => {
                    $scope.recommendations = res.data.recommendations;
                }, (error) => { console.log(error.data); })
                .finally(() => {
                    $timeout(function () {
                        CreateRecommendationCharts()
                    });
                });

            //if (!$inview || !$filter('empty')($scope.recommendations)) return;
            //blockUI('accordion3');
            //$http({
            //    method: 'POST',
            //    url: siteRoot + 'home/index',
            //    data: { type: 'recommendations' }
            //})
            //    .then((res) => {
            //        $scope.recommendations = res.data.recommendations;
            //    }, (error) => { unblockUI('accordion3'); console.log(error.data); })
            //    .finally(() => {
            //        unblockUI('accordion3');
            //        $timeout(function () {
            //            CreateRecommendationCharts()
            //        });
            //    });
        }
        /*global indices*/
        function loadGlobalIndices() {

            $http({
                url: siteRoot + 'home/index',
                data: { type: 'globalindices' },
                method: 'POST'
            }).then((res) => {

                $scope.globalIndicesData = res.data.globalIndices;
                $scope.gblAsia = $filter('filter')($scope.globalIndicesData, { CountryGroupID: 46 });
                $scope.gblEurope = $filter('filter')($scope.globalIndicesData, { CountryGroupID: 45 });
                $scope.gblAmerica = $filter('filter')($scope.globalIndicesData, { CountryGroupID: 47 });

                $scope.gblAsiaMax = maxValue($scope.gblAsia);
                $scope.gblEuropeMax = maxValue($scope.gblEurope);
                $scope.gblAmericaMax = maxValue($scope.gblAmerica);
            }, (error) => { unblockUI('accordion4'); console.log(error.data); }).finally(() => {
                unblockUI('accordion4');
                globalIndicesLoaded = true;
            });
        }

        function saveOrder() {
            var data = $("#list1 li").map(function () {
                return $(this).children().html();
            }).get();
            $("input[name=list1SortOrder]").val(data.join("|"));
        }


    }])
    .controller('homeIndicatorsCtrl', ['$timeout', '$filter', '$scope', '$http', '$q',
        function ($timeout, $filter, $scope, $http, $q) {
            var self = this,
                loaded = false;

            $scope.loadIndicators = function ($inview) {
                if (!$inview || loaded) return;
                blockUI('accordion5');
                $http({
                    url: siteRoot + 'home/index',
                    method: 'POST',
                    data: { type: 'indicators' }
                }).then((res) => {
                    $scope.indicators = res.data.indicators;
                    $scope.indicatorsData = res.data.indicatorsData;
                }, (error) => { unblockUI('accordion5'); console.log(error.data); }).finally(() => {
                    unblockUI('accordion5');

                    $scope.abbrs = $filter('unique')($scope.indicators.map(function (elem) { return $filter('trim')(elem.Abbr); }));
                    $timeout(function () {
                        new createIndicatorCharts().init();
                        $('.economy_indicators').popover({
                            'trigger': 'focus hover click',
                            'content': function () {
                                return $('<div/>').attr({ 'class': 'percentile-tooltip display-inline' }).append($(this).find('.indicator-chart').html());
                            },
                            'title': function () {
                                return '';
                            },
                            'html': true,
                            'placement': 'auto'
                        });
                    });
                });
                loaded = true;
            }
            function createIndicatorCharts() {
                var funcSelf = this;
                this.init = function () {
                    $('div.ind-chart-div').each(function () {
                        var chartType = 'column';
                        var obj = $(this);
                        var unit = obj.data('unit');
                        var factId = parseInt(obj.data('esdfactid'));
                        var seriesName = obj.data('fact');
                        var chartData = [];
                        $scope.indicatorsData.map(function (elem) {
                            if (elem.ESDFactID === factId) {
                                chartData.push({
                                    x: parseInt(elem.AsofDate.slice(6, -2)),
                                    y: parseFloat(elem.Value)
                                })
                            }

                        });
                        funcSelf.createIndicatorCharts(obj.attr('id'), chartType, seriesName, chartData, unit);
                    });
                },

                    this.createIndicatorCharts = function (obj, chartType, seriesName, chartData, unit) {
                        new Highcharts.Chart({
                            chart: {
                                renderTo: obj,
                                type: chartType,
                                margin: [0, 0, 20, 5],
                                padding: [0, 0, 0, 0],
                                backgroundColor: null,
                            },
                            watermark: {
                                text: ''
                            },
                            title: {
                                text: '',
                                x: -20,
                                style: {
                                    "color": "#333333",
                                    "fontSize": "12px"
                                }
                            },
                            subtitle: {
                                text: '',
                                x: -20
                            },
                            xAxis: {
                                type: 'datetime',
                                labels: {
                                    formatter: function () {
                                        return Highcharts.dateFormat('%d/%m/%y ', this.value);
                                    },
                                    style: {
                                        color: '#ADADAD'
                                    }
                                }

                            },
                            yAxis: {
                                title: {
                                    text: ''
                                },
                                labels: {
                                    formatter: function () {
                                        return $filter('WNOrDec')(this.value, 2) + '' + unit;
                                    },
                                    x: -5,
                                    y: -2,
                                    style: {
                                        color: '#ADADAD'
                                    }
                                },
                                plotLines: [{
                                    value: 0,
                                    width: 1,
                                    color: '#ccc'
                                }],
                                gridLineColor: "#ccc",
                                gridLineDashStyle: "Solid",
                                gridLineInterpolation: 2,
                                gridLineWidth: 1,
                                gridZIndex: 1,
                                lineColor: "#ccc",
                                lineWidth: 1,
                                opposite: !1,
                            },
                            tooltip: {
                                formatter: function () {
                                    return '' + this.series.name + ':<br/>'
                                        + Highcharts.dateFormat('%d/%m/%Y', this.x) + '<br/>'
                                        + WNOrDecimal(this.y);
                                },
                                style: {
                                    color: '#ADADAD'
                                }
                            },
                            plotOptions: {
                                series: {
                                    cursor: 'pointer',
                                    marker: {
                                        enabled: false
                                    },

                                }
                            },
                            legend: {
                                layout: 'vertical',
                                align: 'right',
                                verticalAlign: 'middle',
                                borderWidth: 0,
                                enabled: !1
                            },
                            series: [{
                                type: chartType,
                                name: seriesName,
                                data: chartData
                            }]
                        });
                    }
            }


        }])

    .controller('homeRightPanel', ['$global', '$scope', '$http', '$q', '$timeout', '$filter', function ($global, $scope, $http, $q, $timeout, $filter) {
        let gccLoaded = false, eventsLoaded = false, preciousMetalsLoaded = false, crudeOilsLoaded = false;

        $scope.marketId = 0;
        $scope.activePTab = 0;
        $scope.last = 0;
        var triggered = false;
        $scope.init = function (data) {
            $scope.marketId = parseInt(data.stockMarket);
            $scope.PortfolioList = data.portfolioList.portfolioList;
            $scope.PortfolioData = data.portfolioList.portfolioData;
            $scope.last = data.portfolioList.portfolioList.length - 1;

            /*investing ideas*/
            $scope.ideasData = data.investingIdeas;

            console.log(data.investingIdeas);
            $scope.popularSearch = data.popularSearch;

            $timeout(function () {
                CreateInvestingIdeasCharts();
                CreatePortfolioCharts();
            });

        }
        function maxValue(data) {
            return Math.max.apply(Math, data.map(function (val) { return Math.abs(val.Change); }));
        }
        $scope.loadGCCIndices = (($inview) => {
            if (!$inview || gccLoaded) return;
            blockUI('accordionRight3');
            $http({
                url: siteRoot + 'home/HomeRightPanel',
                data: { type: 'gccIndices' },
                method: 'POST'
            }).then((res) => {
                $scope.gccData = res.data.gccIndices;
                $scope.gblgccMax = maxValue($scope.gccData);
            }, (error) => { unblockUI('accordionRight3'); console.log(error.data); }).finally(() => {
                unblockUI('accordionRight3');
                $scope.sortType = 'Change';
                $scope.sortReverse = true;
                $scope.sortMetal = true;
                $scope.sortOil = true;

                $scope.changeOrder = function (type) {
                    $scope.sortType = type;
                    $scope.sortReverse = ($scope.sortReverse) ? false : true;
                    $scope.sortMetal = ($scope.sortMetal) ? false : true;
                    $scope.sortOil = ($scope.sortOil) ? false : true;
                }
                $scope.changeMetalOrder = function (type) {
                    $scope.sortType = type;
                    $scope.sortMetal = ($scope.sortMetal) ? false : true;
                }
                $scope.changeOilOrder = function (type) {
                    $scope.sortType = type;
                    $scope.sortOil = ($scope.sortOil) ? false : true;
                }

                gccLoaded = true;
            });
        });

        $scope.loadPreciousMetals = (() => {
            if (preciousMetalsLoaded) return;
            blockUI('accordionRight5');
            $http({
                method: 'POST',
                url: siteRoot + 'Home/HomeRightPanel',
                data: { type: 'preciousMetals' }
            }).then(function (res) {
                $scope.preciousMetals = res.data.preciousMetals;
            }, (error) => { unblockUI('accordionRight5'); console.log(error.data); }).finally(function () {
                unblockUI('accordionRight5');
                preciousMetalsLoaded = true;
            });

        });
        $scope.loadCrudeOils = (() => {
            if (crudeOilsLoaded) return;
            blockUI('accordionRight5');
            $http({
                method: 'POST',
                url: siteRoot + 'Home/HomeRightPanel',
                data: { type: 'crudeOils' }
            }).then(function (res) {
                $scope.crudeOils = res.data.crudeOils;
            }, (error) => { unblockUI('accordionRight5'); console.log(error.data); }).finally(function () {
                unblockUI('accordionRight5');
                crudeOilsLoaded = true;
            });

        });
        $scope.switchPortfolioTab = function ($event, type) {
            $event.preventDefault();

            if ($event.currentTarget.attributes['disabled'] !== undefined) return;
            var elem;
            switch (type) {
                case 'first': {
                    $scope.activePTab = 0;
                    elem = $('.portfolioList').find("[data-index='" + $scope.activePTab + "']");
                    $timeout(function () {
                        triggered = true;
                        angular.element(elem).trigger('click');
                    });
                    break;
                }
                case 'prev': {
                    $scope.activePTab = $scope.activePTab > 0 ? $scope.activePTab - 1 : $scope.activePTab;
                    elem = $('.portfolioList').find("[data-index='" + $scope.activePTab + "']");
                    $timeout(function () {
                        triggered = true;
                        angular.element(elem).trigger('click');
                    });
                    break;
                }
                case 'next': {
                    $scope.activePTab = $scope.activePTab !== $scope.last ? $scope.activePTab + 1 : $scope.activePTab;
                    elem = $('.portfolioList').find("[data-index='" + $scope.activePTab + "']");
                    $timeout(function () {
                        triggered = true;
                        angular.element(elem).trigger('click');
                    });
                    break;
                }
                case 'last': {
                    $scope.activePTab = $scope.activePTab !== $scope.last ? $scope.last : $scope.activePTab;
                    elem = $('.portfolioList').find("[data-index='" + $scope.activePTab + "']");
                    $timeout(function () {
                        triggered = true;
                        angular.element(elem).trigger('click');
                    });
                    break;
                }
                default: {
                    break;
                }

            }
        }

        $scope.PortfolioDetail = function ($event, $index, id) {
            if (!triggered) return;
            $scope.activePTab = $index;
            blockUI('UserPortfolio');
            $http({
                method: 'GET',
                url: siteRoot + 'Home/UserPortfolio/' + id,
            }).then(function (res) {
                $scope.PortfolioData = res.data;
                $timeout(function () {
                    CreatePortfolioCharts()
                });
            }, (error) => { unblockUI('UserPortfolio'); console.log(error.data); }).then(function () {
                unblockUI('UserPortfolio');
                triggered = false;
            });
        }

        function CreatePortfolioCharts() {
            $(function () {
                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, 0, 2, 0],
                                //width: 70,
                                //height: 20,
                                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 defualt-color"><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);
                };

                var start = +new Date(),
                    $tds = $('.SparklineChartUserPortfolio'),
                    fullLen = $tds.length,
                    n = 0;

                function doChunk() {
                    var time = +new Date(),
                        i,
                        len = $tds.length,
                        $td,
                        stringdata,
                        arr,
                        data,
                        chart;

                    for (i = 0; i < len; i += 1) {
                        $td = $($tds[i]);
                        stringdata = $td.data('chart');
                        chart = {};

                        var chartData = [];
                        angular.forEach(stringdata, function (v) {
                            chartData.push([parseInt(v.Date.slice(6, -2)), v.Price]);
                        });
                        var 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,
                            },
                            exporting: {
                                enabled: false
                            },
                            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();
            });
        }
        function CreateInvestingIdeasCharts() {
            $(function () {
                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, 0, 2, 0],
                                width: 70,
                                height: 20,
                                style: {
                                    overflow: 'visible'
                                },

                                skipClone: true
                            },
                            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: {
                                enabled: !0,
                                backgroundColor: null,
                                borderWidth: 0,
                                shadow: false,
                                useHTML: true,
                                hideDelay: 0,
                                shared: true,
                                padding: 0,
                                positioner: function (w, h, point) {
                                    if (point.plotY < 40) {
                                        return { x: (point.plotX - w) / 1.3, y: (point.plotY - h) + 40 };
                                    } else
                                        return { x: (point.plotX - w) / 1.3, 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);
                };

                var start = +new Date(),
                    $tds = $('.SparklineChart'),
                    fullLen = $tds.length,
                    n = 0;

                function doChunk() {
                    var time = +new Date(),
                        i,
                        len = $tds.length,
                        $td,
                        stringdata,
                        arr,
                        data,
                        chart;

                    for (i = 0; i < len; i += 1) {
                        $td = $($tds[i]);
                        stringdata = $td.data('chart');
                        chart = {};

                        var chartData = [];
                        angular.forEach(stringdata, function (v) {
                            chartData.push([parseInt(v.Date.slice(6, -2)), v.Price]);
                        });
                        var minVal = Math.min.apply(null, stringdata.map(i => i.Price)),
                            maxVal = Math.max.apply(null, stringdata.map(i => i.Price));

                        $td.highcharts('SparkLine', {
                            watermark: {
                                text: ''
                            },
                            exporting: {
                                enabled: false
                            },
                            yAxis: {
                                min: minVal,
                                max: maxVal,
                            },
                            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();
            });
        }


        function loadCalendarEvents() {

            blockUI('accordionRight4');
            $http({
                method: 'POST',
                url: siteRoot + 'Home/HomeRightPanel2',
                data: { marketId: $scope.marketId, type: 'events' }
            }).then(function (res) {
                $scope.homeCalendarPageEvents = res.data.homeCalendarPageEvents;
                var events = [];
                $scope.homeCalendarPageEvents = res.data.homeCalendarPageEvents;
                $scope.homeCalendarPageEvents !== undefined && $scope.homeCalendarPageEvents.map(function (e) {
                    events.push({ title: e.EventCount, start: $filter('date')(e.EventDate.slice(6, -2), 'yyyy-MM-dd'), rendering: 'background' });
                });

                EventsCalendar(events);

            }, (error) => { unblockUI('accordionRight4'); console.log(error.data); }).finally(function () {
                unblockUI('accordionRight4');
                eventsLoaded = true;
            });
        }
        function EventsCalendar(events) {
            $('#homeEventcalendar').fullCalendar({
                header: {
                    left: 'prev',
                    center: 'title',
                    right: 'next'
                },
                titleFormat: 'MMM YYYY',
                defaultDate: moment(),
                contentHeight: 300,
                eventLimit: 1,
                eventLimitText: "",
                events: events,
                weekMode: 'liquid',
                editable: true,
                eventRender: function (event, element, view) {
                    var currentMon = new Date(event.start);
                    var currentMonth = currentMon.getMonth();

                    var currentMonViewStart = new Date(view.start);
                    var currentMonthViewStart = currentMon.getMonth();

                    var currentMonViewEnd = new Date(view.end);
                    var currentMonthViewEnd = currentMonViewEnd.getMonth();

                    if ((currentMonth === currentMonthViewStart) && (currentMonth === currentMonthViewEnd)) {
                        return false;
                    }
                    var dateString = moment(event.start).format('YYYY-MM-DD');

                    $('#homeEventcalendar').find('.fc-day-top[data-date="' + dateString + '"]').each(function (elem) {

                        if ($(this).hasClass('fc-other-month')) { return; }
                        else {
                            $(this).addClass('haveEvent').attr('style', 'cursor:pointer !important;');
                        }
                    });
                },
                dayClick: function (date, jsEvent, view) {
                    var EventDate = date.format().replace(/\-/g, '');
                    var dateString = moment(date._d).format('YYYY-MM-DD');
                    if ($('#homeEventcalendar').find('.haveEvent[data-date="' + dateString + '"]').length) {
                        $('#homeEventcalendar').find('.haveEvent').each(function () { if ($(this).hasClass('current')) $(this).removeClass('current'); })
                        $('#homeEventcalendar').find('.fc-day-top[data-date="' + dateString + '"]').each(function (elem) {
                            if ($(this).hasClass('fc-other-month')) { return; }
                            else {
                                $(this).addClass('current');
                            }
                        });
                        blockUI('accordionRight4');
                        $http({
                            method: 'POST',
                            url: siteRoot + 'home/homerightpanel',
                            data: { date: EventDate, marketId: $scope.marketId },
                        }).then(function (res) {
                            $scope.EventDetail = res.data;
                        }, (error) => { unblockUI('accordionRight4'); console.log(error.data); }).then(function () {
                            unblockUI('accordionRight4');
                        });
                    }
                }
            });
        }

    }])

    .controller('homeRightPanel2', ['$global', '$scope', '$http', '$q', '$timeout', '$filter', function ($global, $scope, $http, $q, $timeout, $filter) {
        let gccLoaded = false, eventsLoaded = false, preciousMetalsLoaded = false, crudeOilsLoaded = false;

        $scope.marketId = 0;
        $scope.activePTab = 0;
        $scope.last = 0;
        var triggered = false;
        $scope.init = function (data) {
            $scope.marketId = parseInt(data.stockMarket);
            loadCalendarEvents();
        }
        function maxValue(data) {
            return Math.max.apply(Math, data.map(function (val) { return Math.abs(val.Change); }));
        }


        $scope.loadPreciousMetals = (() => {
            if (preciousMetalsLoaded) return;
            blockUI('accordionRight5');
            $http({
                method: 'POST',
                url: siteRoot + 'Home/HomeRightPanel2',
                data: { type: 'preciousMetals' }
            }).then(function (res) {
                $scope.preciousMetals = res.data.preciousMetals;
            }, (error) => { unblockUI('accordionRight5'); console.log(error.data); }).finally(function () {
                unblockUI('accordionRight5');
                preciousMetalsLoaded = true;
            });

        });
        $scope.loadCrudeOils = (() => {
            if (crudeOilsLoaded) return;
            blockUI('accordionRight5');
            $http({
                method: 'POST',
                url: siteRoot + 'Home/HomeRightPanel2',
                data: { type: 'crudeOils' }
            }).then(function (res) {
                $scope.crudeOils = res.data.crudeOils;
            }, (error) => { unblockUI('accordionRight5'); console.log(error.data); }).finally(function () {
                unblockUI('accordionRight5');
                crudeOilsLoaded = true;
            });

        });

        function loadCalendarEvents() {

            blockUI('accordionRight4');
            $http({
                method: 'POST',
                url: siteRoot + 'Home/HomeRightPanel2',
                data: { marketId: $scope.marketId, type: 'events' }
            }).then(function (res) {
                $scope.homeCalendarPageEvents = res.data.homeCalendarPageEvents;
                var events = [];
                $scope.homeCalendarPageEvents = res.data.homeCalendarPageEvents;
                $scope.homeCalendarPageEvents !== undefined && $scope.homeCalendarPageEvents.map(function (e) {
                    events.push({ title: e.EventCount, start: $filter('date')(e.EventDate.slice(6, -2), 'yyyy-MM-dd'), rendering: 'background' });
                });

                EventsCalendar(events);

            }, (error) => { unblockUI('accordionRight4'); console.log(error.data); }).finally(function () {
                unblockUI('accordionRight4');
                eventsLoaded = true;
            });
        }
        function EventsCalendar(events) {
            $('#homeEventcalendar').fullCalendar({
                header: {
                    left: 'prev',
                    center: 'title',
                    right: 'next'
                },
                titleFormat: 'MMM YYYY',
                defaultDate: moment(),
                contentHeight: 300,
                eventLimit: 1,
                eventLimitText: "",
                events: events,
                weekMode: 'liquid',
                editable: true,
                eventRender: function (event, element, view) {
                    var currentMon = new Date(event.start);
                    var currentMonth = currentMon.getMonth();

                    var currentMonViewStart = new Date(view.start);
                    var currentMonthViewStart = currentMon.getMonth();

                    var currentMonViewEnd = new Date(view.end);
                    var currentMonthViewEnd = currentMonViewEnd.getMonth();

                    if ((currentMonth === currentMonthViewStart) && (currentMonth === currentMonthViewEnd)) {
                        return false;
                    }
                    var dateString = moment(event.start).format('YYYY-MM-DD');

                    $('#homeEventcalendar').find('.fc-day-top[data-date="' + dateString + '"]').each(function (elem) {

                        if ($(this).hasClass('fc-other-month')) { return; }
                        else {
                            $(this).addClass('haveEvent').attr('style', 'cursor:pointer !important;');
                        }
                    });
                },
                dayClick: function (date, jsEvent, view) {
                    var EventDate = date.format().replace(/\-/g, '');
                    var dateString = moment(date._d).format('YYYY-MM-DD');
                    if ($('#homeEventcalendar').find('.haveEvent[data-date="' + dateString + '"]').length) {
                        $('#homeEventcalendar').find('.haveEvent').each(function () { if ($(this).hasClass('current')) $(this).removeClass('current'); })
                        $('#homeEventcalendar').find('.fc-day-top[data-date="' + dateString + '"]').each(function (elem) {
                            if ($(this).hasClass('fc-other-month')) { return; }
                            else {
                                $(this).addClass('current');
                            }
                        });
                        blockUI('accordionRight4');
                        $http({
                            method: 'POST',
                            url: siteRoot + 'home/homerightpanel',
                            data: { date: EventDate, marketId: $scope.marketId },
                        }).then(function (res) {
                            $scope.EventDetail = res.data;
                        }, (error) => { unblockUI('accordionRight4'); console.log(error.data); }).then(function () {
                            unblockUI('accordionRight4');
                        });
                    }
                }
            });
        }

    }])

    .controller('HomeNewsPartialCtrl', ['$scope', '$http', '$q', '$timeout', '$filter', function ($scope, $http, $q, $timeout, $filter) {
        $scope.newsData = [];
        $scope.NewsCorporate = [];
        $scope.init = (smid) => {
            $scope.stockMarketID = parseInt(smid);
        }
        $scope.LoadNews = function (obj, type, category) {
            $scope.NewsDetail = [];
            blockUI('newPartialAccorion');
            $http({
                method: 'POST',
                url: siteRoot + 'home/newspartial',
                data: { type: type, category: category, marketId: $scope.stockMarketID }
            }).then(function (res) {
                if (parseInt(type) === 3) {
                    $scope.NewsCorporate = res.data.announcements;
                } else {
                    $scope.NewsDetail = res.data.newsModel;
                }

                if (type === 3 || category === 3) {
                    $scope.priceModel = res.data.priceModel;

                    $timeout(() => {
                        CreateNewsCharts();
                    });
                }
            }, (error) => { unblockUI('newPartialAccorion'); console.log(error.data); }).finally(() => {
                unblockUI('newPartialAccorion');
            });
        }
        function CreateNewsCharts() {
            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, 0, 2, 0],
                            //width: 70,
                            //height: 20,
                            style: {
                                overflow: 'visible'
                            },

                            skipClone: true
                        },
                        title: {
                            text: ''
                        },
                        credits: {
                            enabled: false
                        },
                        watermark: {
                            text: ''
                        },
                        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 defualt-color"><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);
            };

            var start = +new Date(),
                $tds = $('.newsChart'),
                fullLen = $tds.length,
                n = 0;

            function doChunk() {
                var time = +new Date(),
                    i,
                    len = $tds.length,
                    $td,
                    stringdata,
                    arr,
                    data,
                    chart;

                for (i = 0; i < len; i += 1) {
                    $td = $($tds[i]);
                    // stringdata = $td.data('chart');
                    var cid = parseInt($td.data('cid'));

                    stringdata = $.grep($scope.priceModel, (elem) => { return elem.CompanyID === cid; });


                    chart = {};
                    var chartData = [];
                    stringdata.length > 0 && angular.forEach(stringdata, function (v) {
                        chartData.push([parseInt(v.PriceDate.slice(6, -2)), v.ClosingPrice]);
                    });
                    var minVal = Math.min.apply(null, stringdata.map(i => i.ClosingPrice)),
                        maxVal = Math.max.apply(null, stringdata.map(i => i.ClosingPrice));

                    $td.highcharts('SparkLine', {
                        yAxis: {
                            min: minVal,
                            max: maxVal,
                        },
                        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();
        }

    }])
    ;