var count = 0;
var nexts = 0;
var $active;
var $next;
var loop;

$(document).ready(function() 
{
	count = $("#slide-runner a").length;
	
	for(var i = 0 ; i < count  ; i++)
	{
		$('#slide-nav').html($('#slide-nav').html() + '<a href="#" id="" onfocus="" onclick="make_next(this , ' + i +')"></a>');
	}
	quick_slide(0);
	loop = setInterval( "slideSwitch()", 6000 );
});

function make_next(a , i)
{
	//Stop the current animation
	$active.stop();
	$next.stop();
	clearInterval(loop);
	
		
	//Start from clicked position
	nexts = i;
	slide(i);
	loop = setInterval( "slideSwitch()", 6000 );
}

function slideSwitch() 
{
    var $active = $('#slide-runner a.active');

    if ( $active.length == 0 ) 
    {
    	$active = $('#slide-runner a:last');
    }

  	slide(nexts);
}

function slide(num)
{
	//Get the number of next slide
	if(num >= count)
	{
		num = 0;
		nexts = 0;
		clearInterval(loop);
	}
	
	$active = $('#slide-runner a.active');

    if ( $active.length == 0 ) 
    {
    	$active = $('#slide-runner a:last');
    }
    
    $next =  $('#slide-runner a:nth(' + nexts + ')');
    
    //Change controller indications
    $('#slide-nav a').removeClass('on');
    var controller = $('#slide-nav a:nth(' + nexts + ')').addClass('on');

    $active.addClass('last-active');
	$active.animate({opacity:0.0} , 1000);
    
    $next.css({opacity: 0.0})
        .addClass('active')
        .animate({opacity: 1.0}, 1000, function() {
            $active.removeClass('active last-active');
        });
    
    nexts++;
}

function quick_slide(num)
{
	//Get the number of next slide
	if(num >= count)
	{
		num = 0;
		nexts = 0;
		clearInterval(loop);
	}
	
	$active = $('#slide-runner a.active');

    if ( $active.length == 0 ) 
    {
    	$active = $('#slide-runner a:last');
    }
    
    $next =  $('#slide-runner a:nth(' + nexts + ')');
    
    //Change controller indications
    $('#slide-nav a').removeClass('on');
    var controller = $('#slide-nav a:nth(' + nexts + ')').addClass('on');

    $active.addClass('last-active');
	$active.animate({opacity:0.0} , 0);
    
    $next.css({opacity: 0.0})
        .addClass('active')
        .animate({opacity: 1.0}, 0, function() {
            $active.removeClass('active last-active');
        });
    
    nexts++;
}

