/* init
*/

function hideNavLists()
{
	//$('#nav .nav-list').hide();
	$('#nav .nav-list ul').slideUp("slow");
	//$('#navCuisines').slideUp("fast", function(){$('#navMealtypes').slideUp("fast")} );
}

function activateNavLinks()
{
	$("#navCuisine").attr("href", "javascript: openNav('#navCuisines');");
	$("#navMealtype").attr("href", "javascript: openNav('#navMealtypes');");
}

function activateSearchLinks(){
	if($(".search-advanced a").size() > 0)
		$(".search-advanced a").attr("href", "javascript: navSearch('advanced');");
	else if($(".search-ingredient a").size() > 0)
		$(".search-ingredient a").attr("href", "javascript: navSearch('ingredient');");
}

function disableSearchSubmit()
{
	$("#search_submit").attr("onclick", "advancedSearch(); return false;");
}

function overlayTopRecipes()
{
	$("#top-recipes .recipe").each(
	function()
	{	
		$(this).addClass("recipe-overlaid");
		$(this).css("background", "url(" + $(this).children("img").attr('src') + ") no-repeat 0 0");
		$(this).attr("onmouseover", "topRecipeOver(this);");
		$(this).attr("onmouseout", "topRecipeOut(this);");
	});
}

function topRecipeOver(el)
{
	//$("#activeTopRecipe h3").css("height", $("#"+$(el).attr('id')+" h3 a").height() + $("#activeTopRecipe .classification").height());
}

function topRecipeOut(el)
{
	
}

function navSearch(searchType)
{
	var NewAdvancedHTML 	= $(".search-ingredient").html().split("ingredient").join("advanced");	
	var NewIngredientHTML 	= $(".search-advanced").html().split("advanced").join("ingredient");

	$(".search-advanced").html(NewAdvancedHTML);
	$(".search-ingredient").html(NewIngredientHTML);
	
	if(searchType == "advanced")
		$("#search-ingredient").fadeOut(400,
			function()
			{
				$("#search-"+searchType).fadeIn(400);
			}
		);
	else if(searchType == "ingredient")
		$("#search-advanced").fadeOut(400,
			function()
			{
				$("#search-"+searchType).fadeIn(400);
			}
		);
}

/*	Search
*/

function removeIngredientSearch(element)
{
    $(element).parent().remove();
}

function addIngredient()
{
	if($("#add_ingredient").size() > 0)
	{	
		if($("#add_ingredient").val().trim() != '')
		{
			var liClass = ($("#search-ingredient li").size() % 2 == 0) ? 'odd' : 'even';
			
			$("#search-ingredient ul").html(
				$("#search-ingredient ul").html() + 
				"<li id='ingredient"+$("#search-ingredient li").size()+"' class='"+liClass+"'><a href='javascript:;' onclick='removeIngredientSearch(this);'><img src='"+site_root+"img/icons/delete.png' alt='remove' /></a><em>"+$("#add_ingredient").val()+"</em></li>"
			);
			
			$("#add_ingredient").val('');
			
			if($("#search-ingredient li").size() > 1)
			{
				$("#search-ingredient fieldset").fadeIn(200);
			}
			
			if($("#search-ingredient li").size() > 2)
			{
				ingredientSearch(); // ajax.js
			}
		}
	} else if($(".recipe-ingredients").size() > 0)
	{
        var add = $('#newIngredientButton').val() == 'Add ingredient';
        if ($("#recipe_ingredient").val().length < 2 ||
            !$("#recipe_quantity").val().match(/^[0-9]+$/) ||
            $("#recipe_quantity").val().length == 0)
        {
            alert('Please fill in all the fields before adding an ingredient!\n(Quantity must be a rounded integer, not a floating point)');
            return;
        }
        if (add) {
            $.ajax({
                type: "POST",
                cache: false,
                url: site_root + "ajax/recipeAddIngredient/",
                data: {ingredient: $("#recipe_ingredient").val(),
                        quantity: $("#recipe_quantity").val(),
                        type: $("#recipe_quantitytype").val(),
                        typegroup: $('#recipe_quantitytype option:selected').attr("class"),
                        recipe: $('#recipe_id').val() },
                success: function(e)
                {
                    $(".recipe-ingredients ul").html(
                        $(".recipe-ingredients ul").html() + e);
                    
                    if($(".recipe-ingredients ul li").size() > 1)
                    {
                        $(".recipe-ingredients ul").fadeIn(200);
                    }
                }
            });
        }
        else
        {
            $.ajax({
                type: "POST",
                cache: false,
                url: site_root + "ajax/recipeEditIngredient/",
                data: {ingredient: $("#recipe_ingredient").val(),
                        quantity: $("#recipe_quantity").val(),
                        type: $("#recipe_quantitytype").val(),
                        ingredientid: $('#recipe_ingredientid').val()},
                success: function(e)
                {
                    $('#ingredient_'+$('#recipe_ingredientid').val()).html(e);
                    $('#ingredient_'+$('#recipe_ingredientid').val()).css('opacity',"1.0");
                    $('#ingredient_'+$('#recipe_ingredientid').val()).fadeIn(200);
                }
            });
            $('#ingredient_'+$('#recipe_ingredientid').val()).fadeOut(200);
        }
        $("#recipe_ingredient").val('');
        $("#recipe_quantity").val('');
        $("#recipe_quantitytype").val('');
        $('#newIngredientButton').val('Add ingredient');
        $('#cancelIngredientButton').hide();
	}
}

