/************************************************************************************************************************************
 *	Slide				jQuery Slide Plugin
 *
 *	@author:			Daniel Benkenstein / neosmart GmbH / www.neosmart.de
 *	@version:			1.0
 *	@date:				Feb 2011
 *	@licence:			MIT (http://www.opensource.org/licenses/mit-license.php)
 *						GPL	(http://www.gnu.org/licenses/gpl.html)
 *	
 ************************************************************************************************************************************/

(function($) {
	
	$.fn.slide = function(options) {
		
		var opts = $.extend({}, $.fn.slide.defaults, options);
		var meta = this;
		var $obj = [];
		var $var = [];
		
		return meta.each(function(x) {
			$obj[x] = [];
			$obj[x]['this'] = $(this);
			$var[x] = [];
			$var[x]['slideX'] = 0;
			$var[x]['slidePos'] = 0;
			var o = $.meta ? $.extend({}, opts, $obj[x]['this'].data()) : opts;
			var output = '';
			var isMobile = (navigator.userAgent.match(/iPhone/i)) || (navigator.userAgent.match(/iPod/i)) || (navigator.userAgent.match(/iPad/i))||(navigator.userAgent.match(/Android/i));
			if(!$.easing[o.easing]) o.easing='linear';
			
			/******************************************************************************************************
			 * Create Markup
			 ******************************************************************************************************/
		
			$obj[x]['this'].wrapInner('<div class="neosmart-slide-wrap"/>');
			$obj[x]['this'].addClass('neosmart-slide loading').prepend('<div class="neosmart-slide-button-prev"/><div class="neosmart-slide-button-next"/>');
			$obj[x]['prev'] = $obj[x]['this'].children('.neosmart-slide-button-prev');
			$obj[x]['next'] = $obj[x]['this'].children('.neosmart-slide-button-next');
			$obj[x]['wrap'] = $obj[x]['this'].children('.neosmart-slide-wrap');
			$obj[x]['wrap'].wrapInner('<div class="neosmart-slide-container"/>');
			$obj[x]['slide'] = $obj[x]['wrap'].children('.neosmart-slide-container').hide();
			
			//optional
			$obj[x]['thumbs'] = $('.js-slide-thumbs[rel="'+$obj[x]['this'].attr('id')+'"] li');

			
			/******************************************************************************************************
			 * Init
			 ******************************************************************************************************/
			 
			var init = function(){
				
				$obj[x]['this'].css({
					width:o.width+'px',
					height:o.height+'px',
					overflow:'hidden'
				});
				
				$obj[x]['wrap'].css({
					width:o.width+'px',
					height:o.height+'px',
					overflow:'hidden'
				});
				
				$obj[x]['slide'].css({
					width:(parseInt(o.width)*o.count)+'px',
					height:o.height+'px',
					overflow:'hidden'
				});
				
				$obj[x]['thumbs'].each(function(i,el){
					$(el).click(function(e){
						slideTo(i);
					});
				}).eq(0).addClass('active');
				

				
				// If there is only one container -> return
				if(o.count==1)
					return;
				
				// Image
				$obj[x]['slide'].find('img').imagesLoaded(fadeInSlide);
				
				// Show Buttons for desktop browsers
				if(!isMobile){
					$obj[x]['prev'].css({opacity:0}).bind({
						mouseover:function(){
							if(o.showButtons=='hover') $obj[x]['prev'].stop().animate({opacity:1},300);
						},
						mouseout:function(){
							if(o.showButtons=='hover') $obj[x]['prev'].stop().animate({opacity:0},300);
						},
						click:function(){
							slideTo('prev');	
						}
					});
					$obj[x]['next'].css({opacity:0}).bind({
						mouseover:function(){
							if(o.showButtons=='hover') $obj[x]['next'].stop().animate({opacity:1},300);
						},
						mouseout:function(){
							if(o.showButtons=='hover') $obj[x]['next'].stop().animate({opacity:0},300);
						},
						click:function(){
							slideTo('next');	
						}
					});
					if(o.showButtons=='true') $obj[x]['next'].css({opacity:1,display:'block'});
				}
				
				// Key Events
				$(document).bind('keydown', function(e) {
					if ((e.keyCode == 37 || e.keyCode == 39) && e.target.tagName !== 'INPUT' && e.target.tagName !== 'TEXTAREA' && e.target.tagName !== 'SELECT') {
						e.preventDefault();
						var dir = (e.keyCode == 37) ? 'prev' : 'next';
						slideTo(dir);
					}
				});

				
				function fadeInSlide(img){
					$obj[x]['slide'].fadeIn(500,function(){
						if(!isMobile && o.showButtons=='hover') $obj[x]['next'].css({opacity:0,display:'block'});							  
					});
				}
				
				function slideTo(v){

					if(!$obj[x]['this'].is(':visible')) return;
					switch(v){
						case 'prev':
							$var[x]['slidePos']-=1;
						break;
						case 'next':
							$var[x]['slidePos']+=1;
						break;
						default:
							$var[x]['slidePos']=v;
						break;
					}
					
					if(!isMobile){
						if($var[x]['slidePos']<1){
							$var[x]['slidePos']=0;
							if($obj[x]['next'].css('display')=='none')$obj[x]['next'].show();
							$obj[x]['prev'].hide();
							if(o.showButtons=='true') $obj[x]['next'].css({opacity:1});
						} else if($var[x]['slidePos']>o.count-2){
							$var[x]['slidePos']=o.count-1;
							if($obj[x]['prev'].css('display')=='none')$obj[x]['prev'].show();
							$obj[x]['next'].hide();
							if(o.showButtons=='true') $obj[x]['prev'].css({opacity:1});
						} else{
							if($obj[x]['prev'].css('display')=='none')$obj[x]['prev'].show();
							if($obj[x]['next'].css('display')=='none')$obj[x]['next'].show();
							if(o.showButtons=='true'){
								$obj[x]['prev'].css({opacity:1});
								$obj[x]['next'].css({opacity:1});
							}
						}
					}
					
					$obj[x]['thumbs'].filter('.active').removeClass('active');
					$obj[x]['thumbs'].eq($var[x]['slidePos']).addClass('active');
					
					$var[x]['slideX'] = -$var[x]['slidePos']*o.width;
					$obj[x]['slide'].stop().animate({marginLeft:$var[x]['slideX']},{duration:500,easing:o.easing});
						
				}
				
				// Enable touchmove for mobile devices
				if(!isMobile)
					return;

				$obj[x]['wrap'].bind('touchstart', function(e){	
					e = e.originalEvent.touches[0];
					var tmpX=diffX=moveX=val=0,startX=e.pageX;
					$obj[x]['wrap'].bind('touchmove',function(ev){
						ev.preventDefault();
						ev = ev.originalEvent.touches[0];						
						diffX = moveX-ev.pageX;
						moveX = exists(ev.pageX)?ev.pageX:0;
						tmpX = (startX-moveX)*o.xFactor;
						if($var[x]['slideX']-tmpX>0)tmpX=$var[x]['slideX'];
						if($var[x]['slideX']-tmpX<-(o.count-1)*o.width)tmpX=$var[x]['slideX']+(o.count-1)*o.width;
						$obj[x]['slide'].stop().css({marginLeft:$var[x]['slideX']-tmpX});
					});
					$obj[x]['wrap'].bind('touchend',function(ev){
						val = -Math.round(($var[x]['slideX']-tmpX)/o.width);
						slideTo(val);						
						$obj[x]['wrap'].unbind('touchmove touchend');
					});
				});
	
			}

			
			/******************************************************************************************************
			 * Helper Functions
			 ******************************************************************************************************/
			 
			function exists(data){
				if(data==false || data==null || data=='undefined' || typeof(data)=='undefined') return false;
				else return true;
			}
			
			init();
		});
	};

	/******************************************************************************************************
	 * Defaults 
	 ******************************************************************************************************/
	 
	$.fn.slide.defaults = {
		count:			1,
		width:			600,
		height:			400,
		xFactor:		3,
		easing:			'easeOutExpo', //fallback: linear
		showButtons:	'hover'
	};
	
	// $('img.photo',this).imagesLoaded(myFunction)	
	$.fn.imagesLoaded = function(callback){
		var elems = this.filter('img'),len = elems.length;
		elems.bind('load',function(){
			if (--len <= 0){callback.call(elems,this);}
		}).each(function(){
			if (this.complete || this.complete === undefined){var src = this.src;this.src = "data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///ywAAAAAAQABAAACAUwAOw==";this.src = src;}  
		}); 
		return this;
	};

})(jQuery);


/******************************************************************************************************
 * Auto-Detection
 ******************************************************************************************************/
 
$(function(){
	var detect = $('.neosmart-slide');
	if(detect.length){
		detect.each(function(){
			var $this = $(this);
			$this.slide({
				count:$this.attr('data-count'),
				width:$this.attr('data-width'),
				height:$this.attr('data-height'),
				easing:$this.attr('data-easing'),
				showButtons:$this.attr('data-showbuttons')
			});
		});
	}
});
