var is_default = false;
var clear_it = true;
var food_count = 0;
var meal_count = 0;
var mealNo = 0;
var input_boxes = new Array();
var meal_input_boxes = new Array();
var dropAt;

//clear textbox upon clicking the textbox so that the user won't have to delete the text themselves
function clearTextbox(ori_text, div_name) {
	if ($(div_name) != null) {
			if ($(div_name).value == ori_text) {
			$(div_name).value = "";
		}
	}
}

//put the values back if user leaves it blank
function fillTextbox(ori_text, div_name) {
	if ($(div_name) != null) {
		if ($(div_name).value == "") {
			$(div_name).value =  ori_text;
		}
	}
}

//get all foods
function getInitialResult() {
	var tmpVar = new Ajax.Updater ( 'result', 'mp_add_getList.php');
}

//get all meal_plans
function getInitialResult_mp() {
	var tmpVar = new Ajax.Updater ( 'result','mp_getList.php');
}

//wait few seconds to run runRequest
function sendRequest() {
	//setTimeout(alert('ajax_call'),500);
	setTimeout(function () {
		runRequest();
	}, 0);
	

}

//submit form to search for the ads
function runRequest() {
	is_default = false;
	var tmpVar = new Ajax.Updater('result', 'mp_add_getList.php', { method:'post', onComplete:function() { $('result').show(); }, asynchronous:true, parameters: $('searchform').serialize(true) });
}

function init() {
	
	var i = "";
	for (i=1; i<= 15; i++) {
		if ($('item'+i) != null)
		{
			var tmpVar2 = new Draggable( "item"+i , { revert: true } );
			Droppables.add('column2', { onDrop: function(element) { dropped(element) } });
		}
	}
}

//e = element that is being dragged
//d = location of being dropped
function dropped(e) {
	
	if (e.childNodes[0].innerHTML == null) {	
	
			//if the selected meal plan is visible only!
			if ( $(selectedMealPlan).style.display != "none" )  {
			//if ( $(selectedMealPlan).style.display == "visible" )  {
		
			//get food id
			if (e.childNodes[9] != null) var food_id = e.childNodes[9].id;
			if (e.childNodes[1] != null) var food_name = e.childNodes[1].innerHTML;
			
			if (e.childNodes[11] != null) var default_size = e.childNodes[11].value;
			if (e.childNodes[13] != null) var default_unit = e.childNodes[13].value;
			
			if (e.childNodes[3] != null) var carb = (e.childNodes[3].value)/default_size; //get carbs of 1 gram then multiply by size again
			if (e.childNodes[5] != null) var protein = (e.childNodes[5].value)/default_size;
			if (e.childNodes[7] != null) var fat = (e.childNodes[7].value)/default_size;
			if (e.childNodes[9] != null) var calories = (e.childNodes[9].value);
			

			var cup = '';
			var oz = '';
			var gram = '';
			var kg = '';
			var lbs = '';
			
			//selected
			switch (default_unit) {
				case 'cup':
					cup = 'selected';
					break;
				case 'oz':
					oz = 'selected';
					break;
				case 'gram':
					gram = 'selected';
					break;
				case 'kg':
					kg = 'selected';
					break;
				case 'lbs':
					lbs = 'selected';
					break;
			}
		
			food_count++;
			//saveBufferData();
			
			$(selectedMealPlan).innerHTML += '<div id="foodId_'+food_id+'_'+food_count+'_dropped" class="foodrow">'
					+'<div class="food-name">'+food_name+'</div>'
					
					+'<input name="food['+selectedMealPlan+'][]" id="food_'+food_id+'" type="hidden" value="'+food_id+'_'+food_count+'" />'
					
					+'<input name="carb['+selectedMealPlan+'][]" id="carb_'+food_id+'" type="hidden" value="'+carb+'" />'
					+'<input name="protein['+selectedMealPlan+'][]" id="protein_'+food_id+'" type="hidden" value="'+protein+'" />'
					+'<input name="fat['+selectedMealPlan+'][]" id="fat_'+food_id+'" type="hidden" value="'+fat+'" />'
					
					+'<input name="cal_for['+selectedMealPlan+'][]" id="cal_for_food_'+food_id+'_'+food_count+'" type="hidden" value="'+calories+'" />'
					+'<div class="food-serve"><input name="foodUnit['+selectedMealPlan+'][]" class="gram" type="text" value="'+default_size+'" id="foodUnit_'+food_count+'" onkeyup="countCalories(\'foodUnit_'+food_count+'\',\'unitType_'+food_id+'_'+food_count+'\',\'foodCal_'+food_id+'_'+food_count+'\', '+calories+', '+carb+', '+protein+', '+fat+')" onKeyPress="return disableEnterKey(event)" />'
					+'<select id="unitType_'+food_id+'_'+food_count+'" name="unitType['+selectedMealPlan+'][]" onchange="countCalories(\'foodUnit_'+food_count+'\',\'unitType_'+food_id+'_'+food_count+'\',\'foodCal_'+food_id+'_'+food_count+'\', '+calories+', '+carb+', '+protein+', '+fat+' )" >'
				
					  +'<option value="cup" '+cup+'>cup</option>'
					  +'<option value="oz" '+oz+'>ounce</option>'
					  +'<option value="gram" '+gram+'>gram</option>'
					  +'<option value="kg" '+kg+'>Kg.</option>'
					  +'<option value="lbs" '+lbs+'>pounds</option>'
					
					+'</select><img src="../img/icon_trash.gif" style="cursor:pointer" onclick="deleteFood(\'foodId_'+food_id+'_'+food_count+'_dropped\', \'foodCal_'+food_id+'_'+food_count+'\')" /></div>'
					+'<div id="foodCal_'+food_id+'_'+food_count+'" class="food-weight">0</div><div class="clearfix"></div>'
					+'</div>';
			//loadBufferData();
						
			countCalories('foodUnit_'+food_count,'unitType_'+food_id+'_'+food_count+'','foodCal_'+food_id+'_'+food_count+'', calories, carb, protein, fat);
		
			foods.push(food_id+'_'+food_count);
			//alert(foods);
		}
	}
}

