/* vars */
var weather = new Array();
var inventory = new Array();
var shoppinglist = new Array();
var technostuff = new Array();
var money = 1000;
var dayofweek = 0;
var day = 0;
var buything = -1;
var buydaysleft = 0;
var eventdaysleft = -1;
var setting_autosave = 1;
var setting_sound = 1;
var setting_autoload = 1;
var language = 'auto';
var sandwiches = new Array();
var ingredients = new Array();
var max_ingredients = 4;
var amount_type1 = 33;
var amount_type2 = 33 + amount_type1;
var header_color = 'white';
var bonusing = new Array();
var malusing = new Array();
var snackbar_name;
var no_sales_counter = 0;
var bgm_enable = 1;
var bgm_volume = 1;
var sfx_enable = 1;
var sfx_volume = 1;
var points = 0;
var achievements = new Array();
var day_sales_counter = 0;
var amount_people = 10;
// helpers
var tempmoney = 0;
var income = 0;
var roundCounter = 0;
var sold_content = '';
var sales = new Array();
var round_opinions = new Array();
var variety_all = new Array();
var input_fields_numeric = 0; // should numeric fields be of html input type numeric
var eventcard_bus = 0;
// constants
var default_days_to_wait = 2;
var roundTime = 1000;
var roundCounterMax = 2;
var game_version = '0.4';
var savegame_version = 3;
var maxCanvasWidth = 640;
var maxCanvasHeight = 400;
var canvasPaddingHeight = 150;
var canvasPaddingWidth = 20;
var aspect_ratio_w = 0.625; // 400 / 640
var aspect_ratio_h = 1.6; // 640 / 400
var current_weather = 'sunny';
var rent;
var points_per_day = 10;
var available_achievements;

function has_achievement(ach_internalname) {
	for (i=0;i<achievements.length;i++) {
		if (achievements[i] == ach_internalname) {
			return true;
		}
	}
	return false;
}

function set_achievement(ach_internalname) {
	achievements.push(ach_internalname);
}

function achievement_get_name(ach_internalname) {
	var achievments_length = getArrayLength(available_achievements);
	for(var ach = 0; ach < achievments_length; ach++) {
		if (ach_internalname == available_achievements[ach].internalname) {
			return available_achievements[ach].title;
		}
	}
	return '';
}

function earn_achievement(ach_internalname) {
	if (!has_achievement(ach_internalname)) {
		set_achievement(ach_internalname);
		toastr.success(jQuery.i18n.prop('ach_earned'), achievement_get_name(ach_internalname));
	}
}


function set_defaults() {
    /* vars */
    weather = new Array();
    inventory = new Array();
    shoppinglist = new Array();
    technostuff = new Array();
    money = 1000;
    dayofweek = 0;
    day = 0;
    buything = -1;
    buydaysleft = 0;
    eventdaysleft = -1;
    setting_autosave = 1;
    setting_sound = 1;
    setting_autoload = 1;
    language = 'auto';
    sandwiches = new Array();
    ingredients = new Array();
    max_ingredients = 4;
    amount_type1 = 33;
    amount_type2 = 33 + amount_type1;
    header_color = 'white';
    bonusing = new Array();
    malusing = new Array();
	snackbar_name = jQuery.i18n.prop('snackbar_title');
	no_sales_counter = 0;
	points = 0;
	achievements = new Array();
	day_sales_counter = 0;
	amount_people = 10;
    // helpers
    tempmoney = 0;
    income = 0;
    roundCounter = 0;
    sold_content = '';
    sales = new Array();
    round_opinions = new Array();
    variety_all = new Array();
    // constants
    default_days_to_wait = 2;
    current_weather = 'sunny';
	rent = 5; // default rent
	
	
	available_achievements = new Array(
		{
			title: jQuery.i18n.prop('ach_500days_title'),
			description: jQuery.i18n.prop('ach_500days_desc'),
			internalname: '500days'
		}, {
			title: jQuery.i18n.prop('ach_mrsandwich_title'),
			description: jQuery.i18n.prop('ach_mrsandwich_desc'),
			internalname: 'mrsandwich'
		}, {
			title: jQuery.i18n.prop('ach_notmyname_title'),
			description: jQuery.i18n.prop('ach_notmyname_desc'),
			internalname: 'notmyname'
		}, {
			title: jQuery.i18n.prop('ach_moneymoneymoney_title'),
			description: jQuery.i18n.prop('ach_moneymoneymoney_desc'),
			internalname: 'moneymoneymoney'
		}, {
			title: jQuery.i18n.prop('ach_everyday_title'),
			description: jQuery.i18n.prop('ach_everyday_desc'),
			internalname: 'everyday'
		}
	);
}

/* check if there has been any sales */
function has_sales() {
	for(i = 0; i< sales.length; i++) {
		if (sales[i].amount > 0) return true;
	}
	return false;
}

/* dont allow further progress in game */
function game_over() {
	/* disable all buttons */
	$('#btn_week').button("disable");
	$('#btn_shop').button("disable");
	$('#btn_research').button("disable");
	$('#sandwichbutton').button("disable");
	$('#start_round').button("disable");
}

function set_autosave() {
	//alert($('#autosavegame').prop('checked'));
	if ($('#autosavegame').prop('checked') == true) {
		setting_autosave = 1;
		//alert(setting_autosave);
	} else {
		setting_autosave = 0;
	}
}

function start() {
	$('#sandwichbutton').button('disable'); // disable it again, strange fx reload behaviour
	$('#sandwichbutton').button({ label: '???' });
	document.getElementById('controls_initial').style.display = 'none';
	document.getElementById('overlay').style.display = 'block';
	//$('.controls').css("display", "inline-block");
	if ($('.controls').hasClass("invisible")) {
        $('.controls').toggleClass("invisible");
    }
    //document.getElementById('version_string').innerHTML = jQuery.i18n.prop('snackbar_title')+' v'+game_version;
	//set_defaults();
	intro();
	if (setting_autosave) save(0);
}

function restart() {
    document.getElementById('dialog').innerHTML = jQuery.i18n.prop('game_restart_content');
    $( "#dialog" ).dialog(
        {
            title: jQuery.i18n.prop('game_restart_title'),
            resizable: false,
            maxHeight: ($(window).height()-10),
            modal: true,
            buttons: [
                { 
                    text: jQuery.i18n.prop('cancel'),
                    click: function() { $( this ).dialog( "close" ); }
                }, {
                    text: jQuery.i18n.prop('confirm'),
                    click: function() {
                        $( this ).dialog( "close" );
                        // close all dialogs
                        $(".ui-dialog-content").dialog("close");
                        // reset things
                        init();
                        start();
                    }
                }
            ]
        });
}

function save(notify) {
	localStorage.setItem("weather", JSON.stringify(weather));
	localStorage.setItem("inventory", JSON.stringify(inventory));
	localStorage.setItem("shoppinglist", JSON.stringify(shoppinglist));
	localStorage.setItem("technostuff", JSON.stringify(technostuff));
	localStorage.setItem("money", money);
	localStorage.setItem("dayofweek", dayofweek);
	localStorage.setItem("day", day);
	localStorage.setItem("buything", buything);
	localStorage.setItem("buydaysleft", buydaysleft);
	localStorage.setItem("eventdaysleft", eventdaysleft);
	localStorage.setItem("setting_autosave", setting_autosave);
    localStorage.setItem("setting_autoload", setting_autoload);
	localStorage.setItem("setting_sound", setting_sound);
	localStorage.setItem("sandwiches", JSON.stringify(sandwiches));
	localStorage.setItem("ingredients", JSON.stringify(ingredients));
	localStorage.setItem("max_ingredients", max_ingredients);
	localStorage.setItem("language", language);
	localStorage.setItem("amount_type1", amount_type1);
	localStorage.setItem("amount_type2", amount_type2);
    localStorage.setItem("header_color", header_color);
    localStorage.setItem("bonusing", JSON.stringify(bonusing));
    localStorage.setItem("malusing", JSON.stringify(malusing));
    localStorage.setItem("savegame_version", savegame_version);
	localStorage.setItem("snackbar_name", snackbar_name);
	localStorage.setItem("no_sales_counter", no_sales_counter);
	localStorage.setItem("bgm_enable", bgm_enable);
	localStorage.setItem("bgm_volume", bgm_volume);
	localStorage.setItem("sfx_enable", sfx_enable);
	localStorage.setItem("sfx_volume", sfx_volume);
	localStorage.setItem("points", points);
	localStorage.setItem("achievements", JSON.stringify(achievements));
	localStorage.setItem("day_sales_counter", day_sales_counter);
	localStorage.setItem("amount_people", amount_people);
	if (notify == 1) simpleDialog(jQuery.i18n.prop('game_save_title'), jQuery.i18n.prop('game_save_success'));
}

