var activeLink;
var abort_timer = false;
var in_transition = false;
var times_through = 0;

function showCarouselItem(dot_clicked, times_through_when_entered) {
	var newActiveCarouselItem = $("#" + $(dot_clicked).attr("rel"));

	if (abort_timer == true) {
		
		$(".carousel li:not(newActiveCarouselItem)").hide();
		newActiveCarouselItem.delay(20).fadeIn(2500);
		activateCarouselDot(dot_clicked);
	} else {
		$(".carousel li:not(newActiveCarouselItem)").fadeOut(2500, function() {
			if (abort_timer == false) {
				newActiveCarouselItem.delay(20).fadeIn(2500);
				activateCarouselDot(dot_clicked);
			}
		});
	}
	
	times_through++;
}

function activateCarouselDot(dot_clicked) {
	
	var currentatlink = $("ul.carousel_dots li a.at");
	
	$(currentatlink).attr("class", "");
	$(currentatlink).children().attr("src", "images/carousel_dot_off.png");

	$(dot_clicked).attr("class", "at");
	$(dot_clicked).children().attr("src", "images/carousel_dot_on.png");
	
}

function linkLoader(dot_clicked) {
	
	abort_timer = true;
	$(document).stopTime("carousel");
	showCarouselItem(dot_clicked, times_through);

	return false;
}

function linkHover(the_dot) {
	if ($(the_dot).attr("class") != "at") {
		$(the_dot).children().attr("src", "images/carousel_dot_on.png");
	}
}

function linkHoverOut(the_dot) {
	if ($(the_dot).attr("class") != "at") {
		$(the_dot).children().attr("src", "images/carousel_dot_off.png");
	}
}

function beginCarousel(delay) {
	
	var count = 2;
	var number_of_dots = $("ul.carousel_dots li a").length;
	
	if (!delay) {
		delay = 5000;
	}
	
	$(document).everyTime(delay, "carousel", function() {

		if (abort_timer == false) {

			// Remove the current active dot.
			var currentatlink = $("ul.carousel_dots li a.at");
			$(currentatlink).attr("class", "");
			$(currentatlink).children().attr("src", "images/carousel_dot_off.png");

			var newatlink = $("ul.carousel_dots li a[banner_id='" + count + "']");

			showCarouselItem(newatlink, times_through);

			// Go through all of the carousel items and loop back to the beginning when done
			if (count == number_of_dots) {
				count = 1;
			} else {
				count++;
			}
		} else {
			$(document).stopTime("carousel");
		}

	});
	
}

function addListeners() {
	$("ul.carousel_dots li a").bind("click keyup", function() {
		$(document).stopTime("carousel");
		return linkLoader(this);
	});
	$("ul.carousel_dots li a").bind("mouseover", function() { return linkHover(this); });
	$("ul.carousel_dots li a").bind("mouseout", function() { return linkHoverOut(this); });

	//$('a.zoom').fancyZoom({scaleImg: false, closeOnClick: true});
	
	$("#banner_hello_bw").fadeOut(3500, function(el) {
		$("#banner_hello_bw").remove();
	});
	
	$("#banner_hello").css("visibility", "visible");
	
	beginCarousel(8000);
}

$(window).load(addListeners);
