var RecipeSearch = {

	//terms object 
	terms : function(){
		//Holder Object
		var that = {};
	
		//Private search terms
		var search_terms = [];
		
		that.clearTerms = function(){
			search_terms = [];
		};

		that.addTerm = function(term){
			search_terms.push(term);
		};

		that.getTerms = function(){
			return search_terms;
		};
		
		return that;
	}(), //Notice the () which executes the function returning the object

	/**
	 * search();	Sends the actual AJAX query for searching
	 **/
	search : function(){
		//display results
		var that = this;
		$.get('/recipes/ajax-search-results',function(d){
			that.loadResults(d);
		});
	},
	
	/**
	 * searchByTerms();	Sends an ajax query, to search for recipes
	 **/
	searchByTerms : function(){
		this.loadResults('Searching for Recipes...');
		var that = this;
		$.post('/recipes/ajax-search-terms',{Terms:this.terms.getTerms().join(',')},function(){
			//display results
			that.search();
		});
	},
	
	/**
	 * searchByKeyword();	Performs a search based only on keywords
	 **/
	searchByKeyword : function(){
		//deselect terms
		$('.dropdown ul li').removeClass('selected');
	
		//retrieve keywords
		var keys = $('#keywords').val();
	
		//Empty search_terms array
		$('.dropdown ul li').removeClass('selected');
		this.terms.clearTerms();
		this.loadResults('Searching for Recipes...');
		//POST to PHP
		var that = this;
		$.post('/recipes/ajax-submit-keywords',{
			keywords:keys
		},function(d){ that.search(); });
	},

	updateSelectedTerm : function(node){
		var term_parts = $(node).attr('id').split('-');
		var type_id = term_parts[1];
		var term_id = term_parts[2];
		var is_selected = $(node).hasClass('selected');

		$('.dropdown ul li').removeClass('selected');
		if(!is_selected){
			$('#term-'+type_id+'-'+term_id).addClass('selected');
		}

		this.terms.clearTerms();
		var that = this;
		$('.dropdown ul li.selected').each(function(){
			var term_parts = $(this).attr('id').split('-');
			var type_id = term_parts[1];
			var term_id = term_parts[2];
			that.terms.addTerm(term_parts[1]+'-'+term_parts[2]);
		});
		this.searchByTerms();
	},
	
	/**
	 * gotoResultPage(); Goes to the given results page
	 * @params	page	int	page to go to
	 **/
	gotoResultPage : function(page){
		this.loadResults('Retrieveing page '+page+'...');
		var that = this;
		$.post('/recipes/ajax-search-goto-page',{Page:page,SortBy:$('#sortBy').val()},function(){
			that.search();
		});
	},
	
	
	/**
	 * loadResults();	Loads the results of a search
	 * @params	data	string	string of data to load into DOM
	 **/
	loadResults : function (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]);
				$('#results-content').html(data[2]);
	
	
			}
		}else $('#content-top').html('<h1 class="recipe-results-number">'+data+'</h1>');
	}	
};