/*
The following js file will contain functions with regards to the overlay popup (Add item, and edit item popups)
*/

var MP_ADDED_ITEMS = {};


function sendCategoryGroupRequest()
{

	var category_selected_value = $('#categories_additem :selected').val();

	if(category_selected_value == "sel")
	{
		
		resetFormAddItem()
		
	}
	else
	{
		
		
		 $.post(
				"/fr_ca/babyclub/menu_planner/ajax_response/add_item_get_category_groups.php",
				{
				  category_id: category_selected_value
				},
				populateCategoryGroups,
				"json"
				
				);
	}
}
function populateCategoryGroups(data)
{
	var selectBox = "<select class='option' name='category_groups' id='category_groups_additem' onchange='javascript:sendProductRequest()' style='width:auto;'><option value='sel'>- Choisir un groupe -</option>"

	for(i=0; i < data.length; i++)
	{
		selectBox = selectBox + "<option value='"+ data[i].category_group_id+"'>"+data[i].category_group_name+"</option>";
	}
	
	selectBox = selectBox + "</select>";
	
	$('#category_groups_select').html(selectBox);
}

function sendProductRequest()
{
	var category_groups_selected_value = $('#category_groups_additem :selected').val();

	if(category_groups_selected_value == "sel")
	{
		resetFormAddItem()
		
	}
	else
	{
		 $.post(
				"/fr_ca/babyclub/menu_planner/ajax_response/add_item_get_products.php",
				{
				  category_group_id: category_groups_selected_value
				},
				populateProducts,
				"json"
				
				);
	}
	
}
function populateProducts(data)
{
	var selectBox = "<select class='option' name='products' id='products_additem' style='width:auto;'><option value='sel'>- Choisir un produit -</option>";

	for(i=0; i < data.length; i++)
	{
		selectBox = selectBox + "<option value='"+ data[i].product_id+"'>"+data[i].product_name+" (&Eacute;tape "+data[i].product_stage+")</option>";
	}
	
	selectBox = selectBox + "</select>";
	
	$('#products_select').html(selectBox);
	
}

