// common.js


$(function() {
	
	var image_rotation_interval = 0;
	var image_rotation_swap = 0;
	
	$('#imageContainer, #welcomeContainer').each(function(i) {
		
		// Create 'fake' image swap buttons
		var c = $('<div class="imageRotationButtonContainer" />');
		var b;
		$(this).children().each(function(j) {
			b = $('<div class="imageRotationButton" />').appendTo(c);
			if (j === i) {
				// Set the first child to active
				$(this).addClass('active');
				b.addClass('active');
			}
		});
		c.appendTo(this);
		
		// Rotate the images
		var self = this;
		image_rotation_interval = setInterval(function() {
			image_rotation_swap = (image_rotation_swap + 1) % ($(self).children().length - 1);
			$(self).children('IMG')
				.removeClass('active')
				.eq(image_rotation_swap).addClass('active');
			$(self).find('.imageRotationButton')
				.removeClass('active')
				.eq(image_rotation_swap).addClass('active');
		}, 2000);
	});
	
	// Swap images when swap button is clicked
	$('.imageRotationButton').live('click', function(e) {
		clearInterval(image_rotation_interval);
		$(this).addClass('active')
			.siblings().removeClass('active');
		$('#imageContainer, #welcomeContainer').children()
			.removeClass('active')
			.eq($(this).index()).addClass('active');
	});
	
	// Show custom country field when selected 
	$('select#country_id').change(function(e) {
		if ($(this).val() == 1) {
			$('input#country_other').css('display','block');
		} else {
			$('input#country_other').css('display','none');
		}
	});
	
	// Lightboxing 
	$('a.lightbox').lightBox({txtImage: '', txtOf: '/'});
		
	// Open external links in blank window 
	var base_href = $('base').get(0).href;
	$('a').each(function(i) {
		if (this.href.indexOf(base_href) !== 0) {
			this.target = '_blank';
		}
	});
	
	// Toggle shipping costs 
	$('a#showShippingCostBtn').click(function(e) {
		e.preventDefault();
		$('div#shipping_costs_container').toggle();
		
	});
	
	// Submit the cart when changes are made to the country / quantities 
	$('table#cart input, table#cart select').change(function(e) { 
		this.form.submit();
	});
	
})

