var st;

var first_run = true;

$(document).ready(function() {
	
	st = new splash_timer();
	
	scrolling();
	
});

function scrolling() {
	
	scroll_time = 2000;

	ticker_left = Math.abs( cleanpx($('#scroller').css('left')));
	

	if(ticker_left > 0) {
			
		remaining = $('#scroller img:first').outerWidth() - ticker_left;
		speed = $('#scroller img:first').outerWidth() / remaining;
		scroll_time /= speed;
		
	}
	
	$('#scroller').animate({ 'left' : - $('#scroller img:first').width() }, scroll_time  , 'linear', function () {
		
			$('#scroller').append( $('#scroller img:first') ); 
			$('#scroller').css({ 'left' : '0' });
			scrolling();
			
	}); 
	
}

function cleanpx(px) {

	var i = (px).indexOf('px');
	
	var x = px.substring(0,i);
	//alert(x);
	return x;
}

function splash_timer() {
		
	var self = this;
	
	this.current_index = '';
	
	this.frames = $('.splash_item');
	
	this.interrupt = false;
	
	this.interval_amount = 4000;
	this.interval;
	this.revert_timeout;
	
	this.init = new function() {
		
		
		
		if(self.current_index == '') {
			self.current_index = 0;
			setTimeout( function() {
				self.show_frame(self.current_index);
				self.timer();
			}, 500);
			
			var data_id = 0;
			
			self.frames.each( function() {
				
				$(this).attr('data-id', ++data_id);
									   
			});
			
		}
		
		self.frames.mouseenter( function() {
			
			if( $(this).attr('state') == 'in') {
			
				self.interrupt = true;

				clearTimeout(self.interval);
				

			}
										
		});
		
	
		self.frames.mouseleave( function() {
			
			self.interrupt = false;
			
			self.timer();
			
		});
		
				
	}
	
	this.timer = function() {
	
		var interval = self.interval_amount;
		
		clearTimeout(self.interval);
		
		self.interval = setTimeout( function() {
			
			self.next();
			
		}, interval);
		
	}
	
	this.next = function() {
		
		self.current_index++;
		
		if(self.current_index > self.frames.length -1 ) {
			self.current_index = 0;
		}
		
		self.show_frame(self.current_index);
		
	
	}
	
	this.revert = function() {
		
		if(self.interrupt == false) {
			self.show_frame(self.current_index);
			self.timer();
		}
	
	}
	
	this.show_frame = function(index) {
		
		self.frames.attr('state', 'out');
		$(self.frames[index]).attr('state', 'in');
		
		var cindex = self.current_index - 1 < 0 ? 0 : self.current_index -1;
		
		
		$(self.frames[cindex]).find('.splash_content').animate({
			right: -470,
			top : 0													  
		
		}, 750, function() {
			
			if(first_run == false) {
				self.frames.stop(true,true).fadeOut();
			} else {
				first_run = false;
			}
		
			$(self.frames[index]).fadeIn( function() {
				
				$(self.frames[index]).find('.splash_content').animate({
					right: 0,
					top : 0																
				}, 750, function() {
					
					self.timer();	
					
				});
																	
			});
			
		});
		
		
	}

}
