$(document).ready(function(){
	$('.prev, .next').hover(		
		function(){
			if (!$(this).hasClass('disabled')) {
				$(this).addClass('hover')
			}
		},
		function(){
				$(this).removeClass('hover')
		}
	)

	$('div.topstories-image-click').click(function(e){	
		document.location = $(this).next().find('.ts-title').children('a').attr('href')
	})
	$('div.ts-selected').click(function(){
		document.location = $('.topstories-image:visible').find('.ts-title').children('a').attr('href')
	})
	
})

var _speed = 800;
//var _timeout = 6000;
//var _delay = 20000;
var _timeout = 2900;
var _delay = 3200;
var _visible = 6;
var _curr =1;
var _count = $('#ts-nav').children().length;
var _isMoving = false;
if (_count < 6 && _count != 0){
	_visible = _count;
  }
  
tsCycleAuto();
tsCarouselAuto();
  
function tsCycleAuto(){
	$('#topstories-image-container').cycle({
		timeout: _timeout,
		speed: _speed,
		delay: _delay,
		before: function(curr, next, opts){
			if (curr == next){return}
			_curr = parseInt($(next).attr('id').slice(6))
			_isMoving = true;
			$('.jc-next').click()
		},
		after : function(curr,next,opts){
			_isMoving = false;
		}
	});
	$('#top_stories .next').click(function(){
		clearAuto('.next')
	})
	$('#top_stories .prev').click(function(){	
		clearAuto('.prev')
	})
	$('.ts-text').show()
}
function clearAuto(dir){
	$('#topstories-image-container').cycle('stop')
	$('#top_stories .next,#top_stories .prev,.jc-next, .jc-prev').unbind('click')
	tsCarouselMan(dir)
}
function tsCarouselAuto(){
	$('#ts-nav-wrapper').jCarouselLite({
		visible: _visible,
		btnNext: '.jc-next',
		btnPrev: '.jc-prev',
		speed: _speed
	})
}		
function tsCarouselMan(dir){
	var _start =_curr-1;  //switch to 0 indexing
	var i = _count - 1;

	$('#ts-nav li:lt('+_visible+')').remove(); //cleanup old cloned divs
	$('#ts-nav li:gt('+i+')').remove();
	
	$('#ts-nav-wrapper').jCarouselLite({
		start:_start,
		visible: _visible,
		btnNext: '#top_stories .next',
		btnPrev: '#top_stories .prev',
		afterEnd: slideBig
	})
	
	if (!(_isMoving && dir == '.next')) {
		$('#top_stories ' + dir).click();
	}			
	setTimeout(function(){$('.topstories-image').css({opacity: 1})},500)	// wait for cycle to end	
}

function slideBig(e){
	var id = $(e[0]).attr('id').slice(6)
	$('#topstories-image-container .topstories-image').hide();			
	$('#topstories-image-container #ts-img'+ id).show();
}