$(function(){
	var lvlCount, lvlWidths, currentLvl, score;
	
	var init = function(){
		lvlCount = 5;
		lvlWidths = new Array();
		for(i = 0; i < lvlCount; i++){
			var w = Math.floor(Math.random()*960)+1;
			lvlWidths.push(w);			
		}
		currentLvl = 1;
		score = 0;
		$('#score').html(score);
		$('#currentLvl').html(currentLvl+'/'+lvlCount);
		createLine();
		$('#pxEstimate').focus();
	}
	
	var createLine = function(){
		var width = lvlWidths[currentLvl-1];
		var offset = (width/2)*-1;
		$('#pxLine').animate({'width': width+'px', 'margin-left' : offset+'px' }, 500, 'easeOutBack');
	}
	
	$('#submit').click(function(e){	
		e.preventDefault();
		var pxEstimate = $('#pxEstimate').val();
		if(isNaN(pxEstimate) || pxEstimate == ''){
			alert('Enter a number');
			$('#pxEstimate').focus();
		} else {			
			if(currentLvl < lvlCount){
				score += Math.abs(lvlWidths[currentLvl-1] - $('#pxEstimate').val());
				$('#score').html(score);
				currentLvl++;
				$('#pxEstimate').val('');
				createLine();				
				$('#currentLvl').html(currentLvl+'/'+lvlCount);
				$('#pxEstimate').focus();
			} else {
				score += Math.abs(lvlWidths[currentLvl-1] - $('#pxEstimate').val());
				$('#score').html(score);
				$('#prevScores').append('<li>'+score+'</li>');
				$('#pxEstimate').val('');
				console.log(score);								
				init();	
			}
		}
	});
	
	init();	
});
