(function($){	

	$.fn.interactive = function(options){	

		var 	el = this,
			defaults = {
				button_left_id:'button-left',
				button_right_id:'button-right',
				bg_id:'interactive-bg',
				items_class:'interactive-items',
				titles_class:'interactive-titles',
				images_class:'interactive-image',
				anim_speed:1500,
				delay:7000,
				slides: [
					'https://moduswines.com/sites/moduswines.com/assets/images/bg_home_2.jpg',
					'https://moduswines.com/sites/moduswines.com/assets/images/bg_home_1.jpg',
					'https://moduswines.com/sites/moduswines.com/assets/images/bg_home_3.jpg'
				]
			},
			settings = $.extend(defaults, options),
			$items = $('.'+ settings.items_class).find('div'),
			$images = $('.'+ settings.images_class),
			$titles = $('.'+ settings.titles_class).find('h1'),
			current_index = 0,
			is_playing = true,
			interval = 0,
			container,
			root_element = ("onorientationchange" in window) ? $(document) : $(window), // hack to acccount for iOS position:fixed shortcomings
			img_ratio,
			bg_img,
			bg_width,
			bg_height,
			bg_offset,
			bg_css;

		init = function(){
			
log('interactive');
			
			//quit if not needed	
			/*if ($('#'+el.selector).length < 1 ){
				return;
			}*/
			
			createButtons();
			
			
			//create container
               $("body").append( $("<div />").attr("id", "interactive-bg"));                  
			container = $('#'+settings.bg_id);
			
			selectSlide();
			
			play();
			
			$(window).resize(adjustBG);
		};
		
		log = function(s){
			if (typeof console != "undefined" && typeof console.debug != "undefined"){
				console.log(s);
			} else {
				//alert(s);
			}
		};
		
		
		play = function(){
			
			is_playing = true;
			
			interval = setInterval(next, settings.delay);
		};	
		
		constrain = function(input){
			if (input < 0){
				input = settings.slides.length;
			} else if (input >= settings.slides.length){
				input = 0;
			} 
			return input;
		};
		
		createButtons = function(){
	
			$('#main-wrapper').append( $('<a id="button-left"><span></span></a><a id="button-right"><span></span></a>') );
			
			$('#'+settings.button_left_id).bind('click',function(e){
				
				e.preventDefault();
				buttonClick(-1);
			});
			$('#'+settings.button_right_id).bind('click',function(e){
				
				e.preventDefault();
				buttonClick(1);
			});
		};
		
		next = function (){
		
			current_index = constrain(current_index + 1);	
			selectSlide();
		};
		
		prev = function (){
		
			current_index = constrain(current_index - 1);	
			selectSlide();
		};
		
		buttonClick = function(dir){
			
			is_playing = false;
			clearInterval(interval);
			
			if (dir < 0){
				prev();//current_index = constrain(current_index - 1);
			} else {
				next();
			}
		};
		
		selectSlide = function(){
log('selectSlide '+current_index);
			//$.backstretch(settings.slides[current_index],{anim_speed: 1000});
			
			
			var 	img,
				src = settings.slides[current_index];
			
			adjustHighlight();
			
			container.find("img").addClass("deleteable");
			
			//load next image
			img = $("<img />")
					.css({position: 'absolute', display:'none', left:$(window).width()})
					.bind("load", function(e){
						
						
log('img loaded '+$(window).width()+' '+settings.anim_speed);
						                      
						var 	self = $(this),
							img_width = this.width || $(e.target).width(),
							img_height= this.height || $(e.target).height();
					
						self.css({width: 'auto', height: 'auto', position:'absolute', display:'block'});

						img_ratio = img_width / img_height;
					
						
						adjustBG(function(){
							var win_width = $(window).width();
							var new_left = (win_width - self.width())/2;
							
							container.find('.deleteable').animate({left:-win_width},settings.anim_speed, function(){ $(this).remove(); });

							self.animate({left:new_left}, settings.anim_speed, function(){
								//self.fadeIn(settings.anim_speed, function(){
								
								// Callback
								if (typeof callback == 'function') callback();
							});
						});
					})
					.appendTo(container);
			
			 img.attr("src", src); //IE img onload event
			 

		};
		adjustBG = function(fn){
			try {
				bg_css = {};//left: 0, top: 0
				bg_width = Math.ceil( root_element.width() );
				bg_height = Math.ceil( bg_width / img_ratio );
			
				// Make adjustments based on image ratio
				if (bg_height >= root_element.height()){
//log('bg_height >= root_element.height()');
					bg_offset = (bg_height - root_element.height()) /2;
					////bg_css.top = -bg_offset;
					
					/*if (settings.centered_y){
						$.extend(bg_css, {top: '-' + bg_offset + 'px'}) 
					}*/
					
				} else {
					
					bg_height = root_element.height();
					bg_width = bg_height * img_ratio;
					bg_offset = (bg_width - root_element.width()) / 2;
					////bg_css.left = -bg_offset;
					/*if (settings.centered_x){
						$.extend(bg_css, {left: '-' + bg_offset + 'px'})
					}*/
				}
				
				$('#'+settings.bg_id+', #'+settings.bg_id+' img:last')//$("#backstretch, #backstretch img:last")
					.width( bg_width )
					.height( bg_height )
					.filter('img')
					.css(bg_css);
					
				var  win_width = $(window).width(),
					img = $('#'+settings.bg_id+' img:last'),
					img_width = img.width();
					new_left = img_width > win_width ? ( win_width - img.width() )/2 : 0;
				
				/////$('#'+settings.bg_id).css({left:new_left});
				
//log('adjustbg '+new_left);
				
//log('adjustbg '+ bg_width +' '+ bg_height);
					
			} catch(err){
log('err adjustbg');
			}
		
			// Execute the passed in function, if necessary
			if (typeof fn == "function") fn();
		};
		
		adjustHighlight = function(){
			
log('adjustHighlight '+current_index);
			
			
			$items.each(function(i){
				if (i == current_index){
					$(this).addClass('active');
				} else {
					$(this).removeClass('active');
				}
			});
			
			/*$items.each(function(i){
				if (i == current_index){
					$(this).addClass('active');
				} else {
					$(this).removeClass('active');
				}
			});
			
			$images.each(function(i){
				if (i == current_index){
					$(this).find('div').fadeIn();
				} else {
					$(this).find('div').fadeOut();
				}
			});*/
			
			$titles.each(function(i){
				if (i == current_index){
					$(this).fadeIn(1000);
				} else {
					$(this).fadeOut(1000);
				}
				
			});
			//settings.titles_class	
			
		};
		
		init();
	};
})(jQuery);
