var $j = jQuery.noConflict();

$j(document).ready(function() {

	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'));
	});
	
	$j('form#subscribe_form').submit(function(e){
		e.preventDefault();
		var subscribe_form = $j(this).serialize();
		$j.post($j(this).attr('action'), subscribe_form, function(success){
			if(success == 'True'){
				var button = $j('form#subscribe_form button.grey');
				var label = button.text();
				var success = $j('<p/>').text('Tack för anmälan!').hide()
					.css({ float: 'right', padding: '3px 15px 0 0' });

				button.after(success);
				button.hide();
				success.fadeIn('slow');
				
				setTimeout(function() { 
					success.remove();
					button.fadeIn(); 
				}, 3500)
			}
		});
	});
	
	$j('form#checkout_form input.field_error').keyup(function(e){
		if(e.keyCode != 9){
			$j(this).removeClass('field_error');
			$j(this).next().remove();
		}
	});
	
	$j('a.toggleImages').click(function(e){
		var tagList = $j(this).next();
		toggleGallery(tagList, $j(this));
	});
	
	$j('a.toggleTags').click(function(e){
		var producerImages = $j(this).parents('li').next('ul');
		toggleGallery(producerImages, $j(this));
	});
	
	openExternalLinksInNewWindows();
});

function toggleGallery(list, link) {
	list.toggle();
	if (list.hasClass('collapsed')){
		list.removeClass('collapsed');
		link.children('strong').children('span.toggle').text('- ');
	} else {
		list.addClass('collapsed');
		link.children('strong').children('span.toggle').text('+');
	}
}

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)
		if(a.attr('href')){
			var href = a.attr('href');
			if (href.indexOf('http') == 0) {
				a.attr('target', '_blank');
			}
		}
	});
}
