/*!
  swipeGallery 0.6.0
  Edited by Michael Rosario - Look North, Inc.
  Examples and documentation at: 
  http://www.app-agentur-bw.de/showcase/swipegallery
  2011 AREA-NET GmbH (www.app-agentur-bw.de | www.area-net.de)
  Version: 0.5.0 (17-MARCH-2011)
  Dual licensed under the MIT and GPL licenses:
  http://www.opensource.org/licenses/mit-license.php
  http://www.gnu.org/licenses/gpl.html
  
  Requires:
  jQuery v1.3.2 or later
  
 */
(function($){

$.fn.idle = function(time)
  { 
      var o = $(this); 
      o.queue(function()
      { 
         setTimeout(function()
         { 
            o.dequeue(); 
         }, time);
      });
  };


$.fn.swipeGallery=function(options){
var settings={
	'classname'		:	'appGallery', 	// Class name for the swipeGallery
	'autoHeight'	:	false,			// Set to true if it's full screen
	'height'		:	'400px',	  	// Height of the Slideshow
	'width'			:	'780px',		// Width of the Slideshow
	'background'	:	'#FFFFFF',		// Background
	'tolerance'		:	0.25,			// Sensitivity
	'debug'			:	false,			// Set true to debug.  Will need a DIV with a class swipeDebug
	'delay'			:	300,			// Delay
	'pager'			:   false,			// Provide class/id of container add auto numbering
	'next'			: 	false,			// Provide class/id of link
	'prev'			: 	false,			// Provide class/id of link
	'captions'		:	false,			// Provide class/id of container
	'autoScroll'	:	false,			// set to true to loop
	'timeout'		:	3000,			// set to true to loop
	'speed'			:	700,			// speed of animation
	'pos'			: 	false,			// Class name of container for pagination # of #,1 of 3, 2 of 3 
	'file'			: 	false			// Class name of container for file location

	}

	var mousedown=false;
	var mouseX=0;
	var imagesLength=0;
	var imagesCurrent=0;
	var xdiff=0;
	var containerHeight=0;
	var containerWidth=0;
	var debugBar=null;
	var touchstart=0;
	var isInit=false;
	var pager=null;
	var _this=$(this);
	var switcher=true;
	var timeout=settings.timeout;
	var speed=settings.speed;
	var run = null;
	
function doResizeImage(listElement){
	$(listElement).css('height',containerHeight);
	$(listElement).css('width',containerWidth);
		var img=$(listElement).find('img');
	
	if(img.width()/containerWidth>img.height()/containerHeight){
	img.width(containerWidth);
			var top=(containerHeight-img.height())/2;
			img.css('marginTop',top+'px');
		}else{img.height(containerHeight);
			var left=parseInt((containerWidth-img.width())/2);
			img.css('marginLeft',left+'px');}
		}
function init(obj,parent,imageHandler){
	if(isInit)return;
	isInit=true;
	imagesLength=0;




	if(settings.autoHeight){
			containerHeight=$(window).height();
			containerWidth=$(window).width();
		}else{
			containerHeight=parseInt(settings.height);
			containerWidth=parseInt(settings.width);
		}

	obj.find('li').each(function(){
		doResizeImage(this);
		imagesLength++;
		})

	 if(settings.pager){
		 var x = 0;
		 var htmlbuttons = "";
		 var pagerLive = $(settings.pager);
		   while(x < imagesLength){
			   htmlbuttons = htmlbuttons + "<a href='#"+ x +"'>"+ x +"</a>"; 
			   x++;
		   };
		   if(settings.autoScroll) {
		   htmlbuttons = htmlbuttons + "<a href='#' class='autoScroll' title='Pause'>"+ x +"</a>"; 
		   }
	 
	 pagerLive.html(htmlbuttons);
	 pagerLive.find('a').eq(0).addClass("activeSlide");
	 pagerLive.find('a:not(".autoScroll")').live('click',function(){  slideTo(this.hash.replace('#',''));  return false;  });
	 pagerLive.find('.autoScroll').live('click',function(){  switcher=false;   $(".autoScroll").addClass('Stop').css("background-position","bottom left").attr('title','Play'); clearInterval(run);	updatePager();  return false; });
 	 pagerLive.find('.autoScroll.Stop').live('click',function(){ $(this).removeClass('Stop').css("background-position","top left").attr('title','Pause'); switcher=true; clearInterval(run); run = setInterval( function(){ loop(); }, timeout ); return false;  });
	
	 };

	if(settings.captions){
		var pagerLive = $(settings.captions);
		pagerLive.html(_this.find('li').eq(0).find('img').attr('alt'));
		}
	if($(settings.file)) { var pagerFile = $(settings.file);
		pagerFile.attr('href',_this.find('li').eq(0).find('img').attr('src')); }
	
	if(settings.next){
		var nextButton = $(settings.next);
		nextButton.live('click',function(){ if(imagesLength-1>imagesCurrent){ slideTo(1+imagesCurrent);} else { /* slideTo(0); */ } return false;  }); 
	}
	if(settings.prev){
		var prevButton = $(settings.prev);
		prevButton.live('click',function(){ if(0<imagesCurrent){ slideTo(-1+imagesCurrent);} else { /* slideTo(imagesLength-1); */ } return false;  }); 
	}

if(settings.autoScroll){  clearInterval(run);	run = setInterval( function(){ loop(); }, timeout ); }

	parent.css('height',containerHeight);
	parent.css('width',containerWidth);
	imageHandler.css('width',containerWidth);
	imageHandler.css('height',containerHeight);
	imageHandler.css('left',parent.position().left);
	imageHandler.css('top',parent.position().top);
	obj.css('width',imagesLength*containerWidth);}

function updatePager(){
if(settings.pager){ 
			var pagerLive = $(settings.pager); 
			pagerLive.find('a').removeClass("activeSlide");
			pagerLive.find('a').eq(imagesCurrent).addClass("activeSlide");
			}
}

function debug(text){
	if(debugBar){
		debugBar.html('<b>DEBUG-BAR: </b>'+text);
		}
	}
	
	
	function loop(){
	if(switcher){
	settings.speed = speed;
		if(imagesCurrent == imagesLength-1){
			image='<li class="temp"><img src="'+_this.find('img').last().attr('src')+'"></li>';
			_this.prepend(image);
			_this.css('left',0);
			imagesCurrent=0;
			updatePager();
			_this.animate({left:-containerWidth},settings.speed, 
			function(){ 
			_this.find('.temp').remove();
				imagesCurrent=0;updateCaptions(imagesCurrent);
				_this.css('left',0);
				}); 
		} else{ imagesCurrent++; updatePager(); }
		if(settings.captions) { updateCaptions(imagesCurrent); };
	if(imagesCurrent<imagesLength) {
	_this.animate({left:-imagesCurrent*containerWidth},settings.speed, function(){ if(settings.autoScroll){  if(switcher){ } else{ _this.stop(true);    $(".autoScroll").addClass('Stop').css("background-position","bottom left").attr('title','Play'); 	updatePager(); }} }); 
	}
	else { 
	imagesCurrent=0;
	updatePager();
		if(settings.captions) { updateCaptions(imagesCurrent) };
	_this.animate({left:0*containerWidth},settings.speed, 
		function(){ 
		
			if(settings.autoScroll){ 
				if(switcher){  } 
				else{ 
					_this.stop(true);    
					$(".autoScroll").addClass('Stop').css("background-position","bottom left").attr('title','Play'); 	
					updatePager(); 
				}
			} 
		});
		}
			} else {
	if(settings.captions) { updateCaptions(imagesCurrent) };
		updatePager();
		clearInterval(run);
	return false; }};


function slideTo(number){
		if(_this.find('.temp').length) { _this.find('.temp').remove(); };
		_this.stop(true);
		_this.animate({left:-number*containerWidth},settings.speed,function(){ if(settings.autoScroll){ if(switcher){ } else{  $(".autoScroll").addClass('Stop').css("background-position","bottom left").attr('title','Play');  }}  });
		imagesCurrent = number;
		var pagerLive = $(settings.pager);
		pagerLive.find('a').removeClass("activeSlide");
		pagerLive.find('a').eq(imagesCurrent).addClass("activeSlide");
		if(settings.captions) { updateCaptions(number) };
		if(settings.pos){ var posLive = $(settings.pos); posLive.html(imagesCurrent*1+1+" of "+imagesLength); };
		if(settings.autoScroll){  clearInterval(run); run = setInterval( function(){ loop(); }, timeout ); }
	return false;
};

function updateCaptions(number){
	var pagerLive = $(settings.captions);
	pagerLive.html(_this.find('li').eq(number).find('img').attr('alt'));
	if($(settings.file)) { var pagerFile = $(settings.file);
	pagerFile.attr('href',_this.find('li').eq(number).find('img').attr('src')); }
	if(imagesCurrent == 0){  var prevButton = $(settings.prev); prevButton.addClass("End").siblings().removeClass("End"); }
	else if(imagesCurrent == imagesLength-1){ var nextButton = $(settings.next); nextButton.addClass("End").siblings().removeClass("End"); }
	else { var nextButton = $(settings.next); nextButton.addClass("End").parent().find('a').removeClass("End"); };
	return false;
};


return this.each( function(){
	var _this=$(this);
	if(options){$.extend(settings,options);}


if(settings.autoHeight){
		containerHeight=$(window).height();
		containerWidth=$(window).width(); 
	}else{
		containerHeight=parseInt(settings.height);
		containerWidth=parseInt(settings.width);
	}
	_this.wrap('<div class="'+settings.classname+'"/>');
	var parent=_this.parent();
	parent.css('backgroundColor',settings.background);
	parent.append('<div class="imageHandler"/>');
	
	if(settings.debug){
		parent.prepend('<div class="swipeDebug" style="font-family:Arial;font-size:11px;text-align:center;position:relative;z-index:200;padding:5px;background-color:#FFFFFF;"><b>DEBUG-BAR</b></div>');
		debugBar=_this.parent().find('.swipeDebug');
		}


	var imageHandler=_this.parent().find('.imageHandler').css('background','url(/images/bg-trans.gif) !important;');
	init(_this,parent,imageHandler);	
	$(window).resize(function(){
	isInit=false;init(_this,parent,imageHandler);
	

})

imageHandler.bind('touchstart',function(event){ switcher=false;
	event.preventDefault();
	var touch=event.originalEvent.touches[0]||event.originalEvent.changedTouches[0];
	if(!this.mousedown){ this.mousedown=true;this.mouseX=touch.pageX; }
	$('.autoScroll').not('.Stop').click(); 
return false;
});
	if(settings.pos){ var posLive = $(settings.pos); posLive.html(imagesCurrent*1+1+" of "+imagesLength); };
imageHandler.bind('touchmove',function(event){
	event.preventDefault();
	var touch=event.originalEvent.touches[0]||event.originalEvent.changedTouches[0];
	if(this.mousedown){xdiff=touch.pageX-this.mouseX;_this.css('left',-imagesCurrent*containerWidth+xdiff);}
		return false;
	});

imageHandler.bind('touchend',function(event){
	event.preventDefault();
	var touch=event.originalEvent.touches[0]||event.originalEvent.changedTouches[0];
	this.mousedown=false;
	if(!xdiff) return false;
	var fullWidth=parseInt(settings.width);
	var halfWidth=fullWidth/2;
	if(-xdiff>halfWidth-fullWidth*settings.tolerance){
			imagesCurrent++;
			debug(imagesCurrent+' = '+imagesLength);
			imagesCurrent=imagesCurrent>=imagesLength?imagesLength-1:
			imagesCurrent;
			_this.animate({left:-imagesCurrent*containerWidth},settings.delay);
		} else if(xdiff>halfWidth-fullWidth*settings.tolerance){
			imagesCurrent--;
			imagesCurrent=imagesCurrent<0?0:imagesCurrent;
			_this.animate({left:-imagesCurrent*containerWidth},settings.delay);
			} else {			
			_this.animate({left:-imagesCurrent*containerWidth},settings.delay);
		}
		if(settings.pager){ 
			var pagerLive = $(settings.pager);
			pagerLive.find('a').removeClass("activeSlide");
			pagerLive.find('a').eq(imagesCurrent).addClass("activeSlide");
			}
		if(settings.captions) { updateCaptions(imagesCurrent); };
		if(settings.pos){ var posLive = $(settings.pos); posLive.html(imagesCurrent*1+1+" of "+imagesLength); };
		xdiff=0;return false;
		});


imageHandler.mouseover(function(event){
return false;
});

imageHandler.mousedown(function(event){ 
	if(switcher){  $('.autoScroll').click();  }
	if(!this.mousedown){this.mousedown=true;this.mouseX=event.pageX; }
	
	return false;
});

imageHandler.mousemove(function(event){ 
	if(this.mousedown){  xdiff=event.pageX-this.mouseX; _this.css('left',-imagesCurrent*containerWidth+xdiff); }
	return false;
});

imageHandler.mouseup(function(event){
	this.mousedown=false;if(!xdiff) return false;
	var fullWidth=parseInt(settings.width);
	var halfWidth=fullWidth/2;debug(xdiff+' > '+halfWidth+' - '+fullWidth+' * '+settings.tolerance);
	if(-xdiff>halfWidth-fullWidth*settings.tolerance){
			imagesCurrent++; 
			imagesCurrent=imagesCurrent>=imagesLength?imagesLength-1:imagesCurrent;
			_this.animate({left:-imagesCurrent*containerWidth},settings.delay);
		
		}else if(xdiff>halfWidth-fullWidth*settings.tolerance ){
			imagesCurrent--; 
			imagesCurrent=imagesCurrent<0?0:imagesCurrent;
			_this.animate({left:-imagesCurrent*containerWidth},settings.delay);
			
		}else{
			_this.animate({left:-imagesCurrent*containerWidth},settings.delay);
		}
		updatePager();
		if(settings.captions){ updateCaptions(imagesCurrent) };
		if(settings.pos){ var posLive = $(settings.pos); posLive.html(imagesCurrent*1+1+" of "+imagesLength); };
	xdiff=0;return false;
});

imageHandler.mouseleave(function(event){
	imageHandler.mouseup();
	});
});



};
})(jQuery);
