//rotating banners

$(document).ready(function(){
	$("#controls li a").click(function(){
            //Performed when a control is clicked
	    shuffle();
	    var rel = $(this).attr("rel");
	    if ( $("#" + rel).hasClass("current") ){
	        return false;
	    }
	    $("#" + rel).show();
	    $(".current").fadeOut().removeClass("current");
	    $("#" + rel).addClass("current");
	    $(".banneractive").removeClass("banneractive");
	    $(this).parents("li").addClass("banneractive");
	    set_new_interval(2000);
	    return false;
	});
    });
    function banner_switch(){
        //This function is called on to switch the banners out when the time limit is reached
        shuffle();
        var next =  $('.banner.current').next('.banner').length ? $('.banner.current').next('.banner') : $('#banners .banner:first');
        $(next).show();
        $(".current").fadeOut().removeClass("current");
        $(next).addClass("current");
        var next_link = $(".banneractive").next("li").length ? $('.banneractive').next('li') : $('#controls li:first');
        $(".banneractive").removeClass("banneractive");
        $(next_link).addClass('banneractive');
    }

    $(function() {
        //Initial timer setting
        slide = setInterval( "banner_switch()", 5000 );
    });

    function set_new_interval(interval){
        //Simply clears out the old timer interval and restarts it
        clearInterval(slide);
        slide = setInterval("banner_switch()", interval);
    }

    function shuffle(){
        //This function takes every .banner and changes the z-index to 1, hides them, then takes the ".current" banner and brings it above and shows it
        $(".banner").css("z-index", 1).hide();
        $(".current").css("z-index", 2).show();
    }


//click rotating banners


$(document).ready(function() {
	var loaded = 0;
	var timerId = 0;
	var current = null;

	var stop = function() {
		clearTimeout(timerId);
		timerId = 0;
	};

	var resume = function(func, el) {
		timerId = window.setTimeout(function() { func(el); }, 4000);
	};

	var reset = function(e) {
		loaded = 0;

		if(e)
			e.fadeOut(500);

		original.fadeIn(500, function() { loaded = 1; });
	};

	var original = $('#home_photo');

	reset();

	//
	$('#banner > a').each(function(i) {
		if(i > 0)
		{
			var banner = $(this);

			$(this).mouseover(function() {
				stop();
			}).mouseout(function() {
				resume(reset, banner);
			});
		}
	});

	$('#banner_menu > li > a').each(function(i) {
		i += 1;
		var banner = $('#banner a:eq(' + i + ')');

		$(this).mouseover(function() {
			if(!loaded)
				return;

			original.hide();

			if(current != null)
				$('#banner > a:eq(' + current +')').hide();

			current = i;

			banner.show();
			stop();
		}).mouseout(function() {
			if(!loaded)
				return;

			resume(reset, banner);
		});
	});
});


