/**
 * Copyright (C) 2009 Nikola Posa (http://www.nikolaposa.in.rs)
 *
 * This program is free software: you can redistribute it and/or modify 
 * it under the terms of the GNU General Public License as published by 
 * the Free Software Foundation, either version 3 of the License, or 
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful, but 
 * WITHOUT ANY WARRANTY; without even the implied warranty of 
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU 
 * General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License 
 * along with this program. If not, see <http://www.gnu.org/licenses/>.
 */
 
$(document).ready(function() {
	if ($('#search_form').length > 0) {
		if (!$('#search_options_toggle').hasClass('collapsible')) {
			$('#search_options').hide();
		}
		
		$('#search_options_toggle').click(function () { 
			$('#search_options').toggle('normal');	
			$(this).toggleClass('collapsible');
		});
		
		$('#search_form').submit(function() {
			var searchQuery = $('#search_form #query').val();
			
			return !(searchQuery == '');
		});
	}
	
	//"Back to search results" functionality.
	
	if ($('.search_result').length > 0) {
		$('.search_result h2 a, .search_result a .more').click(
			function() {
				$.ajax({
					type: 'POST',
					url: $('#base_url').val() + '/front-end/ajax_handlers/webfolio-search/back_to_results_marker.php',
					data: $("#search_form").serialize()
				});
				
				return true;
			}
		);
	}
	
	if ($('#back_to_results').length > 0) {
		$.highlight.setCssClass('wf_search_highlight');
	
		var option = $('#search_option').val();
		var query = $('#search_query').val();
		var strings = query;
		
		if (option != 'exact') { //Many search terms?
			strings = [];
			
			var parts = query.split(' ');
			for(var part in parts) {
				strings.push($.trim(parts[part]));
			}
		}
		
		$('.entry:first').highlight(strings);
	
		//Appending "Back to search results" box.
		$('body').prepend('<div id="back_to_results"><img id = "close_message" src = "' + $('#base_url').val() + '/front-end/img/webfolio-search/close.png" /><a href = "javascript: void(0);" onclick = "$(\'#search_form_partial\').submit(); return false;">' + $('#back_to_results_label').val() + '</a><br /><a href = "javascript: void(0);" onclick = "$.highlight.removeHighlight();">' + $('#remove_highlights_label').val() + '</a></div>');
		$('#back_to_results').css('left', $(window).width() / 2 - $('#back_to_results').width() / 2);
		
		//... and making it static and floating on user's screen.
		$(window).scroll(function()
		{
			$('#back_to_results').animate({top: $(this).scrollTop() + "px" }, {queue: false, duration: 200});
		});
		
		//When the close button at right corner of the message box is clicked.
		$('#close_message').click(function()
		{
			$('#back_to_results').animate({top: "+=15px", opacity: 0}, "slow");
		});
	}
});
