/**
 * 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+');" style="cursor:pointer;">[remove]</a>');	
			//Add term to search_terms array
			search_terms.push('"'+search_terms.length+'":{"Action":"ADD","Class_id":'+class_id+',"Term_id":'+term_id+'}');
			RecipeSearch_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);
		}

	}
}

function RecipeSearch_setSearch(values,callback){
	values['func']="RecipeSearch_setSearch";
	$.post($('#HEADERPATH').val()+'RecipeSearch.php',values,function(){
		if(callback){
			callback.call();
		}
	});
}

/**
 * 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+'}');
			RecipeSearch_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);
	}
}

/**
 *resortResults(); Resorts the search results
 * @params	sort	string	field to sort by
 **/
function resortResults(sort){
	RecipeSearch_loadResults('Sorting Recipes...');
	$.post($('#HEADERPATH').val()+'RecipeSearch.php',{func:'RecipeSearch_searchSort',SortBy:sort},function(){
		RecipeSearch_search();
	});
}


/**
  *gotoResultPage(); Goes to the given results page
  * @params	page	int	page to go to
  **/
function gotoResultPage(page){
	RecipeSearch_loadResults('Retrieveing page '+page+'...');
	$.post($('#HEADERPATH').val()+'RecipeSearch.php',{func:'RecipeSearch_gotoPage',Page:page,SortBy:$('#sortBy').val()},function(){
		RecipeSearch_search();
	});
}

/**
 * RecipeSearch_search();	Sends the actual AJAX query for searching
 **/
function RecipeSearch_search(){
	//display results
	$.post($('#HEADERPATH').val()+'RecipeSearch.php',{func:'RecipeSearch_search'},function(d){
		RecipeSearch_loadResults(d);
	});
}


/**
 *searchByTerms();	Sends an ajax query, to search for recipes
 **/
function searchByTerms(){
	RecipeSearch_loadResults('Searching for Recipes...');
	$.post($('#HEADERPATH').val()+'RecipeSearch.php',{func:'RecipeSearch_searchTerms',Terms:'{"Terms":{'+search_terms.join(',')+'}}'},function(){
		//Clear search_array
		RecipeSearch_resetSearchTerms();
		//Clear timer
		search_timer = false;
		//display results
		RecipeSearch_search();
	});
}

function RecipeSearch_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 RecipeSearch_searchByKeyword(){
	//retrieve keywords
	var keys = $('#keywords').val();
	var is_video = $('#is_video').val()?$('#is_video').val():'no';

	//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();
	RecipeSearch_loadResults('Searching for Recipes...');
	//POST to PHP
	$.post(
			$('#HEADERPATH').val()+'RecipeSearch.php',
			{
				func:"RecipeSearch_submitKeywords",
				keywords:keys,
				"is_video":is_video			
			},
			function(d){ RecipeSearch_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()+'RecipeSearch.php',{
		func:'RecipeSearch_submitQuick',
		keyword:keys,
		search_ready_in:time,
		search_make:s_type,
		search_with:s_with,
		search_flavor:s_flavor
	},function(d){ RecipeSearch_search(); });
}

/**
  *_loadResults();	Loads the results of a search
  * @params	data	string	string of data to load into DOM
  **/
function RecipeSearch_loadResults(data){
	if(data.indexOf('<!--//-->')>0){
		data = data.split('<!--//-->');
		if(data.length>=3){
			$('#content-top').html(data[0]);
			$('#bottom-pagation').html(data[0].split('</h1>')[1]);
			$('#featured-content').html(data[1]);
			$('#featured').css('display',(data[1].length<10 ? 'none':''));
			$('#results-content').html(data[2]);

			//Remove facets
			if(data[3]){
				var removeF = data[3].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();
		RequiresLogin_links();
	}else $('#content-top').html('<h1>'+data+'</h1>');
}


/**
  *_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 RecipeSearch_viewAllResults(){
	RecipeSearch_loadResults('Searching for Recipes...');
	$.post($('#HEADERPATH').val()+'RecipeSearch.php',{func:"RecipeSearch_setSearch",rows:10000,page:1},function(d){
		RecipeSearch_search();
	});
	/*
	$.post($('#HEADERPATH').val()+'RecipeSearch.php',{func:"RecipeSearch_allSearchResults"},function(d){
		RecipeSearch_search();
	});

		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()+'RecipeSearch.php',{func:'RecipeSearch_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;
				}

				RecipeSearch_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();
		}
	 */
}

function RecipeSearch_viewAllVideos(){

	//clear out the keywords and redirect
	$.post(
			$('#HEADERPATH').val()+'RecipeSearch.php',
			{
				func:"RecipeSearch_submitKeywords",
				keywords:"",
				"is_video":"yes",
				rows:"10000"
			},
			function(d){ document.location.href='/RecipeVideoSearch.php';}
	);
}


function RecipeSearch_sortVideos(obj){
	document.location.href='?&'+$(obj).val();
}

function RecipeSearch_filterVideos(){
	var ids = new Array();
	var parts;
	$('#cat-filters .selected').each(function(index,Element){
		parts = $(Element).attr('id').split('-');
		ids.push(parts[1]+'-'+parts[2]);
	});
	var ready = $('#search_ready_in').val();
	var values = {
		keywords:"",
		categories:ids.join(','),
		page:1,
		rows:9,
		readyin:ready
	};
	RecipeSearch_setSearch(values,function(){
		document.location.href="/RecipeVideoSearch.php";
	});
}
