/*
 * 	Snapple Twitter Feed 1.0 - jQuery plugin
 *	written by Mike Fey (Hello Monday)	
 *	http://hellomonday.com
 *
 *	Built for jQuery library
 *	http://jquery.com
 *
 */

 (function($) {

  var methods = {

    init: function(options) {

      return this.each(function() {

        // default configuration properties
        var defaults = {
          twitterId: 'snapple', //the Twitter id
          numPosts: 10, //the number of posts to retrieve from the id
          animationTime: 500, //the time it takes for teh animation to complete
          animate: 'false', //whether or not to play the animation automatically
          animateTime: 6000, //the time in between the animations
          viewed: false //whether or not the plugin has been initialized
        };

        var opts = $.extend(defaults, options);
        var containerDiv = $(this);
        var obArray = [];
        var moveInt = 0;
        var totalLength = 0;
        var animateTimeout = 0;
        var animateInterval = 0;
        var tbInt = 0;
        var mbTo = 0;

        if (opts.viewed == false) {

          $.getJSON("http://twitter.com/statuses/user_timeline.json?screen_name=" + opts.twitterId + "&count=" + opts.numPosts + "&callback=?",
          function(data) {
            $.each(data,
            function(i, item) {
              obArray.push(item);
              totalLength = totalLength + 1;
            });

            layoutFeed();

          });

        } else {
          $('#twitterNav a').unbind();
          $('#twitterNav a').bind('click', tnbClick);
          startAnimation();
        }
        
				//lays out graphic elements
        function layoutFeed() {
          var feedStr = '';

          for (var i = 0; i < obArray.length; i++) {
            feedStr += '<div class="twitterFeedPost">';
            if (obArray[i].text.length > 130) {
              obArray[i].text = obArray[i].text.substr(0, 127) + '...';
            } else {
              obArray[i].text = obArray[i].text.replace(/http:\/\/\S+/g, '<a href="$&" target="_blank">$&</a>');
            }
            feedStr += obArray[i].text;
            feedStr += '</div>';
          }

          containerDiv.css({
            opacity: 0.0
          });
          $('#twitterStatusesInner').html(feedStr);
          $('#twitterStatusesInner').css({
            'width': (totalLength * 142) + 'px'
          });
          containerDiv.stop(true, true).animate({
            opacity: 1.0
          },
          {
            duration: 500,
            specialEasing: {
              opacity: 'easeOutSine'
            }
          });

          createNav();
          //checkButtons();
          if (opts.animate == 'true') {
            startAnimation();
          }
        }
        
				//starts the animation automatically playing
        function startAnimation() {
          animateInterval = setInterval(scrollStatuses, opts.animateTime);
          containerDiv.data('animateInterval', animateInterval);

          tbInt = setInterval(moveBird, 5000);
          containerDiv.data('tbInt', tbInt);
        }
        
				//moves the blue bird graphic every couple seconds
        function moveBird() {
          $('#twitterBird').stop(true, true).animate({
            rotate: '10deg'
          },
          300);

          mbTo = setTimeout(moveBird2, 300);
        }
        
				//second part of bird animation
        function moveBird2() {
          $('#twitterBird').stop(true, true).animate({
            rotate: '-7deg'
          },
          300);

          mbTo = setTimeout(moveBird3, 300);
        }
        
				//third part of bird animation
        function moveBird3() {
          $('#twitterBird').stop(true, true).animate({
            rotate: '0deg'
          },
          300);
        }
        
				//moves the statuses
        function scrollStatuses() {

          moveInt++;
          if (moveInt > (Number(opts.numPosts) - 1)) {
            moveInt = 0;
          }

          moveStatuses();

        }
        
				//creates the arrow buttons
        function createNav() {
          var navHtml = '';
          navHtml += '<a href="#"><div class="twitterNavBtn tnbLeft"></div></a>';
          navHtml += '<a href="#"><div class="twitterNavBtn tnbRight"></div></a>';
          $('#twitterNav').html(navHtml);

          $('#twitterNav a').bind('click', tnbClick);
        }
        
				//the click function for the arrow buttons
        function tnbClick(e) {

          var curBut = $(this).find('.twitterNavBtn').attr('class').split(' ')[1];

          clearTimeout(animateTimeout);
          clearInterval(animateInterval);

          if (curBut == 'tnbLeft') {
            moveInt--;
            if (moveInt < 0) {
              moveInt = Number(opts.numPosts) - 1;
            }
          } else if (curBut == 'tnbRight') {
            moveInt++;
            if (moveInt > Number(opts.numPosts) - 1) {
              moveInt = 0;
            }
          }

          moveStatuses();

          return false;
        }
         
				//moves the statuses
        function moveStatuses() {

          $('#twitterStatusesInner').stop(true, true).animate({
            marginLeft: -(moveInt * 142)
          },
          {
            duration: opts.animationTime,
            specialEasing: {
              marginLeft: 'easeInOutExpo'
            }
          });
        }
        
				//checks the arrow buttons to "disable" them if there are no more statuses
        function checkButtons() {
          if (moveInt == 0) {
            $('.tnbLeft').css({
              opacity: 0.5
            });
          } else {
            $('.tnbLeft').css({
              opacity: 1.0
            });
          }

          if (moveInt == Number(opts.numPosts) - 1) {
            $('.tnbRight').css({
              opacity: 0.5
            });
          } else {
            $('.tnbRight').css({
              opacity: 1.0
            });
          }
        }
      });
    },
    
		//stops the animations
    stop: function() {
      return this.each(function() {
        var containerDiv = $(this);
        var ai = containerDiv.data('animateInterval');
        if (ai) {
          clearInterval(ai);
        }

        var at = containerDiv.data('animateTimeout');
        if (at) {
          clearTimeout(at);
        }

        var tb = containerDiv.data('tbInt');
        if (tb) {
          clearInterval(tb);
        }

      });
    }
  }

  //calls the proper method based on the string passed 
  $.fn.twitterFeed = function(method) {
    if (methods[method]) {
      return methods[method].apply(this, Array.prototype.slice.call(arguments, 1));
    } else if (typeof method === 'object' || !method) {
      return methods.init.apply(this, arguments);
    } else {
      $.error('Method ' + method + ' does not exist on twitterFeed');
    }
  };

})(jQuery);

