var $j = jQuery.noConflict();

$j(document).ready(function() {
	// ### Searchform slidedown, yeah!
	$j('#search-container').hide();
	$j('#toggle-search').click(function() {
		$j('#search-container').slideToggle(function() {
			$j('#query').focus();
		});
	});

	var field = $j('#query');
	var form = field.parent();
	
	// ### Initialize Autocomplete
	field.autocomplete(form.attr('action'), {
		autoFill: false,
		matchContains: true,
		selectFirst: false,
		minChars: 2
	});
	
	// ### Prevent empty search
	form.submit(function(e) {
		if (!field.val()) {
			e.preventDefault();
		}
	});

	// ### Select search query on focus
	field.focus(function() {
		this.select();
	});
	
	// ### Inject popup overide on links with class "popup"
	$j('a.popup').click(function(e) {
		e.preventDefault();
		popup($j(this).attr('href'));
	});
	
	openExternalLinksInNewWindows();
});

function popup() {
	var url = arguments[0];
	var name = 'popup';
	var width = 800;
	var height = 480;

	if (arguments.length >= 2) {
		name = arguments[1];
		if (arguments.length >= 4) {
			width = arguments[2];
			height = arguments[3];
		}
	}

	var w = window.open(url, name, "toolbar=no,location=0,directories=no,scrollbars=yes,resizable=yes,width=" + width + ",height=" + height);
	w.focus();
}

function nextQuote(forward) {
	var current = $j('#quotes ul.quotes li:visible');
	next = forward ? current.next('li') : current.prev('li');
	if (next.length == 0) {
		next = current.parent().children(forward ? 'li:first' : 'li:last');
	}
	current.hide();
	next.show();
}

function openExternalLinksInNewWindows() {
	$j('a').each(function() {
		a = $j(this)
		var href = a.attr('href');
		if (href.indexOf('http') == 0) {
			a.attr('target', '_blank');
		}
	});
}
