$(document).ready(function(){
	var _speed = 100;
	var check_speed = 15000;
	var _numb, n_numb;
	var _step = 23;
	var _hold = $('#counter');
	var _f = false;
	if(_hold.length){
		_hold.html('<div></div><div></div><div></div><div></div><div></div><div></div>');
		var _list = _hold.children();
		
		$.ajax({
			url: 'http://fadderskap.plan-norge.no/gi-ditt-ansikt/counter/init',
			dataType: 'text',
			success: function(_val){
				_numb = parseInt(_val);
				if(!isNaN(_numb)){
					for(var i = 0; i < _list.length; i++){
						_list.get(i)._n = _numb%10*3;
						_numb = Math.floor(_numb/10);
						_list.eq(i).css('top', -_list.get(i)._n*_step);
					}
					_numb = _val;
					_f = true;
					setTimeout(function(){
						updateNumb();
					}, check_speed);
				}
			}
		});
	}
	
	function updateNumb(){
		$.ajax({
			url: 'http://fadderskap.plan-norge.no/gi-ditt-ansikt/counter/update',
			dataType: 'text',
			success: function(_val){
				n_numb = parseInt(_val);
				if(n_numb != _numb && !isNaN(n_numb)){
					if(_f){
						_f = false;
						moveFirst();
					}
				}
				setTimeout(function(){
					updateNumb();
				}, check_speed);
			}
		});
	}
	
	function moveFirst(){
		setTimeout(function(){
			if(_list.get(0)._n < 29) _list.get(0)._n++;
			else{
				_list.get(0)._n = 0;
				moveSecond(1);
			}
			_list.eq(0).css('top', -_list.get(0)._n*_step);
			setTimeout(function(){
				if(_list.get(0)._n < 29) _list.get(0)._n++;
				else{
					_list.get(0)._n = 0;
					moveSecond(1);
				}
				_list.eq(0).css('top', -_list.get(0)._n*_step);
				setTimeout(function(){
					if(_list.get(0)._n < 29) _list.get(0)._n++;
					else{
						_list.get(0)._n = 0;
						moveSecond(1);
					}
					_list.eq(0).css('top', -_list.get(0)._n*_step);
					_numb++;
					if(_numb < n_numb) moveFirst();
					else _f = true;
				}, _speed);
			}, _speed);
		}, _speed);
	}
	function moveSecond(_i){
		setTimeout(function(){
			if(_list.get(_i)._n < 29) _list.get(_i)._n++;
			else{
				_list.get(_i)._n = 0;
				if(_i < 5) moveSecond(_i + 1);
			}
			_list.eq(_i).css('top', -_list.get(_i)._n*_step);
			setTimeout(function(){
				if(_list.get(_i)._n < 29) _list.get(_i)._n++;
				else{
					_list.get(_i)._n = 0;
					if(_i < 5) moveSecond(_i + 1);
				}
				_list.eq(_i).css('top', -_list.get(_i)._n*_step);
				setTimeout(function(){
					if(_list.get(_i)._n < 29) _list.get(_i)._n++;
					else{
						_list.get(_i)._n = 0;
						if(_i < 5) moveSecond(_i + 1);
					}
					_list.eq(_i).css('top', -_list.get(_i)._n*_step);
				}, _speed);
			}, _speed);
		}, _speed);
	}
});
