 angular
     .module('myapp', ['algoliasearch', 'ngSanitize', 'infinite-scroll'])
     .config(function($interpolateProvider) {
         $interpolateProvider.startSymbol('[[');
         $interpolateProvider.endSymbol(']]');
     })
	.filter('isEmpty', function () {
        var bar;
        return function (obj) {
            for (bar in obj) {
                if (obj.hasOwnProperty(bar)) {
                    return false;
                }
            }
            return true;
        };
    })
	.filter('objLength', function() {
		return function(object) {
		var count = 0;

		for(var i in object){
			count++;
		}
		return count;
		}
	})
	.directive('customScroll', function ($log) {
    return {
        restrict: 'A',
        scope: {
            config: '&customScroll'
        },
        link: function postLink(scope, iElement, iAttrs, controller, transcludeFn) {
            var config = scope.config();
            $log.debug('config: ', config);
            // create scroll elemnt
            var elem = iElement.mCustomScrollbar({
                autoHideScrollbar: true,
                theme: 'dark',
                advanced: {
                    updateOnImageLoad: true
                },
                scrollButtons: {
                    enable: true
                }
            });
            // the live options object
            var mObject = elem.data('mCS');
            $log.debug('elem: ', mObject.opt);
        }
    };
	})
 .controller('SearchCtrl', ['$scope', 'algolia', '$location','$filter', function($scope, algolia, $location,$filter) {
     $scope.query = typeof $location.search().query != 'undefined' ? $location.search().query : '';
     $scope.listViewType = 'grid';
     $scope.algoliaIndex = 'products';
	 $scope.listType = 'grid';
     $scope.page = 0;
     $scope.brands = {};
     $scope.reviewses = {};
     $scope.businesses = {};
     $scope.availabilitys = {};
     $scope.reviewses = {};
     $scope.discounts = {};
     $scope.genders = {};
     $scope.colours = {};
     $scope.idealfors = {};
     $scope.categorieses = {};
     $scope.women_clothing_categorys = {};
	 $scope.colors = {};
	 $scope.sizes = {};
	 $scope.colorsizes = {};
	 
     $scope.filterApplied = false;
     
     $scope.facets = [];
     // Replace the following values by your ApplicationID and ApiKey.
     var client = algoliasearch('QF24LY6MH8', '09921a9a308e43dfb330f243fa329939');
     // Replace the following value by the name of the index you want to query.

     $scope.$watch('query', function() {
		$scope.page = 0;
		 /* var algoliasearch = require('algoliasearch');
		 var algoliasearchHelper = require('algoliasearch-helper'); */
		

         var helper = algoliasearchHelper(client, $scope.algoliaIndex, {
             disjunctiveFacets: ['colors','color','size','colorsize','brand','business','categories','availability', 'discount', 'gender','colour','ideal-for','women-clothing-category','reviews','status'], 
         });

         helper.on('result', function(data) {
             $scope.$apply(function() {
                 $scope.nbHits = data.nbHits;
                 $scope.processingTimeMS = data.processingTimeMS;
                 $scope.products = data.hits;
				 $scope.totalPages = $scope.nbHits/20;
				 //$scope.filteredTotalPages = $filter('number')($scope.totalPages, 0);
				 $scope.totalPages = parseInt($scope.totalPages);
				 
				
				$scope.brand 		= $scope.find(data.disjunctiveFacets,'brand');
				$scope.reviews 		= $scope.find(data.disjunctiveFacets,'reviews');
				$scope.business		= $scope.find(data.disjunctiveFacets,'business');
				$scope.availability	= $scope.find(data.disjunctiveFacets,'availability');
				$scope.categories	= $scope.find(data.disjunctiveFacets,'categories');
				$scope.discount 	= $scope.find(data.disjunctiveFacets,'discount');
				$scope.gender 		= $scope.find(data.disjunctiveFacets,'gender');
				$scope.colour 		= $scope.find(data.disjunctiveFacets,'colour');
				$scope.color 		= $scope.find(data.disjunctiveFacets,'color');
				$scope.size 		= $scope.find(data.disjunctiveFacets,'size');
				$scope.colorsize 	= $scope.find(data.disjunctiveFacets,'colorsize');
				$scope.idealfor		= $scope.find(data.disjunctiveFacets,'ideal-for');
				$scope.women_clothing_category		= $scope.find(data.disjunctiveFacets,'women-clothing-category');
				
				
				
                 
				 


             });
         });
		 
		 helper.addDisjunctiveFacetRefinement('status', 'Active');
		 $scope.filterApplied=true;
         helper.setQuery($scope.query).setPage($scope.page).search();



     });
	 $scope.findAvg=function(data){
		 
		var avg=0;
		var index=1;
		for(x in data){
			avg+=parseInt(data[x]);
			index++;
		}
		return avg/index;
	 }
	 $scope.find=function(data, key){
		
		var fecet  =  $filter('filter')(data, {name: key}, true);
		if(fecet.length){
			return fecet[0]['data'];
		}
		else{
			return {};
		}

	 }
	 
	 $scope.clearAll=function(){
		 $scope.brands = {};
		 $scope.reviewses = {};
		 $scope.discounts = {};
		 $scope.genders = {};
		 $scope.colours = {};
		 $scope.idealfors = {};
		 $scope.women_clothing_category = {};
		 $scope.businesses = {};
		 $scope.availabilitys = {};
		 $scope.reviewses = {};
		 $scope.colors = {};
		 $scope.sizes = {};
		 $scope.colorsizes = {};
		 $scope.filter();
	 }
	 
	 
     $scope.sort = function(algoliaIndex,sortby) {
         $scope.sortby = sortby;
         $scope.algoliaIndex = algoliaIndex;
         $scope.filter();
     }
     $scope.filter = function() {
		 $scope.page = 0;
		 $scope.filterApplied=false;
         var facetFilters = [];
         var helper = algoliasearchHelper(client, $scope.algoliaIndex, {
            disjunctiveFacets: ['color','size','colorsize','brand','business','categories','availability', 'discount', 'gender','colour','ideal-for','women-clothing-category','reviews','status']
         });

         helper.on('result', function(data) {
             $scope.$apply(function() {
				 $scope.nbHits = data.nbHits;
                 $scope.processingTimeMS = data.processingTimeMS;
                 $scope.products = data.hits;
				 $scope.totalPages = $scope.nbHits/20;
				 $scope.totalPages = parseInt($scope.totalPages);
				
                $scope.brand 		= $scope.find(data.disjunctiveFacets,'brand');
                $scope.reviews 		= $scope.find(data.disjunctiveFacets,'reviews');
				$scope.business		= $scope.find(data.disjunctiveFacets,'business');
				$scope.availability	= $scope.find(data.disjunctiveFacets,'availability');
				$scope.categories	= $scope.find(data.disjunctiveFacets,'categories');
				$scope.discount 	= $scope.find(data.disjunctiveFacets,'discount');
				$scope.gender 		= $scope.find(data.disjunctiveFacets,'gender');
				$scope.colour 		= $scope.find(data.disjunctiveFacets,'colour');
				$scope.color 		= $scope.find(data.disjunctiveFacets,'color');
				$scope.size 		= $scope.find(data.disjunctiveFacets,'size');
				$scope.colorsize	= $scope.find(data.disjunctiveFacets,'colorsize');
				
				
				var sizes ={};
				var colorselected=false;
				for(x in $scope.colorsize){
					for (key in $scope.color) {
						if ($scope.colors[key]) {
							colorselected=true;
							if(x.indexOf(key)>=0){
							   var size=x.split("|");
							   sizes[size[1]]=$scope.colorsize[x];
							 }
						}
					}
				 
				}
				
				var colorz ={};
				var sizeselected=false;
				for(x in $scope.colorsize){
					for (key in $scope.size) {
						if ($scope.sizes[key]) {
							sizeselected=true;
							if(x.indexOf(key)>=0){
							   var color=x.split("|");
							   colorz[color[0]]=$scope.colorsize[x];
							 }
						}
					}
				 
				}
				if(colorselected){
					$scope.size  = sizes;
				}
				if(sizeselected){
					$scope.color  = colorz;
				}
				

				
				$scope.idealfor		= $scope.find(data.disjunctiveFacets,'ideal-for');
				$scope.women_clothing_category		= $scope.find(data.disjunctiveFacets,'women-clothing-category');
				 
				 
             });

         });

         for (key in $scope.brands) {
             if ($scope.brands[key]) {
                helper.addDisjunctiveFacetRefinement('brand', key);
				$scope.filterApplied=true;
             }
         }
		 for (key in $scope.reviewses) {
             if ($scope.reviewses[key]) {
                helper.addDisjunctiveFacetRefinement('reviews', key);
				$scope.filterApplied=true;
             }
         }
         for (key in $scope.discounts) {
             if ($scope.discounts[key]) {
                 helper.addDisjunctiveFacetRefinement('discount', key);
				 $scope.filterApplied=true;
             }
         }
		 for (key in $scope.gender) {
             if ($scope.genders[key]) {
                 helper.addDisjunctiveFacetRefinement('gender', key);
				 $scope.filterApplied=true;
             }
         }
		 for (key in $scope.colour) {
             
			 if ($scope.colours[key]) {
				 helper.addDisjunctiveFacetRefinement('colour', key);
				 $scope.filterApplied=true;
             }
         }
		 for (key in $scope.idealfor) {
             if ($scope.idealfors[key]) {
                 helper.addDisjunctiveFacetRefinement('ideal-for', key);
				 $scope.filterApplied=true;
             }
         }
		 for (key in $scope.women_clothing_category) {
             if ($scope.women_clothing_categorys[key]) {
                 helper.addDisjunctiveFacetRefinement('women-clothing-category', key);
				 $scope.filterApplied=true;
             }
         }
		 for (key in $scope.business) {
             if ($scope.businesses[key]) {
                 helper.addDisjunctiveFacetRefinement('business', key);
				 $scope.filterApplied=true;
             }

         }
		 for (key in $scope.availability) {
             if ($scope.availabilitys[key]) {
                 helper.addDisjunctiveFacetRefinement('availability', key);
				 $scope.filterApplied=true;
             }
         }
		 for (key in $scope.reviews) {
             if ($scope.reviewses[key]) {
                 helper.addDisjunctiveFacetRefinement('reviews', key);
				 $scope.filterApplied=true;
             }
         }
		 for (key in $scope.categories) {
             if ($scope.categorieses[key]) {
			     helper.addDisjunctiveFacetRefinement('categories', key);
				 $scope.filterApplied=true;
             }
         }
		 
		 for (key in $scope.color) {
             if ($scope.colors[key]) {
				 //helper.addDisjunctiveFacetRefinement('color', key);
				 for (key1 in $scope.size) {
					if ($scope.sizes[key1]) {
						helper.addDisjunctiveFacetRefinement('colorsize', key+'|'+key1);
						$scope.filterApplied=true;
					}else{
						helper.addDisjunctiveFacetRefinement('color', key);
						$scope.filterApplied=false;
					}
				 }			
             }else{
					for (key1 in $scope.size) {
						if ($scope.sizes[key1]) {
							helper.addDisjunctiveFacetRefinement('size', key1);
							$scope.filterApplied=false;
						}
					 }	
			 }
         }
		 helper.addDisjunctiveFacetRefinement('status', 'Active');
		 $scope.filterApplied=true;
		 
         helper.setQuery($scope.query).setPage($scope.page).search();


     };

     $scope.reset = function(type) {
         switch (type) {
            case 'brand':
                 $scope.brands = {};
                 break;
            case 'reviews':
                 $scope.reviewses = {};
                 break;
            case 'discount':
                 $scope.discounts = {};
                 break;
			case 'gender':
                 $scope.genders = {};
                 break;
			case 'colour':
                 $scope.colours = {};
                 break;
			case 'ideal-for':
                 $scope.idealfors = {};
                 break;
			case 'women-clothing-category':
                 $scope.women_clothing_category = {};
                 break;
			case 'business':
                 $scope.businesses = {};
                 break;
			case 'availability':
                 $scope.availabilitys = {};
                 break;
			case 'reviews':
                 $scope.reviewses = {};
                 break;
			case 'categories':
                 $scope.categorieses = {};
                 break;
			case 'color':
                 $scope.colors = {};
				 $scope.sizecolors = {};
                 break;	 
			case 'size':
                 $scope.sizes = {};
				 $scope.sizecolors = {};
                 break;	 	 
			
         }
		 $scope.filter();

     }

     $scope.filterArray = function($obj) {
         var arrKeys = Object.keys($obj);
         var t = arrKeys.map(function(obj) {
             return parseFloat(obj);
         });
         return t.sort();

     }
     $scope.infiniteScroll = function() {
         $scope.page++;
		 console.log(angular.element('#testtt').val());
        var facetFilters = [];
         var helper = algoliasearchHelper(client, $scope.algoliaIndex, {
            disjunctiveFacets: ['color','size','colorsize','brand','business','categories','availability', 'discount', 'gender','colour','ideal-for','women-clothing-category','reviews','status']
         });

         helper.on('result', function(data) {
				$scope.$apply(function() {
				$scope.nbHits = data.nbHits;
                $scope.processingTimeMS = data.processingTimeMS;
                $scope.products = ($scope.products).concat(data.hits);
                $scope.totalPages = $scope.nbHits/20; 
				$scope.totalPages = parseInt($scope.totalPages);
				
				$scope.brand 		= $scope.find(data.disjunctiveFacets,'brand');
				$scope.reviews 		= $scope.find(data.disjunctiveFacets,'reviews');
				$scope.business		= $scope.find(data.disjunctiveFacets,'business');
				$scope.availability	= $scope.find(data.disjunctiveFacets,'availability');
				$scope.categories	= $scope.find(data.disjunctiveFacets,'categories');
				$scope.discount 	= $scope.find(data.disjunctiveFacets,'discount');
				$scope.gender 		= $scope.find(data.disjunctiveFacets,'gender');
				$scope.colour 		= $scope.find(data.disjunctiveFacets,'colour');
				$scope.color 		= $scope.find(data.disjunctiveFacets,'color');
				$scope.size 		= $scope.find(data.disjunctiveFacets,'size');
				$scope.colorsize	= $scope.find(data.disjunctiveFacets,'colorsize');
				
				$scope.idealfor		= $scope.find(data.disjunctiveFacets,'ideal-for');
				$scope.women_clothing_category		= $scope.find(data.disjunctiveFacets,'women-clothing-category');
                 

             });

         });

         for (key in $scope.brands) {
             if ($scope.brands[key]) {
                 helper.addDisjunctiveFacetRefinement('brand', key);
             }
         }
		 for (key in $scope.reviewses) {
             if ($scope.reviewses[key]) {
                 helper.addDisjunctiveFacetRefinement('reviews', key);
             }
         }
         for (key in $scope.discounts) {
             if ($scope.discounts[key]) {
                 helper.addDisjunctiveFacetRefinement('discount', key);
             }
         }
		 for (key in $scope.gender) {
             if ($scope.genders[key]) {
                 helper.addDisjunctiveFacetRefinement('gender', key);
             }
         }
		for (key in $scope.colour) {
             if ($scope.colours[key]) {
                 helper.addDisjunctiveFacetRefinement('colour', key);
             }
         }
		 for (key in $scope.idealfor) {
             if ($scope.idealfors[key]) {
                 helper.addDisjunctiveFacetRefinement('ideal-for', key);
             }
         }
		 for (key in $scope.women_clothing_category) {
             if ($scope.women_clothing_categorys[key]) {
                 helper.addDisjunctiveFacetRefinement('women-clothing-category', key);
             }
         }
		 for (key in $scope.business) {
             if ($scope.businesses[key]) {
                 helper.addDisjunctiveFacetRefinement('business', key);
             }
         }
		 for (key in $scope.availability) {
             if ($scope.availabilitys[key]) {
                 helper.addDisjunctiveFacetRefinement('availability', key);
             }
         }
		 for (key in $scope.reviews) {
             if ($scope.reviewses[key]) {
                 helper.addDisjunctiveFacetRefinement('reviews', key);
             }
         }
		 for (key in $scope.categories) {
             if ($scope.categorieses[key]) {
                 helper.addDisjunctiveFacetRefinement('categories', key);
             }
         }
		 for (key in $scope.color) {
             if ($scope.colors[key]) {
                 helper.addDisjunctiveFacetRefinement('color', key);
             }
         }
		 
		 for (key in $scope.color) {
             if ($scope.colors[key]) {
				 //helper.addDisjunctiveFacetRefinement('color', key);
				 for (key1 in $scope.size) {
					if ($scope.sizes[key1]) {
						helper.addDisjunctiveFacetRefinement('colorsize', key+'|'+key1);
						$scope.filterApplied=true;
					}else{
						helper.addDisjunctiveFacetRefinement('color', key);
						$scope.filterApplied=false;
					}
				 }			
             }else{
					for (key1 in $scope.size) {
						if ($scope.sizes[key1]) {
							helper.addDisjunctiveFacetRefinement('size', key1);
							$scope.filterApplied=false;
						}
					 }	
			 }
         }

		 helper.addDisjunctiveFacetRefinement('status', 'Active');
		 
		 
         helper.setQuery($scope.query).setPage($scope.page).search();
     }




 }]);