/**
 * RecipeSearch.js
 *	-functions to use with RecipeSearch.php page (not contest version)
 **/

 var search_timer = false;
 var search_terms = new Array();
/**
 * addSelectedTerm();	Sends a term_id to ber added to sleected term cookie
 * @params	class_id	int	id of the class
 * @params	term_id		int	id of term to add
 **/
function addSelectedTerm(class_id,term_id,no_submit){
//	alert('add:'+term_id);
	if(!no_submit) no_submit = false;
	if($('#selected-'+class_id+'-'+term_id).length<=0){

	if(no_submit){
			if($('#your-selections').css('display')=='none') $('#your-selections').css('display','');
			$('#term-'+term_id).toggleClass('selected');
			$('#term-'+term_id).unbind('click');
	//		$('#term-'+term_id).bind('click',function(){removeSelectedTerm(class_id,term_id);}); //<-- gets triggered by IE6 after bind
		
			//Add term to list
			$('#your-selections ul ul').append('<li id="selected-'+class_id+'-'+term_id+'"></li>');			
			$('#selected-'+class_id+'-'+term_id).html($('#term-'+term_id).text()+'<a onclick="removeSelectedTerm('+class_id+','+term_id+');" class="command-links">[remove]</a>');	
			//Add term to search_terms array
			search_terms.push('"'+search_terms.length+'":{"Action":"ADD","Class_id":'+class_id+',"Term_id":'+term_id+'}');
			loadResults('Searching for Recipes...');
		}else{

			//if already waiting on a timeout, cancel it.
			if(search_timer) clearTimeout(search_timer);
			//add term to array and selected table
			addSelectedTerm(class_id,term_id,true);
			//start a new timeout
			search_timer = setTimeout('searchByTerms();',3000);
		}
		
	}
}
	


/**
 * removeSelectedTerm();	Removes a term from selected terms
 * @params	class_id	int	the id of the class temr is in
 * @params	term_id		int	id of the term
 **/
function removeSelectedTerm(class_id,term_id,no_submit){
	if(!no_submit) no_submit = false;
	if(no_submit){
		if($('#selected-'+class_id+'-'+term_id).length>=0){
			$('#term-'+term_id).toggleClass('selected');
			$('#term-'+term_id).unbind('click');
			$('#term-'+term_id).bind('click',function(){addSelectedTerm(class_id,term_id);});
			
			//Remove selected term
			$('#selected-'+class_id+'-'+term_id).remove();
			//If selected class has no more elements in list, remove it
			if($('#your-selections  ul ul li').length<=0) $('#your-selections ').css('display','none');
			//remove term to search_term array
			search_terms.push('"'+search_terms.length+'":{"Action":"REMOVE","Class_id":'+class_id+',"Term_id":'+term_id+'}');
			loadResults('Searching for Recipes...');
		}
	}else{
			//if already waiting on a timeout, cancel it.
			if(search_timer) clearTimeout(search_timer);
			//remove term to array and selected table
			removeSelectedTerm(class_id,term_id,true);
			//start a new timeout
			search_timer = setTimeout('searchByTerms();',3000);
	}
}

function removeAllTerms(){
	search_terms = new Array();
	if($('#your-selections ul ul li').length>0){
		$('#your-selections ul ul li').each(function(){
			id = $(this).attr('id');
			if(id.indexOf('selected-')>=0){
				id = id.split('-');
				cls = id[1];
				trm = id[2];
				removeSelectedTerm(cls,trm);
			}
		});
	}
}

/**
 *resortResults(); Resorts the search results
 * @params	sort	string	field to sort by
 **/
 function resortResults(sort){
	loadResults('Sorting Recipes...');
	$.post($('#HEADERPATH').val()+'includes/RecipeSearchEngine.php',{func:'searchSort',SortBy:sort},function(){
		search();
	});
 }
 
 /**
  *gotoResultPage(); Goes to the given results page
  * @params	page	int	page to go to
  **/
  function gotoResultPage(page){
	loadResults('Retrieving page '+page+'...');
	$.post('/recipes/ajax-goto-page',{Page:page,SortBy:$('#sortBy').val()},function(){
		search();
	});
  }
  
/**
 * search();	Sends the actual AJAX query for searching
 **/
function search(){
	//display results
	//if($('#not_search').val()==1){
		//window.location = 'searchresultsview.php';
	//}else{
		$.post('/recipes/ajax-search-results',{func:'search'},function(d){
			loadResults(d);
		});
	//}
}

/**
 *searchByTerms();	Sends an ajax query, to search for recipes
 **/
function searchByTerms(){
	loadResults('Searching for Recipes...');
	$.post('/recipes/search-terms',{func:'searchTerms',Terms:'{"Terms":{'+search_terms.join(',')+'}}'},function(){
		//Clear search_array
		resetSearchTerms();
		//Clear timer
		search_timer = false;
		//display results
		search();
	});
}

function resetSearchTerms(){
	search_terms = new Array();
	if($('#your-selections ul ul li').length>0){
		$('#your-selections ul ul li').each(function(){
			id = $(this).attr('id');
			if(id.indexOf('selected-')>=0){
				id = id.split('-');
				cls = id[1];
				trm = id[2];
				search_terms.push('"'+search_terms.length+'":{"Action":"ADD","Class_id":'+cls+',"Term_id":'+trm+'}');
			}
		});
	}
}

