﻿angular.module('ngScreenerApp', ['rzModule', 'ngSanitize'])
  .controller('PresetScreenerCtrl', ['$scope', '$http', '$q', '$filter', function ($scope, $http, $q, $filter) {
    $scope.Id = undefined;
    $scope.auth = undefined;
    $scope.init = function (baseModel) {
      $scope.Id = baseModel.stockMarketID;
      $scope.auth = Number(baseModel.auth);
      ScreenerData();
    }

    $scope.ScreenerList = $("#ScreenerList").data("screener");
    $scope.ScreenerDate = $filter('date')(new Date($scope.ScreenerList[0].Date), 'MM/dd/yyyy');
    $scope.dateFormat = function (date) {
      return new Date(date);
    }

    function ScreenerData() {
      blockUI('RecentScreener');
      $http({
        method: 'POST',
        url: siteRoot + 'Screener/PresetScreener/',
        data: { id: $scope.Id, ScreenerDate: $scope.ScreenerDate }
      }).then(function (res) {
        $scope.record = res.data;
        $scope.UniqueIndicator = $filter('unique')(res.data.map(function (v) { return v.IndicatorID; }));
      }).catch((error) => {
        unblockUI('RecentScreener');
        console.log(error.data);
        }).finally(() => {
          unblockUI('RecentScreener');
        });
    }

    $scope.MaxArr = function (Id) {
      var filterData = $filter('filter')($scope.record, { IndicatorID: Id }, true);
      return Math.max.apply(Math, filterData.map(function (val) { return Math.abs(val.Value); }));
    }
    $scope.ScreenerUpdate = function () {
      ScreenerData();
    }
  }])
  .controller('MarketScreenerCtrl', ['$scope', '$http', '$q', '$filter', "$timeout", function ($scope, $http, $q, $filter, $timeout) {
    $scope.auth = undefined;
    $scope.Id = $.getQueryString('id');
    $scope.ActiveTab = 3;
    $scope.ScreenerList = $("#ScreenerList").data("screener");
    $scope.ScreenerDate = $filter('date')(new Date($scope.ScreenerList[0].Date), 'MM/dd/yyyy');
    $scope.dateFormat = function (date) {
      return new Date(date);
    }

    var vm = this;
    vm.toggle = function () {
      vm.refreshSlider();
    };
    vm.refreshSlider = function () {
      $timeout(function () {
        $scope.$broadcast('rzSliderForceRender');
      });
    };

    function ScreenerData(PMarketId, PScreenerDate, PflagID) {
      $scope.record = [];
      blockUI('MarketScreener');
      $http({
        method: 'POST',
        url: siteRoot + 'Screener/MarketDataScreener/',
        data: { id: PMarketId, ScreenerDate: PScreenerDate, flagID: PflagID }
      }).then(function (res) {
        $scope.record = res.data.model;
        $scope.auth = Number(res.data.auth);
        if ($scope.ActiveTab === 3) {
          $scope.UniqueIndicator = $filter('unique')(res.data.model.map(function (v) { return v.TypeID; }));
        } else {
          $scope.UniqueIndicator = $filter('unique')(res.data.model.map(function (v) { return v.IndicatorID; }));
        }
      }, (error) => { unblockUI('MarketScreener'); console.log(error.data); }).then(function () {
        vm.toggle();
        unblockUI('MarketScreener');
      });
    }

    $scope.MaxArrChangePer = function (Id) {
      var filterData = $filter('filter')($scope.record, { IndicatorID: Id }, true);
      return Math.max.apply(Math, filterData.map(function (val) { return Math.abs(val.ChangePer); }));
    }
    // with type ID 
    $scope.MaxArrValueByIndicator = function (Id) {
      var filterData = $filter('filter')($scope.record, { IndicatorID: Id }, true);
      return Math.max.apply(Math, filterData.map(function (val) { return Math.abs(val.Value); }));
    }
    $scope.MaxArrValueByType = function (Id) {
      var filterData = $filter('filter')($scope.record, { TypeID: Id }, true);
      return Math.max.apply(Math, filterData.map(function (val) { return Math.abs(val.Value); }));
    }
    $scope.MaxArrValueByIndicatorAndColumn = function (Id, column) {
      var filterData = $filter('filter')($scope.record, { IndicatorID: Id }, true);
      return Math.max.apply(Math, filterData.map(function (val) { return Math.abs(val[column]); }));
    }
    ScreenerData($scope.Id, $scope.ScreenerDate, $scope.ActiveTab);

    $scope.ScreenerUpdate = function () {
      ScreenerData($scope.Id, $scope.ScreenerDate, $scope.ActiveTab);
    }
    $scope.ScreenerDataSwitch = function (id) {
      if ($scope.ActiveTab === id) return;
      $scope.ActiveTab = id;
      ScreenerData($scope.Id, $scope.ScreenerDate, $scope.ActiveTab);
    }
    $scope.sortType = function (val) {
      return val > 0 ? true : false;
    }

  }])
  .controller('FundamentScreenerCtrl', ['$scope', '$http', '$q', '$filter', "$timeout", function ($scope, $http, $q, $filter, $timeout) {
    $scope.Id = $.getQueryString('id');
    $scope.ActiveTab = "1";
    $scope.auth = undefined;

    $scope.ScreenerData = function () {
      $scope.record = [];
      blockUI('FundamentScreener');
      $http({
        method: 'POST',
        url: siteRoot + 'Screener/FundamentalScreener/',
        data: { id: $scope.Id, flagID: $scope.ActiveTab }
      }).then(function (res) {
        $scope.record = res.data.model;
        $scope.auth = Number(res.data.auth);
        $scope.UniqueIndicator = $filter('unique')(res.data.model.map(function (v) { return v.IndicatorID; }));
        $scope.record = res.data.model;
        $scope.UniqueIndicator = $filter('unique')(res.data.model.map(function (v) { return v.IndicatorID; }));
      }, (error) => { unblockUI('FundamentScreener'); console.log(error.data); }).then(function () {
        unblockUI('FundamentScreener');
      });
    }

    $scope.MaxArrValueByIndictor = function (Id) {
      var filterData = $filter('filter')($scope.record, { IndicatorID: Id }, true);
      return Math.max.apply(Math, filterData.map(function (val) { return Math.abs(val.Value); }));
    }

    $scope.ScreenerData();

    $scope.ScreenerUpdate = function () {
      $scope.ScreenerData();
    }
    $scope.ScreenerDataSwitch = function (id) {
      if ($scope.ActiveTab === id) return;
      $scope.ActiveTab = id;
      $scope.ScreenerData();
    }
    $scope.sortBy = function (type) {
      return type !== 6177 && type !== 6175 && type !== 6176 && type !== 6178 && type !== 6170 && type !== 6171 && type !== 6172 ? true : false;
    }

  }])
  .controller('ReportScreenerCtrl', ['$scope', '$http', '$q', '$filter', '$timeout', function ($scope, $http, $q, $filter, $timeout) {

    $scope.ReportSource = [''];
    $scope.searchPeriodValue = 'lastmonth';

    $scope.ReportType = "0";
    var selObj = undefined;
    $scope.ReportTicker = undefined;
    $timeout(() => {
      $(".date-picker").datepicker({
        showOn: 'button',
        buttonImage: '/content/theme/images/x_office_calendar.png',
        buttonImageOnly: true,
        changeMonth: true,
        changeYear: true,
        showAnim: 'slideDown',
        duration: 'fast',
        dateFormat: 'mm/dd/yy'
      });
    });
    $scope.callback = function ($item) {
      if ($item !== undefined && $item !== 'undefined') {
        selObj = $item.originalObject;
        $scope.ReportTicker = selObj.Ticker;
      }
    }
    $scope.focusOut = function () {
      clearText();
    }
    function clearText() {
      $scope.$broadcast('angucomplete-alt:clearInput', 'drp-company-search');
      $scope.ReportTicker = null;
    }
    $scope.$watch('searchPeriodValue', (n, o) => {
      if (n === 'custom') {
        $scope.toDate = '';
        $scope.fromDate = '';
      }
    });
    //paging 
    $scope.itemsPerPage = 25;
    $scope.maxSize = 7;
    //$scope.totalItems = 1;
    $scope.currentPage = 1;
    $scope.setPage = function (pageNo) {
      $scope.currentPage = pageNo;
    };
    var currPage = 0;

    function ScreenerData() {
      var todate, todateFormat, fromdate, fromdateformat, lastMonth, currentDate;

      todate = new Date();
      currentDate = new Date();

      if ($scope.searchPeriodValue === 'lastweek') {
        fromdate = currentDate.setDate(currentDate.getDate() - 7);
      } else if ($scope.searchPeriodValue === 'lastmonth') {
        fromdate = currentDate.setMonth(currentDate.getMonth() - 1);
      } else if ($scope.searchPeriodValue === 'lastyear') {
        fromdate = currentDate.setFullYear(currentDate.getFullYear() - 1);
      } else if ($scope.searchPeriodValue === 'custom') {
        todate = $scope.toDate;
        fromdate = $scope.fromDate;
      }
      todateFormat = $filter('date')(todate, "yyyy-MM-dd");
      fromdateformat = $filter('date')(fromdate, "yyyy-MM-dd");

      blockUI('collapseReportScreener');
      $http({
        method: 'POST',
        url: siteRoot + 'Screener/ReportScreener/',
        data: { Ticker: $scope.ReportTicker, Type: $scope.ReportType, Source: $scope.ReportSource.join(), FromDate: fromdateformat, ToDate: todateFormat }
      }).then(function (res) {
        $scope.data = res.data;
        $scope.totalItems = $scope.data.length;
        $scope.numPages = Math.ceil($scope.totalItems / $scope.itemsPerPage);
        $scope.currentPage = 1;
      }, (error) => { unblockUI('ReportScreener'); console.log(error.data); }).finally(function () {
        clearText();
        unblockUI('collapseReportScreener');
      });
    }
    ScreenerData();

    $scope.UpdateReportScreener = function () {
      ScreenerData();
    }

  }])
  .controller('StockScreenerCtrl', ['$scope', '$http', '$q', '$filter', "$timeout", '$window', '$compile', function ($scope, $http, $q, $filter, $timeout, $window, $compile) {
    /*global variables*/
    $scope.noRecordsToView = "25";
    $scope.paginationMaxSize = 10;
    $scope.currentTab = 'descriptiveTab';
    $scope.selectedFilters = [];
    $scope.stockConstModel = {
      descConstModel: {},
      techConstModel: {},
      vmConstModel: {},
      profConstModel: {},
      growthConstModel: {}

    };

    /*-------------------------------------Start ss Section---------------------------------------------------------------*/
    $scope.ssData = [];
    $scope.ssLoading = true;
    $scope.SSInputModel = {
      /*valuation measures filters */
      StockMarketID: "-998",
      CapSizeID: "-998",
      FreeFloat: "-998",
      EarningDate: "-998",
      VolumeIncreaseDecrease: "-998",
      Volume50DayAverage: "-998",
      RelativeVolume: "-998",
      ValueTraded: "-998",
      /*technical filters*/
      performanceoneDay: '-998',
      performanceWeek: '-998',
      performanceOneMonth: '-998',
      performanceThreeMonth: '-998',
      performanceOneYear: '-998',
      performanceYTD: '-998',
      priceVs52WeekHigh: '-998',
      priceVs50DayMA: '-998',
      priceVs200DayMA: '-998',
      ralativeStrength1M: '-998',
      ralativeStrength3M: '-998',
      ralativeStrength1Y: '-998',
      newHighLow: '-998',
      movingAverages: '-998',
      rsi14: '-998',
      bollingerBands: '-998',

      /*valuation measurs*/
      priceToEarning: '-998',
      priceToBook: '-998',
      priceToRevenue: '-998',
      priceToCashFlow: '-998',
      evtoSales: '-998',
      evtoEBIT: '-998',
      evToEBITDA: '-998',
      marketCapToEV: '-998',
      dividendYield: '-998',
      payoutRatio: '-998',
      marketCap: '-998',
      enterpriseValue: '-998',

      /*profitability */
      grossProfitMargin: '-998',
      operatingMargin: '-998',
      ebitMargin: '-998',
      ebitdaMargin: '-998',
      sellingGeneralExpenses: '-998',
      returnOnIvestedCapital: '-998',
      returnOnCapitalEmployed: '-998',
      returnOnAssets: '-998',
      returnOnEquity: '-998',
      interestMargin: '-998',
      efficiencyRatio: '-998',
      netProfitMargin: '-998',

      /*growth*/
      specialCommissionToInterestRate: '-998',
      netSpecialInterestToInterestRate: '-998',
      revenues: '-998',
      EBITDA: '-998',
      operatingIncome: '-998',
      netImcome: '-998',
      loansAndAdvances: '-998',
      totalAssets: '-998',
      deposits: '-998',
      ownersEquity: '-998'
    };


    $scope.init = function (initData) {
      $scope.stockConstModel = initData;
    }

    $scope.$watchCollection("SSInputModel", function (newValue, oldValue) {

      $timeout(() => {
        $scope.ssData = []; LoadStockScreenerData();

        var filterCount = $filter('filterCount')($scope.SSInputModel, -998);
        $scope.selectedFilters = [];

        for (var prop in $scope.SSInputModel) {

          var randId = Math.floor((Math.random() * 100000) + 1);
          if (Number($scope.SSInputModel[prop]) !== -998) {
            var name = $('.stock-screener-content1').find('select[data-model="' + prop + '"]').attr('data-name');
            $scope.selectedFilters.push({ id: randId, prop: prop, name: name });
            $('.stock-screener-content1').find('select[data-model="' + prop + '"]').addClass('ss-selected');
          } else {
            if (filterCount >= 10)
              $('.stock-screener-content1').find('select[data-model="' + prop + '"]').attr('disabled', true);
            else
              $('.stock-screener-content1').find('select[data-model="' + prop + '"]').removeAttr('disabled');
            $('.stock-screener-content1').find('select[data-model="' + prop + '"]').removeClass('ss-selected');
          }
        }
      });
    });

    function LoadStockScreenerData() {
      blockUI('collapseOne');
      $scope.ssLoading = true;
      $http({
        url: siteRoot + 'screener/getstockscreeneroutputdata',
        data: $scope.SSInputModel,
        method: 'POST',
      })
        .then(function (res) {
          $scope.ssData = res.data.data;
        }, (error) => { unblockUI('collapseOne'); console.log(error.data); })
        .finally(function () {
          unblockUI('collapseOne');
          $scope.ssLoading = false;
          ProcessssPaginatedData();
          //$('.table-fixedHeader').stickyTableHeaders('destroy');
          //angular.element($window).bind("scroll", function (e) {
          //	$(".table-fixedHeader").stickyTableHeaders({ fixedOffset: $('#fullHeader') });
          //});

        });
    }
    //ss pagination
    $scope.totalItems = $scope.ssData.length;
    $scope.currentPage = 1;
    $scope.itemsPerPage = $scope.noRecordsToView;
    $scope.maxSize = 5; //Number of pager buttons to show

    $scope.setPage = function (pageNo) {
      $scope.currentPage = pageNo;
    };
    $scope.setItemsPerPage = function (num) {
      $scope.itemsPerPage = num;
      $scope.currentPage = 1; //reset to first paghe
    }

    /**Sorting*/
    //companies view sorting
    $scope.wSort = {
      column: 'Ticker',
      descending: false
    };

    $scope.wClass = function (column) {
      return column === $scope.wSort.column ? $scope.wSort.descending ? "sorting_asc" : "sorting_desc" : 'sorting';
    };
    $scope.wChange = function (column) {

      if ($scope.wSort.column === column) {
        $scope.wSort.descending = !$scope.wSort.descending;
      } else {
        $scope.wSort.column = column;
        $scope.wSort.descending = false;
      }
      ProcessssPaginatedData();
    };
    $scope.$watch("currentPage", function (newValue, oldValue) {
      ProcessssPaginatedData();
    })
    function ProcessssPaginatedData() {
      $scope.PaginatedData = $filter('orderBy')($scope.ssData, $scope.wSort.column, $scope.wSort.descending);
      if ($scope.PaginatedData !== undefined)
        $scope.PaginatedData = $scope.PaginatedData.slice((($scope.currentPage - 1) * $scope.itemsPerPage), (($scope.currentPage) * $scope.itemsPerPage));

    }
    $scope.pagerInfo = function () {
      let pagerHtml = '';
      let startOfRecord = (($scope.currentPage - 1) * $scope.itemsPerPage) + 1;
      let endOfRecord = ($scope.currentPage) * $scope.itemsPerPage;
      endOfRecord = endOfRecord > $scope.ssData.length ? $scope.ssData.length : endOfRecord;
      return $filter('getLabel')('lblShowing') + ': ' + startOfRecord + ' ' + $filter('getLabel')('lblTo') + ' ' + endOfRecord + ' ' + $filter('getLabel')('lblof') + ' ' + $scope.ssData.length;
    }
    $scope.resetFilters = function (r, $event) {
      $scope.selectedFilters = $.grep($scope.selectedFilters, (filter) => { return filter.name !== r.name; });
      $scope.SSInputModel[r.prop] = "-998";
    }
    $scope.resetAll = function (obj) {
      $timeout(() => {
        Object.getOwnPropertyNames($scope.SSInputModel).forEach(function (prop) {
          $scope.SSInputModel[prop] = "-998";
        });

      });
      angular.element(document.getElementsByClassName('btn-ss-filter')).trigger('click');
    }
  }])
  .controller('advancedScreenerCtrl', ['$scope', '$http', '$q', '$filter', "$timeout", '$window', '$compile', function ($scope, $http, $q, $filter, $timeout, $window, $compile) {
    $scope.langId = parseInt(lang);
    $scope.working = false;
    $scope.screenerData = {};
    $scope.inputDataModel = {
      datePeriod: 0,
      isOfficial: true,
      currencyId: '1',
      stockMarketId: '1',
      sectors: [],
      selectedSectors: [],
      sectorsInSelection: [],
      selectedsectorsInSelection: [],
      selectedRatios: [{ GBFactID: 6177, GBFactRatioID: 0 }, { GBFactID: 6168, GBFactRatioID: 0 }]
    };
    $scope.addedFilters = [];
    $scope.inputData = {};
    $scope.screenerViewData = [];
    $scope.companiesData = [];
    $scope.originalFilterData = [];
    $scope.ratiosData = [];
    
    loadInputData().then((res) => { 
        $timeout(() => {      
        var elems = document.querySelectorAll('.mv-switch');
        elems.forEach(function (elem) {
          var switchery = new Switchery(elem, { color: '#7BAEBF', secondaryColor: '#567A86', jackColor: '#fff', jackSecondaryColor: '#eee', size: 'small' });
        });

          let ticks_labels = [$filter('getLabel')('lblLatest')];
          let ticks_years = [0];
      $scope.inputData.yearsArray.map((el,index) => {
        ticks_labels.push(`${el}`);
        ticks_years.push(index+1)
          });
        var slider = new Slider("#dates-range", {
        rtl: true,
          ticks: ticks_years,
          ticks_labels: ticks_labels,
        ticks_tooltip: false,
        value: $scope.inputDataModel.datePeriod
      });

          $scope.$watch('inputDataModel.isOfficial', function (newValue, oldValue) {
            if (newValue !== oldValue) {
              $timeout(() => { 
              if (newValue)
                $scope.inputDataModel.stockMarketId = '1';
              else
                $scope.inputDataModel.stockMarketId = '0';

                $scope.inputDataModel.sectorsInSelection = [];
                $scope.inputDataModel.selectedRatios = [{ GBFactID: 6177, GBFactRatioID: 0 }, { GBFactID: 6168, GBFactRatioID: 0 }];
              loadInputData().then((res) => { loadCompaniesData('is official'); });
              });//
            }
          });
          $scope.$watch('inputDataModel.sectorsInSelection', (newValue, oldValue) => {
            if (newValue.length !== oldValue.length) {
              loadCompaniesData('sectors in selection');
            }
          });
          $scope.$watch('inputDataModel.datePeriod', function (newValue, oldValue) {
            if (newValue !== oldValue) {
              $scope.inputDataModel.selectedRatios = [{ GBFactID: 6177, GBFactRatioID: 0 }, { GBFactID: 6168, GBFactRatioID: 0 }];
              loadCompaniesData('dateperiod');
            }
          });
          $scope.$watch('inputDataModel.currencyId', function (newValue, oldValue) {
            if (newValue !== oldValue) {
              loadCompaniesData('currency id');
            }
          });
          $scope.$watch('inputDataModel.selectedRatios', function (newValue, oldValue) {
            if (newValue !== oldValue) {

            }
          });
    });
    });
   
    $scope.pushSelectedItems = ((actionType) => {
      switch (actionType) {
        case 'allRight':
          $.map($scope.inputData.sectors, (el) => {
            if (el.StockMarketID === parseInt($scope.inputDataModel.stockMarketId)) $scope.inputDataModel.sectorsInSelection.push(el);
          }).uniqueArray();
          $scope.inputDataModel.sectors = [];
          $scope.inputDataModel.selectedSectors = [];
          break;
        case 'selectedRight':
          if ($scope.inputDataModel.selectedSectors.length > 0) {
            $.map($scope.inputDataModel.sectors, (el) => {
              if ($scope.inputDataModel.selectedSectors.indexOf(el.Key) !== -1) $scope.inputDataModel.sectorsInSelection.push(el);
            }).uniqueArray();
          }
          $scope.inputDataModel.sectors = $.grep($scope.inputDataModel.sectors, (el) => { if ($scope.inputDataModel.selectedSectors.indexOf(el.Key) === -1) return el; }).clean();
          $scope.inputDataModel.selectedSectors = [];
          break;
        case 'selectedLeft':
          if ($scope.inputDataModel.selectedsectorsInSelection.length) {
            $scope.inputDataModel.sectorsInSelection.map((el) => {
              if (el.StockMarketID === parseInt($scope.inputDataModel.stockMarketId)
                && $scope.inputDataModel.selectedsectorsInSelection.indexOf(el.Key) !== -1) {
                $scope.inputDataModel.sectors.push(el);
              }
            });
          }
          $scope.inputDataModel.sectorsInSelection = $.grep($scope.inputDataModel.sectorsInSelection, (el) => { return $scope.inputDataModel.selectedsectorsInSelection.indexOf(el.Key) === -1 ? el : undefined }).clean();

          $scope.inputDataModel.selectedsectorsInSelection = [];
          break;
        case 'allLeft':
          if ($scope.inputDataModel.sectorsInSelection.length) {
            $scope.inputDataModel.sectorsInSelection.map((el) => {
              if (el.StockMarketID === parseInt($scope.inputDataModel.stockMarketId)) {
                $scope.inputDataModel.sectors.push(el);
              }
            });
          }
          $scope.inputDataModel.sectorsInSelection = []
          $scope.inputDataModel.selectedsectorsInSelection = [];
          break;
      };
      resetAddedFilters();
      loadCompaniesData('selected items change');
    });

    $scope.toggleExpand = ((key, $event) => {
      $('.dropdown-menu').on({
        "click": function (e) {
          e.stopPropagation();
        }
      });
      if ($('table tr[data-key="' + key + '"]').hasClass('hidden')) {
        $('table tr[data-key="' + key + '"]').removeClass('hidden', 300).fadeIn();
        $($event.target).closest('th').find('i').removeClass('fa-plus-square-o').addClass('fa-minus-square-o');
      } else {
        $('table tr[data-key="' + key + '"]').addClass('hidden', 300).fadeOut();
        $($event.target).closest('th').find('i').removeClass('fa-minus-square-o').addClass('fa-plus-square-o');
      }
    });

    $scope.toggleGrowthExpand = ((key, $event) => {
      let that = $event.currentTarget;
      $('.dropdown-menu').on({
        "click": function (e) {
          e.stopPropagation();
        }
      });
    
      if ($(that).closest('span').next('table').hasClass('hidden')) {
        $(that).closest('span').next('table').removeClass('hidden', 300).fadeIn();
        $(that).closest('span').find('i').removeClass('fa-plus').addClass('fa-minus');
      } else {
        $(that).closest('span').next('table').addClass('hidden', 300).fadeOut();
        $(that).closest('span').find('i').removeClass('fa-minus').addClass('fa-plus');
      }
    });


    $scope.addRemoveRatioFromFilter = ((obj, $event) => {
      var thisRatio = $scope.inputDataModel.selectedRatios.map((el) =>
                    { if (el.GBFactID === obj.GBFactID && el.GBFactRatioID === obj.GBFactRatioID) return el; }).clean();
      if (thisRatio.length===0) {
        if ($scope.inputDataModel.selectedRatios.length < 10) {
          $scope.inputDataModel.selectedRatios.push({ GBFactID: obj.GBFactID, GBFactRatioID: obj.GBFactRatioID });
          loadRatiosData(obj.GBFactID,obj.GBFactRatioID);
        } else {
          $.notify({
            message: "<h5>At most 10 ratios can be selected.</h5>",
          });
        }
      }
      else {
        $scope.inputDataModel.selectedRatios =
          $.grep($scope.inputDataModel.selectedRatios, (el) =>
              { if (!(el.GBFactID === obj.GBFactID && el.GBFactRatioID === obj.GBFactRatioID)) return el; }).clean();
        $scope.addedFilters = $.grep($scope.addedFilters, (el) =>
              { if (!(el.GBFactID === obj.GBFactID && el.GBFactRatioID === obj.GBFactRatioID)) return el; }).clean();
               
        $scope.ratiosData = $scope.ratiosData.clean().map((el) =>
              { if (!(el.GBFactID === obj.GBFactID && el.GBFactRatioID === obj.GBFactRatioID)) return el; }).clean();
        
        ProcessDataForFilters(obj.GBFactID).then((resp) => { });
      }
      
    });    

    $scope.setSliderValue = ((obj, r, minMax) => {
     
      let sliderId = `#slider${r.GBFactID}${r.GBFactRatioID}`;
      let inputVal = parseFloat(obj.currentTarget.value.replaceAll(',', ''));
      inputVal = inputVal < parseFloat(r.Floor) ? r.Floor : inputVal >= parseFloat(r.Ceil) ? parseFloat(r.Ceil) : inputVal;

        let outputIndexVal = r.TicksArray.map((el) => { if (parseFloat(el.value.toFixed()) >= inputVal) return el.index; }).clean().sortAsc().firstOrDefault();

      if (outputIndexVal !== undefined) {
        $timeout(() => {
          if (minMax === 'min') {
           
            outputIndexVal = outputIndexVal < parseFloat(r.SFloor) || outputIndexVal > parseFloat(r.SCeil) ? parseFloat(r.SFloor) : outputIndexVal;
            $(sliderId).slider('values', 0, outputIndexVal);
            $scope.addedFilters = $scope.addedFilters.map((el) => { if (el.GBFactID === r.GBFactID && el.GBFactRatioID === r.GBFactRatioID) el.SIndex = outputIndexVal; return el; });
          }
          if (minMax === 'max') {
            outputIndexVal = outputIndexVal > parseFloat(r.SCeil) ? parseFloat(r.SCeil) : outputIndexVal;
            $(sliderId).slider('values', 1, outputIndexVal);
            $scope.addedFilters = $scope.addedFilters.map((el) => { if (el.GBFactID === r.GBFactID && el.GBFactRatioID === r.GBFactRatioID) el.MaxIndex = outputIndexVal; return el;});
          }
          obj.currentTarget.value = $filter('number')(inputVal,2);

          $timeout(() => { 
            ProcessDataForFilters(r.GBFactID).then((resp) => {
              $scope.addedFilters.map((el) => {
                if (el.GBFactID === r.GBFactID && el.GBFactRatioID === r.GBFactRatioID) {
                  //console.log(el.SIndex, el.MaxIndex);
                }
              });
            });
          });
        });
      }
    });

    $scope.createSlider = ((r) => {
      let sliderId = `#slider${r.GBFactID}${r.GBFactRatioID}`;
      let ticks = r.TicksArray.map((el) => { return el.value; }).clean();
      $timeout(() => { 
        
        $(sliderId).slider({
          range: true,
          min: r.SFloor,
          max: r.SCeil,
          values: [r.MinIndex, r.MaxIndex],
          slide: function (event, ui) {           
            let lowValue = parseFloat(ticks[ui.values[0]]);
            let highValue = parseFloat(ticks[ui.values[1]]);
            $timeout(() => {
              $(`#txtMin${r.GBFactID}${r.GBFactRatioID}`).val($filter('WNOrDec')(lowValue,2));
              $(`#txtMax${r.GBFactID}${r.GBFactRatioID}`).val($filter('WNOrDec')(highValue, 2));

              $scope.addedFilters.map((el) => { if (el.GBFactID === r.GBFactID && el.GBFactRatioID === r.GBFactRatioID) el.SIndex = ui.values[0]; });
              $scope.addedFilters.map((el) => { if (el.GBFactID === r.GBFactID && el.GBFactRatioID === r.GBFactRatioID) el.MaxIndex = ui.values[1]; });
            }, 100);
        },
        change: function (event, ui) { },
        start: function (event, ui) { },
          stop: function (event, ui) { 
            blockUI('filters-wrapper');
          $timeout(() => {            
            ProcessDataForFilters(r.GBFactID).then((resp) => {
            });
          }, 100);
        }
      });
});

    });
        
    $scope.exportData = function ($event) {
        var $table = $('table.table-tablesorter');
        $table.trigger('outputTable');
    };

    $scope.resetScreener = (() => {
      var addedFilters = angular.copy($scope.addedFilters);
      $scope.addedFilters = [];
      addedFilters.map((filter) => {     
        filter.SIndex = filter.MinIndex;
        filter.MaxIndex = filter.TicksArray.length - 1;
        $scope.addedFilters.push(filter);
      });
      
      $scope.screenerViewData = angular.copy($scope.companiesData);
      createSorter();
    });

    function loadInputData() {      
      let retPromise = new Promise((resolve, reject) => {
        try {
          resetAddedFilters();          
          blockUI('ads-wrapper');
          $http({
            method: 'POST',
            url: siteRoot + 'screener/AdvancedScreener'
          }).then((res) => {
            $scope.inputData = res.data;
          }).catch((ex) => {
            unblockUI('ads-wrapper');
          }).finally(() => {
            $scope.$watch('inputDataModel.stockMarketId', function (newValue, oldValue) {
              if (!$scope.inputData.sectors) return;
              $scope.inputDataModel.sectors = $.grep($scope.inputData.sectors, (el) => {
                if (el.StockMarketID === parseInt($scope.inputDataModel.stockMarketId)) {
                  if ($scope.inputDataModel.sectorsInSelection.length > 0) {
                    if ($scope.inputDataModel.sectorsInSelection.map((el) => { return el.Key; }).indexOf(el.Key) === -1)
                      return el;
                  } else {
                    return el;
                  }
                }
              }).clean();
            }, true);
            resolve('true');
            $scope.pushSelectedItems('allRight');
          });
        } catch (e) {
          reject(e);
        }
      });
      return retPromise;
    };

    function loadCompaniesData(type) { 
     
      if (type === 'is official' || type ==='sectors in selection') return;
      resetAddedFilters();  
      if ($scope.inputDataModel.sectorsInSelection.length === 0) {
        return;
      }
      blockUI('ads-wrapper');
      $http({
        method: 'POST',
        url: siteRoot + 'screener/advancedscreenerdata',
        data: {
          CurrencyID: $scope.inputDataModel.currencyId,
          StockSectorPairs: $scope.inputDataModel.sectorsInSelection.map((el) => {return { StockMarketID: el.StockMarketID, SectorID: el.SectorID }; }),  
          Ratios: $scope.inputDataModel.selectedRatios.map((el) => { return el.GBFactID; }),
          Year: $scope.inputDataModel.datePeriod>0? $scope.inputData.yearsArray[parseInt($scope.inputDataModel.datePeriod)-1]:0,
          IsOfficial: $scope.inputDataModel.isOfficial?1:0,
          flag: 1
        }
      }).then((res) => {  
        $scope.postedYear = parseInt(res.data.Year);
        $scope.companiesData = res.data.companiesData;
        $scope.ratiosData = res.data.ratiosData;
        res.data.filterModel.map((filter) => { $scope.addedFilters.push(filter); });
        $scope.screenerViewData = res.data.companiesData;
        $scope.originalFilterData = angular.copy($scope.addedFilters);   
      }).catch((ex) => {
        unblockUI('ads-wrapper');
      }).finally(() => {
        unblockUI('ads-wrapper');
        createSorter();
      });
    }

    function loadRatiosData(GBFactID, GBFactRatioID) {     
      if ($scope.companiesData.length === 0) return;
      if ($scope.companiesData.length===0|| $scope.inputDataModel.sectorsInSelection.length === 0) {
        $.notify({
          message: "<h5>No sector selected.</h5>",
        });
        return;
      }
        blockUI('ads-wrapper');
      $http({
        method: 'POST',
        url: siteRoot + 'screener/advancedscreenerdata',
        data: {
          CurrencyID: $scope.inputDataModel.currencyId,
          StockSectorPairs: $scope.inputDataModel.sectorsInSelection.map((el) => { return { StockMarketID: el.StockMarketID, SectorID: el.SectorID }; }), 
          Ratios: GBFactID ? GBFactID : $scope.inputDataModel.selectedRatios.map((el) => { return el.GBFactID; }),
          GBFactRatioID:GBFactRatioID,
          Year: $scope.inputDataModel.datePeriod > 0 ? $scope.inputData.yearsArray[parseInt($scope.inputDataModel.datePeriod)-1] : 0,
          IsOfficial: $scope.inputDataModel.isOfficial?1:0,
          flag: 2
        }
      }).then((res) => {
        $scope.postedYear = parseInt(res.data.Year);
        res.data.filterModel.map((filter) => {
          $scope.addedFilters.push(filter);
          $scope.originalFilterData.push(filter);
        });
        $scope.originalFilterData 
        let filterRatios = res.data.ratiosData;
        filterRatios.map((elRatio) => { $scope.ratiosData.push(elRatio); });

        $scope.companiesData = $scope.companiesData.map((cd) => {
          var gbfact = filterRatios.map((fr) => { if (fr.CompanyID === cd.CompanyID) return fr; }).clean().firstOrDefault();
          if (typeof (gbfact) !== 'function' && cd.GBFacts.map((gbf) => { if (gbf.GBFactID === gbfact.GBFactID && gbf.GBFactRatioID === gbfact.GBFactRatioID) return gbf; }).clean().length===0) {
            cd.GBFacts.push(gbfact);
          }
            
          return cd;
        }).clean();

        filterRatios = null;
      }).catch((ex) => {
        unblockUI('ads-wrapper');
      }).finally(() => {
        unblockUI('ads-wrapper');
        createSorter();
      });
    }
   
    function ProcessDataForFilters(GBFactID) {
      var retPromise = new Promise((resolve, reject) => {
        try {
          if (GBFactID) {
            $scope.companiesData.map((el) => {
              let factsInFilter = el.GBFacts.map((tf) => {
                return $scope.addedFilters.map((ff) => { if (ff.GBFactID === tf.GBFactID && ff.GBFactRatioID === tf.GBFactRatioID) return tf; }).clean().length>0? tf:undefined;              
              }).clean();

              let ratiosForCompany = factsInFilter.uniqueArray().map((f) => {
                let filter = $scope.addedFilters.map((elFilter) => { if (elFilter.GBFactID === f.GBFactID && elFilter.GBFactRatioID === f.GBFactRatioID) return elFilter; }).clean().firstOrDefault();
                
                if (typeof (filter) === 'object') {
                  let filterValue = filter.TicksArray[filter.SIndex].value;
                  let filterHighValue = filter.TicksArray[filter.MaxIndex].value;                  
                  if (f.Value >= filterValue && f.Value <= filterHighValue) {
                    return f;
                  }
                } else {
                  return undefined;
                }
              }).clean(); 
            
              if (ratiosForCompany.length === $scope.addedFilters.uniqueArray().length) {
                if ($scope.screenerViewData.map((svd) => { if (svd && svd.CompanyID === el.CompanyID) return svd; }).clean().length === 0) {
                  $scope.screenerViewData.push({
                    CompanyID: el.CompanyID,
                    Company: el.Company,
                    Ticker: el.Ticker,
                    Company_URL: el.Company_URL,
                    Price: el.Price,
                    Change: el.Change,
                    ChangePer: el.ChangePer,
                    GBFacts: ratiosForCompany
                  });
                }
              } else {
                $scope.screenerViewData = $scope.screenerViewData.map((svd) => { if (svd && svd.CompanyID !== el.CompanyID) return svd; }).clean();
              }
            })           
          }
          else {
            $scope.companiesData.map((bel) => {
              let bRatiosForCompany = bel.GBFacts.map((bf) => {
                let bFilter = $scope.addedFilters.map((belFilter) => { if (belFilter.GBFactID === bf.GBFactID && belFilter.GBFactRatioID === bf.GBFactRatioID) return belFilter; }).clean().firstOrDefault();
                let bFilterValue = bFilter.TicksArray[bFilter.SIndex].value;
                let bFilterHighValue = bFilter.TicksArray[bFilter.MaxIndex].value;
                if (bf.Value >= bFilterValue && bf.Value <= bFilterHighValue) {
                  return bf;
                }
              }).clean();
              if (bRatiosForCompany.length === $scope.addedFilters.length) {
                $scope.screenerViewData.push({
                  CompanyID: bel.CompanyID,
                  Company: bel.Company,
                  Ticker: bel.Ticker,
                  Company_URL: bel.Company_URL,
                  Price: bel.Price,
                  Change: bel.Change,
                  ChangePer: bel.ChangePer,
                  GBFacts: bRatiosForCompany
                });
              }
            });
          }

          resolve('resolved');
        } catch (e) {
          reject(e);
        } finally {
          unblockUI('filters-wrapper');
            createSorter();
        }
      });
      return retPromise;
    }
    
    function createSorter() {     
      $("#screenerTable").trigger("destroy");
      $timeout(() => {
        $("#screenerTable").tablesorter({
          textExtraction: function (node) {
            var attr = $(node).attr('data-order');
            if (typeof attr !== 'undefined' && attr !== false) {
              return attr;
            }
            return $(node).text();
          },
          theme: 'blue',
          widgets: ['zebra', 'output'],
          widgetOptions: {
            output_delivery: 'd',
            output_separator: ',',
            output_saveFileName: 'AdvancedScreenerReport.csv'
          },
          sortList: [[2, 1]],
          onRenderHeader: function (index) {
            $(this).find('p.remove-filter-header-link').on('click', function (e) {
              e.stopPropagation();
              let linkElem = $(this).find('span');           
              if (linkElem) {
               
                let addedFilter = $scope.addedFilters.map((el) => { if (el.GBFactID === parseInt($(linkElem).data('gbfactid')) && el.GBFactRatioID === parseInt($(linkElem).data('gbfactratioid'))) return el; }).clean().firstOrDefault();
                if (addedFilter && addedFilter.GBFactID > 0) {
                  $timeout(() => { $scope.addRemoveRatioFromFilter(addedFilter, undefined); createSorter(); });
                }
              }
              
            });
          },
        }).bind("sortStart", function (e, t) {      
          //debugger;
        })
          .bind("sortEnd", function (e, t) {

          });;
        
      });
    };

    function resetAddedFilters() {
      $("#screenerTable").trigger("destroy");      
      $scope.addedFilters = [];
      $scope.screenerViewData = [];
      $scope.companiesData = [];
      $scope.ratiosData = [];
    }
  }])

  ;