/* SANDWICH RELATED FUNCTIONS */

function removeSandwichContent(sandwich, content_number) {
	sandwiches[sandwich]['ingredients'].splice(content_number, 1);
	document.getElementById('sandwich_contents').innerHTML = getSandwichContent(sandwich); // reload sandwich view
	document.getElementById('sandwichdialog').innerHTML = getSandwichesList(); // reload sandwich list (to reflect amount ingredients)
	//$('#sandwichdialog_edit').dialog('option', 'position', 'center');
	recenterDialog('#sandwichdialog_edit');
}

function upSandwichContent(sandwich, content_number) {
	// swap the elements
	var temp_element = sandwiches[sandwich]['ingredients'][content_number-1];
	sandwiches[sandwich]['ingredients'][content_number-1] = sandwiches[sandwich]['ingredients'][content_number];
	sandwiches[sandwich]['ingredients'][content_number] = temp_element;
	document.getElementById('sandwich_contents').innerHTML = getSandwichContent(sandwich); // reload sandwich view
}

function downSandwichContent(sandwich, content_number) {
	// swap the elements
	var temp_element = sandwiches[sandwich]['ingredients'][content_number+1];
	sandwiches[sandwich]['ingredients'][content_number+1] = sandwiches[sandwich]['ingredients'][content_number];
	sandwiches[sandwich]['ingredients'][content_number] = temp_element;
	document.getElementById('sandwich_contents').innerHTML = getSandwichContent(sandwich); // reload sandwich view
}

function getSandwichContent(i) {
	if (sandwiches[i]['ingredients'].length == 0) {
		return jQuery.i18n.prop('ingredients_none');
	} else {

		var cnt = '';
		var total_costs = 0;

		for(j=0;j<sandwiches[i]['ingredients'].length;j++) {
			cnt += '<div class="sandwich_content_item"><div class="sandwich_content_image"><img src="'+ingredients[sandwiches[i]['ingredients'][j]].image+'" /></div><div class="sandwich_content_title">'+ingredients[sandwiches[i]['ingredients'][j]].title+'</div><div class="sandwich_content_costs">'+parseFloat(ingredients[sandwiches[i]['ingredients'][j]].costs).toFixed(2)+' $</div><div class="sandwich_content_commands">';
			if (j > 0) {
				cnt += '<a href="javascript:upSandwichContent('+i+', '+j+')"><img src="img/up.png" alt="'+jQuery.i18n.prop('ingredients_up')+'" title="'+jQuery.i18n.prop('ingredients_up')+'" /></a> ';
			}
			if ((j+1) < sandwiches[i]['ingredients'].length) {
				cnt += '<a href="javascript:downSandwichContent('+i+', '+j+')"><img src="img/down.png" alt="'+jQuery.i18n.prop('ingredients_down')+'" title="'+jQuery.i18n.prop('ingredients_down')+'" /></a> ';
			}
			cnt += '<a href="javascript:removeSandwichContent('+i+', '+j+')"><img src="img/delete.png" alt="'+jQuery.i18n.prop('ingredients_del')+'" title="'+jQuery.i18n.prop('ingredients_del')+'" /></a></div></div>';
			total_costs += parseFloat(ingredients[sandwiches[i]['ingredients'][j]].costs);
		}

		cnt += '<p class="hint">'+jQuery.i18n.prop('sandwich_costs')+': '+parseFloat(total_costs).toFixed(2)+' $, '+jQuery.i18n.prop('sellfor')+' '+parseFloat(getSandwichSellFor(i)).toFixed(2)+' $, '+jQuery.i18n.prop('ingredients_amount', sandwiches[i]['ingredients'].length, max_ingredients)+'</p>';
		
		setSandwichPriceAndScore(i, parseFloat(total_costs).toFixed(2));
		
		return cnt;
	}
}

