$(document).ready(function () {
	CategoryProductCount.init();
});


var CategoryProductCount = {
	_debug: {},
	apiUrl: "http://www.koimarket.com/servlet/Products",
	links: new Array(),
	i: 0,
	
	
	init: function(){
		CategoryProductCount.getLinks();
		CategoryProductCount.delayedRequest();
	},
	
	
	
	getLinks: function(){
		$('a').each(function(linkIndex, link){ 
			if(link.lang != ''){				
				CategoryProductCount.links[CategoryProductCount.links.length] = link;
			}
		});
	},
	
	
	
	//prevents 403 Error from Tomcat [Too many requests per second]
	delayedRequest: function(){
		if (!(CategoryProductCount.i >= 0)) {
			CategoryProductCount.i = 0;
		}
		
		setTimeout((function(){
			
			return function(){
				var interval = 1;
				
				//if we have not exceeded the array length continue calling the delayedRequest function
				if(CategoryProductCount.i < CategoryProductCount.links.length){
					CategoryProductCount.delayedRequest();
				}
				
				
				$.each(CategoryProductCount.links, function(linkIndex, link){ 
					
					//get links within batch
					if(linkIndex >= CategoryProductCount.i && linkIndex < CategoryProductCount.i + interval){
						CategoryProductCount.getSubCategoryCount(link);
					}
				});
				
				CategoryProductCount.i += interval;
			}
		})(CategoryProductCount.links[CategoryProductCount.i]), 400);
		
	},
	
	
	
	getSubCategoryCount: function(e){
		//Build storefront API url with subcategory.parentChainDisplay (stored in .lang attribute of element)
		var url = CategoryProductCount.apiUrl + "?category=" + e.lang;
		
		CategoryProductCount._debug[e.lang] = url;
		
		//Post URL to storefront API and get results -> store JSON data in the products object
		$.get(
			url, 
			function(data, textStatus) {
				
				//prepare response string for JSON -> remove block comment
				responseString = data.replace(/\/\*.+\*\//g, '');
				
				// this will give us an array of objects
				//var productData = JSON.parse(responseString);
				var productData = $.parseJSON(responseString);
				
				var products = new Array();
				products = productData.echo;
				
				//place returned total in subCategoryCount element
				$(e).append(' <span>(' + products.total + ')</span>');			
			}, 
		'text');
	}
}
