/* === Fader === */

$(function() {
	$.fn.heroSwap = function(options) {
		var o = $.extend({}, $.fn.heroSwap.defaults, options);
		o.container = '#' + $(this).attr('id');
		o.container_static = $(this).attr('id');
		o.animation_ref = o.container_static + '_' + o.animation_ref;
		var timer, continue_cycle = true, next_hero, current_hero = o.default_hero;
		var heroes = $(this).find(o.content_class + " li");
		var navs = $(this).find(o.nav_class + " li");
		var swap = function(a,b) {
			if(a != b) {
				set_active(b);
				var fout = $(heroes[a]);
				var fin = $(heroes[b]);
				fout.fadeOut(o.fade_time);
				fin.fadeIn(o.fade_time);
				fin.find("p").css("left","-300px");
				fin.find("p").animate({left: 0},600);
			}
		}
		var set_active = function(i)
		{
			$(navs[current_hero]).removeClass('active');
			current_hero = i;
			$(navs[i]).addClass('active');
		}
		var get_next_hero = function(i)
		{
			var next = current_hero + 1;
			if(next+1 > heroes.length)
			{
				next_hero = 0;
			}
			else
			{
				next_hero = next;
			}
		}
		var cycle = function(type) {
			if (continue_cycle == true) {
				if (heroes.length >= 1) {
					get_next_hero(current_hero);
					
					timer = setTimeout(function(){
						swap(current_hero, next_hero);
						cycle();
					}, o.cycle_delay);
				}
			}
		}
		if(o.cycle == true) {
			cycle(o.type);
		}
		$(this).find(o.nav_class + " li").each(function(i) {
			$(heroes[i]).css({
				'position':'absolute',
				'top':'0',
				'left':'0',
				'display':'list-item',
				'overflow':'hidden'
			});
			
			if(i != current_hero)
			{
				$(heroes[i]).css({
					'display':'none'
				});
			}
			$(this).click(function() {
				var clicked_nav = navs.index(this);
				if(o.cycle == true)
				{
					clearTimeout(timer);
					continue_cycle = false;
				}
				swap(current_hero, clicked_nav);
				return false;
			});
		});
		set_active(o.default_hero);
	};
	$.fn.heroSwap.defaults = {
		default_hero	: 0,
		container		: "#hero",
		nav_class		: ".hero-nav",
		content_class	: ".hero-content",
		animation_ref	: "in_anim_0o0o",
		cycle			: true,
		cycle_delay		: 4000,
		type			: 'fade',
		fade_time		: 1500
	};
});