function drawMealPlan(mealName, fadeBool) {

	if (mealName != '') {
			
		mealNo++;
		meal_count++;
		$('no_of_meals').innerHTML = "<p> No of meals <strong>" + meal_count + "</strong> </p>";
		
		//var hider = 'style="display:none;"';
		if (fadeBool == true) var hider = 'style="display:none;"';
		else var hider = "";
		
		
		var mealBlocks = 	'<div style="cursor: move;" id="meal'+mealNo+'" '+hider+' " onclick="selectMealPlan(\'meal'+mealNo+'\')" >'+ 
							'<input name="meal_index[]" id="meal'+meal_count+'" type="hidden" value="'+meal_count+'" />'+
							'<p class="mealnamerow">'+
							'<input name="meal_name[]" id="meal_name'+meal_count+'" class="mealname" type="text" value="'+mealName+' (edit name)" onKeyPress="return disableEnterKey(event)" />'+
							'<img src="../img/icon_trash.gif" style="cursor:pointer" onclick="deleteMeal(\'meal'+mealNo+'\')"/></p>'+
							'<!-- div to hold foods in this meal -->'+
								'<div id="meal'+mealNo+'_droppable" class="droppables">'+
								'<div id="notification_meal'+mealNo+'"></div></div></div>'; 
		
				
		
		//$('dropAt').innerHTML += mealBlocks;
		$('meal_space').innerHTML += mealBlocks;
		
		//new Effect.Appear('meal'+mealNo, { queue: 'end' } );
		
		if (fadeBool == true) { Effect.Appear('meal'+mealNo );}
		else {
			if ($('meal'+mealNo) != null) { $('meal'+mealNo).show(); }
		}
	}
	
	Sortable.create('meal_space',{ constraint: 'vertical', tag: 'div' });
}

function disableEnterKey(e) {
     var key;     
     if(window.event)
          key = window.event.keyCode; //IE
     else
          key = e.which; //firefox     
     return (key != 13);
}

function deleteMeal(mealID) {
	
	var food_deleted = 0;
	
	for (i=4; i < 30; i++) {
	
		if ($(mealID).childNodes[i] != null) {
			foodID = $(mealID).childNodes[i].id;
			div_id = 'foodCal_' + $(mealID).childNodes[i].childNodes[0].value;
		
			deleteFood(foodID, div_id);
			food_deleted++;
		}
		
	}
	
	food_count = food_count - food_deleted;
		
	Effect.Fade( $(mealID));
	//$('meal_space').removeChild($(mealID));
	meal_count--;
	$('no_of_meals').innerHTML = "<p> No of meals <strong>" + meal_count + "</strong> </p>";
	
}