/**
 *searchByKeyword();	Performs a search based only on keywords
 **/
function searchByKeyword(){
	//retrieve keywords
	var keys = $('#go_recipe').val();
	
	//Remove all previous selected terms
	var id,cls,trm;
	if($('#your-selections ul ul li').length>0){
		$('#your-selections ul ul li').each(function(){
			id = $(this).attr('id');
			if(id.indexOf('selected-')>=0){
				id = id.split('-');
				cls = id[1];
				trm = id[2];
				removeSelectedTerm(cls,trm,true);
			}
		});
	}

	//Empty search_terms array
	search_terms = new Array();
	loadResults('Searching for Recipes...');
	//POST to PHP
	//$.post($('#HEADERPATH').val()+'includes/RecipeSearchEngine.php',{
	$.post('/recipes/ajax-submit-keywords',{
		func:'submitKeywords',
		keywords:keys
		},
		function(d){ 
			search(); 
		});
}

/**
 *submitQuickSearch();	Performs the quick search
 **/
 function submitQuickSearch(){
	//Retrieve Search fields
	var keys 	 = $('#keyword').val();
	var time 	 = $('#search_ready_in').val();
	var s_type 	 = $('#search_make').val();
	var s_with 	 = $('#search_with').val();
	var s_flavor = $('#search_flavor').val();
	
	//Remove all previous selected terms
	var id,cls,trm;
	if($('#your-selections ul ul li').length>0){
		$('#your-selections ul ul li').each(function(){
			id = $(this).attr('id');
			if(id.indexOf('selected-')>=0){
				id = id.split('-');
				cls = id[1];
				trm = id[2];
				removeSelectedTerm(cls,trm,true);
			}
		});
	}

	//Empty search_terms array
	search_terms = new Array();
	
	//Add to seletected terms - BUT NOT TO COOKIE! (PHP will handle that below)
	var x = s_type.split(':');
	addSelectedTerm(x[0],x[1],true);
	
	x = s_with.split(':');
	addSelectedTerm(x[0],x[1],true);
	
	x = s_flavor.split(':');
	addSelectedTerm(x[0],x[1],true);
	
	//POST to PHP
	$.post($('#HEADERPATH').val()+'includes/RecipeSearchEngine.php',{
		func:'submitQuick',
		keyword:keys,
		search_ready_in:time,
		search_make:s_type,
		search_with:s_with,
		search_flavor:s_flavor
	},function(d){ search(); });
 }
 
 /**
  *_loadResults();	Loads the results of a search
  * @params	data	string	string of data to load into DOM
  **/
 function loadResults(data){
	if(data.indexOf('<!--//-->')>0){
		data = data.split('<!--//-->');
		if(data.length>=3){
			$('#content-top').html(data[0]);
			$('#top-pagation').html(data[1]);
			$('#bottom-pagation').html(data[1]);
			$('#featured-content').html(data[2]);
			$('#featured').css('display',(data[2].length<10 ? 'none':''));
			$('#results-content').html(data[3]);
			
			//Remove facets
			if(data[4]){
				var removeF = data[4].split('|');
				for(var f in removeF){
					var v = removeF[f].split('-');
					
					if($('#selected-'+v[0]+'-'+v[1]).length>=0){
						$('#term-'+v[1]).toggleClass('selected');
						$('#term-'+v[1]).unbind("click");
						$('#term-'+v[1]).bind("click",function(){addSelectedTerm(v[0],v[1]);});
			
						//Remove selected term
						$('#selected-'+v[0]+'-'+v[1]).remove();
						//If selected class has no more elements in list, remove it
						if($('#your-selections  ul ul li').length<=0) $('#your-selections ').css('display','none');
					}
				}
					
//EDIT HERE				
				// Later on tell user facets were removed
			}
			
		}
	//	Rate_link();
	//	RecipeBox_link();
	}else $('#content-top').html(data);
 }
 
 
 /**
  *_viewAll();	Loads all search results
  * @params		page	int		curerent page we're on
  * @params		pages	int		total number of pages
  **/

  var view_all = '';
  var view_start = false;
  var old_h1 = '';
  function viewAll(results,page){
		var timer = new Date();
		var stop= '';
		if(!page) var page = 1;
		
		if(page==1){
			view_start = timer.getTime();
			old_h1 = $('#content-top h1').text();
			$('#content-top').html('<h1>Retrieving All Recipes...</h1><div class="sorter"> loading results ...</div>');
			$('#bottom-pagation').html('<div class="sorter"> loading results ...</div>');
		}
		
		var count = Math.ceil(results/340);
		if(count>=page){
			//Get results for current page
			$.post($('#HEADERPATH').val()+'includes/RecipeSearchEngine.php',{func:'pageResults',Page:page},function(d){
				var stop = timer.getTime();
				view_all+=d;
				if((view_start-stop)>5){
					$('#results-content').append(view_all);
					view_all = '';
					view_start = stop;
				}
				
				viewAll(results,(page+1));
			});
		}else{
			$('#content-top').html('<h1>'+results+' Recipes Found</h1>');
			$('#content-top h1').text(old_h1);
			$('#bottom-pagation').html('');
			if(view_all!='') $('#results-content').append(view_all);
			RecipeBox_link();
			Rate_link();
		}
	}
	
	


