$(document).ready(function() {
	// Highlight
	
	$("form#submit").submit(function() {
		$("form#submit .signup").attr('href', '#');
		var email = $('#mce-EMAIL').attr('value');  
		$.ajax({  
			type: "POST",  
			url: "subscribe.php",  
			data: "EMAIL="+ email,  
			success: function(){  
				$('form#submit').fadeOut(function(){$('p.form_success').fadeIn();});  
		  
			},
			error: function(){  
				$('form#submit').fadeOut(function(){$('p.form_error').fadeIn();});  
		  
			} 
		});  
		return false;  
	});
	
	// Products
	var caroucallback = function(active_item, active_position) {
		if(this.children.length === (active_position + 1 )) {
			setTimeout(function() {
				$('.device', $('.products .product:visible')).tinycarousel_stop();
				setTimeout(function() {
					switchToProduct(false);
				}, 1500);
			}, 1000);
		}
	}

	function highlightProduct(index) {
		var active = $('.products .product:visible');
		var next_active = $('.products .product')[index];

		$(active).fadeOut(150, function() {
			$('.device', active).tinycarousel_destroy();
			$(next_active).fadeIn(150);
			$('.device', next_active).tinycarousel({interval: true, callback: caroucallback });
		});

		$('.products .selector a.active').removeClass('active');

		$($('.products .selector .details a')[index]).addClass('active');

	}

	function switchToProduct(goingLeft) {
		var curr_active = $('.products .details a[class=active]')[0].rel * 1;
		var num_prods = $('.products .product').length;
		var nextIndex = 0;
		if(goingLeft) {
			nextIndex = curr_active - 1;
			if(nextIndex < 0) {
				nextIndex = num_prods - 1;
			}
		} else {
			nextIndex = (curr_active+1) % num_prods;
		}
		highlightProduct(nextIndex);
	}

	$('.products .product:first .device').tinycarousel({interval: true, callback: caroucallback});

	$('.products .selector .details a').click(function() {
		highlightProduct(this.rel * 1);
		return false;
	});

	$('.products .selector .prev').click(function() {
		switchToProduct(true);
		return false;
	});

	$('.products .selector .next').click(function() {
		switchToProduct(false);
		return false;
	});

	
	
});


