var sbrunning = false;
var box_interval;

$(document).ready(function(){ 
	$(document).pngFix();
	
	/** start boxes **/
	$('#start-box-holder .start-box-prev, #start-box-holder .start-box-next').hide();
	var total_boxes = $('#start-boxes .box').length;
	
	// position the boxes
	$('#start-boxes .box').each(function(key, item) {
		$(this).css('margin-left', 335*key);
	});
	
	$('#start-box-holder').bind('mouseover', function() {
		$('#start-box-holder .start-box-prev, #start-box-holder .start-box-next').show();
	}).bind('mouseout', function() {
		$('#start-box-holder .start-box-prev, #start-box-holder .start-box-next').hide();
	});
	
	function get_first_box() {
		var box;
		var box_margin = 100000;

		$('#start-boxes .box').each(function(key, item) {
			if(box_margin > parseInt($(this).css('margin-left'))) {
				box = $(this);
				box_margin = parseInt($(this).css('margin-left'));
			}
		});	
	
		return box;
	}
	
	function get_last_box() {
		var box;
		var box_margin = 0;
		$('#start-boxes .box').each(function(key, item) {
			if(box_margin < parseInt($(this).css('margin-left'))) {
				box = $(this);
				box_margin = parseInt($(this).css('margin-left'));
			}
		});
		
		return box;
	}
	
	function prev_box() {
		if(sbrunning)
			return;
			
		sbrunning = true;
	
		$('#start-boxes .box').each(function(key, item) {
			if(key == 0) {
				var box = get_last_box();
				$(box).css('margin-left', -335);
			}
		
			var onCompletePrev;
			if(total_boxes-1 == key) {			
				onCompletePrev = function() {
					sbrunning = false;
				}
			}
			
			$(this).animate({marginLeft: parseInt($(this).css('margin-left'))+335}, 600, "swing", onCompletePrev);
		});
	}
	
	function next_box() {
		if(sbrunning)
			return;
			
		sbrunning = true;
	
		$('#start-boxes .box').each(function(key, item) {
			var onComplete;
			if(total_boxes-1 == key) {
				onComplete = function() {
					var box = get_first_box();
					$(box).css('margin-left', (total_boxes*335)-335);
					sbrunning = false;
				}
			}
			
			$(this).animate({marginLeft: parseInt($(this).css('margin-left'))-335}, 600, "swing", onComplete);
		});
	}
	
	if($('#start-boxes .box').length > 2) {		
		$('.start-box-prev').click(function() {
			clearInterval(box_interval);
			prev_box();
		});
		
		$('.start-box-next').click(function() {
			clearInterval(box_interval);
			next_box();
		});
	
		// interval
		box_interval = setInterval(function() {
			next_box();
		}, 15000);
	}
});