function cancelEdit()
{
    $(".recipe-ingredients ul li").css("opacity","1.0");
    $('#newIngredientButton').val('Add ingredient');
    $('#recipe_ingredient').val('');
    $('#recipe_quantity').val('');
    $('#recipe_quantitytype').val('');
    $('#cancelIngredientButton').hide();
}

function deleteIngredient(id)
{
    $.ajax({
        type: "POST",
        cache: false,
        url: site_root + "ajax/recipeDeleteIngredient/",
        data: {ingredient: id,
                recipe: $('#recipe_id').val() },
        success: function(e)
        {
            $(".recipe-ingredients ul").html(e);
            
            if($(".recipe-ingredients ul li").size() > 1)
            {
                $(".recipe-ingredients ul").fadeIn(200);
            }
        }
    });
}

function editIngredient(id)
{
    $('#recipe_ingredient').val($('#ingredient_'+id+' .name').html());
    $('#recipe_quantity').val($('#ingredient_'+id+' .amount').html());
    $('#recipe_quantitytype').val($('#ingredient_'+id+' .name').html());
    $(".recipe-ingredients ul li").css("opacity","1.0");
    $('#ingredient_'+id).css("opacity","0.5");
    $('#recipe_ingredientid').val(id);
    $('#newIngredientButton').val('Edit ingredient');
    $('#cancelIngredientButton').show();
    ingredientRefresh($('#recipe_ingredient').val());
}

function openIngredientSuggest()
{
	$("#ingredient-suggest").show();
}

function sexyListOutput(listId)
{
	$("#"+listId+" li").hide();
	$("#"+listId).show();
	
	var oCount = 0;
	$("#"+listId+" li").each(
		function()
		{
			oCount++;
			$(this).attr("id", "recipe"+oCount);
			setTimeout("$('#recipe"+oCount+"').fadeIn(200);", oCount*150);
		}
	);
}


/* 	General User Experience
*/ 

function openNav(id)
{
	var speed = 400;

	$(id+" ul").slideDown(speed*1.5, 
	function() {
		if(id=='#navCuisines')
		{
			$("#navMealtypes ul").slideUp(speed);
		}
		else if(id=='#navMealtypes')
		{
			$("#navCuisines ul").slideUp(speed);
		}
	});
	
	return;
}

/*	Recipe Comments
*/

function replyTo(commentId)
{
	$("#comment_replyto").val(commentId);

	if(commentId==0)
	{
		$("#replyto").hide();
	} else
	{
		$("#replyto_short").html($("#comment"+commentId+" .comment-contents p:first-child").html());
		$("#replyto_username").html($("#comment"+commentId+" h3 .name a").html());
		$("#replyto").show();
	}

}

/*	Recipe Measures
*/

