$(document).ready(function(){
	
	// Customisable -----
	prod_per_page = 8;
	
	// Static       -----
	cur_prod_page = 1;
	max_prod_page = 0;
	page_has_products = true;
	cur_prod_hash = parseInt(window.location.hash.replace('#',''));
	
	// Functions   -----
	
	function update_prod_page(){
		
		if(page_has_products){
			window.location.hash = cur_prod_page;
		}
		
		list_ids_start = ((cur_prod_page*prod_per_page)-prod_per_page)+1;
		list_ids_end = cur_prod_page*prod_per_page;
		
		$(".plistprod").each(function(){
			fixed_id = parseInt($(this).attr('id').replace('plp',''));
			if((fixed_id < list_ids_start) || (fixed_id > list_ids_end)){
				$(this).hide();
			} else {
				$(this).show();
			}
		});
		
		$(".plistpageg").each(function(){
			if(parseInt($(this).attr('rel')) == cur_prod_page){
				$(this).addClass('plistpagega');
			} else {
				$(this).removeClass('plistpagega');
			}
		});
	}
	
	function check_prod_hash(){
		new_hash = parseInt(window.location.hash.replace('#',''));
		
		if(new_hash != cur_prod_hash){
			cur_prod_page = new_hash;
			update_prod_page();
		} else {
			return;
		}
		
	}
	
	function build_prod_pages(){
		max_prod_page = Math.ceil(parseInt($(".plistprod").length)/prod_per_page);
		if(max_prod_page <= 1){
			if(max_prod_page == 0){
				page_has_products = false;	
			}
			$("#plistpage").hide();
			return;
		}
		for(z=1;z<=max_prod_page;z++){
			if(z == cur_prod_page){
				$("#plistpages").append('<a class="plistpageg plistpagega" rel="'+z+'" href="javascript:void(0)">'+z+'</a>&nbsp;&nbsp;');
			} else {
				$("#plistpages").append('<a class="plistpageg" rel="'+z+'" href="javascript:void(0)">'+z+'</a>&nbsp;&nbsp;');
			}
		}
	
		$(".plistpageg").each(function(){
			if($(this).attr('rel') == ''){ return; }
			$(this).click(function(){
				cur_prod_page = parseInt($(this).attr('rel'));
				update_prod_page();
			})
		})

	}
	
	$("#pageFwd").each(function(){
		$(this).click(function(){
			if(cur_prod_page == max_prod_page){ return; }
			cur_prod_page = cur_prod_page + 1;
			update_prod_page();
		})
	});
	
	$("#pageBack").each(function(){
		$(this).click(function(){
			if(cur_prod_page == 1){ return; }
			cur_prod_page = cur_prod_page - 1;
			update_prod_page();
		})
	});
	
	// Init      -------
	
	build_prod_pages();
	if((cur_prod_hash >= 1) && (cur_prod_hash <= max_prod_page)){
		cur_prod_page = cur_prod_hash;
		update_prod_page();
	} else {
		update_prod_page();	
	}
	setInterval(function(){check_prod_hash()},300);
	
});