function load(notify) {
	
	if (parseInt(localStorage.getItem("savegame_version")) != savegame_version) {
		if (parseInt(localStorage.getItem("savegame_version")) == 2) {
			simpleDialog(jQuery.i18n.prop('game_load_error'), jQuery.i18n.prop('game_load_reset_4'));
		}
	} else if (localStorage.getItem("weather") !== null) {
        //if (parseInt(localStorage.getItem("savegame_version")) == savegame_version) {
            document.getElementById('controls_initial').style.display = 'none';
            document.getElementById('overlay').style.display = 'block';
            if ($('.controls').hasClass('invisible')) $('.controls').toggleClass("invisible");
            weather = JSON.parse(localStorage.getItem("weather"));
            inventory = JSON.parse(localStorage.getItem("inventory"));
            shoppinglist = JSON.parse(localStorage.getItem("shoppinglist"));
            technostuff = JSON.parse(localStorage.getItem("technostuff"));
            money = parseInt(localStorage.getItem("money"));
            dayofweek = parseInt(localStorage.getItem("dayofweek"));
            day = parseInt(localStorage.getItem("day"));
            buything = localStorage.getItem("buything");
            buydaysleft = parseInt(localStorage.getItem("buydaysleft"));
            eventdaysleft = parseInt(localStorage.getItem("eventdaysleft"));
            setting_autosave = parseInt(localStorage.getItem("setting_autosave"));
            if (setting_autosave == 1) {
                $('#autosavegame').prop('checked', true);
            } else {
                $('#autosavegame').prop('checked', false);
            }
            setting_autoload = parseInt(localStorage.getItem("setting_autoload"));
            setting_sound = parseInt(localStorage.getItem("setting_sound"));
            sandwiches = JSON.parse(localStorage.getItem("sandwiches"));
            ingredients = JSON.parse(localStorage.getItem("ingredients"));
            language = localStorage.getItem("language");
            amount_type1 = localStorage.getItem("amount_type1");
            amount_type2 = localStorage.getItem("amount_type2");
            header_color = localStorage.getItem("header_color");
			bonusing = JSON.parse(localStorage.getItem("bonusing"));
			malusing = JSON.parse(localStorage.getItem("malusing"));
			
			/* since v0.3 begin */
			if (localStorage.getItem("snackbar_name") !== null) {
				snackbar_name = localStorage.getItem("snackbar_name");
			}
			
			if (localStorage.getItem("no_sales_counter") !== null) {
				no_sales_counter = parseInt(localStorage.getItem("no_sales_counter"));
			}
			
			if (localStorage.getItem("bgm_enable") !== null) bgm_enable = parseInt(localStorage.getItem("bgm_enable"));
			if (localStorage.getItem("bgm_volume") !== null) bgm_volume = parseInt(localStorage.getItem("bgm_volume"));
			if (localStorage.getItem("sfx_enable") !== null) sfx_enable = parseInt(localStorage.getItem("sfx_enable"));
			if (localStorage.getItem("sfx_volume") !== null) sfx_volume = parseInt(localStorage.getItem("sfx_volume"));
			/* since v0.3 end */
						
			/* v0.3.1 - bugfix for certain savegames */
			if (bonusing.length == 0) {
				chooseBonusMalusIngredients();
			}

			// v0.3.5 bugfix
			if (localStorage.getItem("max_ingredients") !== null) max_ingredients = parseInt(localStorage.getItem("max_ingredients"));
			
			/* v0.4 begin */
			if (localStorage.getItem("points") !== null) points = parseInt(localStorage.getItem("points"));
			if (localStorage.getItem("achievements") !== null) achievements = JSON.parse(localStorage.getItem("achievements"));
			if (localStorage.getItem("day_sales_counter") !== null) day_sales_counter = parseInt(localStorage.getItem("day_sales_counter"));
			if (localStorage.getItem("amount_people") !== null) amount_people = parseInt(localStorage.getItem("amount_people"));
			/* v0.4 end */
			
            setWeather(weather[2]);
            updateMoney();
            updateDayOfWeek();
            updateDay();
            
            if (has_techno_item('sandwichmaker')) {
            	//$('#sandwichbutton').label = jQuery.i18n.prop('sandwichbutton');
            	$('#sandwichbutton').button({ label: jQuery.i18n.prop('sandwichbutton') });
            	$('#sandwichbutton').button("enable");
            } else {
            	$('#sandwichbutton').button({ label: '???' });
            	$('#sandwichbutton').button("disable");
            }
            
            if (bgm_enable) {
				bgm_start();
			} else {
				bgm_stop();
			}
            
            if ((notify == true) || (notify == undefined)) simpleDialog(jQuery.i18n.prop('game_load_title'), jQuery.i18n.prop('game_load_success'));
        /*} else {
            simpleDialog(jQuery.i18n.prop('game_load_error'), jQuery.i18n.prop('game_load_error_version'));
        }*/
	} else {
		simpleDialog(jQuery.i18n.prop('game_load_title'), jQuery.i18n.prop('game_load_none'));
	}
}

function simpleDialog(title, msg, dialogwidth) {
	if (dialogwidth == undefined) dialogwidth = '300';
	dialogwidth += 'px';
	document.getElementById('dialog').innerHTML = '<p>'+msg+'</p>';
	$( "#dialog" ).dialog({title: title, width: dialogwidth, resizable: false, maxHeight: ($(window).height()-10), modal: true, buttons: [{ text: jQuery.i18n.prop('ok'), click: function() { $( this ).dialog( "close" ); } }] });
}

function gameMenue(title, msg) {
	$( "#gamemenue" ).dialog({title: jQuery.i18n.prop('game_menue_title'), modal: true, resizable: false, maxHeight: ($(window).height()-10), buttons: [{ text: jQuery.i18n.prop('ok'), click: function() { $( this ).dialog( "close" ); } }]});
}

function intro() {
	simpleDialog(jQuery.i18n.prop('welcome'), jQuery.i18n.prop('welcome_text'));
}

function buytechno(num) {
//	technostuff[num].bought = 1;
	if (technostuff[num].deliverytime == 0) {
		technostuff[num].bought = 1;
	} else {
		buything = num;
		buydaysleft = technostuff[num].deliverytime;
	}
	
	var real_price = Math.floor(technostuff[num].price*(1+technostuff[num].currentlevel*0.1));
	
    money -= real_price;
	points += real_price;
	reloadTechnoDialog();
	updateMoney();
}

function technoDialog() {
	reloadTechnoDialog();
	$( "#technodialog" ).dialog({title: jQuery.i18n.prop('techno_title'), width: 500, modal: true ,resizable: false, maxHeight: ($(window).height()-10), buttons: [{ text: jQuery.i18n.prop('ok'), click: function() {  if (setting_autosave) save(0); $( this ).dialog( "close" ); } }]});
	$( document ).tooltip();
}

function updateSnackbarName() {
	snackbar_name = document.getElementById('snackbar_name').value;
	if (snackbar_name == '') {
		snackbar_name = jQuery.i18n.prop('snackbar_title');
	} else if (snackbar_name != jQuery.i18n.prop('snackbar_title')) {
		earn_achievement('notmyname');
	}
	redraw();
}

function reloadTechnoDialog() {
	var contents = new Array();
	contents['techno'] = '';
	contents['licenses'] = '';
	contents['product'] = '';
	
	if (has_techno_item('imbiss', 2)) {
		if (document.getElementById('tab_sign') == null) {
			$('#technotabs ul').append('<li><a id="tab_sign" href="#sign">'+jQuery.i18n.prop('tab_sign')+'</a></li>');
			$('#technotabs').append('<div id="sign"><p>'+jQuery.i18n.prop('sign_desc')+'</p><input type="text" onchange="updateSnackbarName();" maxlength="20" name="snackbar_name" id="snackbar_name" value="'+snackbar_name+'" /></div>');
			$( "#technotabs" ).tabs("refresh");
		}
	}
	
	for (i=0;i<technostuff.length;i++) {
		content = '<div class="table_row">';
		//content += '<div class="table_cell techno_icon"><img title="'+technostuff[i].description+'" src="img/help.png" /></div>';
		content += '<div class="table_cell techno_label"><span title="'+technostuff[i].description+'">';
		content += technostuff[i].name+' ';
		if ((technostuff[i].maxlevel > 1) && (technostuff[i].currentlevel > 0)) {
			content += '('+jQuery.i18n.prop('level')+' '+ technostuff[i].currentlevel+') ';
		}
		content += '</span></div><div class="table_cell"><button class="techno_button" id="techno_'+i+'" onclick="buytechno('+i+')"';
		
		var real_price = Math.floor(technostuff[i].price*(1+technostuff[i].currentlevel*0.1));
		
		/* das hier wird gerade gekauft */
		if (buything == i) {
			content += ' disabled="disabled">'+jQuery.i18n.prop('delivering')+' ('+buydaysleft+' '+jQuery.i18n.prop('days')+')';
			if (technostuff[i].maxlevel > 1) {
				content += ' ('+jQuery.i18n.prop('level')+' '+ (technostuff[i].currentlevel+1)+')';
			}
		/* etwas anderes wird gerade gekauft */
		} else if (buydaysleft > 0) {
			content += ' disabled="disabled">'+jQuery.i18n.prop('not_for_sale');
		} else if (((technostuff[i].bought) && (technostuff[i].maxlevel == 1)) || 
					((technostuff[i].maxlevel > 1) && (technostuff[i].maxlevel == technostuff[i].currentlevel))) {
			content += ' disabled="disabled">'+jQuery.i18n.prop('sold');
		/* nicht genug geld dafür */
		} else if (real_price > money) {
			content += ' disabled="disabled">'+real_price+'$';
		/* kaufen kaufen */
		} else {
			content += '>'+real_price+'$';
			//content += '>Kaufen';
			if (technostuff[i].maxlevel > 1) {
				content += ' ('+jQuery.i18n.prop('level')+' '+ (technostuff[i].currentlevel+1)+')';
			}
		}
		content += '</button></div>';
		content += '</div>';
		contents[technostuff[i].type] += content;
	}
	
	if (contents['licenses'] == '') contents['licenses'] = jQuery.i18n.prop('no_lics_available');
	if (contents['product'] == '') contents['product'] = jQuery.i18n.prop('no_prod_available');
	
	document.getElementById('techno').innerHTML = contents['techno'];
	document.getElementById('licenses').innerHTML = contents['licenses'];
	document.getElementById('products').innerHTML = contents['product'];
    
    document.getElementById('technomoney').innerHTML = money+'$';
}

/* check if we have this item */
function has_techno_item(item, level) {
	if (level == undefined) level = 0;
	for (i=0;i<technostuff.length;i++) {
		if (technostuff[i].internalname == item) {
			if ((technostuff[i].bought) && (technostuff[i].currentlevel >= level)) {
				return true;
			}
		}
	}
	return false;
}

/*new_sandwich['name'] = document.getElementById('sandwichname_newname').value;
    new_sandwich['creation_day'] = day;
	new_sandwich['ingredients'] = new Array();*/

/*function sandwichitem(newname, newcreationday, newingredients) {
	this.name = newname;
	this.creation_day = newcreationday;
	this.ingredients = new Array();
	this.sellfor_set = 0;
}*/

function shoppingitem(itemname, amount, daysleft) {
	this.name = itemname;
	this.amount = amount;
	this.daysleft = daysleft;
}

//function item(newname, refreshment, satiation, price, type) {
function item(newname, refreshment, price, type) {
	this.name = newname;
	this.refreshment = refreshment;
//	this.satiation = satiation;
	this.amount = 0;
	this.price = price;
	this.type = type;
	this.sellFor = price+1;
}

function technostuff_add(new_item) {
	var zdescription = '';
	if (new_item.description !== undefined) zdescription = new_item.description;
	var zprice = 0;
	if (new_item.price !== undefined) zprice = new_item.price;
	var zmaxlevel = 0;
	if (new_item.maxlevel !== undefined) zmaxlevel = new_item.maxlevel;
	var zcurrentlevel = 0;
	if (new_item.currentlevel !== undefined) zcurrentlevel = new_item.currentlevel;
	var zdeliverytime = 7;
	if (new_item.category != 'techno') {
		zdeliverytime = 3;
	}
	if (new_item.deliverytime !== undefined) zdeliverytime = new_item.deliverytime;
	
	technostuff.push({
		internalname: new_item.internalname,
		name: new_item.name,
		type: new_item.category,
		description: zdescription,
		price: zprice,
		maxlevel: zmaxlevel,
		currentlevel: zcurrentlevel,
		deliverytime: zdeliverytime,
		bought: 0
	});
}