function deleteFood(foodID, div_id) {
	
	
	//selected_food_id = $(selectedMealPlan).childNodes[3].childNodes[1].value;
	if ($(foodID).childNodes[6].childNodes[0]) {
		
		original_serving_size = $(foodID).childNodes[6].childNodes[0].value;
		//$('total_calories').innerHTML = calories;
		
		$(foodID).childNodes[6].childNodes[0].value = 0;
	}
	
	
	$(foodID).innerHTML = "";
	
	myCalories[div_id] = 0;
	myCarb[div_id] = 0;
	myProtein[div_id] = 0;
	myFat[div_id] = 0;
	SumCalories(myCalories);
	

	//$('total_calories').innerHTML = twoDecimals(total_calories);
	//$(selectedMealPlan).removeChild($(foodID));
	//$('dropAt_notify').innerHTML = $(foodID).innerHTML;
	Effect.Fade( $(foodID), { duration: 0.7 } );
	
	food_count--;
}

function selectMealPlan(mealID) {
	
	//mealID = NEW 
	//selectedMealPlan = PREVIOUS MEAL PLAN
	
	//if the clicked id isn't the current id 
	Droppables.remove('column2');
	
	if (mealID != selectedMealPlan) {
		
		//reset the last one
		//if the previous one does exist (if this is NOT the first one)
		if ($(selectedMealPlan) != null) {
			
			// what happens when a div is unselected/de-selected (?) i'm not sure what the real term is...
			//============================================================================================
			$(selectedMealPlan).className = "";
			//new Effect.Scale(selectedMealPlan, 50, { scaleX: false } );
			var tmpVar = new Effect.Morph(selectedMealPlan, { style: 'background:#FFFFFF',  duration: 0.8});
			$('notification_'+selectedMealPlan).innerHTML = '';
			//============================================================================================
			
			//remove droppable effect
			//alert(selectedMealPlan+'_droppable removed from being droppable');
			//Droppables.remove(selectedMealPlan);
		}
		
		//what happens when a DIV is selected
		//============================================================================================
		$(mealID).className = "selected_meal";
		//new Effect.Scale(mealID, 200, { scaleX: false } );
		var tmpVar2 = new Effect.Morph(mealID, { style: 'background:#FDFBF7',  duration: 0.8 });
		$('notification_'+mealID).innerHTML = '';
		//============================================================================================
		
		///Droppables.add(mealID, { onDrop: function(element) { dropped(element) } }); //dropped(element)
		//Droppables.add('column2', { onDrop: function(element) { dropped(element) } }); //dropped(element)
				
		//record the new selected Meal Plan
		selectedMealPlan = mealID;
		
	}
	
}

function reloadGraph(carbs, fat, protein ) {
	var f = $('graph_iframe');
	f.src = "meal_plan_graph.php?protein=" + protein + "&fat= " + fat + "&carbs=" + carbs;
}

function mp_pageChange(page) {
	gotoPage = 'mp_add_getList.php?page='+page;
	if (is_default == true) gotoPage = 'mp_add_getList.php?page='+ page + '&mode=default'; //untuk page yg load automatically (so that page 2 dia x screw up)
	
	$('loading').style.display='block';
	var tmpVar = new Ajax.Updater('result', gotoPage, { method:'post',	onComplete:function() { var tmpVar2 = new Effect.Fade('loading');	}, asynchronous:true, parameters: $('searchform').serialize(true) }	);
}

function saveBufferData() {
	//  buffer array
	//=========================================================================
		for (i = 0; i < food_count; i++) {
			//save the item's value so that it wudnt reset when dragged into the meal
			
			if ($F('foodUnit_'+(i+1)) != null) {
				alert($F('foodUnit_'+(i+1)));
				input_boxes[i] = $F('foodUnit_'+(i+1));
			}
			
		}

	
	for (i = 0; i < meal_count; i++) {
		//save the item's value so that it wudnt reset when dragged into the meal
					
		if ($F('meal_name'+(i+1) ) != null) {
			meal_input_boxes[i] = $F('meal_name'+ (i+1) );
		}
	}
	
	//============================end buffer====================================
}

function loadBufferData() {
	//  buffer array
	
	// situation: when dragged into a div, the contents of the divs reset itself because of the innerHTML usage.
	
	//=========================================================================
	for (i = 0; i < food_count; i++) {
		//save the item's value so that it wudnt reset when dragged into the meal
		
		if (input_boxes[i] != null) {
			$F('foodUnit_'+(i+1)) = parseFloat(input_boxes[i]);
			
		}
	}
	
	/*for (i = 1; i <= meal_count; i++) {
		//save the item's value so that it wudnt reset when dragged into the meal
				
		if (meal_input_boxes[i] != null) {
			$F('meal_name'+i) = meal_input_boxes[i];
		}
	}*/
	
	//============================end buffer====================================
}