function getSandwichScore(sandwich) {
	var overall_score = 10;
    var types = new Array();
    var ingreds = new Array();
    var has_bonus_0 = false;
    var has_bonus_1 = false;
    var has_malus_0 = false;
    var has_malus_1 = false;
	console.log('getsandwichscore = '+sandwich);
	
	/* no ingredients at all */
	if (sandwiches[sandwich]['ingredients'].length == 0) {
		return 0;
	}
	
	for(var jx=0;jx<sandwiches[sandwich]['ingredients'].length;jx++) {
		if (ingredients[sandwiches[sandwich]['ingredients'][jx]].score == undefined) {
			overall_score += 10;
		} else {
			overall_score += sandwiches[sandwich]['ingredients'][jx].score;
		}
		console.log("type is "+ingredients[sandwiches[sandwich]['ingredients'][jx]].type);
		if (types[ingredients[sandwiches[sandwich]['ingredients'][jx]].type] == undefined) {
            types[ingredients[sandwiches[sandwich]['ingredients'][jx]].type] = 1;
            
        } else {
            types[ingredients[sandwiches[sandwich]['ingredients'][jx]].type]++;
        }
        if (ingreds[ingredients[sandwiches[sandwich]['ingredients'][jx]].title] == undefined) {
            ingreds[ingredients[sandwiches[sandwich]['ingredients'][jx]].title] = 1;
        } else {
            ingreds[ingredients[sandwiches[sandwich]['ingredients'][jx]].title]++;
        }
        if (sandwiches[sandwich]['ingredients'][jx] == bonusing[0]) {
            has_bonus_0 = true;
        } else if (sandwiches[sandwich]['ingredients'][jx] == bonusing[1]) {
            has_bonus_1 = true;
        } else if (sandwiches[sandwich]['ingredients'][jx] == malusing[0]) {
            has_malus_0 = true;
        } else if (sandwiches[sandwich]['ingredients'][jx] == malusing[1]) {
            has_malus_1 = true;
        }
	}
	console.log(types);
    console.log(ingreds);
    
    var types_len = getArrayLength(types);
    var ingreds_len = getArrayLength(types);
    
	console.log("types l "+types_len+", ingreds l "+ingreds_len);
	
	// check if only consists of one type
	if (types_len <= 1) {
        overall_score = 0;
        console.log("too few types of ingredients");
    }
    
    /* check for good stuff */
    if (has_bonus_0 || has_bonus_1) {
        overall_score * 2;
    }
    
    /* check for bad stuff */
    if (has_malus_0 || has_malus_1) {
        overall_score / 2;
    }
        
    // check if there is bread at all
    if (types['bread'] == 0) {
        overall_score = 0;
        console.log("no bread");
    }
    
    // check if there is too much bread ( > 66%)
    if (types['bread'] > ((2 * sandwiches[sandwich]['ingredients'].length) / 3)) {
        overall_score = overall_score / 5;
        console.log("too much bread");
    }
    
    // check if there is bread on the bottom
    if (ingredients[sandwiches[sandwich]['ingredients'][sandwiches[sandwich]['ingredients'].length-1]].type != 'bread') {
        overall_score = overall_score / 5;
        console.log("no bread at the bottom but "+ingredients[sandwiches[sandwich]['ingredients'][sandwiches[sandwich]['ingredients'].length-1]].type);
    }
    
    // take age into account
    var age = day - sandwiches[sandwich]['creation_day'];
    overall_score = overall_score - (day * 0.02); // loose 2% a day
    
	console.log("sandwich score is "+overall_score);
	return overall_score;
}

function getSandwichSellFor(sandwich) {
	for(js=0;js<inventory.length;js++) {
	    if ((inventory[js].internalname == sandwich) && (inventory[js].type == 'snacks')) {
	        return inventory[js].sellFor;
	    }
	}
	return 0;
}

function setSandwichPriceAndScore(sandwich, price) {
	for(js=0;js<inventory.length;js++) {
	    if ((inventory[js].internalname == sandwich) && (inventory[js].type == 'snacks')) {
	        inventory[js].price = price;
			inventory[js].score = getSandwichScore(sandwich);
	        break;
	    }
	}
}

/* set initial sellfor */
function setSandwichSellFor(i) {
	if (sandwiches[i]['sellfor_set'] == 0) {
		sell_for = 0;
		if (sandwiches[i]['ingredients'].length > 0) {
			for(j=0;j<sandwiches[i]['ingredients'].length;j++) {
				sell_for += parseFloat(ingredients[sandwiches[i]['ingredients'][j]].costs);
			}
			sell_for += 1;
		}
	
		for(js=0;js<inventory.length;js++) {
			if ((inventory[js].internalname == i) && (inventory[js].type == 'snacks')) {
			    inventory[js].sellFor = sell_for;
			    sandwiches[i]['sellfor_set'] = 1;
			    break;
			}
		}
	}
}

