$(document).ready(function(){
	
	var $images = $('.home_feature .images img');
	var $texts = $('.home_feature .texts .text');
	var $controls = $('.home_feature .controls .button');
	
	var options = {
		image_speed: 800,
		text_speed: 400,
		is_changing: false,
		current:null,
		previous:null,
		can_loop:true,
		auto_change:true,
		auto_change_time: 5500,
		auto_change_timer:null,
		text_delay:0
	}
	
	// stop text fading in ie 8 and less
	if( $.browser.msie && $.browser.version <= 8 ) options.text_speed = 0;	
	
	$controls.bind('click',function() {
		var index = $controls.index(this);
		if(!options.is_changing && index!=options.current) {
			options.previous = options.current;
			options.current = index;
			bannerChange();
		}
	});	
	
	function nextImage() {
		if( options.is_changing ) return;
		options.previous = options.current;							  
		options.current+=1 ;
		if(options.current>$images.size()-1 && options.can_loop==true) {
			options.current=0;
			options.previous=$images.size()-1;
			bannerChange();
		} else if (options.current>$images.size()-1 && options.can_loop==false) {
			options.current=$images.size()-1;
		} else {
			bannerChange();
		}
	}
			
		
	function autoChange() {
		if( $images.size() -1 < 1 || !options.auto_change || options.is_changing ) return; 
		if ( options.auto_change_timer ) window.clearTimeout( options.auto_change_timer );
		options.auto_change_timer = window.setTimeout( function(){ nextImage(); } , options.auto_change_time );
	}
		
	function bannerChange() {
		options.is_changing=true;
		$texts.eq(options.previous).fadeOut(options.text_speed,function(){						
			$controls.eq(options.previous).removeClass('active');
			$controls.eq(options.current).addClass('active');
			$images.eq(options.previous).fadeOut(options.image_speed);
			$images.eq(options.current).fadeIn(options.image_speed,function(){
				$texts.eq(options.current).delay(options.text_delay).fadeIn(options.text_speed,function(){
					options.is_changing=false;
					autoChange();
				});																 
			});
		});
	}
	
	// if ie add the date to image src so .load works with cached images
	if( $.browser.msie ) $images.eq(0).attr( 'src' , $images.eq(0).attr('src') + '&' + new Date().getTime() );
	
	// start autochanger
	autoChange();
	
});