function changeServings()
{
	var originalServings = $("#recipe .ingredients .servings em").html();
	var currentServings = $("#recipe .ingredients .servings em span").html();
	
	var newHTML = "<strong>Currently</strong> meant for ";
	
	newHTML +="<em><select onchange='convertByServings(this.value)'>";
	
	for(i=1; i<=20; i++)
	{
		personString = (i==1) ? "person" : "people";
		selected = (i == currentServings) ? " selected='selected'" : "";
		newHTML += "<option"+selected+" value='"+i+"'>"+i+" "+personString+"</option>";
	}
	
	newHTML +="</select></em>";
	newHTML +="<span class='hide'>Originally for "+originalServings+"</span>";
	
	$("#recipe .ingredients .servings").html(newHTML);
}

	function convertByServings(newServings)
	{
		$('#recipe .ingredients .conversion-data em').html(newServings);
		applyConversion();
/*		var conversionFactor = newServings / $("#recipe .ingredients .servings .hide span").html();
		
		var count=0;
		$("#recipe .ingredients table .amount .current").each(
			function()
			{
				$(this).html((Math.round($("#recipe .ingredients .originalamount em").get(count).innerHTML * conversionFactor *10)/10).toString());
			
				count++;
			}
		);*/
	}

function toStep(i)
{
    $e('#recipeStep').value = i;
    $e('#recipeForm').submit();
}
function addStep()
{
    $e('#newStep').disabled = "disabled";
    $e('#newStepButton').disabled = "disabled";
    $.ajax({
        type: "POST",
        cache: false,
        url: site_root + "ajax/recipeAddStep/",
        data: { recipe: $('#recipe_id').val(),
                description: $e('#newStep').value },
        success: function(e)
        {
            $e('#recipe-steps').innerHTML = e;
        }
    });
}

function stepDelete(id)
{
    $.ajax({
        type: "POST",
        cache: false,
        url: site_root + "ajax/recipeDelStep/",
        data: { step: id },
        success: function(e)
        {
            $e('#recipe-steps').innerHTML = e;
        }
    });
}

function stepMoveDown(id)
{
    $.ajax({
        type: "POST",
        cache: false,
        url: site_root + "ajax/recipeStepDown/",
        data: { step: id },
        success: function(e)
        {
            $e('#recipe-steps').innerHTML = e;
        }
    });
}

function stepMoveUp(id)
{
    $.ajax({
        type: "POST",
        cache: false,
        url: site_root + "ajax/recipeStepUp/",
        data: { step: id },
        success: function(e)
        {
            $e('#recipe-steps').innerHTML = e;
        }
    });
}

function stepEdit(id, value)
{
    $.ajax({
        type: "POST",
        cache: false,
        url: site_root + "ajax/recipeEditStep/",
        data: { step: id, value: value },
        success: function(e)
        {
            $e('#stepdd_' + id).innerHTML = e;
        }
    });
}

function delImage(imgid)
{
    $.ajax({
        type: "POST",
        cache: false,
        url: site_root + "ajax/recipeDelImage/",
        data: { image: imgid },
        success: function(e)
        {
            $e('#image_holder').innerHTML = e;
        }
    });
}

function moveImage(imgid, dir)
{
    $.ajax({
        type: "POST",
        cache: false,
        url: site_root + "ajax/recipeMoveImage/",
        data: { image: imgid,
                direction: dir },
        success: function(e)
        {
            $e('#image_holder').innerHTML = e;
        }
    });
}


function addFileStart()
{
    $e('#recipe_image').disabled = "disabled";
    $e('#recipe_image_button').disabled = "disabled";
}

function addFileComplete()
{
    $.ajax({
        type: "POST",
        cache: false,
        url: site_root + "ajax/recipeListImages/",
        data: { recipe: $('#recipe_id').val()},
        success: function(e)
        {
            $e('#image_holder').innerHTML = e;
        }
    });
}