function inventory_add(new_item) {
    var zdescription = '';
    if (new_item.description !== undefined) zdescription = new_item.description;
    var zsellfor = new_item.price+1;
    if (new_item.sellfor !== undefined) zsellfor = new_item.sellfor;
    var zamount = 0;
    if (new_item.amount !== undefined) zamount = new_item.amount;
    var zrefreshment = 0;
    if (new_item.refreshment !== undefined) zrefreshment = new_item.refreshment;
    var zinternalname = new_item.name.toLowerCase();
    if (new_item.internalname !== undefined) zinternalname = new_item.internalname;
    var zkcal = 0;
    if (new_item.kcal !== undefined) zkcal = new_item.kcal;
    var zsugar = 0;
    if (new_item.sugar !== undefined) zsugar = new_item.sugar;
    var zscore = 0;
    if (new_item.score !== undefined) zscore = new_item.score;
    var zsandwich = false;
    if (new_item.sandwich !== undefined) zsandwich = new_item.sandwich;
    inventory.push({
        internalname: zinternalname,
        name: new_item.name,
        type: new_item.type,
        price: new_item.price,
        sellFor: zsellfor,
        amount: zamount,
        description: zdescription,
        refreshment: zrefreshment,
        kcal: zkcal,
        sugar: zsugar,
        score: zscore,
        sandwich: zsandwich
    });
}

function init() {
    set_defaults();
	generateWeather();
	setWeather(weather[2]);
	
    inventory_add({ name: jQuery.i18n.prop('p_coke'), price: 3, sellfor: 4, type: 'drinks', amount: 5, kcal: 129, sugar: 33, score: 40 });
    inventory_add({ name: jQuery.i18n.prop('p_water'), price: 1, sellfor: 2, type: 'drinks', amount: 5, kcal: 0, sugar: 0, score: 20 });
    inventory_add({ name: jQuery.i18n.prop('p_chips'), price: 5, sellfor: 7, type: 'snacks', amount: 5, kcal: 925, sugar: 8, score: 30 });
    inventory_add({ name: jQuery.i18n.prop('p_apple'), price: 2, sellfor: 3, type: 'snacks', amount: 3, kcal: 54, sugar: 10, score: 20 });
    
	technostuff_add({
		internalname: 'imbiss',
		name: jQuery.i18n.prop('p_imbiss'),
		description: jQuery.i18n.prop('p_imbiss_desc'),
		price: 1800,
		maxlevel: 12,
		currentlevel: 1,
		category: 'techno'
	});
	
	technostuff_add({
		internalname: 'fridge',
		name: jQuery.i18n.prop('p_fridge'),
		description: jQuery.i18n.prop('p_fridge_desc'),
		price: 450,
		maxlevel: 16,
		currentlevel: 1,
		category: 'techno'
	});
	
	technostuff_add({
		internalname: 'voglr',
		name: jQuery.i18n.prop('p_voglr'),
		description: jQuery.i18n.prop('p_voglr_desc'),
		price: 300,
		maxlevel: 1,
		currentlevel: 0,
		category: 'techno'
	});
	
	updateMoney();
	updateDayOfWeek();
	updateDay();
	$( "#tabs" ).tabs();
	$( "#technotabs" ).tabs();
	$( "#sandwichcontent_tabs" ).tabs();
    
    if (setting_autosave) $('#autosavegame').prop('checked', true);
	
	$('#btn_week').button("enable");
	$('#btn_shop').button("enable");
	$('#btn_research').button("enable");
	//$('#sandwichbutton').button("enable");
	$('#start_round').button("enable");
	
	/*if (bgm_enable) {
		bgm_start();
	} else {
		bgm_stop();
		console.log("disaasdasd");
	}*/
}

function bgm_start() {
	if (navigator.userAgent == 'Android') {
		AndAud.resumeAudio("00_artificial_recreation__void_main");
	} else {
		document.getElementById('bgm_track_01').play();
	}
	bgm_enable = 1;
}

function bgm_next_track() {
}

function bgm_stop() {
	if (navigator.userAgent == 'Android') {
		AndAud.stopAudio();
	} else {
		document.getElementById('bgm_track_01').pause();
	}
	bgm_enable = 0;
}

function bgm_toggle() {
	if (bgm_enable == 0) {
		bgm_start();
	} else {
		bgm_stop();
	}
	save(0);
	console.log("bgm_enable is now "+bgm_enable);
}

function setWeather(weather) {
    if (current_weather != weather) {
        current_weather = weather;
        redraw();
    }
}
function showPeople(want) {
/*	switch(want) {
		case 0:
			document.getElementById('people').style.backgroundImage = "none";
		break;
		case 1:
			document.getElementById('people').style.backgroundImage = "url('img/people.gif')";
		break;
	}*/
}
function generateWeather() {
	weather = new Array();
	var r = 0;
	for (i=0; i<9; i++) {
		weather[i] = generateDayWeather();
	}
}
function generateDayWeather() {
	r = Math.floor((Math.random()*100)+1);
	if (r < 20) {
		return 'cloudy';
	} else if (r < 40) {
		return 'rainy';
	} else {
		return 'sunny';
	}
}
function moveWeather() {
	weather.shift();
	weather.push(generateDayWeather());
}
function getDayName(day) {
	switch(day) {
		case 0: return jQuery.i18n.prop('monday');
		case 1: return jQuery.i18n.prop('tuesday');
		case 2: return jQuery.i18n.prop('wednesday');
		case 3: return jQuery.i18n.prop('thursday');
		case 4: return jQuery.i18n.prop('friday');
		case 5: return jQuery.i18n.prop('saturday');
		case 6: return jQuery.i18n.prop('sunday');
	}
}
function nextday() {
	var shoppinglistdialogcontent = '';
	dayofweek++;
	points += points_per_day;
	if (dayofweek > 6) {
		dayofweek = 0;
	} else if (dayofweek == 4) {		// 4 is sunday...
		// every week an eventcard
		eventCard();
        // and new bonus/malus ingredients
        chooseBonusMalusIngredients();
	}
	
	day++;
	
	if (day == 500) {
		earn_achievement('500days');
	}
	
	showPeople(0);
	moveWeather();
    setWeather(weather[2]);
    updateMoney();
	
	if (money > 3000) earn_achievement('moneymoneymoney');
	
    updateDayOfWeek();
    updateDay();
    setAllSandwichScore();
	shoppinglistdialogcontent = process_shopping_list();
	if (shoppinglistdialogcontent != '') {
		simpleDialog(jQuery.i18n.prop('delivery'), shoppinglistdialogcontent);
		/*document.getElementById('deliveries').innerHTML = shoppinglistdialogcontent;
		$( "#deliveries" ).dialog({title: jQuery.i18n.prop('delivery'), resizable: false, modal: true, maxHeight: ($(window).height()-10), buttons: [{ text: jQuery.i18n.prop('ok'), click: function() { $( this ).dialog( "close" ); } }]});*/
	}
	
	if (!has_sales()) {
		no_sales_counter++;
		day_sales_counter = 0;
		if (no_sales_counter == 4) {
			simpleDialog(jQuery.i18n.prop('warning'), jQuery.i18n.prop('warning_no_sales'));
		} else if (no_sales_counter == 8) {
			simpleDialog(jQuery.i18n.prop('warning'), jQuery.i18n.prop('game_over_no_sales'));
			game_over();
		}
	} else {
		no_sales_counter = 0;
		day_sales_counter++;
		if (day_sales_counter == 14) earn_achievement('everyday');
	}
		
	sold_content = '';
	if (eventdaysleft >= 0) eventdaysleft--;
	if (setting_autosave) save(0);
}

function recenterDialog(which) {
	//$(which).dialog('option', 'position', 'center');
	$(which).dialog( "option", "position", { my: "center", at: "center", of: window } );
}

function handleRound() {
	roundCounter++;
	simulate_people_v2();
	document.getElementById('sold').innerHTML = simulate_people_content();
	recenterDialog('#roundprogressdialog');
	if (roundCounter <= roundCounterMax) {
		window.setTimeout('handleRound()', roundTime);
	} else {
		nextday();
	}
	updateRoundProgress();
}

function startRound() {
    variety_all['drinks'] = get_variety('drinks', 9999, 9999);
    variety_all['snacks'] = get_variety('snacks', 9999, 9999);
    variety_all['ice'] = get_variety('ice', 9999, 9999);
    variety_all['wares'] = get_variety('wares', 9999, 9999);

	round_opinions = new Array(); // leere letzte meinungen

	sales = deepCopy(inventory);
	for(i = 0; i< sales.length; i++) {
		sales[i].amount = 0;
	}
	round_opinions = new Array();
	document.getElementById('sold').innerHTML = '';
	document.getElementById('roundprogressbarlabel').innerHTML = '';
	
	$( "#roundprogressdialog" ).dialog({id: "progressdialogok", resizable: false, modal: true, maxHeight: ($(window).height()-10), buttons: [{ text: jQuery.i18n.prop('voglr'), id: 'roundvoglr', click: function() {showOpinions()}}, { text: jQuery.i18n.prop('ok'), id: 'roundok', click: function() { $( this ).dialog( "close" ); } } ] } );
	$('#roundprogressdialog').dialog('option', 'title', jQuery.i18n.prop('round_started'));
	//$(".ui-dialog-buttonpane button:contains('VogLr')").button("disable");
	$("#roundok").button("disable");
	$("#roundvoglr").button("disable");
		
	var progressbar = $( "#roundprogressbar" ),
		progressLabel = $( "#roundprogressbarlabel" );
	progressbar.progressbar({
		value: false,
		complete: function() {
			document.getElementById('roundprogressbarlabel').innerHTML = jQuery.i18n.prop('round_finished');
			$('#roundprogressdialog').dialog('option', 'title', jQuery.i18n.prop('round_finished'));
			//$(".ui-dialog-buttonpane button:contains('OK')").button("enable");
			$("#roundok").button("enable");
			if (has_techno_item('voglr')) {
				//$(".ui-dialog-buttonpane button:contains('VogLr')").button("enable");
				$("#roundvoglr").button("enable");
			}
		}
	});
	roundCounter = 0;
	updateRoundProgress();
	income = 0;
	window.setTimeout('handleRound()', roundTime);
}

function showOpinions() {
	var random_numbers = new Array();
	var max_numbers = 5;
	var content = jQuery.i18n.prop('voglr_nomsg');
	if (round_opinions.length > 0) {
		content = '<p>'+jQuery.i18n.prop('voglr_random', max_numbers)+':</p><ul id="voglr">';
		
		for(number = 0; number < max_numbers; number++) {
			var new_number = Math.floor(Math.random() * round_opinions.length);
			if (random_numbers[new_number] == undefined) {
				content += '<li>';
				switch(round_opinions[new_number].feeling) {
					case 'sad':
						content += '<img src="img/face-sad.png" /> ';
					break;
					case 'happy':
						content += '<img src="img/face-smile.png" /> ';
					break;
					case 'neutral':
						content += '<img src="img/face-plain.png" /> ';
					break;
				}
				content += round_opinions[new_number].message+'</li>';
				random_numbers[new_number] = 1;
			} else {
				number--;
				continue;
			}
		}
		content += '</ul>';
	}
	simpleDialog(jQuery.i18n.prop('voglr_written'), content, '400');
}