function hideMenuPlannerError(close_box_on_ok)
{
  if(close_box_on_ok == undefined)
  {
	  close_box_on_ok = "false"
  }
  
  if(close_box_on_ok == "true")
  {
	  BAM_AD_hide();
  }
  else
  {
	 $('#menuplanner_error_content').hide()
     $('#menuplanner_content').show()  
  }
  
  
  
}
function showMenuPlannerError()
{
  //this function shows the menu planner error and hides the main content area
  $('#menuplanner_error_content').show()
  $('#menuplanner_content').hide()
}
function hideTools()
{
	BAM_AD_hide();
}
function resetFormAddItem()
{
	$('#category_groups_select').html("<select class='option' name='category_groups' name='category_groups_additem' style='width:auto;'><option value='sel'>- Choisir un groupe -</option></select>")
	$('#products_select').html("<select class='option' name='products' name='products_additem' style='width:auto;'> <option value='sel'>- Choisir un produit -</option></select>")
}
function submitFormMenuPlanner(isedit)
{
	  if(isedit == undefined)
	  {
		  isedit = "false"
	  }
	  
	   var child_id = $('#child_id').val();
	   
	   var error_text = "";
	   
	   if(isedit == "false")
	   {
	   		var categories_selected_index      = $('#categories_additem :selected').val();
			var categories_selected_value      = $('#categories_additem :selected').val();
	   		var category_groups_selected_value = $('#category_groups_additem :selected').val();
	   		var product_selected_value         = $('#products_additem :selected').val();
			var product_selected_text          = $('#products_additem :selected').text();	  
	   		var other_product                  = $('#other_product_additem').val();

	   		var isCheck = false //boolean used to check if user has selected at least one checkbox true if there is at least one checked check box
	   
	   		var isCategoriesSelected = true
	   		var isCategoryGroupSelected = true
	   		var isProductSelected = true
			
			
			if(categories_selected_value == "sel" && other_product == "")
	   		{
		   		error_text = "Choisissez une cat&eacute;gorie.<br/>"
		   		isCategoriesSelected = false
	   		}
	   		if(category_groups_selected_value == "sel" && other_product == "")
	   		{
		   		error_text = error_text + "Choisissez un groupe.<br/>"
		   		isCategoryGroupSelected = false
	   		}
	   
	   		if(product_selected_value == "sel" && other_product == "")
	   		{
		    	error_text = error_text + "Choisissez un produit.<br/>"
		    	isProductSelected = false
	   		}
	    }
	   		
	  

	   
	var data = {};
	MP_ADDED_ITEMS = {};
	
	
	var dayNamesList = new Array( 'sun', 'mon', 'tues', 'wed', 'thurs', 'fri', 'sat');
	var mealsList    = new Array('break', 'morning_snack', 'lunch', 'afternoon_snack', 'dinner', 'other_snack');		
	
	//Get the arry length, faster execution
	var dnLength = dayNamesList.length;
	var mLength  = mealsList.length;
	
	//Loops through the days of the week
	
	for(var i=0;i<dnLength;i++)
	{
		//alert('IN I LOOP '+dayNamesList[ i ]);
		//Loops through the meals
		for(var j=0;j<mLength;j++)
		{			
		   var itemName = dayNamesList[ i ] + '_' + mealsList[ j ];
		   if( $('#'+itemName ).val() == 1 )
		   {			  
			 data[ itemName ] = $('#'+itemName ).val();
			 MP_ADDED_ITEMS[ i ] = product_selected_text;
			 isCheck = true;
		   }		
		}
		
	}
		    	   
	    
	   //if there are no checkboxes selected
	   if(isCheck == false)
	   {
		   error_text = error_text + "Choisissez le(s) repas et le(s) jour(s) <br/>auxquels vous aimeriez ajouter l&rsquo;&eacute;l&eacute;ment."
		   
		  
	   }
	   
	   
	   if(error_text != "")
	   {
		   $('#menuplanner_error_text').html(error_text)
		   showMenuPlannerError()
	   }
	   //if the user has selected at least one check box and chose a child we send the ajax request
	   else
	   {
		  
		   if(product_selected_value != "sel")
		   {
			   other_product = "";
		   }
		   else
		   {
			   product_selected_value = "-1";
		   }
		   
		   
		   
		   //////////////////////////////////
		   //MP_ADDED_ITEMS
		   
		   
			//Adding non meal related data   
			data[ 'isedit' ]        = isedit;
			data[ 'child' ]         = child_id;
			data[ 'prod' ]          = product_selected_value;
			data[ 'other_product' ] = other_product;		  
			
			
			var urlAddItem  = '/fr_ca/babyclub/menu_planner/ajax_response/menuplanner_response.php';
			
			$.post(
				urlAddItem,
				data,
				formResponseMenuPlanner,
				"json"		
			);
		  
	     
		   
	   }

	   
}
function submitFormMenuPlanner_notheinz()
{
	   isedit = "true";
	  
	   var child_id      = $('#child_id').val();
	   var prod          = $('#products_additem :selected').val();
	   var other_product = $('#other_product_additem').val();
	   
	 	var data = { 'child': child_id, 'prod': product_selected_value, 'other_product': other_product };
	   
	   
	   $('#menuplanner_error_text').html(error_text);
	   showMenuPlannerError();
	  
		$.post( "/fr_ca/products/ajax_response/menuplanner_response.php", data, formResponseMenuPlanner, "json" );
}


function setMenuPlannerAddedItems()
{
	
//tues_morning_snack_1
}

function getAvailableWeekDayRow( week_day )
{
	
	//NOT USEDDDDDDDDDDDDDDDD
	week_day = 2;
	
	
	var dayNamesList = new Array('mon', 'tues', 'wed', 'thurs', 'fri', 'sat', 'sun');
	var mealsList    = new Array('break', 'morning_snack', 'lunch', 'afternoon_snack', 'dinner', 'other_snack');		
	var dayName = dayNamesList[week_day];
	//Get the arry length, faster execution
	var dnLength = dayNamesList.length;
	var mLength  = mealsList.length;
	
	var emptyRow = '';
	//Loops through the days of the week

	var currentRow = 1;
		//Loops through the meals
		for(var j=0;j<mLength;j++)
		{
			var nameValue = $('#'+dayName+'_'+mealsList[j]+'name'+currentRow).html();
			if(nameValue == '')
			{
				emptyRow
			}
			currentRow++
		}
		
		
		//mon_morning_snack

}