/* re-set score of all sandwiches */
function setAllSandwichScore() {
    for(ja=0;ja<inventory.length;ja++) {
        if (inventory[ja].sandwich == true) {
            inventory[ja].score = getSandwichScore(inventory[ja].internalname);
        }
    }
}

function addIngredients(sandwich, content) {
	if (sandwiches[sandwich]['ingredients'].length < max_ingredients) {
		sandwiches[sandwich]['ingredients'].unshift(content);
		document.getElementById('sandwich_contents').innerHTML = getSandwichContent(sandwich); // reload sandwich view
		document.getElementById('sandwichdialog').innerHTML = getSandwichesList(); // reload sandwich list (to reflect amount ingredients)
		//$('#sandwichdialog_edit').dialog('option', 'position', 'center');
		recenterDialog('#sandwichdialog_edit');
	} else {
		simpleDialog(jQuery.i18n.prop('ingredients_add_error'), jQuery.i18n.prop('ingredients_add_error_max', max_ingredients));
	}
}

function chooseBonusMalusIngredients() {
    console.log('choosing bonusmalus ingredients...');
    if (ingredients.length >= 4) {
        /*bonusing[0] = -1;
        bonusing[1] = -1;
        malusing[0] = -1;
        malusing[1] = -1;
        while((bonusing[0] == bonusing[1]) || (malusing[0] == malusing[1])) {
            bonusing[0] = Math.floor((Math.random()*ingredients.length));
            bonusing[1] = Math.floor((Math.random()*ingredients.length));
            malusing[0] = Math.floor((Math.random()*ingredients.length));
            malusing[1] = Math.floor((Math.random()*ingredients.length));
        }*/
        
        var arr = []
		while(arr.length < 4){
			var randomnumber = Math.floor((Math.random()*ingredients.length));
			var found=false;
			for(var i=0;i<arr.length;i++) {
				if(arr[i]==randomnumber) {found=true;break}
			}
			if(!found)arr[arr.length]=randomnumber;
		}
	
		bonusing[0] = arr[0];
		bonusing[1] = arr[1];
		malusing[0] = arr[2];
		malusing[1] = arr[3];

    }
    console.log('done');
}

function addSandwichContent(i) {
	document.getElementById('bread').innerHTML = '';
	document.getElementById('sauces').innerHTML = '';
	document.getElementById('meat').innerHTML = '';
	document.getElementById('fruits').innerHTML = '';
	document.getElementById('cheese').innerHTML = '';
	for(j=0;j<ingredients.length;j++) {
		document.getElementById(ingredients[j].type).innerHTML += '<div class="content_list_item"><div class="content_list_image"><img src="'+ingredients[j].image+'" /></div><div class="content_list_title">'+ingredients[j].title+'</div><div class="content_list_costs">'+parseFloat(ingredients[j].costs).toFixed(2)+' $</div><div class="sandwich_content_commands"><a href="javascript:addIngredients('+i+', '+j+')"><img src="img/add.png" alt="'+jQuery.i18n.prop('ingredients_add_single')+'" title="'+jQuery.i18n.prop('ingredients_add_single')+'" /></a></div></div>';
	}
	$( "#sandwichcontent_add" ).dialog({title: jQuery.i18n.prop('ingredients_add_title'), width: '600px', modal: true, resizable: false, maxHeight: ($(window).height()-10), buttons: [{ text: jQuery.i18n.prop('close'), click: function() { setSandwichSellFor(i); $( this ).dialog( "close" ); } }]});
}

function editSandwich(i) {
	document.getElementById('sandwich_contents').innerHTML = getSandwichContent(i);
	//$( "#sortable" ).sortable();
	$( "#sortable" ).disableSelection();
	$( "#sandwichdialog_edit" ).dialog({title: jQuery.i18n.prop('ingredients_add', sandwiches[i]['name']), width: '600px', modal: true, maxHeight: ($(window).height()-10), resizable: false, buttons: [{ text: jQuery.i18n.prop('ingredients_add'), click: function() { addSandwichContent(i); }}, { text: jQuery.i18n.prop('close'), click: function() { $( this ).dialog( "close" ); } }]});
}