function buyDialog() {
	var type = '';
	var agreed = false;
	
	document.getElementById('drinks').innerHTML = '<div class="table">';
	document.getElementById('snacks').innerHTML = '<div class="table">';
	document.getElementById('ice').innerHTML = '<div class="table">';
	document.getElementById('wares').innerHTML = '<div class="table">';
	
	var elements = new Array();
	elements['drinks'] = '';
	elements['snacks'] = '';
	elements['ice'] = '';
	elements['wares'] = '';
	
	var default_header = '<div class="table">';
	
	var orders_tab_content = '';
	
	ordersdialogcontent = get_current_orders();
	orders_tab_content = '<p><b>'+jQuery.i18n.prop('orders_open')+'</b><br />';
	if (ordersdialogcontent != '') {
		orders_tab_content += ordersdialogcontent;
	} else {
		orders_tab_content += jQuery.i18n.prop('orders_none');
	}
	document.getElementById('orders').innerHTML = orders_tab_content+'</p>';
	
	/* inventory */
    tempmoney = money;
    document.getElementById('tempmoney').innerHTML = tempmoney+'$';
	elements['drinks'] = default_header;
	elements['snacks'] = default_header;
	for (i=0;i<inventory.length;i++) {
		elements[inventory[i].type] += '<div class="table_row">';
		elements[inventory[i].type] += '<div class="table_cell"><span class="emphase">'+inventory[i].name+'</span></div><div class="table_cell">'+jQuery.i18n.prop('price')+'&nbsp;'+inventory[i].price+'$<br />';
        elements[inventory[i].type] += jQuery.i18n.prop('sellfor')+' ';
		
		if (input_fields_numeric) {
			elements[inventory[i].type] += '<input id="sellfor_'+i+'" type="number" step="0.01" min="0" maxlength="5" size="4" value="'+inventory[i].sellFor+'" />';
		} else {
			elements[inventory[i].type] += '<input id="sellfor_'+i+'" type="text" maxlength="5" size="4" value="'+inventory[i].sellFor+'" />';
		}
		
		elements[inventory[i].type] += '$</div><div class="table_cell">'+jQuery.i18n.prop('stock')+' '+inventory[i].amount+'<br />';
        elements[inventory[i].type] += jQuery.i18n.prop('buy')+' <div class="inventory_buy">';
		
		elements[inventory[i].type] += '<button onclick="sellItem('+i+')">-</button>';
		if (input_fields_numeric) {
			elements[inventory[i].type] += '<input onchange="shop_recalc_money()" id="amount_'+i+'" maxlength="4" type="number" min="0" step="1" size="3" value="0" />';
		} else {
			elements[inventory[i].type] += '<input onchange="shop_recalc_money()" id="amount_'+i+'" maxlength="4" type="text" min="1" size="3" value="0" />';
		}
		elements[inventory[i].type] += '<button onclick="buyItem('+i+')">+</button>';
		elements[inventory[i].type] += '</div></div></div>';
	}
	
	elements['drinks'] += '</div>';
	elements['snacks'] += '</div>';

	if (elements['ice'] == '') {
		elements['ice'] = jQuery.i18n.prop('products_none');
	} else {
		elements['ice'] = default_header+elements['ice'];
	}

	if (elements['wares'] == '') {
		elements['wares'] = jQuery.i18n.prop('products_none');
	} else {
		elements['wares'] = default_header+elements['wares'];
	}
	
	document.getElementById('drinks').innerHTML = elements['drinks'];
	document.getElementById('snacks').innerHTML = elements['snacks'];
	document.getElementById('ice').innerHTML = elements['ice'];
	document.getElementById('wares').innerHTML = elements['wares'];
	
    $( "#buydialog" ).dialog({
        title: jQuery.i18n.prop('buy_title'),
        modal: true,
        resizable: false,
        width: '600px',
        maxHeight: ($(window).height()-10),
        buttons: [{
            text: jQuery.i18n.prop('cancel'),
            click: function() {
                $( this ).dialog( "close" );
            }}, {
            text: jQuery.i18n.prop('confirm'),
            click: function() {
                if (confirmOrder()) {
                	agreed = true;
	                updateMoney();
                    if (setting_autosave) save(0);
	                $(this).dialog("close");
	            }
            }
                
            }
        ]
        
    });
	document.getElementById('drinks').innerHTML += '</div>';
	document.getElementById('snacks').innerHTML += '</div>';
	document.getElementById('ice').innerHTML += '</div>';
	document.getElementById('wares').innerHTML += '</div>';
	
	updateTempMoney();
}

