/**
 *	Wide Slider
 *
 *	Created by: Arlind Nushi (http://www.arlindnushi.com)
 */
 
(function($, window, undefined)
{
	
	var body = $("body");
	var win = $(window);
	var doc = $(document);
	
	
	$.fn.wideslider = function(options, arg1, arg2)
	{
		var o = {
			delay: 1000,
			autoSwitch: 0,
			onFinish: function(){},
			
			nextPrev: null,
			prevNextOnKeyboard: false,
			
			sliderNav: null,
				
			// Auto Center Inside
			autoCenter: '',
			autoCenterTop: 0,
			
			
			// Animation Engine
			animationEngine: 'jquery' // jquery or gsap
		};
		
		$.extend(o, options);
		
		this.each(function()
		{
			var self = this;
			
			var $container = $(this);
			
			if(typeof options == 'string')
			{
				var methods = $container.data('methods');
				
				if(methods[options])
				{
					methods[options].apply(this, [arg1, arg2]);
				}
				return;
			}
			
			
			// Per container options
			var pco = {
				items: null,
				images_container: null,
				images: null,
				
				// Index
				index: 0,
				total_items: 0,
				last_slide: $(null),
				
				// Next Prev Nav
				next: $(null),
				prev: $(null),
				
				// Slide Options
				inactiveIndex: 1,
				activeIndex: 2,
				
				// DOM
				sliderNav: $(null)
			};
			
			// Images Container
			pco.images_container = $('<div class="ws_images_container" />');
			
			// Get Items
			pco.items = $container.children();
			pco.total_items = pco.items.size();
			
				
			
			// Get Item Images
			pco.items.each(function(i)
			{
				var $item = $(this);
				
				var image = $item.find('> img:first');
				
				$item.data('itemImage', image);
				image.detach();
				
				image.data('itemEl', $item);
				
				$item.data('index', i);
				image.data('index', i);
				
				image.on({
					click: function(ev)
					{
						var $img = $(this);
						var href = $img.data('href');
						
						if(href)
						{
							window.location.href =  href;
						}
					}
				});
				
				pco.images_container.append(image);
			});
			
			// Initialize pco.images
			pco.images = pco.images_container.find('img');
			
			// Append to the document
			body.prepend(pco.images_container);
			
			// Hide Items
			pco.items.hide();
			
			// Show The Slider
			$container.show();
			
			// Set Click Events
			$container.parent().parent().parent().on('click', function(ev)
			{
				var image = jQuery( pco.images.get(pco.index) )

				if(jQuery(ev.target).is('div'))
				{
					image.trigger('click');
				}
				
			});
			
			/* FUNCTIONS */
			
				// Get Slide by Index
				var getSlide = function(index)
				{
					var slide = $(null);
					
					pco.items.each(function(i)
					{
						if(i == index)
						{
							slide = $(this);
						}
					});
					
					return slide;
				};		
				
				
				// Get Previous Index
				var getPreviousIndex = function()
				{
					var index = pco.index - 1;
					
					if(index < 0)
						index = pco.total_items - 1;
					
					return index;
				};
				
				
				// Get Next Index
				var getNextIndex = function()
				{
					var index = (pco.index + 1) % pco.total_items;
					
					
					return index;
				};
				
				
				// Generate Next Prev Navigation
				var generateNextPrevNav = function()
				{
					var container = typeof o.nextPrev == 'string' ? $(o.nextPrev) : o.nextPrev;
					
					var prev_slide = $('<a href="#" class="prev">Previous</a>');
					var next_slide = $('<a href="#" class="next">Next</a>');
					
					prev_slide.data('direction', -1);
					next_slide.data('direction', 1);
					
					container.append(prev_slide);
					container.append(next_slide);
					
					// Add Events
					prev_slide.add(next_slide).on('click', function(ev)
					{
						ev.preventDefault();
						
						var direction = $(this).data('direction');
						
						var to_index = direction == -1 ? getPreviousIndex() : getNextIndex();
						stopAutoSwitch();
						
						showSlide(to_index);
					});
				};
				
				
				// Generate Slider Numbers Navigation
				var generateSliderNav = function(i)
				{
					var container = typeof o.sliderNav == 'string' ? $(o.sliderNav) : o.sliderNav;
					
					pco.items.each(function(i)
					{
						var slider_nav_item = $('<a href="#" class="slider_nav_item">'+(i+1)+'</a>');
						slider_nav_item.data('index', i);
						
						slider_nav_item.on('click', function(ev)
						{
							ev.preventDefault();
							
							var index = $(this).data('index');
							
							showSlide(index);
						});
						
						// Append the index slider link
						container.append(slider_nav_item);
					});	
				};
				
				
				var setSliderNavActive = function(i)
				{
					var container = typeof o.sliderNav == 'string' ? $(o.sliderNav) : o.sliderNav;
					
					if(container.length == 0)
						return;
					
					var slider_nav_items = container.find('a');
					var slider_nav_item = $(slider_nav_items.get(i));
					
					slider_nav_items.removeClass('active');
					
					slider_nav_item.addClass('active');
				};
				
				// Show Slide Without Animation
				var showSlideNoAnimation = function(index)
				{
					var item = getSlide(index);
					
					setSliderNavActive(index);
					
					if(item.length)
					{
						// Switch Indexes
						if(pco.last_slide.size())
						{
							pco.last_slide.data('itemImage').css({zIndex: pco.inactiveIndex});
							pco.last_slide.hide();
						}
							
						item.data('itemImage').css({zIndex: pco.activeIndex});
						
						item.show();
						
						pco.index = index;
						pco.last_slide = item;
					}
				};
				
				// Show Slide With Animation
				var showSlide = function(index)
				{
					var item = getSlide(index);
					
					setSliderNavActive(index);
					
					if(pco.total_items < 2)
						return;
					
					if(item.length)
					{						
						var fade_delay = parseInt(o.delay/2, 10);
						 
						var to_show = item,
							to_show_image = item.data('itemImage');
						
						var to_hide = pco.last_slide,
							to_hide_image = pco.last_slide.data('itemImage');
						
						// Switch Indexes
						to_show_image.css({zIndex: pco.activeIndex});
						to_hide_image.css({zIndex: pco.inactiveIndex});
						
						// Switch Image
						if(o.animationEngine == 'gsap') // GreenSock Animation Platform TweenMax
						{
							to_show_image.css({opacity: 0, visibility: 'visible'});
							
							var show_el = to_show_image.get(0);
							var se_tween = TweenMax.to(show_el, o.delay / 1000, {css : {autoAlpha: 1}});
							
							var hide_el = to_hide_image.get(0);
							var he_tween = TweenMax.to(hide_el, o.delay / 1000, {css : {autoAlpha: 0}});
						}
						else
						if(o.animationEngine == 'jquery') // jQuery Animation Engine
						{
							to_show_image.stop().fadeTo(0, 0).animate({opacity: 1}, {duration: o.delay, easing: 'easeInOutQuad'});
							to_hide_image.stop().animate({opacity: 0}, {duration: o.delay, easing: 'easeInOutQuad', complete: o.onFinish});
						}
						
						
						// Margin Top (for autocenter)
						if(o.autoCenter)
						{
							var last_slide_top = pco.last_slide.data('topMargin');
							var curr_slide_top = item.data('topMargin');
						}
							
						
						// Switch Text						
						to_hide.stop().animate({opacity: 0}, {duration: fade_delay / 3, easing: 'easeInOutSine', complete: 
							function()
							{
								to_hide.hide();
								
								var to_show_animate_options = {
									opacity: 1
								};
								
								if(o.autoCenter)
								{
									to_show.css({marginTop: last_slide_top});
									to_show_animate_options.marginTop = curr_slide_top;
								}
								
								to_show.show().fadeTo(0,0).animate(to_show_animate_options, {duration: fade_delay / 2, easing: 'easeInOutSine'});
							}
						});
						
						pco.index = index;
						pco.activeIndex = index;
						pco.last_slide = to_show;
					}
				};
				
				
				var as_interval = null;
				
				var stopAutoSwitch = function()
				{
					window.clearInterval(as_interval);
					as_interval = null;
				};
				
				var startAutoSwitch = function(timeout)
				{
					if(o.autoSwitch == 0)
						return;
						
					as_interval = setInterval(function()
					{
						showSlide( getNextIndex() );
					}, timeout);
				};
				
				var autoSwitch = function(timeout)
				{
					startAutoSwitch(timeout);
					
					pco.images_container.add($container)
					.on('mouseenter', function()
					{
						stopAutoSwitch();
					})
					.on('mouseleave', function()
					{
						startAutoSwitch(timeout);
					});
				};
				
				
				var sliderAutoCenter = function()
				{
					var container = typeof o.autoCenter == 'string' ? $(o.autoCenter) : o.autoCenter;
					var items = pco.items;
					
					var extra_top = o.autoCenterTop;
					
					var ct_height = container.height();
					
					items.each(function(i)
					{
						var $item = $(this);
						
						var item_height = $item.height();
						
						var top_margin = parseInt((ct_height - item_height) / 2, 10) + extra_top;
						
						$item.data('topMargin', top_margin).css({
							//position: 'relative',
							marginTop: top_margin
						});
					});
				}
			
			
			/* SETUP SLIDER */
			
			
			// Generate Navigation (if allowed)
			if(o.nextPrev)
			{
				generateNextPrevNav();
			}
			
			// Generate Slider Numbers (if allowed)
			if(o.sliderNav)
			{
				generateSliderNav();
			}
			
			// Show First Slide
			showSlideNoAnimation(0);
			
			// Auto Center
			if(o.autoCenter)
			{
				sliderAutoCenter();
			}
			
			
			// Check for autoswitch
			pco.images_container.imagesLoaded(function()
			{
				var as = 0;
				
				if(as = $container.data('autoswitch'))
				{
					autoSwitch(as);
				}
			});
			
			
			// Prev Next On KeyBoard
			if(o.prevNextOnKeyboard)
			{
				win.on('keyup', function(e)
				{
					if(e.keyCode == 37)
					{
						showSlide( getPreviousIndex() );
						stopAutoSwitch();
					}
					else
					if(e.keyCode == 39)
					{
						showSlide( getNextIndex() );
						stopAutoSwitch();
					}
				});
			}
			
			// Assign Instance
			var instance = {
				autoCenter: sliderAutoCenter
			};
			
			$container.data('methods', instance);
		});
		
	}
	
})(jQuery, window);