/*
 * 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: 1500,
			  displayTime: 6000,
			  displayThumbnails: 1,
			  imgHeight: 193,
			  imgWidth: 255
			};
      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 autopilot = 0;

        //$(obj).width(o.imgWidth).height(o.imgHeight);

        $('li:last', obj).prependTo($('ul', obj));
        $('ul', obj).css('left', -o.imgWidth + 'px');
        $('ul', obj).width(9999);

        // Build thumbnail viewer and thumbnail divs
        $('<div class="SlideControls" id="thumbs' + randID + '"></div>').insertAfter('.SlideshowCaption');
        for (i = 0; i <= numSlides - 1; i++) {
          var thumbTitle = $('li:eq(' + (i + 1) + ')', obj).attr('title');
          if (i == (numSlides - 1)) thumbTitle = $('li:eq(0)', obj).attr('title');
          var strThumbNumber = 01;
          if (i + 1 < 10) {
            strThumbNumber = '0' + (i + 1);
          } else {
            strThumbNumber = i + 1;
          }
          $('#thumbs' + randID).append('<div class="SlideNavigation InActive" title="' + thumbTitle + '" id="thumb' + randID + '_' + (i + 1) + '">' + strThumbNumber + '</div>');
          if (i == 0) $('#thumb' + randID + '_1').removeClass('InActive');
        }
        $('#thumbs' + randID + ' div.SlideNavigation:not(:first)');
        $("p.SlideshowCaption").html($('#thumbs' + randID + ' div').attr('title'));
        // 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

        // Left and right arrow image button actions
        if ($(".btn_rt").length != 0) {
          $('.btn_rt').addClass('btn_rt' + randID);
          $('.btn_rt' + randID).click(function () {
            autopilot = 0;
            anim('next');
            clearTimeout(clearInt);
            return false;
          });
        }
        if ($(".btn_lt").length != 0) {
          $('.btn_lt').addClass('btn_lt' + randID);
          $('.btn_lt' + randID).click(function () {
            autopilot = 0;
            anim('prev');
            clearTimeout(clearInt);
            return false;
          });
        }

		if ($(".pause_btn").length != 0) {
			$('.pause_btn').addClass('pause_btn' + randID);
			  $('.pause_btn' + randID).click(function () {
				autopilot = 0;
				clearTimeout(clearInt);
				$('.pause_btn'+randID).fadeOut(250);
				$('.play_btn'+randID).fadeIn(250);
			  });
		}
		
		if ($(".play_btn").length != 0) {
			$('.play_btn').addClass('play_btn' + randID);
			  $('.play_btn' + randID).click(function () {
				autopilot = 1;
				anim('next');
				$('.play_btn'+randID).fadeOut(250);
				$('.pause_btn'+randID).fadeIn(250);
				clearInt=setInterval(function(){anim('next');},o.displayTime+o.transitionSpeed);
				setTimeout(function(){$('#pause_btn'+randID).show();$('#progress'+randID).fadeIn().width(o.imgWidth).height(5);},o.transitionSpeed);
			  });
		}

        if ($(".btn_next").length != 0) {
          $(".btn_next").each(function (index) {
            $(this).addClass('btn_next' + randID + index);
            $(this).click(function () {
              autopilot = 0;
              anim('next');
              clearTimeout(clearInt);
              return false;
            });
          });
        }

        function thumbclick(event) {
          target_num = this.id.split('_'); // we want target_num[1]
          if (curr != target_num[1]) {
            $('#thumb' + randID + '_' + curr).addClass('InActive');
            clearTimeout(clearInt);
            $('#thumbs' + randID + ' div').css({ 'cursor': 'default' }).unbind('click'); // Unbind the thumbnail click event until the transition has ended
            autopilot = 0;
          }
          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 borderpatrol(elem) {
          $('#thumbs' + randID + ' div').addClass('InActive');
          $("p.SlideshowCaption").html(elem.attr('title'));
          elem.removeClass('InActive');
        }

        function anim(direction, dist) {

          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': -o.imgWidth * (dist + 1) + "px" }, 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();
                }
                $(this).css({ 'left': -o.imgWidth });
                curr = curr + dist;
                $('#thumbs' + randID + ' div').bind('click', thumbclick).css({ 'cursor': 'pointer' });
              });
            }
            else {
              borderpatrol($('#thumb' + randID + '_' + (curr + 1)));
              $('#thumbs' + randID + ' div').unbind('click');
              $('li:first', obj).clone().insertAfter($('li:last', obj));
              $('ul', obj).animate({ 'left': -o.imgWidth * 2 + 'px' }, o.transitionSpeed, function () {
                $('li:first', obj).remove();
                $('ul', obj).css('left', -o.imgWidth + 'px');
                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': (-o.imgWidth * (dist + 1)) }).animate({ left: -o.imgWidth }, o.transitionSpeed, function () {
                $('li:gt(' + (numSlides - 1) + ')', obj).remove();
                curr = curr - dist;
                $('#thumbs' + randID + ' div').bind('click', thumbclick).css({ 'cursor': 'pointer' });
              });
            }
            else {
              borderpatrol($('#thumb' + randID + '_' + (curr - 1)));
              $('#thumbs' + randID + ' div').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', -o.imgWidth * 2 + 'px').animate({ 'left': -o.imgWidth + 'px' }, o.transitionSpeed, function () {
                $('li:last', obj).remove();
                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);
        //var clearInt;

      });
    }
  });
})(jQuery);