function confirmOrder() {
	if (tempmoney < 0) {
		simpleDialog(jQuery.i18n.prop('sorry'), jQuery.i18n.prop('not_enough_money'));
		return false;
	} else {
		var buyme = 0;
		money = tempmoney;
		for (i=0;i<inventory.length;i++) {
		    buyme = parseInt(document.getElementById('amount_'+i).value);
		    if ((buyme > 0) && (!isNaN(buyme))) {
		        shoppinglist.push(new shoppingitem(inventory[i].name, buyme, default_days_to_wait));
		    }
		    setSellFor(i);
		}
	}
	return true;
}
function process_shopping_list() {
	var content = '';
	var new_shopping_list = new Array();
	for (j=0;j<shoppinglist.length;j++) {
		if (shoppinglist[j].daysleft > 0) {
			shoppinglist[j].daysleft--;
		}
		if (shoppinglist[j].daysleft == 0) {
			for (i=0;i<inventory.length;i++) {
				if (inventory[i].name == shoppinglist[j].name) {
					inventory[i].amount += parseInt(shoppinglist[j].amount);
					content += '<li>'+shoppinglist[j].amount+' x '+shoppinglist[j].name+'</li>';
					/*shoppinglist.splice(j, 1);
					break;*/
				}
			}
		} else {
			new_shopping_list.push(shoppinglist[j]);
		}
	}
	shoppinglist = new_shopping_list;
	if (buydaysleft > 0) {
		buydaysleft--;
	}
	if ((buything != -1) && (buydaysleft == 0)) {
		technostuff[buything].bought = 1;
		content += '<li>'+technostuff[buything].name;
		if (technostuff[buything].maxlevel > 1) {
			technostuff[buything].currentlevel++;
			content += ' (Level '+technostuff[buything].currentlevel+')';
		}
		content += '</li>';
		switch(technostuff[buything].internalname) {
			/* IMBISSSTAND ZEUGS BEGINN */
			case 'imbiss':
				if (technostuff[buything].currentlevel == 2) {
					technostuff_add({ internalname: 'freezer', name: jQuery.i18n.prop('p_freezer'), description: jQuery.i18n.prop('p_freezer_desc'), price: 700, maxlevel: 10, current_level: 0, category: 'techno' });
				} else if (technostuff[buything].currentlevel == 3) {
					technostuff_add({ internalname: 'grill', name: jQuery.i18n.prop('p_grill'), description: jQuery.i18n.prop('p_grill_desc'), price: 700, maxlevel: 3, current_level: 0, category: 'techno' });
				} else if (technostuff[buything].currentlevel == 4) {
					amount_people += 10;
				} else if (technostuff[buything].currentlevel == 5) {
					technostuff_add({ internalname: 'coffee', name: jQuery.i18n.prop('p_coffeemaker'), description: jQuery.i18n.prop('p_coffeemaker_desc'), price: 600, maxlevel: 1, current_level: 0, category: 'techno' });
				} else if (technostuff[buything].currentlevel == 5) {
					technostuff_add({ internalname: 'kebabspear', name: jQuery.i18n.prop('p_kebabspear'), description: jQuery.i18n.prop('p_kebabspear_desc'), price: 900, maxlevel: 1, current_level: 0, category: 'techno' });
				} else if (technostuff[buything].currentlevel == 6) {
					amount_people += 10;
				} else if (technostuff[buything].currentlevel == 7) {
					technostuff_add({ internalname: 'oven', name: jQuery.i18n.prop('p_oven'), description: jQuery.i18n.prop('p_oven_desc'), price: 1000, maxlevel: 2, current_level: 0, category: 'techno' });
				} else if (technostuff[buything].currentlevel == 8) {
					technostuff_add({ internalname: 'friteuse', name: jQuery.i18n.prop('p_friteuse'), description: jQuery.i18n.prop('p_friteuse_desc'), price: 800, maxlevel: 1, current_level: 0, category: 'licenses' });					
				} else if (technostuff[buything].currentlevel == 9) {
					amount_people += 10;
				} else if (technostuff[buything].currentlevel == 10) {
					technostuff_add({ internalname: 'tabaklic', name: jQuery.i18n.prop('p_tabaklic'),	description: jQuery.i18n.prop('p_tabaklic_desc'), price: 1000, maxlevel: 2, current_level: 0, category: 'licenses' });
				} else if (technostuff[buything].currentlevel == 11) {
					technostuff_add({ internalname: 'alclic', name: jQuery.i18n.prop('p_alclic'), description: jQuery.i18n.prop('p_alclic_desc'), price: 1000, maxlevel: 2, current_level: 0, category: 'techno' });
				} else if (technostuff[buything].currentlevel == 12) {
					amount_people += 10;
				}
			break;
			amount_people += 5;
			/* IMBISSSTAND ZEUGS ENDE */
			
			/* KÜHLSCHRANK ZEUGS BEGINN */
			case 'fridge':
				if (technostuff[buything].currentlevel == 2) {
					
					inventory_add({ name: jQuery.i18n.prop('p_mineralwater'), price: 2.5, type: 'drinks', kcal:0, sugar: 0, score: 20 });
					
					technostuff_add({
						internalname: 'sandwichmaker',
						name: jQuery.i18n.prop('p_sandwichmaker'),
						description: jQuery.i18n.prop('p_sandwichmaker_desc'),
						price: 500,
						maxlevel: 1,
						currentlevel: 0,
						category: 'techno'
					});
					
                    ingredients.push({
                        title: jQuery.i18n.prop('p_tomato'),
                        image: "img/tomato.png",
                        type: "fruits",
                        kcal: 3,
                        costs: 1.25
                    });
                    
                    ingredients.push({
                        title: jQuery.i18n.prop('p_ketchup'),
                        image: "img/ketchup.png",
                        type: "sauces",
                        kcal: 25,
                        costs: 1.25
                    });
                    
				} else if (technostuff[buything].currentlevel == 3) {
                    technostuff_add({ internalname: 'herbsoda', name: jQuery.i18n.prop('p_herbsoda'), description: jQuery.i18n.prop('p_herbsoda_desc'), price: 200, maxlevel: 1, current_level: 0, category: 'product' });
                    
                    ingredients.push({
                        title: jQuery.i18n.prop('p_mustard'),
                        image: "img/mustard.png",
                        type: "sauces",
                        kcal: 25,
                        costs: 1.25
                    });
                    
				} else if (technostuff[buything].currentlevel == 4) {
					inventory_add({ name: jQuery.i18n.prop('p_lemon_lemonade'), price: 4, type: 'drinks', kcal:129, sugar: 33, score: 40 });
					
					ingredients.push({
                        title: jQuery.i18n.prop('p_cucumber'),
                        image: "img/cucumber.png",
                        type: "fruits",
                        kcal: 1,
                        costs: 1.25
                    });
					
				} else if (technostuff[buything].currentlevel == 5) {
				
					technostuff_add({ internalname: 'energydrink', name: jQuery.i18n.prop('p_energydrink'), description: 'Energy Drink entwickeln.', price: 200, maxlevel: 1, current_level: 0, category: 'product' });
				
					ingredients.push({
                        title: jQuery.i18n.prop('p_salad'),
                        image: "img/salad.png",
                        type: "fruits",
                        kcal: 5,
                        costs: 1.25
                    });
                    
                    max_ingredients += 1;
					
				} else if (technostuff[buything].currentlevel == 6) {
				
					inventory_add({ name: jQuery.i18n.prop('p_orangejuice'), price: 3.75, type: 'drinks', kcal:120, sugar: 30, score: 30 });
				
					ingredients.push({
						title: jQuery.i18n.prop('p_mozarella'),
						image: "img/mozarella.png",
						type: "cheese",
						kcal: 131,
						costs: 1.50
					});
				
					
				} else if (technostuff[buything].currentlevel == 7) {
					
					ingredients.push({
                        title: jQuery.i18n.prop('p_mayo'),
                        image: "img/mayo.png",
                        type: "sauces",
                        kcal: 100,
                        costs: 1.25
                    });
                    
				} else if (technostuff[buything].currentlevel == 8) {
				
					ingredients.push({
                        title: jQuery.i18n.prop('p_garlicsauce'),
                        image: "img/garlicsauce.png",
                        type: "sauces",
                        kcal: 25,
                        costs: 1.25
                    });
				
				} else if (technostuff[buything].currentlevel == 9) {
					
					ingredients.push({
                        title: jQuery.i18n.prop('p_joghurtsauce'),
                        image: "img/joghurtsauce.png",
                        type: "sauces",
                        kcal: 25,
                        costs: 1.25
                    });
					
				} else if (technostuff[buything].currentlevel == 10) {
				
					ingredients.push({
                        title: jQuery.i18n.prop('p_curry'),
                        image: "img/curry.png",
                        type: "sauces",
                        kcal: 25,
                        costs: 1.25
                    });
                    
					max_ingredients += 1;
				} else if (technostuff[buything].currentlevel == 11) {
				
					ingredients.push({
                        title: jQuery.i18n.prop('p_peppersauce'),
                        image: "img/peppersauce.png",
                        type: "sauces",
                        kcal: 25,
                        costs: 1.25
                    });
                    
				} else if (technostuff[buything].currentlevel == 12) {
				
					ingredients.push({
						title: jQuery.i18n.prop('p_parmesan'),
						image: "img/parmesan.png",
						type: "cheese",
						kcal: 115,
						costs: 1.50
					});
				
				} else if (technostuff[buything].currentlevel == 13) {
				
					ingredients.push({
                        title: jQuery.i18n.prop('p_chillisauce'),
                        image: "img/chillisauce.png",
                        type: "sauces",
                        kcal: 25,
                        costs: 1.25
                    });
				
				} else if (technostuff[buything].currentlevel == 14) {
					ingredients.push({
						title: jQuery.i18n.prop('p_ham'),
						image: "img/ham.png",
						type: "meat",
						kcal: 36,
						costs: 1.60
					});
				} else if (technostuff[buything].currentlevel == 15) {
					ingredients.push({
						title: jQuery.i18n.prop('p_salami'),
						image: "img/salami.png",
						type: "meat",
						kcal: 300,
						costs: 1.60
					});
					max_ingredients += 1;
				} else if (technostuff[buything].currentlevel == 16) {
					ingredients.push({
                        title: jQuery.i18n.prop('p_onion'),
                        image: "img/onion.png",
                        type: "fruits",
                        kcal: 1,
                        costs: 1.25
                    });
                    max_ingredients += 1;
                    amount_people += 10;
				}
			break;
			case 'herbsoda':
                inventory_add({ name: jQuery.i18n.prop('p_herbsoda'), price: 3, type: 'drinks', kcal:129, sugar: 33, score: 40 });
				//inventory.push(new item('Kräuterlimonade', 1, 6, 'drinks'));
			break;
			case 'energydrink':
                inventory_add({ name: jQuery.i18n.prop('p_energydrink'), price: 4, type: 'drinks', kcal:56, sugar: 14, score: 40 });
				//inventory.push(new item('Energy Drink', 1, 6, 'drinks'));
			break;
			/* KÜHLSCHRANK ZEUGS ENDE */
			
			/* SANDWICHMAKER ZEUGS BEGINN */
			case 'sandwichmaker':
				$('#sandwichbutton').button({ label: jQuery.i18n.prop('sandwichbutton') });
				$('#sandwichbutton').button("enable");
                
                ingredients.push({
                    title: jQuery.i18n.prop('p_toast'),
                    image: "img/toast.png",
                    type: "bread",
                    kcal: 143,
                    costs: 1.00
                });
                
                ingredients.push({
                    title: jQuery.i18n.prop('p_butter'),
                    image: "img/butter.png",
                    type: "cheese",
                    kcal: 25,
                    costs: 1.25
                });
                
                ingredients.push({
                    title: jQuery.i18n.prop('p_gouda'),
                    image: "img/gouda.png",
                    type: "cheese",
                    kcal: 416,
                    costs: 1.50
                });
                
                chooseBonusMalusIngredients();
                
			break;
			/* SANDWICHMAKER ZEUGS ENDE */
			
			/* VOGLR ZEUGS BEGINN */
			case 'voglr':
			break;
			/* VOGLR ZEUGS ENDE */
			
			/* GEFRIERSCHRANK ZEUGS BEGINN */
			case 'freezer': // freezer
				if (technostuff[buything].currentlevel == 1) {
                    inventory_add({ name: jQuery.i18n.prop('p_vanillacice'), price: 6, type: 'ice', kcal:124, sugar: 20, score: 40 });
				} else if (technostuff[buything].currentlevel == 2) {
					technostuff_add({ internalname: 'schokoice', name: jQuery.i18n.prop('p_schokoice'), description: jQuery.i18n.prop('p_schokoice_desc'), price: 200, maxlevel: 1, current_level: 0, category: 'product' });
				} else if (technostuff[buything].currentlevel == 3) {
					technostuff_add({ internalname: 'strawberryice', name: jQuery.i18n.prop('p_strawberryice'), description: jQuery.i18n.prop('p_strawberryice_desc'), price: 200, maxlevel: 1, current_level: 0, category: 'product' });
				} else if (technostuff[buything].currentlevel == 4) {
					technostuff_add({ internalname: 'lemonice', name: jQuery.i18n.prop('p_lemonice'), description: jQuery.i18n.prop('p_lemonice_desc'), price: 200, maxlevel: 1, current_level: 0, category: 'product' });
				} else if (technostuff[buything].currentlevel == 5) {
					technostuff_add({ internalname: 'bananaice', name: jQuery.i18n.prop('p_bananaice'), description: jQuery.i18n.prop('p_bananaice_desc'), price: 200, maxlevel: 1, current_level: 0, category: 'product' });
				} else if (technostuff[buything].currentlevel == 6) {
					technostuff_add({ internalname: 'mangoice', name: jQuery.i18n.prop('p_mangoice'), description: jQuery.i18n.prop('p_mangoice_desc'), price: 200, maxlevel: 1, current_level: 0, category: 'product' });
				} else if (technostuff[buything].currentlevel == 7) {
					technostuff_add({ internalname: 'stracciatellaice', name: jQuery.i18n.prop('p_stracciatellaice'), description: jQuery.i18n.prop('p_stracciatellaice_desc'), price: 200, maxlevel: 1, current_level: 0, category: 'product' });
				} else if (technostuff[buything].currentlevel == 8) {
					technostuff_add({ internalname: 'raspberryice', name: jQuery.i18n.prop('p_raspberryice'), description: jQuery.i18n.prop('p_raspberryice_desc'), price: 200, maxlevel: 1, current_level: 0, category: 'product' });
				} else if (technostuff[buything].currentlevel == 9) {
					technostuff_add({ internalname: 'nougatice', name: jQuery.i18n.prop('p_nougatice'), description: jQuery.i18n.prop('p_nougatice_desc'), price: 200, maxlevel: 1, current_level: 0, category: 'product' });
				} else if (technostuff[buything].currentlevel == 10) {
					technostuff_add({ internalname: 'blueberryice', name: jQuery.i18n.prop('p_blueberryice'), description: jQuery.i18n.prop('p_blueberryice_desc'), price: 200, maxlevel: 1, current_level: 0, category: 'product' });
					amount_people += 10;
				}
			break;
			case 'schokoice':
                inventory_add({ name: jQuery.i18n.prop('p_schokoice'), price: 6, type: 'ice', kcal:265, sugar: 21, score: 40 });
			break;
			case 'strawberryice':
                inventory_add({ name: jQuery.i18n.prop('p_strawberryice'), price: 6, type: 'ice', kcal:195, sugar: 21, score: 40 });
			break;
			case 'lemonice':
                inventory_add({ name: jQuery.i18n.prop('p_lemonice'), price: 6, type: 'ice', kcal:195, sugar: 21, score: 40 });
			break;
			case 'stracciatellaice':
                inventory_add({ name: jQuery.i18n.prop('p_stracciatellaice'), price: 6, type: 'ice', kcal:241, sugar: 21, score: 40 });
			break;
			case 'mangoice':
                inventory_add({ name: jQuery.i18n.prop('p_mangoice'), price: 6, type: 'ice', kcal:195, sugar: 21, score: 40 });
			break;
			case 'bananaice':
                inventory_add({ name: jQuery.i18n.prop('p_bananaice'), price: 6, type: 'ice', kcal:195, sugar: 21, score: 40 });
			break;
			case 'raspberryice':
                inventory_add({ name: jQuery.i18n.prop('p_raspberryice'), price: 6, type: 'ice', kcal:195, sugar: 21, score: 40 });
			break;
			case 'nougatice':
                inventory_add({ name: jQuery.i18n.prop('p_nougatice'), price: 6, type: 'ice', kcal:195, sugar: 21, score: 40 });
			break;
			case 'blueberryice':
                inventory_add({ name: jQuery.i18n.prop('p_blueberryice'), price: 6, type: 'ice', kcal:195, sugar: 21, score: 40 });
			break;
			/* GEFRIERSCHRANK ZEUGS ENDE */
			
			/* GRILL ZEUGS BEGINN */
			case 'grill':
				if (technostuff[buything].currentlevel == 1) {
					technostuff_add({ internalname: 'bratwurstl', name: jQuery.i18n.prop('p_bratwurstl'), description: jQuery.i18n.prop('p_bratwurstl_desc'), price: 200, maxlevel: 1, current_level: 0, category: 'product' });
                    ingredients.push({
                        title: jQuery.i18n.prop('p_toasted'),
                        image: "img/toasted.png",
                        type: "bread",
                        kcal: 143,
                        costs: 1.20
                    });
				} else if (technostuff[buything].currentlevel == 2) {
					technostuff_add({ internalname: 'burger', name: jQuery.i18n.prop('p_burger'), description: jQuery.i18n.prop('p_burger_desc'), price: 200, maxlevel: 1, current_level: 0, category: 'product' });
                    
                    ingredients.push({
                        title: jQuery.i18n.prop('p_grillsauce'),
                        image: "img/grillsauce.png",
                        type: "sauces",
                        kcal: 25,
                        costs: 1.25
                    });

                } else if (technostuff[buything].currentlevel == 3) {
                
                	technostuff_add({ internalname: 'bbqsauce', name: jQuery.i18n.prop('p_bbqsauce'), description: jQuery.i18n.prop('p_bbqsauce_desc'), price: 200, maxlevel: 1, current_level: 0, category: 'product' });
                
					ingredients.push({
                        title: jQuery.i18n.prop('p_cocktailsauce'),
                        image: "img/cocktailsauce.png",
                        type: "sauces",
                        kcal: 25,
                        costs: 1.25
                    });
                    
				} else if (technostuff[buything].currentlevel == 4) {

					technostuff_add({ internalname: 'bacon', name: jQuery.i18n.prop('p_bacon'), description: jQuery.i18n.prop('p_bacon_desc'), price: 200, maxlevel: 1, current_level: 0, category: 'product' });

					amount_people += 5;
                }
			break;
			case 'bacon':
				
				ingredients.push({
                    title: jQuery.i18n.prop('p_bacon'),
                    image: "img/bacon.png",
                    type: "meat",
                    kcal: 160,
                    costs: 1.50
                });
                
                amount_people += 10;
                
			break;
			case 'bbqsauce':
				                                    
                ingredients.push({
                    title: jQuery.i18n.prop('p_bbqsauce'),
                    image: "img/bbqsauce.png",
                    type: "sauces",
                    kcal: 25,
                    costs: 1.25
                });
                    
			break;
			case 'bratwurstl':
                inventory_add({ name: jQuery.i18n.prop('p_bratwurstl'), price: 6, type: 'snacks', kcal:306, sugar: 0, score: 40 });
			break;
			case 'burger':
                inventory_add({ name: jQuery.i18n.prop('p_hamburger'), price: 8, type: 'snacks', kcal:700, sugar: 7, score: 40 });
				
				ingredients.push({
					title: jQuery.i18n.prop('p_sesame_top'),
					image: "img/sesame_top.png",
					type: "bread",
					kcal: 143,
					costs: 1.00
				});
				ingredients.push({
					title: jQuery.i18n.prop('p_sesame_bottom'),
					image: "img/sesame_bottom.png",
					type: "bread",
					kcal: 143,
					costs: 1.00
				});
				ingredients.push({
					title: jQuery.i18n.prop('p_patty'),
					image: "img/patty.png",
					type: "meat",
					kcal: 200,
					costs: 2.00
				});
				ingredients.push({
					title: jQuery.i18n.prop('p_patty_piggy'),
					image: "img/patty-piggy.png",
					type: "meat",
					kcal: 200,
					costs: 2.00
				});
				ingredients.push({
					title: jQuery.i18n.prop('p_cheddar'),
					image: "img/cheddar.png",
					type: "cheese",
					kcal: 101,
					costs: 1.50
				});
				
				amount_people += 10;
			break;
			/* GRILL ZEUGS ENDE */
			
			/* KAFFEEMASCHINE BEGINN */
			case 'coffee':
                inventory_add({ name: jQuery.i18n.prop('p_cappuccino'), price: 4, type: 'drinks', kcal:197, sugar: 5, score: 40 });
				technostuff_add({ internalname: 'hotchoko', name: jQuery.i18n.prop('p_hotchoko'), description: jQuery.i18n.prop('p_hotchoko_desc'), price: 200, maxlevel: 1, current_level: 0, category: 'product' });
			break;
			case 'hotchoko':
                inventory_add({ name: jQuery.i18n.prop('p_hotchoko'), price: 4.5, type: 'drinks', kcal:948, sugar: 9, score: 40 });
			break;
			/* KAFFEEMASCHINE ENDE */
			
			/* KEBABSPIEß BEGINN */
			case 'kebabspear':
                inventory_add({ name: jQuery.i18n.prop('p_kebab'), price: 6.5, type: 'snacks', kcal:928, sugar: 13, score: 40 });
				technostuff_add({ internalname: 'durum', name: jQuery.i18n.prop('p_durum'), description: jQuery.i18n.prop('p_durum_desc'), price: 200, maxlevel: 1, current_level: 0, category: 'product' });
				
				ingredients.push({
					title: jQuery.i18n.prop('p_pide'),
					image: "img/pide.png",
					type: "bread",
					kcal: 120,
					costs: 1.10
				});
				
				ingredients.push({
					title: jQuery.i18n.prop('p_kebabmeat'),
					image: "img/kebab.png",
					type: "meat",
					kcal: 120,
					costs: 1.90
				});
				
			break;
			case 'durum':
                inventory_add({ name: jQuery.i18n.prop('p_durum'), price: 6.75, type: 'snacks', kcal:880, sugar: 125, score: 40 });
			break;
			/* KEBABSPIEß ENDE */
			
			/* BACKOFEN BEGINN */
			case 'oven':
				if (technostuff[buything].currentlevel == 1) {
                    inventory_add({ name: jQuery.i18n.prop('p_hambaguette'), price: 7, type: 'snacks', kcal:256, sugar: 35, score: 40 });
					technostuff_add({ internalname: 'salamibaguette', name: jQuery.i18n.prop('p_salamibaguette'), description: jQuery.i18n.prop('p_salamibaguette_desc'), price: 200, maxlevel: 1, current_level: 0, category: 'product' });
				} else if (technostuff[buything].currentlevel == 2) {
                    inventory_add({ name: jQuery.i18n.prop('p_hampizza'), price: 7, type: 'snacks', kcal:775, sugar: 98, score: 40 });
					technostuff_add({ internalname: 'salamipizza', name: jQuery.i18n.prop('p_salamipizza'), description: jQuery.i18n.prop('p_salamipizza_desc'), price: 200, maxlevel: 1, current_level: 0, category: 'product' });
					
					ingredients.push({
                        title: jQuery.i18n.prop('p_pizzabase'),
                        image: "img/pizzabase.png",
                        type: "bread",
                        kcal: 200,
                        costs: 1.50
                    });
					
					ingredients.push({
                        title: jQuery.i18n.prop('p_tomatosauce'),
                        image: "img/tomatosauce.png",
                        type: "sauces",
                        kcal: 38,
                        costs: 1.00
                    });
					
					amount_people += 10;
				}
			break;
			case 'salamibaguette':
                inventory_add({ name: jQuery.i18n.prop('p_salamibaguette'), price: 8, type: 'snacks', kcal:881, sugar: 108, score: 50 });
			break;
			case 'salamipizza':
                inventory_add({ name: jQuery.i18n.prop('p_salamipizza'), price: 8, type: 'snacks', kcal:256, sugar: 35, score: 50 });
			break;
			/* BACKOFEN ENDE */
			
			/* ALKOHOLLIZENZ BEGINN */
			case 'alclic':
				technostuff_add({ internalname: 'beer', name: jQuery.i18n.prop('p_beer'), description: jQuery.i18n.prop('p_beer_desc'), price: 200, maxlevel: 1, current_level: 0, category: 'product' });
				technostuff_add({ internalname: 'gspritzter', name: jQuery.i18n.prop('p_spritzer'), description: jQuery.i18n.prop('p_spritzer_desc'), price: 200, maxlevel: 1, current_level: 0, category: 'product' });
				technostuff_add({ internalname: 'alcopop', name: jQuery.i18n.prop('p_alcopop'), description: jQuery.i18n.prop('p_alcopop_desc'), price: 200, maxlevel: 1, current_level: 0, category: 'product' });
			break;
			case 'beer':
                inventory_add({ name: jQuery.i18n.prop('p_beer'), price: 7, type: 'drinks', kcal:215, sugar: 15, score: 60 });
			break;
			case 'gspritzter':
                inventory_add({ name: jQuery.i18n.prop('p_spritzer'), price: 8, type: 'drinks', kcal:136, sugar: 2, score: 40 });
			break;
			case 'alcopop':
                inventory_add({ name: jQuery.i18n.prop('p_alcopop'), price: 12, type: 'drinks', kcal:715, sugar: 22, score: 40 });
			break;
			/* ALKOHOLLIZENZ ENDE */
			
			/* FRITEUSE BEGINN */
			case 'friteuse':
				technostuff_add({ internalname: 'langos', name: jQuery.i18n.prop('p_langos'), description: jQuery.i18n.prop('p_langos_desc'), price: 200, maxlevel: 1, current_level: 0, category: 'product' });
				technostuff_add({ internalname: 'pommes', name: jQuery.i18n.prop('p_pommes'), description: jQuery.i18n.prop('p_pommes_desc'), price: 200, maxlevel: 1, current_level: 0, category: 'product' });
			break;
			case 'langos':
                inventory_add({ name: jQuery.i18n.prop('p_langos'), price: 7, type: 'snacks', kcal:2042, sugar: 65, score: 60 });
			break;
			case 'pommes':
                inventory_add({ name: jQuery.i18n.prop('p_pommes'), price: 5, type: 'snacks', kcal:1923, sugar: 69, score: 60 });
			break;
			/* ALKOHOLLIZENZ ENDE */
			
			/* TABAKLIZENZ BEGINN */
			case 'tabaklic':
				technostuff_add({ internalname: 'cigarettes', name:  jQuery.i18n.prop('p_cigarettes'), description:  jQuery.i18n.prop('p_cigarettes_desc'), price: 200, maxlevel: 1, current_level: 0, category: 'product' });
				technostuff_add({ internalname: 'cigar', name:  jQuery.i18n.prop('p_cigar'), description:  jQuery.i18n.prop('p_cigar_desc'), price: 200, maxlevel: 1, current_level: 0, category: 'product' });
			break;
			case 'cigarettes':
                inventory_add({ name:  jQuery.i18n.prop('p_cigarettes'), price: 14, type: 'wares', score: 40 });
                amount_people += 10;
			break;
			case 'cigar':
                inventory_add({ name:  jQuery.i18n.prop('p_cigar'), price: 15, type: 'wares', score: 40 });
                amount_people += 10;
			break;
			/* TABAKLIZENZ ENDE */
		}
		buything = -1;
	}
	if (content != '') {
		content = '<p>'+jQuery.i18n.prop('delivery_desc')+'</p><ul>'+content+'</ul>';
	}
	return content;
}
function get_current_orders() {
	var content = '';
	for (j=0;j<shoppinglist.length;j++) {
		content += '<span class="label">'+shoppinglist[j].name+'</span>: '+shoppinglist[j].amount+' x ('+jQuery.i18n.prop('days_remaining', shoppinglist[j].daysleft)+')<br />';
	}
	return content;
}


