var bgIndex = {
	data : null,
	total : 0,
	// Just true for the initial results
	fake : true,
	page : 1,
	pageTotal : 1,
	value : '',
	sortBy : '',
	
	
	init : function() {
		jQuery("#little-search").submit(bgIndex.littleSearch);
		jQuery("#little-search-category").change(bgIndex.littleSearch);
		if(post_list) {
			bgIndex.data = post_list.data;
			bgIndex.total = post_list.total;
			bgIndex.page = post_list.page;
			bgIndex.pageTotal = post_list.pageTotal;
			bgIndex.value = post_list.q;
			bgIndex.fake = post_list.fake;
			bgIndex.displaySearch(bgIndex.data, 0);
		}	
	},
	
	
	
	/**************************************************************************************************************************************
	*************************************** SEARCH methods ********************************************************************************
	***************************************************************************************************************************************/
	
	/* Displays both the initial search list and also the
	 * later addendums by actual search methods. */
	displaySearch : function(results, start) {
		var end = Math.min(start + 24, results.length);
		var user_end = Math.min(bgIndex.total, bgIndex.page * 24);
		var user_start = ((bgIndex.page -1) * 24) +1;
		if(!bgIndex.fake && bgIndex.total != undefined) {
			jQuery("#result-metadata").text('Found ' + bgIndex.total + ' recipes.  Displaying results ' + user_start + '-' + user_end);
		} else if(bgIndex.total != undefined) {
			jQuery("#result-metadata").text('Showing the ' + bgIndex.total + ' most recent drinks.');
		}
		
		// Make a quick exit if there's a math/counting problem
		if(end < start) return;
		
		/* Clear the results and keep going. */
		jQuery("#search-results").empty();
		
		var toDisplay = results.slice(start, end);
		var lastNum = 1;
		
		/* Now iterate over them and display them. */
		jQuery.each(toDisplay, function() {
		/* Damn inconsistent shit */
			if(!this.fbp_title) {
				this.fbp_title = this.title;
				this.fbp_url = this.url;
				this.fbp_id = this.id;
				this.fbp_pubid = this.id;
				this.bin_data = jQuery.evalJSON(this.data);
			}
			// Choose a random number for our blanks
			var num = 0;
			do {
				num = Math.floor(Math.random() * 7) + 1;
			} while(num == lastNum);
			lastNum = num;
			jQuery("#search-results").append(
				jQuery.create("div", {"class" : "resultbox"}).append(
					jQuery.create("div", {"class" : "lfloat"}).append(
						jQuery.create("img", {"src" : (this.bin_data.photo && this.bin_data.photo.url) ? this.bin_data.photo.url : "/style/bartendersguide/gfx/bartendersguide_blank0" + (num) + ".png", "alt" : "", "class" : "border", "style" : "width: 75px; height: 75px"})
					)
				).append(
					jQuery.create("div", {"class" : "grid_4"}).append(
						jQuery.create('p', null).append(
							jQuery.create('a', {'href' : this.fbp_url}, this.fbp_title)
						).append('<br />').append(bgIndex.ellipsize(this.bin_data.directions, 20))
					)
				).append(
					jQuery.create('div', {'class' : 'rfloat txtsmall', 'style' : 'width: 125px'}).append(
						jQuery.create('p', {'id' : 'rating-' + this.fbp_id})
					).append(
						jQuery.create('div', null).append(
							jQuery.create('a', {'href' : this.fbp_url}, 'Read Comments')
						)
					).append(
						jQuery.create('a', {'href' : 'javascript:bgIndex.addToFavorites("' + this.fbp_pubid + '");'}, 'Add to Favorites')
					)
				).append(
					jQuery.create('div', {'class' : 'clear'})
				)
			);
			
			// Create the rating
			bRate.create(	
					'rating-' + this.fbp_id,	// HTML id
					'article',				// Type
					this.fbp_pubid,			// Item's ID
					true,					// Static flag?
					this.rate_value,			// Dur?
					this.rate_count			// Hurdur?
			);
		});
		
		// Now do the bottom-of-the list page display thingamabob
		bgIndex.createPaging();
	},
	
	/* Calls to the server to make search results. */
	doSearch : function(value) {
		var opts = {
			'q' : value,
			'p' : bgIndex.page,
			'sort' : bgIndex.sortBy
		}
		if(bgIndex.category) opts.category = bgIndex.category;
		
		jQuery.get(
			"/a/search/posts.api/" + getTime(),
			opts,
			function(jdata) {
				if(jdata.errno == 0) {
					bgIndex.data = jdata.result;
					bgIndex.page = jdata.page;
					bgIndex.pageTotal = jdata.pageCount;
					bgIndex.total = jdata.total;
					bgIndex.fake = false;
					// Show off!
					bgIndex.displaySearch(bgIndex.data, 0);
				}
			},
			'json'
		);
		
		return false;
	},
	
	/* Pulls the search value from the small search box and passes it back to do the
	 * search.  Zippy doo-da-day! */
	littleSearch : function(event) {
		var value = jQuery("#little-search-text").val();
		
		//if(jQuery.trim(value) != "") {
			bgIndex.page = 1;
			bgIndex.value = value;
			bgIndex.sortBy = '';
			bgIndex.category = jQuery('#little-search-category').val();
			bgIndex.doSearch(value);
		//}
		
		event.preventDefault();
		return false;
	},

	/* Resubmits for search, just with a new page. */
	changePage : function(target) {
		if(target > bgIndex.pageTotal)
			bgIndex.page = bgIndex.pageTotal;
		else if(target < 1)
			bgIndex.page = 1;
		else
			bgIndex.page = target;
		
		/* Now, go search */
		bgIndex.doSearch(bgIndex.value);
	},

	/***************************************************************************************************************************
	************************** UTILITY/LISTENER Methods ************************************************************************
	****************************************************************************************************************************/

	/* Sorts the elements of the search results and displays them. */
	sort : function(order) {
		if(bgIndex.data && bgIndex.fake == true && order != 'random') {
			if(order == 'title')
				bgIndex.data.sort(function(a, b) { if(a.fbp_title < b.fbp_title) return -1; else return 1; });
			if(order == 'rating')
				bgIndex.data.sort(function(a, b) { return b.rate_value - a.rate_value; });
			if(order == 'relevance' && bgIndex.sortBy != 'relevance')
				bgIndex.data.sort(function(a, b) { return Math.random() - 0.5; });
			
			bgIndex.sortBy = order;				
			bgIndex.displaySearch(bgIndex.data, 0);
		} else {
			bgIndex.sortBy = order;
			bgIndex.page = 1;
			
			bgIndex.doSearch(bgIndex.value);
		}
	},

	/* Displays the paging within the div#pager ul element. */
	createPaging : function() {
		var p = bgIndex.page;		// Current _p_age
		var e = bgIndex.pageTotal;	// _e_nd page
		var l = jQuery('.pager ul');	// _l_ist
		
		// Clear old values
		jQuery(l).empty();
		
		// Don't display paging if only one element exists
		if(e == 1) return;
		
		if(p > 1) {
			bgIndex.createPagingElement(l, p - 1, 'Prev');
		}
		
		// Always give a page 1
		bgIndex.createPagingElement(l, 1);
		
		// Some elipses for when we need them
		if(p > 4) jQuery(l).append('<li>...</li>');
		
		// And always start at least 2 pages below
		var ctr = 2;
		for(ctr = p - 2; ctr <= p + 2; ctr++) {
			// Skip some, if we're out of range
			if(ctr < 2 || ctr > e) continue;
			
			// Otherwise, add them on!
			bgIndex.createPagingElement(l, ctr);
		}
		
		// Check to see if we need a final page
		if(ctr <= e - 1) {
			jQuery(l).append('<li>...</li>');
		}
		
		if(ctr <= e) {
			bgIndex.createPagingElement(l, e);
		}
		
		// And, finally, a Next option
		if(p < e)
			bgIndex.createPagingElement(l, p + 1, 'Next');
	},
	
	/* Just a quick helper to create an element in the paging portion
	 * of our search results.  The text argument is optional and will
	 * default to the same value as page if it does not exist or evals
	 * to false. */
	createPagingElement : function(place, page, text) {
		jQuery(place).append(
			jQuery.create('li').append(
				jQuery.create('a', {'href' : 'javascript:bgIndex.changePage(' + page + ');'}, text ? text : page)
			)
		);
	},

	/* Truncates a string to a maximum of <words> words long and
	 * appends a '...' at the end of the string if the string is
	 * longer than specified.
	 * 
	 * Probably should handle more terminal punctuation than a ., but
	 * there is no definite need for it to do so at this time.
	 */
	ellipsize : function(str, words) {
		var regex = /\s+/;
		
		var results = str.split(regex);
		
		var i = 0;
		var result = '';
		for(i = 0; i < words && i < results.length; i++) {
			//var results = regex.exec(str);
			result += ' ' + results[i];
		}
		
		if(results.length > words) {
			if(result.charAt(result.length - 1) == '.') result += '..';
			else result += '...';
		}
		
		return result;
	},
	
	/* A quick, dirty hack to push favorites from the home/search pages.
	 * Ugh!
	 */
	addToFavorites : function(id) {
		jQuery.get(
			'/a/control-bar.api/' + getTime(),
			{ 'action' : 'addfavorite',
			  'blogID' : id
			},
			function(jdata) {
				if(jdata.errno == 0) {
					jQuery.prompt("Added to favorites.  Congratulations.");
				}
				
				if(jdata.errno == -1) {
					jQuery.prompt("You must login to perform that function.");
				}
				
				if(jdata.errno == -100) {
					jQuery.prompt("Not added - perhaps it is already in your favorites?");
				}
			},
			'json'
		);
	}
};

jQuery(document).ready(function() {
	bgIndex.init();
});
