

    var selectedInput = '';
	var keyIsDown = '';
	var key = '';
	var timerID = '';
	var delay = 200;
	
	function fireTimerEvent(){
		setVal();
		doCalc()
		if (keyIsDown) timerID = self.setTimeout("fireTimerEvent()", delay);
	}
	
	function addCommas(nStr){
		nStr += '';
		x = nStr.split('.');
		x1 = x[0];
		x2 = x.length > 1 ? '.' + x[1] : '';
		var rgx = /(\d+)(\d{3})/;
		while (rgx.test(x1)) {
			x1 = x1.replace(rgx, '$1' + ',' + '$2');
		}
		return x1 + x2;
	}
	function roundNumber(num, dec) {
		var result = Math.round(num*Math.pow(10,dec))/Math.pow(10,dec);
		return result;
	}
	function formatNum(num, out){
		if (num!='') {		
			if (out==true){
				newNum = roundNumber(num , 1);
				newNum = addCommas(newNum);
			} else {
				num += '';
				strNum = num.replace(/^[^0-9]+/g, '')
				newNum = parseFloat(strNum, 2);
			}
		} else {
			newNum = 0;
		}

		return newNum;
	}
	
	function setVal(){
		curVal = parseFloat($(selectedInput).val());
		if (keyIsDown==true && curVal >= 0) {
			delay -= delay*.1;
			switch (key){
			case 38:
				newVal = curVal + 1;
				break;
			case 40:
				if (curVal > 0) newVal = curVal - 1;
				break;
			}
			$(selectedInput).val(newVal);
		}
	}
	function doCalc(){
		br = formatNum($('#bitrate').val(), false);
		l = formatNum($('#length').val(), false);
		c = formatNum($('#playcount').val(), false);
		KBpm = br/8*60;
		MBpm = KBpm / 1024;
		MBph = MBpm * 60;
		
	
		totalMB = MBpm * formatNum(l, false) * formatNum(c, false);
		totalGB = totalMB / 1024;
	
		if (!isNaN(KBpm)) $('#KBpm').html(formatNum(KBpm, true));
		if (!isNaN(MBpm)) $('#MBpm').html(formatNum(MBpm, true));
		if (!isNaN(MBph)) $('#MBph').html(formatNum(MBph, true));
		if (!isNaN(totalGB)) $('#bandwidthusage').html(formatNum(totalGB, true));
		if (!isNaN(totalMB)) $('#bandwidthusageMB').html(formatNum(totalMB, true));
	}

	$(function(){
	    $('input').focus(function() {
	        selectedInput = this;
	    });
	    $('input').blur(function() {
	    	selectedInput = '';
	    });
		$(document).keydown(function(e){
			key = e.charCode || e.keyCode || 0;
			keyIsDown = key==40 || key==38;
			//setVal();
			fireTimerEvent();
		});
		$(document).keyup(function(){
			keyIsDown = false;
			doCalc();
			delay = 200;
		});
		$('#qualities').change(function(){
			quality = $('#qualities option:selected').val();
			$('#bitrate').val(quality);
			doCalc();
		});
		doCalc();
		

	});