function updateTempMoney() {
	var tempmoney_container = document.getElementById('tempmoney');
	tempmoney_container.innerHTML = tempmoney+'$';
	if (tempmoney <= 0) {
		tempmoney_container.className = 'red';
	} else {
		tempmoney_container.className = 'normal';
	}
}

function shop_recalc_money() {
	var buyme = 0;
	tempmoney = money;
	for (var recalc_i=0;recalc_i<inventory.length;recalc_i++) {
        buyme = parseInt(document.getElementById('amount_'+recalc_i).value);
        if ((buyme < 0) || (isNaN(buyme))) {
        	document.getElementById('amount_'+recalc_i).value = 0;
			//console.log("something illegal: "+document.getElementById('amount_'+recalc_i).value);
        } else {
        	tempmoney -= buyme*inventory[recalc_i].sellFor;
        }
	}
	updateTempMoney();
}
function buyItem(i) {
	if ((tempmoney - inventory[i].price) >= 0) {
		tempmoney -= inventory[i].price;
		updateTempMoney();
		document.getElementById('amount_'+i).value = parseInt(document.getElementById('amount_'+i).value)+1;
		//updateMoney();
	} else {
		simpleDialog(jQuery.i18n.prop('sorry'), jQuery.i18n.prop('not_enough_money'));
	}
}
function sellItem(i) {
	if (parseInt(document.getElementById('amount_'+i).value) > 0) {
		tempmoney += inventory[i].price;
		updateTempMoney();
		document.getElementById('amount_'+i).value = parseInt(document.getElementById('amount_'+i).value)-1;
	}
}
function updateDayOfWeek() {
	var getDay = dayofweek+2;
	if (getDay > 6) getDay = getDay - 7;
	document.getElementById('dayofweek').innerHTML = getDayName(getDay);
}
function updateDay() {
	reloadCheckWeather();
	document.getElementById('day').innerHTML = day+1;
}
function updateRoundProgress() {
	var progressbar = $( "#roundprogressbar" );
	if (roundCounter < 3) {
		progressbar.progressbar("value", roundCounter*33);
	} else {
		progressbar.progressbar("value", 100);
	}
}
function updateMoney() {
	document.getElementById('money').innerHTML = money;
}
function setSellFor(i) {
//	var num = parseFloat(document.getElementById('sellfor_'+i).value);
	var num = parseFloat(document.getElementById('sellfor_'+i).value).toFixed(2);
	if (isNaN(num)) num = 0;
	inventory[i].sellFor = parseFloat(num);
}
function reloadCheckWeather() {
	if (weather.length == 0) {
		generateWeather();
	}
	var value = '';
	var dialog = document.getElementById('week_dialog');
	var weekday = dayofweek;
	for (i=0; i<weather.length; i++) {
		if (i == 2) {
			value += '<span class="row current">';
		} else {
			value += '<span class="row">';
		}
		value += '<span class="label_weekday">'+getDayName(weekday)+'</span>: '+getWeatherLabel(weather[i]);
		if (eventdaysleft >= 0) {
			if (i == (eventdaysleft+2)) value += ' ('+jQuery.i18n.prop('event')+')';
		}
		
		if (i == 2) {
			value += ' ('+jQuery.i18n.prop('today')+')';
		}
		
		value += '<br />';
		value += '</span>';
		weekday++;
		if (weekday > 6) weekday = 0;
	}
	dialog.innerHTML = '<p>'+value+'</p>';
}
function checkWeather() {
	reloadCheckWeather();
	$( "#week_dialog" ).dialog({title: jQuery.i18n.prop('week_forecast'), resizable: false, modal: false, maxHeight: ($(window).height()-10), buttons: [{ text: jQuery.i18n.prop('ok'), click: function() { $( this ).dialog( "close" ); } }]});
}
function getWeatherLabel(type) {
	switch(type) {
		case 'sunny': return jQuery.i18n.prop('sunny');
		case 'cloudy': return jQuery.i18n.prop('cloudy');
		case 'rainy': return jQuery.i18n.prop('rainy');
	}
}

