!!(function() {
	var aUnits = {
		'wenig': 30,
		'normal': 40,
		'viel': 50,
		'sehr viel': 60
	}
	var iHunger = 40;
	var iRolls = 1;
	var $oRolls = $('#halfRolls');
	var $oSelect = $('#hunger');
    var aMeasures = ['G', 'KG', 'T'];

	var inf = function(iIn) {
		var sIn = String(Math.round(iIn));
		var rGx = /(\d+)(\d{3})/;
		while(rGx.test(sIn)) sIn = sIn.replace(rGx, '$1.$2');
		return sIn;
	}
	var nf = function(fIn) {
		var aIn = String(parseFloat(fIn).toFixed(2)).split('.');
		var rGx = /(\d+)(\d{3})/;
		while(rGx.test(aIn[0])) aIn[0] = aIn[0].replace(rGx, '$1.$2');
		return aIn.join(',');
	}
    var calc = function() {
        var fHack = iRolls * iHunger;
        var sMeas = '';
		var bDiv = false;
        for(var i in aMeasures) {
            sMeas = aMeasures[i];
            if(fHack < 1000) break;
            fHack /= 1000;
			bDiv = true;
        }
		document.location.hash = 'r'+iRolls+'-m'+iHunger;
        $('#out').text('Bestell '+(bDiv ? nf(fHack) : inf(fHack))+' '+sMeas+' Mett beim Metzger, bro.');
    } 

	var aMatch = document.location.hash.match(/r(\d+)-m(\d+)/);
	if(aMatch) {
		iRolls = parseInt(aMatch[1]);
		iHunger = parseInt(aMatch[2]);
		calc();
	}

	$oRolls.val(iRolls).on('change', function() {
		iRolls = parseInt($oRolls.val());
	});
        
    $.each(aUnits, function(name, e) {
        $oSelect.append($('<option>').attr('value', e).prop('selected', e == iHunger).text(name));
    }); 
    
	$oSelect.on('change', function() {
		iHunger = $oSelect.val();
	});

	$('#calc').on('click', calc);

})();
