/*
 * 	Snapple Module 1.0 - jQuery plugin
 *	written by Mike Fey (Hello Monday)	
 *	http://hellomonday.com
 *
 *	Built for jQuery library
 *	http://jquery.com
 *
 *  Controls spinning cap for real facts module
 *  on snapple.com
 */
 (function($) {

  var methods = {
    init: function(options) {

      // default configuration properties
      var defaults = {
        moveTime: 6000, //how long in between cap "spins"
        size: 'small', //whether to animate the collapsed or expanded module cap
        play: true, //whether to play, if false then the cap will not spin
      }

      var mainDiv;
      var factDiv;
      var headerDiv;
      var factLength;
      var moveInt;
      var moveInterval;
      var animateInterval;
      var moveInt;
      var opts = $.extend(defaults, options);
      var moveTime;
      var frameInt = 0;
      var numFrames = 6;
      var spinSetInt = 0;
      var curBrowser = navigator.userAgent.toLowerCase();
      var viewingCurrent = true;
      var curStart = 0;
      var curEnd = 0;
      var switchTimeout = 0;
      var showTimeout = 0;

      return this.each(function() {

        mainDiv = $(this);

        if (opts.size == 'small') {
          factDiv = mainDiv.find('#realfactsTextInner');
          headerDiv = $('#realfactsTextHeader');
          factLength = factDiv.find('.realfactBlock').length;
        } else {
          $('.expandedFactUrl').hide();
          factDiv = mainDiv.find('#realFactsExpandedFactContainerInner');
          headerDiv = $('#realFactsExpandedFactHeader');
          factLength = factDiv.find('.realfactExpandedBlock').length;

          $('#realFactsLeftBtn').css({
            opacity: 0.3
          });

          $('#realFactsLeftBtn').bind('mouseenter', {
            btnType: 'left'
          },
          realFactsAbOver);

          $('#realFactsLeftBtn').bind('mouseleave', {
            btnType: 'left'
          },
          realFactsAbOut);

          $('#realFactsLeftBtn').bind('click', {
            btnType: 'left'
          },
          realFactsAbClick);

          $('#realFactsRightBtn').css({
            opacity: 0.3
          });

          $('#realFactsRightBtn').bind('mouseenter', {
            btnType: 'right'
          },
          realFactsAbOver);

          $('#realFactsRightBtn').bind('mouseleave', {
            btnType: 'right'
          },
          realFactsAbOut);

          $('#realFactsRightBtn').bind('click', {
            btnType: 'right'
          },
          realFactsAbClick);

          $('#realFactsExpandedRetiredPlaque').hide();
          $('#realFactsSwitchBtn').bind('click', switchCurrent);

          $('#realFactsExpandedFactContainer').bind('click', {
            btnType: 'right'
          },
          realFactsAbClick);

        }

        if (opts.size == 'small') {
          moveInt = randomNumber(322, factLength - 1);
        } else {
          moveInt = randomNumber(322, factLength - 1);
          curStart = moveInt;
          curEnd = factLength - 1;
        }

        moveInterval = 0;
        moveTime = opts.moveTime;
        animateInterval = 0;

        setFactPos();

        if (opts.play == true) {
          moveInterval = setInterval(showFact, opts.moveTime);
          mainDiv.data('moveInterval', moveInterval);
        }
      });
      
			//rollover for the arrows for the expanded Real Facts module (not currently used)
      function realFactsAbOver(e) {
        $(this).stop(true, true).animate({
          opacity: 1.0
        },
        {
          duration: 200,
          specialEasing: {
            opacity: 'easeOutSine'
          }
        });
      }
      
			//rollout for the arrows for the expanded Real Facts module (not currently used)
      function realFactsAbOut(e) {
        $(this).stop(true, true).animate({
          opacity: 0.3
        },
        {
          duration: 500,
          specialEasing: {
            opacity: 'easeOutSine'
          }
        });
      }
      
			//click for the cap in the expanded Real Facts module (not currently used)
      function realFactsAbClick(e) {
        if (e.data.btnType == 'left') {
          var minNum = 322;
          if (viewingCurrent == false) {
            minNum = 0;
          }
          if (moveInt > minNum) {
            moveInt--;
            showFact();
          }
        }

        if (e.data.btnType == 'right') {
          if (moveInt < curEnd) {
            moveInt++;
            showFact();
          }
        }
      }
      
			//changes the fact shown in the cap in the expanded Real Facts module (not currently used)
      function switchCurrent(e) {

        $('#retiredCap').hide();
        $('#scholarCap').hide();

        clearTimeout(switchTimeout);

        if (viewingCurrent == true) {
          viewingCurrent = false;
          moveInt = randomNumber(0, 321);
          curStart = moveInt;
          curEnd = 321;

          $('#realFactsSwitchBtn p').html('Real Facts');

          if (curBrowser.indexOf('msie 8.0') == -1 && curBrowser.indexOf('msie 7.0') == -1) {
            $('#realFactsExpandedRetiredPlaque').stop(true, true).show().css({
              opacity: 0.0
            }).animate({
              opacity: 1.0
            },
            {
              duration: 300,
              specialEasing: {
                opacity: 'easeOutSine'
              }
            });

            $('#realFactsExpandedPlaque').stop(true, true).show().animate({
              opacity: 0.0
            },
            {
              duration: 300,
              specialEasing: {
                opacity: 'easeOutSine'
              }
            });
          } else {
            $('#realFactsExpandedRetiredPlaque').show();
            $('#realFactsExpandedPlaque').hide();
          }

        } else {
          viewingCurrent = true;
          moveInt = randomNumber(322, factLength - 1);
          curStart = moveInt;
          curEnd = factLength - 1;

          $('#realFactsSwitchBtn p').html('Retired Real Facts');

          if (curBrowser.indexOf('msie 8.0') == -1 && curBrowser.indexOf('msie 7.0') == -1) {
            $('#realFactsExpandedRetiredPlaque').stop(true, true).show().css({
              opacity: 0.0
            }).animate({
              opacity: 0.0
            },
            {
              duration: 300,
              specialEasing: {
                opacity: 'easeOutSine'
              }
            });

            $('#realFactsExpandedPlaque').stop(true, true).show().animate({
              opacity: 1.0
            },
            {
              duration: 300,
              specialEasing: {
                opacity: 'easeOutSine'
              }
            });
          } else {
            $('#realFactsExpandedRetiredPlaque').hide();
            $('#realFactsExpandedPlaque').show();
          }


        }

        switchTimeout = setTimeout(showFact, 300);

      }
      
			//shows the fact text in the expanded Real Facts module (not currently used)
      function showFact() {

        $('#retiredCap').fadeOut();
        $('#scholarCap').fadeOut();

        clearInterval(animateInterval);
        clearTimeout(showTimeout);

        if (opts.play == true) {
          moveInt = randomNumber(322, factLength);
        }

        if (curBrowser.indexOf('msie 8.0') == -1 && curBrowser.indexOf('msie 7.0') == -1) {
          factDiv.stop(true, true).animate({
            opacity: 0.0
          },
          {
            duration: 300,
            specialEasing: {
              opacity: 'easeOutExpo'
            }
          });

          headerDiv.stop(true, true).animate({
            opacity: 0.0
          },
          {
            duration: 300,
            specialEasing: {
              opacity: 'easeOutExpo'
            }
          });

          $('#rfLearnMoreBtn').stop(true, true).animate({
            opacity: 0.0
          },
          {
            duration: 300,
            specialEasing: {
              opacity: 'easeOutExpo'
            }
          });

        } else {
          factDiv.hide();
          headerDiv.hide();
          $('#rfLearnMoreBtn').hide();
        }

        spinSetInt = 0;

        showTimeout = setTimeout(function() {
          animateInterval = setInterval(animateCap, 20);
        },
        300);

      }
      
			//"spins" cap
      function animateCap() {
        frameInt++;
        if (frameInt > numFrames) {
          frameInt = 0;
          spinSetInt++;
        }

        if (spinSetInt == 4) {
          clearInterval(animateInterval);
          setFactPos();
        }

        var capDiv = $('#realfactsCap');

        if (opts.size == 'large') {
          capDiv = $('#realFactsExpandedCapContainer');
        }

        var lPos = 0;

        switch (frameInt) {
        case 0:
          if (opts.size == 'small') {
            lPos = -2;
          }

          if (opts.size == 'large') {
            lPos = 0;
          }
          break;
        case 1:
          if (opts.size == 'small') {
            lPos = -200;
          }

          if (opts.size == 'large') {
            lPos = -345;
          }
          break;
        case 2:
          if (opts.size == 'small') {
            lPos = -400;
          }

          if (opts.size == 'large') {
            lPos = -690;
          }
          break;
        case 3:
          if (opts.size == 'small') {
            lPos = -600;
          }

          if (opts.size == 'large') {
            lPos = -1035;
          }
          break;
        case 4:
          if (opts.size == 'small') {
            lPos = -800;
          }

          if (opts.size == 'large') {
            lPos = -1380;
          }
          break;
        case 5:
          if (opts.size == 'small') {
            lPos = -1000;
          }

          if (opts.size == 'large') {
            lPos = -1725;
          }
          break;
        default:
          if (opts.size == 'small') {
            lPos = -2;
          }

          if (opts.size == 'large') {
            lPos = 0;
          }
        }

        capDiv.css({
          'background-position': lPos + 'px 0px'
        });

      }
      
			//sets the div containing all the fact text to the right position
      function setFactPos() {
        var np = -moveInt * 120;
        if (opts.size == 'large') {
          var np = -moveInt * 300;
        }

        factDiv.css({
          'margin-top': np + 'px'
        });

        var linkFound = false;

        $('#rfLearnMoreBtn').hide();

        if (opts.size == 'large') {
          $('.realfactExpandedBlock').each(function(ind) {

            if ($(this).position().top == np * -1) {
              if ($(this).attr('class').indexOf('rfeCap') != -1) {
                if (viewingCurrent == true) {
                  $('#scholarCap').fadeIn();
                } else {
                  $('#retiredCap').fadeIn();
                }

                $('#realFactsExpandedFactHeader').fadeOut();
              } else {
                $('#scholarCap').fadeOut();
                $('#retiredCap').fadeOut();
              }
            }

            if ($(this).position().top == np * -1 && $(this).find('.expandedFactUrl').length > 0) {
              linkFound = true;
              $('#rfLearnMoreBtn a').attr('href', 'http://' + $(this).find('.expandedFactUrl').html());
            }
          });

        }

        if (curBrowser.indexOf('msie 8.0') == -1 && curBrowser.indexOf('msie 7.0') == -1) {
          factDiv.stop(true, true).animate({
            opacity: 1.0
          },
          {
            duration: 500,
            specialEasing: {
              opacity: 'easeOutExpo'
            }
          });

          headerDiv.stop(true, true).animate({
            opacity: 1.0
          },
          {
            duration: 500,
            specialEasing: {
              opacity: 'easeOutExpo'
            }
          });

          if (linkFound == true) {
            $('#rfLearnMoreBtn').show();
            $('#rfLearnMoreBtn').stop(true, true).animate({
              opacity: 1.0
            },
            {
              duration: 500,
              specialEasing: {
                opacity: 'easeOutExpo'
              }
            });
          }
        } else {
          factDiv.show();
          headerDiv.show();
          if (linkFound == true) {
            $('#rfLearnMoreBtn').show();
          }
        }

      }

      function randomNumber(rangemin, rangemax) {
        var num = Math.floor(rangemin + (1 + rangemax - rangemin) * Math.random());
        return num;
      }

    },
    
		//stops the cap from spinning
    stop: function() {
      return this.each(function() {
        mainDiv = $(this);
        var mt = mainDiv.data('moveInterval');
        if (mt) {
          clearInterval(mt);
        }
      });
    }
  };

  //calls the proper method based on the string passed
  $.fn.snappleRealFactsCap = 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 snappleRealFactsCap');
    }
  };

})(jQuery);
