/*
 * jQuery slider plugin
 * @version 1.0.0
 */

(function($){
	$.fn.extend({ 
		infiniteCarousel: function(options)
		{
			var defaults =
			{
				transitionSpeed: 810,
				displayTime: 10500,
				textholderHeight: 1,
				thumbnailFontSize: '14px'
			};
	
			var options = $.extend(defaults, options);
	
    		return this.each(function() {
    			var randID = Math.round(Math.random()*100000000);
				var o=options;
				var obj = $(this);
				var curr = 1;
				var numSlides = $('li', obj).length; // Number of images
				var slideHeight = 250;
				var slideWidth = 990;
				var autopilot = 1;
		
				$('p', obj).hide(); // Hide any text paragraphs in the carousel
				$(obj).width(slideWidth).height(slideHeight);

	
				// Move last image and stick it on the front
				$(obj).css({'overflow':'hidden','position':'relative'});
				$('li:last',obj).prependTo($('ul', obj));
				$('ul',obj).css('left',-slideWidth+'px');
				$('ul',obj).width(9999);

				$('ul',obj).css({'list-style':'none','margin':'0','padding':'0','position':'relative'});
				$('li',obj).css({'display':'inline','float':'left'});


				// Build textholder div
				$(obj).append('<div id="textholder'+randID+'" class="textholder"></div>');
				var correctTHHeight = parseInt($('#textholder'+randID).css('paddingRight'));
				showtext($('li:eq(1) p', obj).html());


				// Build Navigation Bar 

					// Prev/next button(img)
				$('#navBar').append('<div id="btn_lt' + randID + '" ><a class="navButton" style="left:0px" href="javascript:void(0);"><img style="float:left" src="App_Themes/components/keyframe/arrowPrev.gif" /><span style="float:left">Prev Feature</span></a></div>')
				$('#navBar').append('<div id="btn_rt' + randID + '" ><a class="navButton" style="right:0px" href="javascript:void(0);"><img style="float:right" src="App_Themes/components/keyframe/arrowNext.gif" /><span style="float:right">Next Feature</span></a></div>')
					
					// Left and right arrow image button actions
					$('#btn_rt'+randID).click(function(){
						autopilot = 0;
						anim('next');
						setTimeout(function(){$('#play_btn'+randID).fadeIn(250);},o.transitionSpeed);
						clearTimeout(clearInt);
					});
					$('#btn_lt'+randID).click(function(){
						autopilot = 0;
						anim('prev');
						setTimeout(function(){$('#play_btn'+randID).fadeIn(250);},o.transitionSpeed);
						clearTimeout(clearInt);
					});

					// Thumbnail viewer and thumbnail divs
					$('#navBar').append('<div id="thumbs'+randID+'" class="thumbs"></div>');
					for(i=0;i<=numSlides-1;i++)
					{
						thumb = $('img:eq('+(i+1)+')', obj).attr('src');
						$('#thumbs' + randID).append('<div class="thumb" id="thumb' + randID + '_' + (i + 1) + '" style="cursor:pointer;display:inline;float:left;background-image:url(\'App_themes/components/keyframe/thumbEmpty.gif\');width:19px;height:19px;padding:0;overflow:hidden;text-align:center;border:none;margin:0px 5px 0px 5px;">&nbsp;&nbsp;&nbsp;&nbsp;</div>');
						if (i == 0) $('#thumb' + randID + '_1').css({ 'background-image': 'url(\'App_themes/components/keyframe/thumbFilled.gif\')' });
					}
					// Next two lines are a special case to handle the first list element which was originally the last
					thumb = $('img:first', obj).attr('src');
					$('#thumb' + randID + '_' + numSlides).css({ 'background-image': 'url(\'App_themes/components/keyframe/thumbEmpty.gif\')' });
					$('#thumbs'+randID+' div.thumb:not(:first)').css({'opacity':'.65'}); // makes all thumbs 65% opaque except the first one
					$('#thumbs'+randID+' div.thumb').hover(function(){$(this).animate({'opacity':.99},150)},function(){if(curr!=this.id.split('_')[1]) $(this).animate({'opacity':.65},250)}); // add hover to thumbs

					// Assign click handler for the thumbnails. Normally the format $('.thumb') would work but since it's outside of our object (obj) it would get called multiple times
					$('#thumbs'+randID+' div').bind('click', thumbclick); // We use bind instead of just plain click so that we can repeatedly remove and reattach the handler


				function thumbclick(event)
				{
					target_num = this.id.split('_'); // we want target_num[1]
					if(curr != target_num[1])
					{
						$('#thumb' + randID + '_' + curr).css({ 'background-image': 'url(\'App_themes/components/keyframe/thumbEmpty.gif\')' });
						clearTimeout(clearInt);
						$('#thumbs'+randID+' div').css({'cursor':'default'}).unbind('click'); // Unbind the thumbnail click event until the transition has ended
						autopilot = 0;
						setTimeout(function(){$('#play_btn'+randID).fadeIn(250);},o.transitionSpeed);
					}
					if(target_num[1] > curr)
					{
						diff = target_num[1] - curr;
						anim('next',diff);
					}
					if(target_num[1] < curr)
					{
						diff = curr - target_num[1];
						anim('prev', diff);
					}
				}
				function showtext(t)
				{
					// the text will always be the text of the second list item (if it exists)
					if(t != null)
					{
						$('#textholder'+randID).html(t).animate({marginBottom:'0px'},500); // Raise textholder
					}
				}
				function borderpatrol(elem)
				{
					$('#thumbs' + randID + ' div').css({ 'background-image': 'url(\'App_themes/components/keyframe/thumbEmpty.gif\')' }).animate({ opacity: 0.65 }, 500);
					setTimeout(function() { elem.css({ 'background-image': 'url(\'App_themes/components/keyframe/thumbFilled.gif\')' }).animate({ 'opacity': .99 }, 500); }, o.transitionSpeed);
				}
				function anim(direction,dist)
				{
					// Fade left/right arrows out when transitioning
					$('#btn_rt'+randID).fadeOut(500);
					$('#btn_lt'+randID).fadeOut(500);
					
					// animate textholder out of frame
					$('#textholder'+randID).animate({marginBottom:(-slideHeight*o.textholderHeight)-(correctTHHeight * 2)+'px'},500);					

					if(direction == "next")
					{
						if(curr==numSlides) curr=0;
						if(dist>1)
						{
							borderpatrol($('#thumb'+randID+'_'+(curr+dist)));
							$('li:lt(2)', obj).clone().insertAfter($('li:last', obj));
							$('ul', obj).animate({left:-slideWidth*(dist+1)},o.transitionSpeed,function(){
								$('li:lt(2)', obj).remove();
								for(j=1;j<=dist-2;j++)
								{
									$('li:first', obj).clone().insertAfter($('li:last', obj));
									$('li:first', obj).remove();
								}
								$('#btn_rt'+randID).fadeIn(500);
								$('#btn_lt'+randID).fadeIn(500);
								showtext($('li:eq(1) p', obj).html());
								$(this).css({'left':-slideWidth});
								curr = curr+dist;
								$('#thumbs'+randID+' div').bind('click', thumbclick).css({'cursor':'pointer'});
							});
						}
						else
						{
							borderpatrol($('#thumb'+randID+'_'+(curr+1)));
							$('#thumbs'+randID+' div').css({'cursor':'default'}).unbind('click'); // Unbind the thumbnail click event until the transition has ended
							// Copy leftmost (first) li and insert it after the last li
							$('li:first', obj).clone().insertAfter($('li:last', obj));	
							// Update width and left position of ul and animate ul to the left
							$('ul', obj)
								.animate({left:-slideWidth*2},o.transitionSpeed,function(){
									$('li:first', obj).remove();
									$('ul', obj).css('left',-slideWidth+'px');
									$('#btn_rt'+randID).fadeIn(500);
									$('#btn_lt'+randID).fadeIn(500);
									showtext($('li:eq(1) p', obj).html());
									curr=curr+1;
									$('#thumbs'+randID+' div').bind('click', thumbclick).css({'cursor':'pointer'});
								});
						}
					}
					if(direction == "prev")
					{
						if(dist>1)
						{
							borderpatrol($('#thumb'+randID+'_'+(curr-dist)));
							$('li:gt('+(numSlides-(dist+1))+')', obj).clone().insertBefore($('li:first', obj));
							$('ul', obj).css({'left':(-slideWidth*(dist+1))}).animate({left:-slideWidth},o.transitionSpeed,function(){
								$('li:gt('+(numSlides-1)+')', obj).remove();
								$('#btn_rt'+randID).fadeIn(500);
								$('#btn_lt'+randID).fadeIn(500);
								showtext($('li:eq(1) p', obj).html());
								curr = curr - dist;
								$('#thumbs'+randID+' div').bind('click', thumbclick).css({'cursor':'pointer'});
							});
						}
						else
						{
							borderpatrol($('#thumb'+randID+'_'+(curr-1)));
							$('#thumbs'+randID+' div').css({'cursor':'default'}).unbind('click'); // Unbind the thumbnail click event until the transition has ended
							// Copy rightmost (last) li and insert it after the first li
							$('li:last', obj).clone().insertBefore($('li:first', obj));
							// Update width and left position of ul and animate ul to the right
							$('ul', obj)
								.css('left',-slideWidth*2+'px')
								.animate({left:-slideWidth},o.transitionSpeed,function(){
									$('li:last', obj).remove();
									$('#btn_rt'+randID).fadeIn(500);
									$('#btn_lt'+randID).fadeIn(500);
									if(autopilot) $('#pause_btn'+randID).fadeIn(250);
									showtext($('li:eq(1) p', obj).html());
									curr=curr-1;
									if(curr==0) curr=numSlides;
									$('#thumbs'+randID+' div').bind('click', thumbclick).css({'cursor':'pointer'});
								});
						}
					}
				}

				var clearInt = setInterval(function(){anim('next');},o.displayTime+o.transitionSpeed);
//				$('#progress'+randID).animate({'width':0},o.displayTime+o.transitionSpeed,function(){
//					$('#pause_btn'+randID).fadeOut(100);
//					setTimeout(function(){$('#pause_btn'+randID).fadeIn(250)},o.transitionSpeed)
//				});
  		});
    	}
	});
})(jQuery);
