﻿angular.module('searchApp', ['rzModule', 'ngSanitize'])
	.controller('generalSearchCtrl', ['$scope', '$http', '$document', '$filter', '$uibModal', '$timeout', '$q', '$window','$global',
		function ($scope, $http, $document, $filter, $uibModal, $timeout, $q, $window,$global) {
			var self = this;
			$scope.focus = 0;
			$scope.search_text = '';
			$scope.currentTab = 'equities';
			$scope.defaultTab = 'recent';
			$scope.psResults = [];
			$scope.searchResults = [];
			$scope.loading = false;

			$scope.total = null;
			$scope.pageSize = 10;
			$scope.isMore = false;
			$scope.pageNum = 1;
			$scope.loadMoreSearchData = function () {
				if ($scope.loading) return;
				if ($scope.search_text.length > 0)
					$scope.loadData();
			};
			$scope.resetPage = function () {
				$scope.total = null;
				$scope.pageSize = 10;
				$scope.isMore = false;
				$scope.pageNum = 1;
				$scope.hasMore = true;
				$scope.searchResults = [];
			}
			$timeout(function () {
				$document.trigger('click');
				$document.find('.searchresults').removeAttr('style');
				$scope.currentTab = 'equities';
			});
			$scope.$watch('search_text', function (o, n) {
				if ($scope.search_text.length > 0)
					$scope.focus = 2;
				else
					$scope.focus = 1;
			});
			$scope.gsTabChange = function (ctab) {
				$scope.currentTab = ctab;
				$scope.resetPage();
				$scope.loadData();
			}
			$scope.processSearch = function ($event) {
				if ($scope.search_text.length > 0) {
					$scope.focus = 0;
				} else {
					$scope.focus = 1;
				}

			}
			$document.on('click', function (e) {
				$scope.focus = $(e.target).closest('div.topbar').length > 0 ? $scope.search_text.length > 0 ? 2 : 1 : 0;
				$scope.$digest();
			});
			$scope.resetAndloadData = function ($event) {
				
				var keyCode = $event.which || $event.keyCode;
				if (keyCode == 13) {
					window.location.href = "/Home/GenAI?q=" + $scope.search_text;
					//alert(objId);
					//$("#rcdqty-" + objId).focus();
				}

				$timeout(function () {
					$scope.resetPage();
					$scope.loadData();
				}, 300);
			}
			$scope.loadData = function () {
				if ($scope.search_text.length > 0) {
					self.loadSearch_Text();

				} else {
					self.loadPS();
				}

			}
			//popular searches load
			this.loadPS = function () {        
				$http({
					url:siteRoot+ 'home/gsearchdetail',
					method: 'POST',
					type: 'json',
					data: { psearches: $scope.defaultTab==='recent'?1:2 },
					beforeSend: function () {
						$scope.loading = true;
					},
					complete: function () {
						$scope.loading = false;
					}
				}).then(function (res) {
					$scope.psResults = res.data;
					}, (error) => { console.log(error.data); });
			}
			//general search by search text

			var canceler = $q.defer();
			var resolved = false;

			var cancel = function () {
				canceler.resolve("http call aborted");
			};

			this.loadSearch_Text = function () {
				if (resolved) {
					cancel();
				}

				canceler = $q.defer();
				resolved = true;
				if ($scope.pageNum > 1 && !$scope.hasMore)
					return;
				self.request = $http({
					url: siteRoot + 'home/gsearchdetail',
					method: 'post',
					headers: { "X-HTTP-Method-Override": "POST" },
					beforeSend: function () {
						$scope.loading = true;
					},
					complete: function () {
						$scope.loading = false;
					},
					data: { search_text: $.trim($scope.search_text), category: $scope.currentTab, langID: 1, gsearch: true, pageNum: $scope.pageNum, pageSize: $scope.pageSize },
					timeout: canceler.promise
				}).success(function (res) {

					if ($scope.pageNum == 1)
						$scope.searchResults = res;
					else {
						res.length > 0 && $.map(res, function (elem) { $scope.searchResults.push(elem); });
					}
					resolved = false;
					$scope.total = res.firstOrDefault().total;
					$scope.pageNum = Math.ceil($scope.total / $scope.pageSize) > $scope.pageNum ? $scope.pageNum + 1 : $scope.pageNum;
					$scope.hasMore = Math.ceil($scope.total / $scope.pageSize) > $scope.pageNum ? true : false;
					})
					.error((err) => { console.log(err); });

			}
			$scope.gsearch_sr_click = function (robj) {

				//var template = '';
				//var controller = '';
				//var stamp = robj.Stamp;
				//var data = [];
				//switch (stamp) {
				//	case "equities":
				//		template = '/content/theme/ng/partials/equities.html',
				//		controller = 'equitiesCtrl'
				//		break;

				//	case "official indices":
				//	case "official indices sectors":
				//	case "gcc indices":
				//	case "gcc indices sectors":
				//	case "gcc indices caps":
				//	case "official indices caps":
				//		template = '/content/theme/ng/partials/officialindices.html',
				//		controller = 'indicesCtrl';
				//		break;
				//	case "global indices":
				//	case "commodities":
				//		template = '/content/theme/ng/partials/globalindices.html',
				//		controller = 'globalIndicesCtrl';
				//		break;
				//	case "funds":
				//		template = "/Content/Theme/ng/partials/funds.html",
				//		controller = 'fundsCtrl';
				//		break;
				//	case "indicators":
				//		template = "/Content/Theme/ng/partials/indicators.html",
				//		controller = 'indicatorsCtrl';
				//		break;
				//}

				$window.location.href = robj.URL;
				unblockUI();

				//$http({
				//	url: siteRoot + 'home/gsearchdetail',
				//	method: 'post',
				//	headers: { "X-HTTP-Method-Override": "POST" },
				//	data: { model: robj, ajax: true },
				//	beforeSend: function () {
				//		blockUI();
				//	},
				//	complete: function () {
				//		unblockUI();
				//	}
				//	})
				//	.success(function (res) {
				//	data = res;
				//	})
				//	.error((err) => { console.log(err.data); })
				//	.then(function () {

				//		var modalInstance = $uibModal.open({
				//		templateUrl: template,
				//		//templateUrl:'/content/theme/ng/partials/test.html',
				//		controller: controller,
				//		scope: $scope,
				//		windowClass: 'app-modal-window',
				//		resolve: {
				//			'data': { s: robj, data: data }
				//		}
				//	});
				//}).catch(function (e) {
				//	unblockUI();
				//});				
			};

			$scope.AddToPortfolioSearchClick = function (data) {
						var modalInstance = $uibModal.open({
							//templateUrl: '/content/theme/ng/partials/addportfoliopopup.html',
              template: `<div class="width-300" data-company="{{companyData|json}}"><div class="popup-header"><a title="Close" class="popup-close" href="javascript:" ng-click="Close();"><i class="fa fa-times"></i></a><div class="popup-header-content"><h5 class="search-h5 color-white" style="padding:5px">{{'lblAdd'|getLabel}} ({{companyData.CompanyName}})</h5></div></div><div class="clearfix"></div><div id="portfolioBody" class="modal-body" style="min-height:200px;padding-top:0"><div class="col-lg-12 col-md-12 col-sm-12 col-xs-12"><div class="row"><div class="sccol"><div class="edit_port"><div class="container-fluid"><form method="POST" name="companyForm" ng-submit="companyForm.$valid && addSearchCompanyToPortfolio(company)" novalidate><p><uib-progressbar ng-show="working" class="progress-striped active" value="dynamic" type="success"><i class="fa fa-spinner fa-spin"></i> {{'lblProcessing'|getLabel}}</uib-progressbar></p><div ng-show="success" class="alert alert-success padding-10 no-margin" role="alert"><strong ng-bind="'lblSuccess'|getLabel"></strong> {{'lblPortfolioSaveSuccessfull'|getLabel}}</div><div ng-show="info" class="alert alert-warning padding-10 no-margin" role="alert"><strong ng-bind="'lblInfo'|getLabel"></strong> <i class="fa fa-info"></i> {{infoMessage}}</div><div ng-show="error" class="alert alert-danger padding-10 no-margin" role="alert"><strong ng-bind="'lblError'|getLabel"></strong> {{'lblErrorMessage'|getLabel}}</div><input type="hidden" name="companyId" ng-model="company.companyId" ng-value="{{companyId}}" ng-required="companyId===0?true:false" ng-pattern="/^[0-9]+\.?[0-9]*$/" /><div ng-show="companyForm.$submitted || companyForm.companyId.$touched" class="validation-div"><span ng-show="companyForm.companyId.$error.required" class="padding-5 alert alert-danger">{{'lblRequired'|getLabel}}</span><span ng-show="companyForm.companyId.$error.pattern" class="padding-5 alert alert-danger">{{'lblInvalidName'|getLabel}}</span></div><div class="form-group"><label for="exampleInputName2" class="labelport" ng-bind-template="{{'lblPortfolio'|getLabel}}"></label><select name="portfolioId" class="form-control2" ng-model="company.portfolioId" ng-change="ParamChanged($event)" title="{{'lblPortfolio'|getLabel}}"><option ng-repeat="c in portfolioOptions" ng-selected="PortfolioID == c.Id" value="{{c.Id}}">{{c.Text}}</option></select></div><div class="form-group"><label for="exampleInputName2" class="labelport" ng-bind-template="{{'lblTransactionType'|getLabel}}"></label><select name="transactionTypeId" class="form-control2" ng-model="company.transactionTypeId" ng-change="ParamChanged($event)" title="{{'lblTransactionType'|getLabel}}"><option ng-repeat="c in actionTypes" ng-selected="TransactionTypeID == c.TransactionTypeID" value="{{c.TransactionTypeID}}">{{c.Transaction}}</option></select></div><div class="form-group"><label for="exampleInputName2" class="labelport" ng-bind="'lblQuantity'|getLabel"></label><input type="text" class="form-controlport" ng-model="company.Quantity" name="Quantity" placeholder="{{'lblQuantity'|getLabel}}" value="" ng-required="true" title="Quantity" ng-pattern="/^[0-9]+\.?[0-9]*$/"><div ng-show="companyForm.$submitted || companyForm.Quantity.$touched" class="validation-div"><span ng-show="companyForm.Quantity.$error.required" class="padding-5 alert alert-danger">{{'lblRequired'|getLabel}}</span><span ng-show="companyForm.Quantity.$error.pattern" class="padding-5 alert alert-danger">{{'lblInvalidName'|getLabel}}</span></div></div><div class="form-group"><label for="exampleInputName2" class="labelport" ng-bind="'lblSharePrice'|getLabel"></label><input type="text" class="form-controlport" ng-model="company.SharePrice" name="SharePrice" placeholder="{{'lblSharePrice'|getLabel}}" value="" ng-required="true" title="Quantity" ng-pattern="/^[0-9]+\.?[0-9]*$/" /><div ng-show="companyForm.$submitted || companyForm.SharePrice.$touched" class="validation-div"><span ng-show="companyForm.SharePrice.$error.required" class="padding-5 alert alert-danger">{{'lblRequired'|getLabel}}</span><span ng-show="companyForm.SharePrice.$error.pattern" class="padding-5 alert alert-danger">{{'lblInvalidName'|getLabel}}</span></div></div><div class="form-group"><label class="labelport" ng-bind="'lblCommission'|getLabel"></label><input type="text" class="form-controlport" ng-model="company.Commission" name="Commission" placeholder="{{'lblCommission'|getLabel}}" value="" title="{{'lblCommission'|getLabel}}" ng-pattern="/^[0-9]+\.?[0-9]*$/" /><div ng-show="companyForm.$submitted || companyForm.Commission.$touched" class="validation-div"><span ng-show="companyForm.Commission.$error.required" class="padding-5 alert alert-danger">{{'lblRequired'|getLabel}}</span><span ng-show="companyForm.Commission.$error.pattern" class="padding-5 alert alert-danger">{{'lblInvalidName'|getLabel}}</span></div></div><div class="col-sm-12"><div class="row sccol"><label class="col-sm-8 no-padding-left labelport" ng-bind="'lblDate'|getLabel"></label><div class="form-group no-margin-bottom"><div class='input-group date'><input onblur="" id="datepicker" type='text' name="portfolioDate" title="{{'lblDate'|getLabel}}" ng-model="company.portfolioDate" class="form-control" ng-required="company.portfolioDate.length==0?true:false" placeholder="dd/mm/yyyy" style="height:25px!important" readonly/><span class="input-group-addon" style="padding:3px 12px"><span class="fa fa-calendar"></span></span></div></div><div ng-show="companyForm.$submitted || companyForm.portfolioDate.$touched" class="validation-div"><span ng-show="companyForm.portfolioDate.$error.required" class="padding-5 alert alert-danger">{{'lblRequired'|getLabel}}</span><span ng-show="companyForm.portfolioDate.$error.pattern" class="padding-5 alert alert-danger">{{'lblInvalidDate'|getLabel}}</span></div></div></div><hr class="hr-small" /><div class="space-10"></div><div class="col-sm-12 no-padding"><ul class="nav nav-pills" role="tablist"><li role="presentation" class="pull-left"><button type="submit" class="btn btn_portfolio btn-primary">Save</button></li><li role="presentation" class="pull-right"><button ng-click="Close()" type="button" class="btn btn_portfolio btn-warning pull-right">Close</button></li></ul></div></form></div></div></div></div></div></div></div><style>#ui-datepicker-div,.datepicker{z-index:1060!important;display:block}</style>`,
              controller: 'addSearchCompanyToPortfolioPopupCtrl',
							scope: $scope,
							windowClass: 'app-modal-window',
							resolve: {
								'data': { data: data }
							}
						});						
      }
      $scope.AddSearchFundToPortfolioClick = function (data) {
        var modalInstance = $uibModal.open({
          templateUrl: '/content/theme/ng/partials/AddFundToPortfolioPopup.html',
          //template: `<div class="width-300" data-company="{{companyData|json}}"><div class="popup-header"><a title="Close" class="popup-close" href="javascript:" ng-click="Close();"><i class="fa fa-times"></i></a><div class="popup-header-content"><h5 class="search-h5 color-white" style="padding:5px">{{'lblAdd'|getLabel}} ({{companyData.CompanyName}})</h5></div></div><div class="clearfix"></div><div id="portfolioBody" class="modal-body" style="min-height:200px;padding-top:0"><div class="col-lg-12 col-md-12 col-sm-12 col-xs-12"><div class="row"><div class="sccol"><div class="edit_port"><div class="container-fluid"><form method="POST" name="companyForm" ng-submit="companyForm.$valid && addSearchCompanyToPortfolio(company)" novalidate><p><uib-progressbar ng-show="working" class="progress-striped active" value="dynamic" type="success"><i class="fa fa-spinner fa-spin"></i> {{'lblProcessing'|getLabel}}</uib-progressbar></p><div ng-show="success" class="alert alert-success padding-10 no-margin" role="alert"><strong ng-bind="'lblSuccess'|getLabel"></strong> {{'lblPortfolioSaveSuccessfull'|getLabel}}</div><div ng-show="info" class="alert alert-warning padding-10 no-margin" role="alert"><strong ng-bind="'lblInfo'|getLabel"></strong> <i class="fa fa-info"></i> {{infoMessage}}</div><div ng-show="error" class="alert alert-danger padding-10 no-margin" role="alert"><strong ng-bind="'lblError'|getLabel"></strong> {{'lblErrorMessage'|getLabel}}</div><input type="hidden" name="companyId" ng-model="company.companyId" ng-value="{{companyId}}" ng-required="companyId===0?true:false" ng-pattern="/^[0-9]+\.?[0-9]*$/" /><div ng-show="companyForm.$submitted || companyForm.companyId.$touched" class="validation-div"><span ng-show="companyForm.companyId.$error.required" class="padding-5 alert alert-danger">{{'lblRequired'|getLabel}}</span><span ng-show="companyForm.companyId.$error.pattern" class="padding-5 alert alert-danger">{{'lblInvalidName'|getLabel}}</span></div><div class="form-group"><label for="exampleInputName2" class="labelport" ng-bind-template="{{'lblPortfolio'|getLabel}}"></label><select name="portfolioId" class="form-control2" ng-model="company.portfolioId" ng-change="ParamChanged($event)" title="{{'lblPortfolio'|getLabel}}"><option ng-repeat="c in portfolioOptions" ng-selected="PortfolioID == c.Id" value="{{c.Id}}">{{c.Text}}</option></select></div><div class="form-group"><label for="exampleInputName2" class="labelport" ng-bind-template="{{'lblTransactionType'|getLabel}}"></label><select name="transactionTypeId" class="form-control2" ng-model="company.transactionTypeId" ng-change="ParamChanged($event)" title="{{'lblTransactionType'|getLabel}}"><option ng-repeat="c in actionTypes" ng-selected="TransactionTypeID == c.TransactionTypeID" value="{{c.TransactionTypeID}}">{{c.Transaction}}</option></select></div><div class="form-group"><label for="exampleInputName2" class="labelport" ng-bind="'lblQuantity'|getLabel"></label><input type="text" class="form-controlport" ng-model="company.Quantity" name="Quantity" placeholder="{{'lblQuantity'|getLabel}}" value="" ng-required="true" title="Quantity" ng-pattern="/^[0-9]+\.?[0-9]*$/"><div ng-show="companyForm.$submitted || companyForm.Quantity.$touched" class="validation-div"><span ng-show="companyForm.Quantity.$error.required" class="padding-5 alert alert-danger">{{'lblRequired'|getLabel}}</span><span ng-show="companyForm.Quantity.$error.pattern" class="padding-5 alert alert-danger">{{'lblInvalidName'|getLabel}}</span></div></div><div class="form-group"><label for="exampleInputName2" class="labelport" ng-bind="'lblSharePrice'|getLabel"></label><input type="text" class="form-controlport" ng-model="company.SharePrice" name="SharePrice" placeholder="{{'lblSharePrice'|getLabel}}" value="" ng-required="true" title="Quantity" ng-pattern="/^[0-9]+\.?[0-9]*$/" /><div ng-show="companyForm.$submitted || companyForm.SharePrice.$touched" class="validation-div"><span ng-show="companyForm.SharePrice.$error.required" class="padding-5 alert alert-danger">{{'lblRequired'|getLabel}}</span><span ng-show="companyForm.SharePrice.$error.pattern" class="padding-5 alert alert-danger">{{'lblInvalidName'|getLabel}}</span></div></div><div class="form-group"><label class="labelport" ng-bind="'lblCommission'|getLabel"></label><input type="text" class="form-controlport" ng-model="company.Commission" name="Commission" placeholder="{{'lblCommission'|getLabel}}" value="" title="{{'lblCommission'|getLabel}}" ng-pattern="/^[0-9]+\.?[0-9]*$/" /><div ng-show="companyForm.$submitted || companyForm.Commission.$touched" class="validation-div"><span ng-show="companyForm.Commission.$error.required" class="padding-5 alert alert-danger">{{'lblRequired'|getLabel}}</span><span ng-show="companyForm.Commission.$error.pattern" class="padding-5 alert alert-danger">{{'lblInvalidName'|getLabel}}</span></div></div><div class="col-sm-12"><div class="row sccol"><label class="col-sm-8 no-padding-left labelport" ng-bind="'lblDate'|getLabel"></label><div class="form-group no-margin-bottom"><div class='input-group date'><input onblur="" id="datepicker" type='text' name="portfolioDate" title="{{'lblDate'|getLabel}}" ng-model="company.portfolioDate" class="form-control" ng-required="company.portfolioDate.length==0?true:false" placeholder="dd/mm/yyyy" style="height:25px!important" readonly/><span class="input-group-addon" style="padding:3px 12px"><span class="fa fa-calendar"></span></span></div></div><div ng-show="companyForm.$submitted || companyForm.portfolioDate.$touched" class="validation-div"><span ng-show="companyForm.portfolioDate.$error.required" class="padding-5 alert alert-danger">{{'lblRequired'|getLabel}}</span><span ng-show="companyForm.portfolioDate.$error.pattern" class="padding-5 alert alert-danger">{{'lblInvalidDate'|getLabel}}</span></div></div></div><hr class="hr-small" /><div class="space-10"></div><div class="col-sm-12 no-padding"><ul class="nav nav-pills" role="tablist"><li role="presentation" class="pull-left"><button type="submit" class="btn btn_portfolio btn-primary">Save</button></li><li role="presentation" class="pull-right"><button ng-click="Close()" type="button" class="btn btn_portfolio btn-warning pull-right">Close</button></li></ul></div></form></div></div></div></div></div></div></div><style>#ui-datepicker-div,.datepicker{z-index:1060!important;display:block}</style>`,
          controller: 'addSearchFundToPortfolioPopupCtrl',
          scope: $scope,
          windowClass: 'app-modal-window',
          resolve: {
            'data': { data: data }
          }
        });
      }

		}])
	.controller('equitiesCtrl', ['$global','$scope','$uibModalInstance', '$uibModal', '$http', '$filter', 'data', function ($global,$scope, $uibModalInstance, $uibModal, $http, $filter, data) {
		var self = this; $scope.isListed = false;
		$uibModalInstance.rendered.then(function () {
			var reqObj = data.s;
			$scope.content = data.data;
      $scope.isListed = $scope.content.stockInfo.IsListed === 0 ? false : true;      
      self.createChart(data.data.Prices);
		});
		$scope.Close = function () {
			$uibModalInstance.close();
		};

    this.createChart = function (prices) {
      var data = [], datax = [], datay = [];
      angular.forEach(prices, function (v) {
        var date = parseInt(v.PriceDate.slice(6, -2));
        var price = v.ClosingPrice;
        data.push([date,price]);
        datax.push(date);
        datay.push(price);
      });



		Highcharts.chart('contEquities', {
		
        chart: {
				padding: [10, 0, 0, 0],
				backgroundColor: "#000",
				borderColor: '#3a3a3a',
          events: {
            click: function (e) {
              window.location.href = $filter('getURL')($scope.content.PriceComparison);
            }
          }
        },      
        title: {
          text: '',
          x: -20 //center
        },
        subtitle: {
          text: '',
          x: -20
        },
        xAxis: {
			type: 'datetime',
			gridLineColor: '#3a3a3a',
          labels: {
            formatter: function () {
              return Highcharts.dateFormat('%d/%m  ', this.value);
            },

            style: {
              color: '#ADADAD'
            }
          },
        },
        yAxis: {
          gridLineColor: '#3a3a3a',
          title: '',
          opposite: true,
          labels: {
            x: +5,
            y: +2,
            style: {
				color: '#ADADAD'
            }
          },
          gridLineDashStyle: "Solid",
          gridLineWidth: 1,
          lineWidth: 0
        },
        plotOptions: {
          series: {
            marker: {
              enabled: false,
              symbol: 'circle',
              radius: 1
            }
          }
        },
        tooltip: {
          formatter: function () {
				return '<b class="defualt-color">' + Highcharts.dateFormat('%b %e, %Y', new Date(this.x)) + '</b> :' + "<label class='defualt-color'>" + + $filter('number')(this.y, 2) + "</label>";
          }
        },
        credits: {
          enabled: false
        },
        legend: {
          layout: 'vertical',
          align: 'right',
          verticalAlign: 'middle',
          borderWidth: 0,
          enabled: false
        },
        series: [{
          name: $scope.content.CompanyName,
          data: data,
          color: '#52658f',
          type: 'line',
          threshold: null,
          fillColor: {
            linearGradient: {
              x1: 0,
              y1: 0,
              x2: 0,
              y2: 1
            },
            stops: [
              [0, 'rgba(83, 151, 177,.5)'],
              [1, 'rgba(83, 151, 177,.5)']
            ]
          }
        }],

      });
    }
     
		$scope.AddToPortfolio = function ($event) {
			$event.preventDefault();
			$uibModalInstance.close();
      $scope.$parent.AddToPortfolioSearchClick($scope.content);

		}
		$scope.addCompanyToMyWatchList = function ($event) {
			$event.preventDefault();
			$http({
				url: siteRoot + 'home/gsaddcompanytowatchlist',
				method: 'POST',
				data: { companyId :$scope.content.CompanyID}
			}, function ()
			{
				utility.alert($global.getResources('lblError'), '<span style="float:left; margin:0 7px 50px 0;"><i class="fa fa-trash"></i></span>' + $global.getResources('lblErrorOccured'));
			})
				.then(function (res) {
				if (parseInt(res.data.result) > 0) {
					$('<div></div>').dialog({
						modal: true,
						title: $global.getResources("lblSuccess"),
						open: function () {
							$(this).html($global.getResources('lblCompanyAddedToWatchList'));
						},
						'buttons': [
						{
							text: $global.getResources("lblClose"),
							click: function () {
								$(this).dialog("close");
							}
						},
						{
							text: $global.getResources("lblGoToMyWatchList"),
							click: function () {
								window.location = res.data.url;
								$(this).dialog("close");
								$uibModalInstance.close();
							}
						}
						]
					}).css("font-size", "14px");
				} else {
					utility.alert($global.getResources("lblInfo"), '<span style="float:left; margin:0 7px 50px 0;"><i class="fa fa-info-circle"></i></span>'+$global.getResources("lblYouAlreadyHveThisCompanyInWatchList"));
				}

			});
		}
	}])
	.controller('addSearchCompanyToPortfolioPopupCtrl', ['$global', '$http', '$scope', '$compile', '$uibModalInstance', '$filter', 'data', '$timeout',
		function ($global,$http, $scope, $compile, $uibModalInstance, $filter, data, $timeout) {
			var self = this;
			$scope.success = false;
			$scope.error = false;
			$scope.info = false;
			$scope.infoMessage = "";
			$scope.working = false;
			$scope.PortfolioID = 0;
			$scope.TransactionTypeID = 0;
			$scope.companyData = {};
      $scope.company = {
        portfolioId:'',
				Quantity: '',
				SharePrice: '',
				Commission: '',
				portfolioDate: ''
			};
			$uibModalInstance.rendered.then(function () {
				$timeout(() => {
					$scope.$apply();
				});
				
				$scope.companyData = data.data;
				initFunc();
			});
			$scope.Close = function () {
				$uibModalInstance.close();
			};

      $scope.addSearchCompanyToPortfolio = function (company) {
				Reset();
        Reset();
        $("form[name=companyForm] :input").prop("disabled", true);
        $scope.working = true;
        $http({
          url: siteRoot + 'tools/saveportfolio',
          method: 'POST',
          data: {
            PortfolioID: company.portfolioId,
            CompanyID: $scope.companyData.CompanyID,
            SymbolTicker: $scope.companyData.Ticker,
            Quantity: company.Quantity,
            SharePrice: company.SharePrice,
            Commision: company.Commission,
            BuyDate: company.portfolioDate,
            Note: company.Notes,
            Transaction: company.transactionTypeId
          }
        }, function (error) {
          $scope.error = true;
          $timeout(function () {
            $scope.error = false;
          }, 1500);
        }).then(function (resp) {
          if (resp.data === '0') {
            $scope.success = true;
            $timeout(function () {
              $uibModalInstance.close();
            }, 1500);
          } else if (resp.data === '-2') {
            $scope.info = true;
            $scope.infoMessage = $global.getResources('lblCompanyAlreadyExistInfPortfolio');
            $timeout(function () {
              $scope.info = false;
              $scope.infoMessage = '';
            }, 6000);
          }
        }).finally(function () {
          $("form[name=companyForm] :input").prop("disabled", false);
          $scope.working = false;
        });
			}
			function initFunc() {
				$http({
					url: siteRoot + 'home/GSAddCompanyToPortfolio',
					method: 'POST'
				}).then(function (resp) {
					$scope.portfolioOptions = resp.data.options;
					$scope.actionTypes = resp.data.actionTypes;
					$timeout(function () {
            $scope.PortfolioID = $scope.portfolioOptions.firstOrDefault().Id;            
            $scope.TransactionTypeID = $scope.actionTypes.firstOrDefault().TransactionTypeID.toString();
            $scope.company.portfolioId = resp.data.options.firstOrDefault().Id;
						$timeout(function () {		                    
							$("#datepicker").datepicker({
								changeMonth: true,
								dateFormat: 'dd/mm/yy',
								changeYear: true
							});
							$('#datepicker').datepicker('setDate', 'now');
							$scope.company.portfolioDate = $.datepicker.formatDate("dd/mm/yy", $("#datepicker").datepicker("getDate"));
						});
					});
					}, (error) => { console.log(error.data); });
			}
			function Reset() {
				$scope.success = false;
				$scope.error = false;
				$scope.info = false;
				$scope.infoMessage = "";
				$scope.working = false;
				$("form[name=companyForm] :input").prop("disabled", false);
			}
		}])
	.controller('indicesCtrl', ['$scope', '$uibModalInstance', '$http', '$filter', 'data', function ($scope, $uibModalInstance, $http, $filter, data) {
		var self = this;
		$uibModalInstance.rendered.then(function () {
			var s = data.s;
			$scope.content = data.data;
			self.createChart(data.data.indices);

		});
		$scope.Close = function () {
			$uibModalInstance.close();
		};

		this.createChart = function (indices) {

			var data = [], datax = [], datay = [];
			angular.forEach(indices, function (v) {
				var date = parseInt(v.Date.substr(6));
				var price = v.Closing;
				data.push({
					date, price
				});
				datax.push(date);
				datay.push(price);
			});

			new Highcharts.chart('contIndices', {
				chart: {
					
					//margin: [15,25, 25, 0],
					padding: [0, 0, 0, 0]
        },
				navigation: {
					buttonOptions: {
						enabled: false
					}
				},
				title: {
					text: '',
					x: -20 //center
				},
				subtitle: {
					text: '',
					x: -20
				},
				title: {
					text: ''
				},
				scrollbar: {
					enabled: false
				},
				rangeSelector: {
					enabled: false
				},
				navigator: {
					enabled: false
				},
				exporting: {
					enabled: false
				},
				xAxis: {
					gridLineColor: '#88bff5',
					tickInterval: 10,
					min: 0,
					max: null,
					type: 'datetime',
					dateTimeLabelFormats: {
						hour: '%l:%M %p'
					},
					labels: {
						formatter: function () {
							return Highcharts.dateFormat('%d/%m  ', this.value);
						},
						style: {
							color: '#222'
						}
					},
					crosshair: {
						width: 0.5,
						color: '#fff',
						zIndex: 50
					},
					categories: datax
				},
				yAxis: {
					gridLineColor: '#ececec',
					//alternateGridColor: '#FeFeFe',
					title: '',
					opposite: !0,
					labels: {
						x: +5,
						y: +2,
						style: {
							color: '#222'
						}
					},
					gridLineDashStyle: "Solid",
					gridLineInterpolation: 1000,
					gridLineWidth: 1,
					lineWidth: 0,
					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;
									}
				},
				plotOptions: {
					series: {
						marker: {
							enabled: false,
							symbol: 'circle',
							radius: 1
						}
					}
				},
				tooltip: {
					formatter: function () {
						return '<b>' + Highcharts.dateFormat('%b %e, %Y', new Date(this.x)) + '</b> :' + $filter('number')(this.y, 2);;
					}
				},
				credits: {
					enabled: false
				},
				legend: {
					layout: 'vertical',
					align: 'right',
					verticalAlign: 'middle',
					borderWidth: 0,
					enabled: false
				},
				series: [{
					name: $scope.content.CompanyName,
					data: datay,
					color: '#52658f',
					type: 'line',
					threshold: null,
					fillColor: {
						linearGradient: {
							x1: 0,
							y1: 0,
							x2: 0,
							y2: 1
						},
						stops: [
							[0, 'rgba(83, 151, 177,.5)'],
							[1, 'rgba(83, 151, 177,.5)']
						]
					}
				}],
			});

		},
		this.sortData = function (array) {

			// temporary array holds objects with position and sort-value
			var mapped = array.map(function (el, i) {
				return { index: i, value: el };
			})

			// sorting the mapped array containing the reduced values
			mapped.sort(function (a, b) {
				return +(a.value > b.value) || +(a.value === b.value) - 1;
			});
			array = mapped.map(function (el) {
				return el.value;
			});
			return array;
		}

	}])
	.controller('globalIndicesCtrl', ['$scope', '$uibModalInstance', '$http', '$filter', 'data', function ($scope, $uibModalInstance, $http, $filter, data) {
		var self = this;
		$uibModalInstance.rendered.then(function () {
			var s = data.s;
			$scope.content = data.data;
			self.createChart(data.data.indices);

		});
		$scope.Close = function () {
			$uibModalInstance.close();
		};

		this.createChart = function (indices) {
			var data = [], datax = [], datay = [];
			angular.forEach(indices, function (v) {
				var date = parseInt(v.Date.substr(6));
				datax.push(date);
				datay.push(parseFloat(v.Closing));
			});

			new Highcharts.chart('contGlobalIndices', {
				chart: {	       
					//margin: [15, 25, 25, 0],
					padding: [0, 0, 0, 0]
				},
				navigation: {
					buttonOptions: {
						enabled: false
					}
        },
				title: {
					text: '',
					x: -20 //center
				},
				subtitle: {
					text: '',
					x: -20
				},
				scrollbar: {
					enabled: false
				},
				rangeSelector: {
					enabled: false
				},
				navigator: {
					enabled: false
				},
				exporting: {
					enabled: false
				},
				xAxis: {
					gridLineColor: '#88bff5',
					tickInterval: 10,
					min: 0,
					max: null,
					type: 'datetime',
					dateTimeLabelFormats: {
						hour: '%l:%M %p'
					},
					labels: {
						formatter: function () {
							return Highcharts.dateFormat('%d/%m ', this.value);
						},
						style: {
							color: '#222',
							direction: 'ltr'
						}
					},
					crosshair: {
						width: 0.5,
						color: '#222',
						zIndex: 50
					},
					categories: datax
				},
				yAxis: {	        
					title: '',
					opposite: true,
					
					labels: {
						formatter:function(){
							return this.value;
						},

						x: +5,
						y: +2,
						style: {
							color: '#222'
						}
					},
					gridLineDashStyle: "Solid",
					//gridLineInterpolation: 1000,
					gridLineWidth: 1,	        
					lineWidth: 0,
					gridLineColor: '#ececec',
					//alternateGridColor: '#FeFeFe',
					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;
									}
				},
				plotOptions: {
					series: {
						marker: {
							enabled: false,
							symbol: 'circle',
							radius: 1
						}
					}
				},
				tooltip: {
					formatter: function () {
						return '<b>' + Highcharts.dateFormat('%b %e, %Y', new Date(this.x)) + '</b> :' + $filter('number')(this.y, 2);
					}
				},
				credits: {
					enabled: false
				},
				legend: {
					layout: 'vertical',
					align: 'right',
					verticalAlign: 'middle',
					borderWidth: 0,
					enabled: false
				},
				series: [{
					name: $scope.content.CompanyName,
					data: datay,
					color: '#52658f',
					type: 'line',
					threshold: null	        
				}],

			});

		}

	}])
	.controller('fundsCtrl', ['$scope', '$uibModalInstance', '$http', '$filter', 'data', function ($scope, $uibModalInstance, $http, $filter, data) {
		var self = this;
		$uibModalInstance.rendered.then(function () {
			var s = data.s;
			$scope.content = data.data;
			self.createChart(data.data.funds);

		});
		$scope.Close = function () {
			$uibModalInstance.close();
		};

		this.createChart = function (indices) {
			var datax = [], datay = [];
			angular.forEach(indices, function (v) {
				var date = parseInt(v.Date.substr(6));
				var price = v.Close;
				datax.push(date);
				datay.push(price);
			});

			new Highcharts.chart('contFunds', {
				chart: {	       
					//margin: [15, 0, 25, 0],
					padding: [0, 0, 0, 0]
        },
				navigation: {
					buttonOptions: {
						enabled: false
					}
				},
				title: {
					text: '',
					x: -20 //center
				},
				subtitle: {
					text: '',
					x: -20
				},
				title: {
					text: ''
				},
				scrollbar: {
					enabled: false
				},
				rangeSelector: {
					enabled: false
				},
				navigator: {
					enabled: false
				},
				exporting: {
					enabled: false
				},
				xAxis: {
					gridLineColor: '#88bff5',
					tickInterval: 10,
					min: 0,
					max: null,
					type: 'datetime',
					dateTimeLabelFormats: {
						hour: '%l:%M %p'
					},
					labels: {
						formatter: function () {
							return Highcharts.dateFormat('%d/%m', this.value);
						},
						style: {
							color: '#222'
						}
					},
					crosshair: {
						width: 0.5,
						color: '#fff',
						zIndex: 50
					},
					categories: datax
				},
				yAxis: {	        
					title: '',
					opposite: !0,
					labels: {
						x: +5,
						y: +2,
						style: {
							color: '#222'
						}
					},
					gridLineDashStyle: "Solid",
					//gridLineInterpolation: 1000,
					gridLineWidth: 1,	        
					lineWidth: 0,
					gridLineColor: '#ececec',
					//alternateGridColor: '#FeFeFe',
					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;
									}
				},
				plotOptions: {
					series: {
						marker: {
							enabled: false,
							symbol: 'circle',
							radius: 1
						}
					}
				},
				tooltip: {
					formatter: function () {
						return '<b>' + Highcharts.dateFormat('%b %e, %Y', new Date(this.x)) + '</b> :' + $filter('number')(this.y, 2);
					}
				},
				credits: {
					enabled: false
				},
				legend: {
					layout: 'vertical',
					align: 'right',
					verticalAlign: 'middle',
					borderWidth: 0,
					enabled: false
				},
				series: [{
					name: $scope.content.CompanyName,
					data: datay,
					color: '#52658f',
					type: 'line',
					threshold: null
				}],
			});

		}

    $scope.AddSearchFundToPortfolio = function ($event) {
      $event.preventDefault();
      $uibModalInstance.close();
      $scope.$parent.AddSearchFundToPortfolioClick($scope.content);

    }
    $scope.addCompanyToMyWatchList = function ($event) {
      $event.preventDefault();
      $http({
        url: siteRoot + 'home/gsaddcompanytowatchlist',
        method: 'POST',
        data: { companyId: $scope.content.CompanyID }
      }, function () {
          utility.alert($global.getResources('lblError'), '<span style="float:left; margin:0 7px 50px 0;"><i class="fa fa-trash"></i></span>' + $global.getResources('lblErrorOccured'));
        })
        .then(function (res) {
          if (parseInt(res.data.result) > 0) {
            $('<div></div>').dialog({
              modal: true,
              title: $global.getResources("lblSuccess"),
              open: function () {
                $(this).html($global.getResources('lblCompanyAddedToWatchList'));
              },
              'buttons': [
                {
                  text: $global.getResources("lblClose"),
                  click: function () {
                    $(this).dialog("close");
                  }
                },
                {
                  text: $global.getResources("lblGoToMyWatchList"),
                  click: function () {
                    window.location = res.data.url;
                    $(this).dialog("close");
                    $uibModalInstance.close();
                  }
                }
              ]
            }).css("font-size", "14px");
          } else {
            utility.alert($global.getResources("lblInfo"), '<span style="float:left; margin:0 7px 50px 0;"><i class="fa fa-info-circle"></i></span>' + $global.getResources("lblYouAlreadyHveThisCompanyInWatchList"));
          }

        });
    }



  }])
  .controller('addSearchFundToPortfolioPopupCtrl', ['$global', '$http', '$scope', '$compile', '$uibModalInstance', '$filter', 'data', '$timeout',
    function ($global, $http, $scope, $compile, $uibModalInstance, $filter, data, $timeout) {
      var self = this;
      $scope.success = false;
      $scope.error = false;
      $scope.info = false;
      $scope.infoMessage = "";
      $scope.working = false;
      $scope.PortfolioID = 0;
      $scope.TransactionTypeID = 0;
      $scope.fundData = {};
      $scope.fund = {
        portfolioId: 0,
        transactionTypeId:0,
        Quantity: '',
        UnitPrice: '',
        Commission: '',
        portfolioDate: ''
      };
      $uibModalInstance.rendered.then(function () {
        $timeout(() => {
          $scope.$apply();
        });

        $scope.fundData = data.data;
        initFunc();
      });
      $scope.Close = function () {
        $uibModalInstance.close();
      };

      $scope.addSearchFundToPortfolio = function (fund) {
        Reset();
        
        $("form[name=fundForm] :input").prop("disabled", true);
        $scope.working = true;
        $http({
          url: siteRoot + 'tools/savefundsinportfolio',
          method: 'POST',
          data: {
            PortfolioID: fund.portfolioId,
            MFundID: $scope.fundData.MFundID,
            fundQuantity: fund.Quantity,
            fundUnitPrice: fund.UnitPrice,
            fundCommission: fund.Commission,
            fundDate: fund.portfolioDate,
            fundNotes: fund.Notes,
            fundTransactionType: fund.transactionTypeId
          }
        }, function (error) {
          $scope.error = true;
          $timeout(function () {
            $scope.error = false;
          }, 1500);
        }).then(function (resp) {
          if (parseInt(resp.data)>0) {
            $scope.success = true;
            $timeout(function () {
              $uibModalInstance.close();
            }, 1500);
          } else if (parseInt(resp.data)<0) {
            $scope.info = true;
            $scope.infoMessage = $global.getResources('lblMutualFundAlreadyExistInfPortfolio');
            $timeout(function () {
              $scope.info = false;
              $scope.infoMessage = '';
            }, 6000);
          }
        }).finally(function () {
          $("form[name=fundForm] :input").prop("disabled", false);
          $scope.working = false;          
        });
      }
      function initFunc() {
        $http({
          url: siteRoot + 'home/GSAddCompanyToPortfolio',
          method: 'POST'
        }).then(function (resp) {
          $scope.portfolioOptions = resp.data.options;
          $scope.actionTypes = resp.data.actionTypes;
          $timeout(function () {
            $scope.PortfolioID = $scope.portfolioOptions.firstOrDefault().Id;
            $scope.TransactionTypeID = $scope.actionTypes.firstOrDefault().TransactionTypeID.toString();
            $scope.fund.portfolioId = $scope.PortfolioID;
            $scope.fund.transactionTypeId = $scope.TransactionTypeID;
            $timeout(function () {
              $("#datepicker").datepicker({
                changeMonth: true,
                dateFormat: 'dd/mm/yy',
                changeYear: true
              });
              $('#datepicker').datepicker('setDate', 'now');
              $scope.fund.portfolioDate = $.datepicker.formatDate("dd/mm/yy", $("#datepicker").datepicker("getDate"));
            });
          });
        }, (error) => { console.log(error.data); });
      }
      function Reset() {
        $scope.success = false;
        $scope.error = false;
        $scope.info = false;
        $scope.infoMessage = "";
        $scope.working = false;
        $("form[name=fundForm] :input").prop("disabled", false);
      }
    }])

	.controller('indicatorsCtrl', ['$scope', '$uibModalInstance', '$http', '$filter', 'data', function ($scope, $uibModalInstance, $http, $filter, data) {
		var self = this;
		$uibModalInstance.rendered.then(function () {
			var s = data.s;

			$scope.content = data.data;
			self.createChart(data.data.detail);

		});
		$scope.Close = function () {
			$uibModalInstance.close();
		};

		this.createChart = function (indicators) {
			var iddatax = [], iddatay = [];

			angular.forEach(indicators, function (v) {
				var date = parseInt(v.AsofDate.slice(6, -2));
				iddatax.push(date);
				iddatay.push({ y: v.Value, measure: v.MeasurementUnit });
			});
			new Highcharts.chart('contIndicators', {
				chart: {	       
					//margin: [15, 25, 25, 50],
					padding: [0, 0, 0, 0]
        },
				navigation: {
					buttonOptions: {
						enabled: false
					}
				},
				title: {
					text: '',
					x: -20 //center
				},
				subtitle: {
					text: '',
					x: -20
				},
				title: {
					text: ''
				},
				scrollbar: {
					enabled: false
				},
				rangeSelector: {
					enabled: false
				},
				navigator: {
					enabled: false
				},
				exporting: {
					enabled: false
				},
				xAxis: {
					gridLineColor: '#88bff5',
					tickInterval: 3,
					min: 0,
					max: null,
					type: 'datetime',

					labels: {
						formatter: function () {
							return Highcharts.dateFormat('%d/%m/%Y', this.value);
						},
						style: {
							color: '#222'
						}
					},
					categories: iddatax
				},
				yAxis: {	        
					title: '',
					opposite: !1,
					labels: {
						x: +5,
						y: +2,
						style: {
							color: '#222'
						},
						formatter: function () {
							return $filter('Abbr')(this.value);
						}
					},
					gridLineDashStyle: "Solid",
					//gridLineInterpolation: 1000,
					gridLineWidth: 1,
					lineWidth: 1,
					gridLineColor: '#ececec',
					//alternateGridColor: '#FeFeFe',
					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;
					}
				},
				plotOptions: {
					series: {
						marker: {
							enabled: false,
							symbol: 'circle',
							radius: 1
						}
					}
				},
				tooltip: {
					formatter: function () {
						return '<b>' + Highcharts.dateFormat('%b %e, %Y', new Date(this.x)) + '</b> :' + $filter('number')(this.y, 2) + ' ' + this.point.measure;
					}
				},
				credits: {
					enabled: false
				},
				legend: {
					layout: 'vertical',
					align: 'right',
					verticalAlign: 'middle',
					borderWidth: 0,
					enabled: false
				},
				series: [{
					name: $scope.content.CompanyName,
					data: iddatay,
					color: '#52658f',
					type: 'column',
					threshold: null
				}],
			});

		}

	}])
;