function simulate_people_content() {
	var return_string = '';
	for (i = 0; i < sales.length; i++) {
		if (sales[i].amount > 0) {
			return_string += sales[i].name+': '+sales[i].amount+'<br />';
		}
	}
	if (income > 0) {
		return_string += '<span class="income">'+jQuery.i18n.prop('income')+' '+income+'$</span>';
	}
	return return_string;
}

function get_number_of_inventory_item(int_name) {
        for (k=0;k<inventory.length;k++) {
        if (inventory[k].internalname == int_name) return k;
    }
    return -1;
}

function simulate_people_v2() {
	console.log('simulate_people_v2()');
    round_amount_people = amount_people; // how many guests do we have today (in one round!!)
    
    // three days sunny in a row
    if ((weather[0] == 'sunny') && (weather[1] == 'sunny') && (weather[2] == 'sunny')) {
        round_amount_people = round_amount_people * 2; // more people are coming
        //want_type = want_type+10; // more people want something to drink
    // two days sunny in a row
    } else if ((weather[1] == 'sunny') && (weather[2] == 'sunny')) {
        round_amount_people = round_amount_people * 1.5; // more people are coming
        //want_type = want_type+10; // more people want something to drink
    } else if (weather[2] == 'cloudy') {
        round_amount_people = round_amount_people * 0.8; // less people are coming
    } else if (weather[2] == 'rainy') {
        round_amount_people = round_amount_people * 0.6; // less people are coming
    }

	/* ereigniskarte mit reisebus */    
    if (eventcard_bus == 1) {
    	round_amount_people = round_amount_people * 2; // more people are coming
    	eventcard_bus = 0;
    }

    /* eine veranstaltung findet statt */
    if (eventdaysleft == 0) {
        round_amount_people = round_amount_people * 2; // more people are coming
    }
    
    round_amount_people = Math.floor(round_amount_people);
    
    /* jede person benötigt gewisse eigenschaften */
    /* also, was für typen an leuten gibt es? */
    /* typen, die sich gesund ernähren, dh wenig zucker, wenig kalorien */
    /* typen, die ungesund essen, dh viel zucker, viel kalorien */
    /* typen, die beides essen? */
    /* super... */
    /* persons erzeugen */
    for(person = 0; person < round_amount_people; person++) {
    	//console.log('round_amount_people: '+round_amount_people+', person='+person);
    
        var type = Math.floor((Math.random()*100));
        human_wants = 'snacks';
        human_max_kcal = 400;
        human_max_sugar = 50;
        human_drink_refreshment = 0;
        human_drink_hot = 0;
        
        /* lets decide what he/she wants today */
        var wants = Math.floor((Math.random()*3));
        switch(wants) {
            case 0:
                human_wants = 'drinks';
                break;
            case 1:
                human_wants = 'snacks';
                break;
            case 2:
                human_wants = 'ice';
                break;
            case 3:
                human_wants = 'wares';
                break;
        }
        
        /* lets check if we want ice/wares but don't have that */
        if (human_wants == 'ice') {
            if (!has_techno_item('freezer')) {
                var decide = Math.floor((Math.random()*10));
                /* we nag around */
                if (decide < 2) {
                    round_opinions.push({ feeling: 'sad', message: jQuery.i18n.prop('opinion_ice_none')});
                    continue;
                /* we take something to drink instead */
                } else {
                    human_wants = 'drinks';
                }
            }
        }
        if (human_wants == 'wares') {
            if (!has_techno_item('tabaklic')) {
                var decide = Math.floor((Math.random()*10));
                /* we nag around */
                if (decide < 2) {
                    round_opinions.push({ feeling: 'sad', message: jQuery.i18n.prop('opinion_tobacco_none')});
                    continue;
                /* we take something to eat instead */
                } else {
                    human_wants = 'snacks';
                }
            }
        }
        
        /* make some weather decisions, do people want hot drinks? */
        if (human_wants == 'drinks') {
            var want_hot_drink = Math.floor((Math.random()*10));
            if (weather[2] == 'rainy') {
                if (want_hot_drink < 5) {
                    human_drink_hot = 1;
                }
            } else if (weather[2] == 'cloudy') {
                if (want_hot_drink < 3) {
                    human_drink_hot = 1;
                }
            }
        }
        
        /* type 1 */
        if (type < amount_type1) {
            human_max_kcal -= 280;
            human_max_sugar -= 20;
        /* type 2 */
        } else if (type < amount_type2) {
            human_max_kcal += 1000;
            human_max_sugar += 20;
        /* type 3 */
        } else {
        }
        
        /* na gut, lassen wir die spiele beginnen */
        /* mal sehen was für uns in frage kommt */
        var variety = get_variety(human_wants, human_max_kcal, human_max_sugar);

        //console.log("variety length = "+variety.length);
        //console.log("variety_all length = "+variety_all[human_wants].length);
        /* für uns gibt es nichts :( */
        if (variety.length == 0) {
            if (variety_all[human_wants].length > 0) {
                round_opinions.push({ feeling: 'sad', message: jQuery.i18n.prop('opinion_healtyh_none')});
            } else {
                round_opinions.push({ feeling: 'sad', message: jQuery.i18n.prop('opinion_selection_less')});
            }
            continue;
        }
        
        /* fast keine auswahl :( */
        if (variety.length*5 < variety_all[human_wants].length) {
            var pissed_off = Math.floor((Math.random()*2));
            if (pissed_off == 1) {
                round_opinions.push({ feeling: 'sad', message: jQuery.i18n.prop('opinion_healtyh_none')});
                continue;
            }
        }
        
        /* sodala wir treffen unsere wahl */
        var max_score = 0; // = 100
        for(var score_counter=0; score_counter < variety.length; score_counter++) {
            //console.log("score for "+score_counter+" ("+variety[score_counter].name+") is "+variety[score_counter].score);
            max_score += variety[score_counter].score;
        }
        
        //console.log("score is "+max_score);
        
        /* wieviel prozent ist ein score wert */
        var score_part = Math.ceil(max_score / 100);
        
        //console.log("1 score is "+score_part);
        
        // roll the dice
        //var number = Math.floor(Math.random()*variety.length);
        var number = Math.floor(Math.random()*100+1);
        
        //console.log("our number is "+number);
        
        var number_counter = 0;
        while((number > 0) && (number_counter < variety.length )) {
            //console.log("number_counter is "+number_counter);
            number -= score_part*variety[number_counter].score;
            number_counter++;
        }
        number_counter--;
        //console.log("number_counter is "+number_counter);
        //console.log("and the winner is "+number_counter+" which is "+variety[number_counter].name);
        
        
        //console.log('variety_length '+variety.length+' number '+number);
        //console.log(variety);
        var want_product = variety[number_counter];
        
        //continue;
        
        var buy_it = 0;
		/* nichts kaufen, dass eine score von 0 oder niedriger hat */
		if (variety[number_counter].score <= 0) {
			buy_it = 0;
			round_opinions.push({ feeling: 'sad', message: jQuery.i18n.prop('opinion_zeroscore', want_product.name)});
        /* wenns unterm einkaufspreis is kaufens die leute immer */
        } else if (want_product.price > want_product.sellFor) {
            buy_it = 1;
            round_opinions.push({ feeling: 'happy', message: jQuery.i18n.prop('opinion_cheap', want_product.name)});
        /* kostet es mehr als das dreifache vom einkaufspreis -> niemand kaufts */
        } else if (want_product.sellFor > (want_product.price*3)) {
            round_opinions.push({ feeling: 'sad', message: jQuery.i18n.prop('opinion_expensive_much', want_product.name)});
            continue;
        /* je nach preis (3*einkaufspreis = 100%) kaufens die leute */
        } else {
            /* siehe bsp unten */
            var x = (100 / (want_product.price*3)) * (want_product.sellFor - want_product.price);
            /* ermitteln einer zahl von 1 bis 100 */
            var r2 = Math.floor((Math.random()*100)+1);
            /* wenn die zahl größer is als unser x dann wirds gekauft */
            
            var well_no = Math.floor((Math.random()*2));
            if (well_no != 1) {
		        if (r2 > x) {
		            buy_it = 1;
		            round_opinions.push({ feeling: 'happy', message: jQuery.i18n.prop('opinion_bought', want_product.name)});
		        } else {
		            round_opinions.push({ feeling: 'sad', message: jQuery.i18n.prop('opinion_expensive', want_product.name)});
		        }
            } else {
            	round_opinions.push({ feeling: 'neutral', message: jQuery.i18n.prop('opinion_later', want_product.name)});
            }
            
            /* beispiel
            chips kosten 10$, wir verkaufens um 21$
            10$ * 3 = 30$, das ist das maximum
            
            30$ ... 100% kaufens nicht?
            21$ ... (100 / 30) * 21 = 70% kaufens ned?
            
            wir ziehen noch den einkaufspreis ab damit der prozentsatz besser wird...
            21$ ... (100/30) * (21-10) = 36,6% kaufens ned            
            */
            
        }
        
        /* wenns gekauft worden ist */
        if (buy_it) {
            
            want_product.amount--; /* aus dem inventar entfernen */
            money += want_product.sellFor; /* geld hinzufügen */
            income += want_product.sellFor; /* geld hinzufügen */
            points += (want_product.sellFor - want_product.price); /* add points */
            updateMoney(); /* geld betrag updaten */
            var product = get_number_of_inventory_item(want_product.internalname);
            if (product > -1) sales[product].amount++; /* verkauf statistik aktualisieren */
        }
    }
    
    if (has_techno_item('sandwichmaker')) {
        round_opinions.push({ feeling: 'neutral', message: jQuery.i18n.prop('opinion_bonus', ingredients[bonusing[0]].title)});
        round_opinions.push({ feeling: 'neutral', message: jQuery.i18n.prop('opinion_bonus', ingredients[bonusing[1]].title)});
        round_opinions.push({ feeling: 'neutral', message: jQuery.i18n.prop('opinion_malus', ingredients[bonusing[0]].title)});
        round_opinions.push({ feeling: 'neutral', message: jQuery.i18n.prop('opinion_malus', ingredients[bonusing[1]].title)});
    }
    
}