function formResponseMenuPlanner(data)
{
	//if there is no error we show the confirmation message
	//alert(data[0]);
	var child_id = $('#child_id').val();
	if(data[0] == "false")
	{
		
		for( var index in MP_ADDED_ITEMS)
		{
			
			sendRequestPopualteMenuPlanner(index,child_id);
		}
		
		
		resetFormMenuPlanner();
		//success message
		 $('#menuplanner_error_text').html("Les renseignements ont &eacute;t&eacute; ajout&eacute;s avec succ&egrave;s au planificateur de menus de votre enfant.");
		 showMenuPlannerError()
		 
		 $('#menuplanner_error_button').html("<img src='/fr_ca/products/includes/images/helpful_tools/bt_ok.jpg' onclick=\"javascript:hideMenuPlannerError('true')\" width='70' height='26' >")
		 
		 for(i=0;i<7;i++)
		 {
	  		uncheckAll(i)
		}
		 
		 //from menu_planner_load.js
		 ///sendRequestPopualteMenuPlanner(data['week_day'], data['child_id']);
	
	}
	//this could occur if the user has already inserted 5 items for a given weekday and given type
	else
	{
		//resetFormMenuPlanner();
		
		error_text_full = "Veuillez prendre note qu&rsquo;il y a une limite de 5 &eacute;l&eacute;ments par repas pour chaque jour de la semaine. <br/>Le menu du repas et du jour surlign&eacute;s est complet. <br/>"
		
		error_text_duplicate = "Cet &eacute;l&eacute;ment a d&eacute;j&agrave; &eacute;t&eacute; ajout&eacute; au menu du repas et du jour surlign&eacute;s."
		
		
		
		//replacing the checkboxes by x's in on the div's returned by the ajax response
		for(i=0;i<data.length;i++)
		{
		
			if(data[i].error_type == "1")
			{
			
				
				$('#menuplanner_error_text').html(error_text_duplicate)
				
				$("#" + data[i].div_name).attr("style","background-color:red")
		
		        showMenuPlannerError()
				
				
			}
			//we change the checkboxes to x
			else
			{
				
				$('#' + data[i].div_name).attr("src","/fr_ca/products/includes/images/helpful_tools/checkbox_none.gif");
				$('#menuplanner_error_text').html(error_text_full)
		
		        showMenuPlannerError()
			}
			
		}
		
		
		
	}
}
function resetFormMenuPlanner(swapimage)
{
	if(swapimage == undefined)
	{
		swapimage = "true"
	}
	
	
	//reseting the form elements
	$('#category_groups_select').html("<select class='option' name='category_groups' id='category_groups_additem' style='width:auto;'><option value='sel'>- Choisir un groupe -</option></select>")
	$('#products_select').html("<select class='option' name='products' id='products_additem' style='width:auto;'> <option value='sel'>- Choisir un produit -</option></select>")

	
	var data = {}		
	var dayNamesList = new Array('mon', 'tues', 'wed', 'thurs', 'fri', 'sat', 'sun');
	var mealsList    = new Array('break', 'morning_snack', 'lunch', 'afternoon_snack', 'dinner', 'other_snack');		
	
	//Get the arry length, faster execution
	var dnLength = dayNamesList.length;
	var mLength  = mealsList.length;
	
	//Loops through the days of the week
	for(var i=0;i<dnLength;i++)
	{
		
		//Loops through the meals
		for(var j=0;j<mLength;j++)
		{
			var itemName = dayNamesList[ i ] + '_' + mealsList[ j ];
			var itemValue = $( '#' + itemName ).val();
			if( itemValue == "1" )
			{			  
			  $( '#' + itemName ).val('');
			  if(swapimage == "true")
			  {
				swapCheckBox( itemName + '_image',itemName,'1','true','/fr_ca/products/includes/images/helpful_tools/')
			  }
			}			
		}
		
	}	
	    	
	//hiding the error message
	hideMenuPlannerError();
}

function countNumCharactersNote()
{
	var other_product = $('#other_product_additem').attr("value")
	
	if(other_product.length > 50)
	{
		
		other_product = other_product.substr(0,50)
		$('#other_product_additem').attr("value",other_product)
		
		 
		
		
		
	}
	
}



