/*
 * jQuery infinitecarousel plugin
 * @author admin@catchmyfame.com - http://www.catchmyfame.com
 * @version 1.2.2
 * @date August 31, 2009
 * @category jQuery plugin
 * @copyright (c) 2009 admin@catchmyfame.com (www.catchmyfame.com)
 * @license CC Attribution-Share Alike 3.0 - http://creativecommons.org/licenses/by-sa/3.0/
 */

(function($){
	$.fn.extend({ 
		infiniteCarousel: function(options)
		{
			var defaults = 
			{
				transitionSpeed : 1000,
				displayTime : 6000,
				textholderHeight : .2,
				displayProgressBar : 0,
				displayThumbnails: 1,
				displayThumbnailNumbers: 1,
				displayThumbnailBackground: 0,
				thumbnailWidth: '15px',
				thumbnailHeight: '20px',
				thumbnailFontSize: '12px;',
				parentControlsDivId: '',
				autoscroll: 'no'
			};
		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 numDivs = $('div', obj).length; // Number of images
				var divHeight = $('div:first', obj).height();
				var divWidth = $('div:first', obj).width();
				var autopilot = (o.autoscroll == 'no') ? 0 : 1;
		
				$('p', obj).hide(); // Hide any text paragraphs in the carousel
				$(obj).width(divWidth).height(divHeight);
			
				// Build progress bar
				if(o.displayProgressBar)
				{
					$(obj).append('<div id="progress'+randID+'" style="position:absolute;bottom:0;background:#bbb;left:'+$(obj).css('paddingLeft')+'"></div>');
					$('#progress'+randID).width(divWidth).height(5).css('opacity','.5');
				}
			
				// 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',-divWidth+'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 thats as wide as the carousel and 20%-25% of the height
				$(obj).append('<div id="textholder'+randID+'" class="textholder" style="position:absolute;bottom:0px;margin-bottom:'+-divHeight*o.textholderHeight+'px;left:'+$(obj).css('paddingLeft')+'"></div>');
				var correctTHWidth = parseInt($('#textholder'+randID).css('paddingTop'));
				var correctTHHeight = parseInt($('#textholder'+randID).css('paddingRight'));
				$('#textholder'+randID).width(divWidth-(correctTHWidth * 2)).height((divHeight*o.textholderHeight)-(correctTHHeight * 2)).css({'backgroundColor':'#FFF','opacity':'0.5'});
				showtext($('li:eq(1) p', obj).html());
			
				// Prev/next button(img) 
				html = '<div id="btn_rt'+randID+'" style="position:absolute;right:0;top:'+((divHeight/2)-15)+'px"><a href="javascript:void(0);"><img style="border:none;margin-right:2px" src="site_images/RightArrow.gif" /></a></div>';
				html += '<div id="btn_lt'+randID+'" style="position:absolute;left:0;top:'+((divHeight/2)-15)+'px"><a href="javascript:void(0);"><img style="border:none;margin-left:2px" src="site_images/LeftArrow.gif" /></a></div>';
				$(obj).append(html);
							
				// Left and right arrow image button actions
				
				
				
				$('#btn_rt'+randID).click(function(){
					$('#progress'+randID).stop().fadeOut();
					anim('next');

				});
				
				$('#btn_lt'+randID).click(function(){
					$('#progress'+randID).stop().fadeOut();
					anim('prev');

				});
			
//thumbs
				if(o.displayThumbnails)
				{
					// Build thumbnail viewer and thumbnail divs
					if (o.parentControlsDivId.length > 0)
					{
						window.document.getElementById(o.parentControlsDivId).innerHTML = '<div id="thumbs'+randID+'" style="text-align:right;padding-top:5px;"></div>';
					}
					else
					{
						$(obj).after('<div id="thumbs'+randID+'" style="position:relative;overflow:auto;text-align:left;padding-top:5px;"></div>');
					}
					for(i=0;i<=numDivs-1;i++)
					{
						$('#thumbs'+randID).append('<div class="thumb" id="thumb'+randID+'_'+(i+1)+'" style="cursor:pointer;display:inline;width:'+o.thumbnailWidth+';height:'+o.thumbnailHeight+';line-height:'+o.thumbnailHeight+';padding:0;overflow:hidden;text-align:center;border:0px;margin-right:8px;font-size:'+o.thumbnailFontSize+';font-family:Arial, Helvetica;color:#8e8e8e;">'+(i+1)+'</div>');
						if(i==0) $('#thumb'+randID+'_1').css({'color':'#cc9933', 'text-decoration':'underline'});
					}

					//$('#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
				
					if(!o.displayThumbnailNumbers) $('#thumbs'+randID+' div').text('');
				}
				function thumbclick(event)
				{
					target_num = this.id.split('_'); // we want target_num[1]


					if(curr != target_num[1])
					{
						$('#thumb'+randID+'_'+curr).css({'text-decoration':'underline'});
						$('#progress'+randID).stop().fadeOut();
						$('#thumbs'+randID+' div').css({'cursor':'default'}).unbind('click'); // Unbind the thumbnail click event until the transition has ended

					}
					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
						showminmax();
					}
				}
				function showminmax()
				{
						if(!autopilot)
						{
							html = '<img style="position:absolute;top:2px;right:18px;display:none;cursor:pointer" src="/images/jquerycarousel/down.png" title="Minimize" alt="minimize" id="min" /><img style="position:absolute;top:2px;right:18px;display:none;cursor:pointer" src="/images/jquerycarousel/up.png" title="Maximize" alt="maximize" id="max" />';
							html += '<img style="position:absolute;top:2px;right:6px;display:none;cursor:pointer" src="/images/jquerycarousel/close.png" title="Close" alt="close" id="close" />';
							$('#textholder'+randID).append(html);
							$('#min').fadeIn(250).click(function(){$('#textholder'+randID).animate({marginBottom:(-divHeight*o.textholderHeight)-(correctTHHeight * 2)+24+'px'},500,function(){$("#min,#max").toggle();});});
							$('#max').click(function(){$('#textholder'+randID).animate({marginBottom:'0px'},500,function(){$("#min,#max").toggle();});});
							$('#close').fadeIn(250).click(function(){$('#textholder'+randID).animate({marginBottom:(-divHeight*o.textholderHeight)-(correctTHHeight * 2)+'px'},500);});
						}
				}
				function borderpatrol(elem)
				{
					$('#thumbs'+randID+' div').css({'color':'#8e8e8e', 'text-decoration':'none'});
					elem.css({'color':'#cc9933', 'text-decoration':'underline'});
				}
				function anim(direction,dist)
				{
					// Fade left/right arrows out when transitioning
					$('#btn_rt'+randID).css({'alpha':'0', 'display':'none'});
					$('#btn_lt'+randID).css({'alpha':'0', 'display':'none'});
					
					// animate textholder out of frame
					$('#textholder'+randID).animate({marginBottom:(-divHeight*o.textholderHeight)-(correctTHHeight * 2)+'px'},500);					

					if(direction == "next")
					{
						if(curr==numDivs) curr=0;
						if(dist>1)
						{
   						clearTimeout(clearInt);
							borderpatrol($('#thumb'+randID+'_'+(curr+dist)));
							$('li:lt(2)', obj).clone().insertAfter($('li:last', obj));
							$('ul', obj).animate({left:-divWidth*(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).css({'alpha':'1', 'display':''});
								$('#btn_lt'+randID).css({'alpha':'1', 'display':''});

								showtext($('li:eq(1) p', obj).html());
								$(this).css({'left':-divWidth});
								curr = curr+dist;
								$('#thumbs'+randID+' div').bind('click', thumbclick).css({'cursor':'pointer'});
								if (o.autoscroll != 'no')
								{
								   //clearInt = setInterval(function(){anim('next');},o.displayTime+o.transitionSpeed);
								   clearInt = setInterval(function(){anim('next');},o.displayTime);
								}
							});
						}
						else
						{
						   clearTimeout(clearInt);
						   
							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:-divWidth*2},o.transitionSpeed,function(){
									$('li:first', obj).remove();
									$('ul', obj).css('left',-divWidth+'px');
						   		$('#btn_rt'+randID).css({'alpha':'1', 'display':''});
								   $('#btn_lt'+randID).css({'alpha':'1', 'display':''});
 
									showtext($('li:eq(1) p', obj).html());
									if(autopilot)
									{
										$('#progress'+randID).width(divWidth).height(5);
										$('#progress'+randID).animate({'width':0},o.displayTime,function(){
	                              //removed play pause button stuff here
										});
									}
									curr=curr+1;
									$('#thumbs'+randID+' div').bind('click', thumbclick).css({'cursor':'pointer'});
									if (o.autoscroll != 'no')
								   {
									   clearInt = setInterval(function(){anim('next');},o.displayTime);
                           }
								});
						}
					}
					if(direction == "prev")
					{

						if(dist>1)
						{
						   clearTimeout(clearInt);
							borderpatrol($('#thumb'+randID+'_'+ (curr-dist) ));
							$('li:gt('+(numDivs-(dist+1))+')', obj).clone().insertBefore($('li:first', obj));
							$('ul', obj).css({'left':(-divWidth*(dist+1))}).animate({left:-divWidth},o.transitionSpeed,function(){
								$('li:gt('+(numDivs-1)+')', obj).remove();
								$('#btn_rt'+randID).css({'alpha':'1', 'display':''});
								$('#btn_lt'+randID).css({'alpha':'1', 'display':''});

								showtext($('li:eq(1) p', obj).html());
								curr = curr - dist;
								$('#thumbs'+randID+' div').bind('click', thumbclick).css({'cursor':'pointer'});
								if (o.autoscroll != 'no')
								{
								   clearInt = setInterval(function(){anim('next');},o.displayTime);
                        }
							});
						}
						else
						{
						   clearTimeout(clearInt);
							borderpatrol($('#thumb'+randID+'_'+ (((curr-1) == 0) ? numDivs: (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',-divWidth*2+'px')
								.animate({left:-divWidth},o.transitionSpeed,function(){
									$('li:last', obj).remove();
								$('#btn_rt'+randID).css({'alpha':'1', 'display':''});
								$('#btn_lt'+randID).css({'alpha':'1', 'display':''});
									
									showtext($('li:eq(1) p', obj).html());
									curr=curr-1;
									if(curr==0) curr=numDivs;
									$('#thumbs'+randID+' div').bind('click', thumbclick).css({'cursor':'pointer'});
									if (o.autoscroll != 'no')
								   {
									   clearInt = setInterval(function(){anim('next');},o.displayTime);
                           }
								});
						}
					}
				}
            var clearInt = (o.autoscroll != 'no') ? setInterval(function(){anim('next');},o.displayTime) : 0;
//				$('#progress'+randID).animate({'width':0},o.displayTime+o.transitionSpeed,function(){
               // removed play pause buttons
//				});
  		});
    	}
	});
})(jQuery);