function get_variety(type, max_kcal, max_sugar) {
    var ret = new Array();
    for (k=0;k<inventory.length;k++) {
       console.log(k);
        if ((inventory[k].type == type) && (inventory[k].amount > 0) && (inventory[k].kcal < max_kcal) && (inventory[k].sugar < max_sugar)) {
            ret.push(inventory[k]);
        }
    }
    console.log(ret);
    return ret;
}

function eventCard() {
	var card = Math.floor(Math.random()*7);
	//alert(card);
	var card_shown = 1;
	var card_content = '<b>#'+card+'</b><br />';
	switch(card) {
		case 0: /* nix */
			card_shown = 0;
		break;
		case 1: /* lotterie */
			card_content += jQuery.i18n.prop('eventcard_lottery');
			money += 20;
			updateMoney();
		break;
		case 2: /* falschparken */
			card_content += jQuery.i18n.prop('eventcard_fine');
			money -= 15;
			updateMoney();
		break;
		case 3: /* stromausfall des gefrierschranks */
			if (has_techno_item('freezer', 0)) {
				card_content += jQuery.i18n.prop('eventcard_freezer');
				var content = '';
				for (i=0;i<inventory.length;i++) {
					if ((inventory[i].type == 'ice') && (inventory[i].amount > 0)) {
						var bad = Math.floor(Math.random()*inventory[i].amount);
						if (bad > 0) {
							inventory[i].amount -= bad;
							content += '<br />'+inventory[i].name+': '+bad;
						}
					}
				}
				if (content == '') {
					card_content += ' '+jQuery.i18n.prop('eventcard_freezer_none');
				} else {
					card_content += ' '+jQuery.i18n.prop('eventcard_freezer_bad')+':'+content;
				}
			} else {
				card_shown = 0;
			}
		break;
		case 4:	/* event */
			eventdaysleft = 4;
			card_content += jQuery.i18n.prop('eventcard_event', eventdaysleft);
		break;
		case 5: /* delivery problem */
			if (shoppinglist.length > 0) {
				for (j=0;j<shoppinglist.length;j++) {
					shoppinglist[j].daysleft++;
				}
				card_content += jQuery.i18n.prop('eventcard_delivery');
			} else {
				card_shown = 0;
			}
		break;
		case 6: /* reisebus */
			card_content += jQuery.i18n.prop('eventcard_fine');
			eventcard_bus = 1;
		break;
		default:
			card_shown = 0;
		break;
	}
	if (card_shown == 1) {
		simpleDialog(jQuery.i18n.prop('eventcard_title'), '<p>'+card_content+'</p>');
		//document.getElementById('eventcard').innerHTML = 'Eine ereignislose Woche geht vorüber.';
		//$( "#eventcard" ).dialog({title: jQuery.i18n.prop('eventcard_title'), modal: true, resizable: false, maxHeight: ($(window).height()-10), buttons: [{ text: jQuery.i18n.prop('ok'), click: function() { $( this ).dialog( "close" ); } }]});
	}
}

function help_link(title, page) {
    return '<a class="help_link" href="#" onclick="javascript:help(\''+page+'\')">'+title+'</a>';
}

function helpDialog(title, msg, return_to, dialogwidth) {
    if (dialogwidth == undefined) dialogwidth = '500';
    if (return_to == undefined) return_to = 0;
    dialogwidth += 'px';
    document.getElementById('dialog').innerHTML = msg;
    $( "#dialog" ).dialog({title: title, width: dialogwidth, resizable: false, maxHeight: ($(window).height()-10), modal: true, buttons: [{ text: jQuery.i18n.prop('ok'), click: function() {
        $( this ).dialog( "close" ); 
        if (return_to == 1) help(); /* return to help index */
    } }] });
}

function achievementsDialog() {
	var content = '<p class="hint">'+jQuery.i18n.prop('points')+': '+points+' + '+(amount_people-10)+'</p>';
	var achievments_length = getArrayLength(available_achievements);
	for(var ach = 0; ach < achievments_length; ach++) {
		content += '<div class="achievement_entry';
		if (has_achievement(available_achievements[ach].internalname)) {
			content += ' earned';
		}
		content += '">';
		content += '<div class="achievement_title">'+available_achievements[ach].title+'</div>';
		content += '<div class="achievement_desc">'+available_achievements[ach].description+'</div>';
		content += '</div>';
	}
	simpleDialog(jQuery.i18n.prop('achievements_title'), content, 500);
}

function credits() {
	$( "#creditsdialog" ).dialog({title: jQuery.i18n.prop('game_info'), width: '300px', resizable: false, maxHeight: ($(window).height()-10), modal: true, buttons: [{ text: jQuery.i18n.prop('ok'), click: function() { $( this ).dialog( "close" ); } }] });
}
function help(page) {
    var page_content = '';
    if (page == undefined) {
        
        page_content = '<p>'+jQuery.i18n.prop('help_topics')+'</p>';
        page_content += '<ul>';
        page_content += '<li>'+help_link(jQuery.i18n.prop('help_topics_general'), 'general')+'</li>';
        page_content += '<li>'+help_link(jQuery.i18n.prop('help_topics_week'), 'week')+'</li>';
        page_content += '<li>'+help_link(jQuery.i18n.prop('help_topics_shop'), 'shop')+'</li>';
        page_content += '<li>'+help_link(jQuery.i18n.prop('help_topics_research'), 'research')+'</li>';
        if (has_techno_item('sandwichmaker')) {
            page_content += '<li>'+help_link(jQuery.i18n.prop('help_topics_sandwiches'), 'sandwiches')+'</li>';
        }
        page_content += '</ul>';
        
        simpleDialog(jQuery.i18n.prop('help_title'), page_content);
    } else if (page == 'general') {
        page_content = jQuery.i18n.prop('help_topics_general_content');
        helpDialog(jQuery.i18n.prop('help_topics_general'), page_content, 1);
    } else if (page == 'week') {
        page_content = jQuery.i18n.prop('help_topics_week_content');
        helpDialog(jQuery.i18n.prop('help_topics_week'), page_content, 1);
    } else if (page == 'shop') {
        page_content = jQuery.i18n.prop('help_topics_shop_content');
        helpDialog(jQuery.i18n.prop('help_topics_shop'), page_content, 1);
    } else if (page == 'research') {
        page_content = jQuery.i18n.prop('help_topics_research_content');
        helpDialog(jQuery.i18n.prop('help_topics_research'), page_content, 1);
    } else if (page == 'sandwiches') {
        page_content = jQuery.i18n.prop('help_topics_sandwiches_content');
        helpDialog(jQuery.i18n.prop('help_topics_sandwiches'), page_content, 1);
    }
    
}