function delSandwich(i) {
	sandwiches.splice(i, 1);
	document.getElementById('sandwichdialog').innerHTML = getSandwichesList();
    // we need to remove it from the inventory as well :/
    for(j=0;j<inventory.length;j++) {
        //alert(inventory[j].internalname);
        if ((inventory[j].internalname == i) && (inventory[j].type == 'snacks')) {
            inventory.splice(j, 1);
            break;
        }
    }
    //$('#sandwichdialog').dialog('option', 'position', 'center');
    recenterDialog('#sandwichdialog');
}

function getSandwichesList() {
    var ret = '';
    if (sandwiches.length == 0) {
        ret = '<p>'+jQuery.i18n.prop('sandwiches_none')+'</p>';
    } else {
        ret = '';
        for(i=0;i<sandwiches.length;i++) {
            ret += '<div class="sandwich_list_item"><div class="sandwich_list_title">'+sandwiches[i]['name']+'<br /><span class="sandwich_list_ingredients">'+sandwiches[i]['ingredients'].length+' '+jQuery.i18n.prop('ingredients')+'</span></div>';
            //ret += '<div class="sandwich_list_commands"><button onclick="editSandwich('+i+')">Zutaten bearbeiten</div>';
            ret += '<div class="sandwich_list_commands"><button onclick="javascript:editSandwich('+i+')"><img title="'+jQuery.i18n.prop('sandwich_edit')+'" alt="'+jQuery.i18n.prop('sandwich_edit')+'" src="img/edit.png" /></button> <button onclick="javascript:delSandwich('+i+')"><img title="'+jQuery.i18n.prop('sandwich_del')+'" alt="'+jQuery.i18n.prop('sandwich_del')+'" src="img/delete.png" /></button></div></div>';
            ret += '</div>';
        }
    }
    return ret;
}

function sandwichDialog_close() {
	if (sandwiches.length > 0) earn_achievement('mrsandwich');
	if (setting_autosave) save(0);
}

function sandwichDialog() {
    document.getElementById('sandwichdialog').innerHTML = getSandwichesList();
	$( "#sandwichdialog" ).dialog({title: jQuery.i18n.prop('sandwiches_title'), modal: true, resizable: false, maxHeight: ($(window).height()-10), buttons: [{ text: jQuery.i18n.prop('sandwich_new'), click: function() { sandwichDialog_new(); }}, { text: jQuery.i18n.prop('close'), click: function() {  sandwichDialog_close(); $( this ).dialog( "close" ); } }]});
}

function sandwichDialog_new() {
    $( "#sandwichdialog_new" ).dialog({title: jQuery.i18n.prop('sandwich_new_desc'), modal: true, resizable: false, maxHeight: ($(window).height()-10), buttons: [{ text: jQuery.i18n.prop('sandwich_new_title'), click: function() {
        if (document.getElementById('sandwichname_newname').value != '') {
            sandwich_create();
            //$('#sandwichdialog').dialog('option', 'position', 'center');
            recenterDialog('#sandwichdialog');
            $(this).dialog("close");
        } else {
            simpleDialog(jQuery.i18n.prop('sandwich_error'), jQuery.i18n.prop(sandwich_error_name));
        }
    }}, { text: jQuery.i18n.prop('sandwich_new_cancel'), click: function() { $( this ).dialog( "close" ); } }]});
}

function sandwich_create() {
	/*var new_sandwich = new Array();
	new_sandwich['name'] = document.getElementById('sandwichname_newname').value;
    new_sandwich['creation_day'] = day;
	new_sandwich['ingredients'] = new Array();*/
    sandwiches.push({
    	name: document.getElementById('sandwichname_newname').value,
    	creation_day: day,
    	ingredients: new Array(),
    	sellfor_set: 0
    });
    document.getElementById('sandwichdialog').innerHTML = getSandwichesList();
    /* this adds sandwich to the inventory */
    inventory_add({ name: document.getElementById('sandwichname_newname').value, internalname: (sandwiches.length-1), price: 0, type: 'snacks', score: 0, sandwich: true });
    /* clean up for next usage */
    document.getElementById('sandwichname_newname').value = '';
}