function ingredientRefresh(name)
{
    $("#recipe_quantitytype").hide();
    $.ajax({
        type: "POST",
        cache: false,
        url: site_root + "ajax/recipeIngredientType/",
        data: {'ingredient': name},
        success: function(e)
        {
            var oldvalue = $('#recipe_quantitytype').val();
            var newvalue = '';
            var found = false;
            
            $('#recipe_quantitytype optgroup').attr('disabled',1);
            $('#recipe_quantitytype optgroup'+e).removeAttr('disabled');
        
            $('#recipe_quantitytype optgroup:enabled').each(function(e) {
                    $(this).children().each(function (e) {
                        if ($(this).val() == oldvalue)
                        {
                            newvalue = $(this).val();
                            found = true;
                        }
                        else if (!found && newvalue == '') newvalue = $(this).val();
                    })
                });
            //$e('#recipe_quantitytype').selectedIndex = sl;
            //$('#recipe_quantitytype').val($e('#recipe_quantitytype').options[sl].value);
            //alert('From ' + oldvalue + ' to ' +  $e('#recipe_quantitytype').options[sl].value);
            $('#recipe_quantitytype').show();
            $('#recipe_quantitytype').val(newvalue);
        }
    });    
}    


function applyConversion()
{
	var people = $('#recipe .ingredients .conversion-data em').html();
	var system = $('#recipe .ingredients .conversion-data strong').html();
	var servings = $("#recipe .ingredients .servings .hide span").html();

	if (servings == null)
	{
		servings = $("#recipe .ingredients .servings span").html();
	}

	var conversionFactor = people / servings;

	$('#recipe .ingredients tr').each(
		function()
		{
			var basetype = $(this).children(".originalamount").children("strong").html();
			var basescale = $(this).children(".originalamount").children("small").html();
			var baseval = $(this).children(".originalamount").children("em").html() * conversionFactor * systemScale(basetype, basescale);
			var newing = measureConverter(baseval,basetype,system);
			
			$(this).children(".amount").children("span").html(newing['value']);
			$(this).children(".measure").children("span").html(newing['type']);
		}
	);
}

function systemScale(type, scale)
{
	for (var s in convertArr[type.toLowerCase()])
	{
		for (var i in convertArr[type.toLowerCase()][s])
		{
			if (i == scale)
			{
				return convertArr[type.toLowerCase()][s][i];
			}
		}
	}
	return 0;
}

function changeMeasures()
{
	var currentMeasure = $("#recipe .ingredients .measures em").html();
	var newHTML = "Measures are in ";
	
	if(currentMeasure == "Metric")
	{
		metricSelected = " selected='selected'";
		imperialSelected = "";
	} else {
		metricSelected = "";
		imperialSelected = " selected='selected'";
	}
	
	newHTML +="<em><select onchange='convertByMeasures(this.value)'>";
	newHTML +="<option"+metricSelected+" value='metric'>Metric</option>";
	newHTML +="<option"+imperialSelected+" value='imperial'>Imperial</option>";
	newHTML +="</select></em>";

	$("#recipe .ingredients .measures").html(newHTML);
}

function convertByMeasures(newvalue)
{
	$('#recipe .ingredients .conversion-data strong').html(newvalue);
	applyConversion();
}


var convertArr = {
					'solid':{
						'metric':{
							'gr':1,
							'kg':1000},
						'imperial':{
							'tsp':4.33,
							'tbsp':14,
							'oz':28,
							'cup':225,
							'lb':453.6}},
				   	'fluid':{
						'metric':{
							'ml':1,
							'dl':10,
							'cl':100,
							'l':1000},
						'imperial':{
							'tsp':5,
							'tbsp':15,
							'oz':30,
							'cup':240,
							'pt':473.18,
							'qt':946.35,
							'gal':3785.41}},
					'piece':{
						'metric':{
							'piece':1},
						'imperial':{
							'piece':1}}
					};

function measureConverter(value, type, system)
{
	/*
	value in base values
	system in 0 (metric) or 1 (imperial)
	type in 0 (solid), 1 (fluid) or 2 (pieces)
	*/
	type = type.toLowerCase();
	system = system.toLowerCase();

	var newvalue = 1E10;
	var newname = '';
	var debug = '';
	debug = type + "-" + system + ": " + value + "\n";

	for (var i in convertArr[type][system])
	{
		debug += "   " + i + " = " + convertArr[type][system][i] + "\n";

		var tempval = value / convertArr[type][system][i];
		if ((tempval >= 1 && tempval < newvalue) ||
			(newvalue == 1E10))
		{
			debug += "         newval! " + tempval + "\n" ;

			newvalue = tempval;
			newname = i;
		}
	}
	//alert(debug);
	return {'value':(Math.round(newvalue*100)/100),'type':newname};
}

