$(document).ready(function() {
	//Rotate #frame
	setTimeout("rotateFrame()", 3000);
	
	//carousels
	$('.carousel').each(function(i) { carousel(this, i); });
	
	$('*[rel="fade"]').each(function() {
		$(this).fadeTo(0, .75);
		
		$(this).hover(
			function() {
				$(this).stop().fadeTo(150, 1);
			},
			function() {
				$(this).stop().fadeTo(250, .75);
			}
		);
	});
	
	$('#success').css({'opacity' : '0', 'display' : 'block'}).stop().fadeTo(500, 0, function() {
		$(this).fadeTo(500, .9, function() {
			$(this).fadeTo(5000, .9, function() {
				$(this).fadeTo(500, 0);	
			});
		});
	});
	
});

function rotateFrame() {
	
	var img = $('#frame').find('img');
	var count = $(img).attr('rel');
	
	//prepare for switch
	$(img).css({'z-index' : '10'})
	if ( count > 5 ) { count = 0; }

	//Spawn the next image behind the current and fade current out.
	$(img).clone(true).insertAfter($(img)).css({'z-index' : '0'})
		.attr('src', path + '/images/rotate_home/' + ((count * 1) + 1) + '.jpg')
		.attr('rel', ((count * 1) + 1));

	//Fade out and detach old image
	$(img).stop().fadeTo(750, 0, function() {
		$(img).remove();
		setTimeout("rotateFrame()", 3000);
	});
}

function carousel (obj, i) {
	//Calculate width & animate to propper asked for:
	var M = $(obj).attr('rel') * 1;
	var wid = M * 144;
	
	// Calculate width of containing div
	var count = $(obj).find('span').length;
	$(obj).find('.contain').css({ 'width' : (count * 144) + 'px', 'overflow' : 'hidden' });
	
	//Set positions
	$(obj).find('.contain').css({'left' : '0px'});
	$(obj).css({'width' : (wid + 30) + 'px' });
	
	// Set width of visible area
	$(obj).find('.mid').stop().animate({width:wid + 'px'}, 500, function() {
		prepare_carousel(this, i);
	});
	
}
function scroll_right(obj, i) {
	var left = $('.mid').find('div').css('left').replace('px', '').replace('-', '');
	var width = ($('.mid').find('div').css('width').replace('px', '') * 1) - ($('.mid').css('width').replace('px', '') * 1);
	
	if ( left == width ) { 
		$('.mid').find('div').stop().animate({left: '-=50px'}, 200, function() {
			$('.mid').find('div').animate({left: '+=50px'}, 300);
		});	
	} else {
		$('.mid').find('div').stop().animate({left:'-=144px'}, {queue:true});
	}
}

function scroll_left(obj, i) {
	var left = $('.mid').find('div').css('left').replace('px', '');
	
	if ( left == 0 ) {
		$('.mid').find('div').animate({left: '-=50px'}, {queue:true});
		$('.mid').find('div').animate({left: '+=50px'}, {queue:true});
		
	} else {
		$('.mid').find('div').stop().animate({left: '+=144px'}, {queue:true});
	}
}

function prepare_carousel(obj, i) {
	$('.sright').click(function() {
		scroll_right($(obj), i);
	});
	
	$('.sleft').click(function() {
		scroll_left($(obj), i);
	});
}

function even_divs(obj) {
	var big = 0;
	$(obj).each(function() {
		var height = $(this).height();
		if ( height >= big ) { big = height; }
	});
	$(obj).each(function() { 
		$(this).stop().animate({height:big}, 500);
	});
}
