/*
 * 	Snapple Image Slider 1.0 - jQuery plugin
 *	written by Mike Fey (Hello Monday)	
 *	http://hellomonday.com
 *
 *	Built for jQuery library
 *	http://jquery.com
 */
 (function($) {

  //object containing all methods
  var methods = {
    init: function(options) {

      // default configuration properties
      var defaults = {
        buttonContainer: 'buttonContainer', //the div className that will hold the image indicators
        imageWidth: 10, //the width in pixels of the images
        imageHeight: 10, //the height in pixels of the images
        topOffset: 0, //an offset from the top in pixels
        animationTime: 1000, //time it takes to transition from one image to the other
        animationDelay: 3000, //time in between the image animations
        startDelay: 0, //time in before the images start animating
        viewed: true, //whether the plugin has already been initialized
        type: 'slideLeft', //how the images should transition - "slideLeft", "slideDown", "fade", or "tv"
        vertNav: 'false' //whether the nav should be stacked vertically or horizontally
      }

      var totalWidth = 0;
      var moveInterval = 0;
      var moveInt = 0;
      var mainDiv;
      var regDiv;
      var cloneDiv;
      var totalLength = 0;
      var resetTimeout = 0;
      var startDelay = 0;
      var totalWidth = 0;
      var totalHeight = 0;
      var options = $.extend(defaults, options);
      var buttonContDiv = $('#' + options.buttonContainer);
      var mainDiv = $(this).find(".sliderImageContainer");
      var delayStartTimeout = 0;

      return this.each(function() {
	
				//setup graphic elements
        if (options.type == 'slideLeft' || options.type == 'fade') {
          mainDiv.css({
            'width': options.imageWidth + 'px',
            'height': options.imageHeight + 'px'
          });
        }

        totalLength = mainDiv.find('.sliderImage').length;
        totalWidth = options.imageWidth * totalLength;
        totalHeight = (options.imageHeight) * totalLength;

        mainDiv.data('type', options.type);

        if (options.type == 'slideLeft') {
          mainDiv.find('.sliderImageContainerInner').css({
            'width': ((totalWidth * 2) + 80) + 'px'
          });

          regDiv = mainDiv.find('.sliderImages');
          cloneDiv = regDiv.clone();
          regDiv.prepend(cloneDiv);
          mainDiv.data('cloneDiv', cloneDiv);
        }

        if (options.type == 'slideDown') {

          if (options.viewed == false) {
            mainDiv.find('.sliderImage').each(function(ind) {
              $(this).prependTo($(this).parent());
            });
          }

          if (options.viewed == false) {
            mainDiv.find('.sliderImageContainerInner').css({
              'height': (totalHeight * 2) + 'px',
              'width': options.imageWidth + 'px'
            });
          }

          regDiv = mainDiv.find('.sliderImages');

          if (options.viewed == true) {
            regDiv.css({
              'margin-top': '12px'
            });
          }

          cloneDiv = regDiv.clone();
          regDiv.before(cloneDiv);
          mainDiv.data('cloneDiv', cloneDiv);
          cloneDiv.css({
            'margin-bottom': '-12px',
            'margin-top': '12px'
          });

          mainDiv.find('.sliderImageContainerInner').css({
            'margin-top': ( - totalHeight * 2) + (options.imageHeight) - 24 + options.topOffset + 'px'
          });

        }

        if (options.type == 'fade' || options.type == 'tv' || options.type == 'flashFade') {

          mainDiv.find('.sliderImages').css({
            'height': options.imageHeight + 'px',
            'width': options.imageWidth + 'px'
          });

          mainDiv.find('.sliderImage').each(function(it) {
            $(this).css({
              'position': 'absolute',
              'left': '0px'
            });
            if (it > 0) {
              $(this).css({
                opacity: 0.0
              });
            } else {
              $(this).css({
                opacity: 1.0
              });
            }
          });
        }

        if (options.type == 'tv') {
          if ($(this).find('.tvStaticSmall').length == 0) {
            mainDiv.append('<div class="tvStaticSmall"></div>');
            mainDiv.find('.tvStaticSmall').css({
              'width': mainDiv.width() + 'px',
              'height': mainDiv.height() + 'px',
              'position': 'absolute',
              opacity: 0.0
            });
          }
        }

        if (totalLength > 1) {
          delayStartTimeout = setTimeout(function() {
            var slideInterval = 0;
            slideInterval = setInterval(moveImages, options.animationDelay);
            mainDiv.data('slideInterval', slideInterval);
          },
          options.startDelay);

          mainDiv.data('delayStartTimeout', delayStartTimeout);
          createNav();
        }

      });
      
			//creates the dots that indicate which image is being shown
      function createNav() {
        var navHtml = ''
        for (var i = 0; i < totalLength; i++) {
          if (i == 0) {
            navHtml += '<div class="sliderBtn sliderBtnSelected"></div>';
          } else {
            navHtml += '<div class="sliderBtn"></div>';
          }
        }
        buttonContDiv.html(navHtml);
      }
      
			//transitions between images
      function moveImages() {

        moveInt++;

        if (options.type == 'fade' || options.type == 'flashFade') {

          if (moveInt > totalLength - 1) {
            moveInt = 0;
          }

          mainDiv.find('.sliderImage').each(function(it) {
            if (it == moveInt) {
              if (options.type == 'fade') {
                $(this).css({
                  'z-index': 900
                });
              }

              if (options.type == 'flashFade') {
                $(this).css({
                  opacity: 0.0
                });
              }

              $(this).stop(true, true).animate({
                opacity: 1.0
              },
              {
                duration: options.animationTime,
                specialEasing: {
                  opacity: 'easeOutSine'
                }
              });
            } else {
              if (options.type == 'fade') {

                var rzi = Math.round(800 / (mainDiv.find('.sliderImage').length - 1));

                $(this).css({
                  'z-index': (it * rzi)
                });
                $(this).stop(true, true).delay(options.animationTime).animate({
                  opacity: 0.0
                },
                {
                  duration: 100
                });

              } else {
                $(this).css({
                  opacity: 0.0
                });
              }
            }
          });

        }

        if (options.type == 'tv') {

          if (moveInt > totalLength - 1) {
            moveInt = 0;
          }


          mainDiv.find('.sliderImage').each(function(it) {

            mainDiv.find('.tvStaticSmall').css({
              'opacity': 1.0
            });

            if (it == moveInt) {
              $(this).css({
                'z-index': 600,
                opacity: 1.0
              });
            } else {
              var rzi = Math.round(500 / (mainDiv.find('.sliderImage').length - 1));

              $(this).css({
                'z-index': (it * rzi),
                opacity: 0.0
              });
            }
          });


          mainDiv.find('.tvStaticSmall').stop(true, true).delay(200).animate({
            opacity: 0.0
          },
          {
            duration: options.animationTime,
            specialEasing: {
              opacity: 'easeOutSine'
            }
          });

        }

        if (options.type == 'slideLeft' || options.type == 'slideDown') {
          if (moveInt > totalLength - 1) {
            setTimeout(resetPosition, options.animationTime);
          }
        }

        if (options.type == 'slideLeft') {
          mainDiv.find('.sliderImageContainerInner').stop(true, true).animate({
            marginLeft: -(moveInt * options.imageWidth)
          },
          {
            duration: options.animationTime,
            specialEasing: {
              marginLeft: 'easeInOutExpo'
            }
          });
        }

        if (options.type == 'slideDown') {

          var minusOffset = 0;

          mainDiv.find('.sliderImageContainerInner').stop(true, true).animate({
            marginTop: ( - totalHeight * 2) + ((moveInt + 1) * options.imageHeight) - 24 + options.topOffset + minusOffset
          },
          {
            duration: options.animationTime,
            specialEasing: {
              marginTop: 'easeInOutExpo'
            }
          });
        }

        buttonContDiv.find('.sliderBtn').each(function(index) {
          if (index == moveInt) {
            $(this).addClass('sliderBtnSelected');
          } else {
            $(this).removeClass('sliderBtnSelected');
          }
        });

        if (options.type == 'slideLeft' || options.type == 'slideDown') {
          if (moveInt > totalLength - 1) {
            buttonContDiv.find('.sliderBtn:first').addClass('sliderBtnSelected');
          }
        }

      }
      
			//resest the images when the last one has been animated to,
			//to give the illusion that the scroll is endless
      function resetPosition() {
        moveInt = 0;

        if (options.type == 'slideLeft') {
          mainDiv.find('.sliderImageContainerInner').stop(true, true).css({
            'margin-left': '0px'
          });
        }

        if (options.type == 'slideDown') {
          mainDiv.find('.sliderImageContainerInner').stop(true, true).css({
            'margin-top': ( - totalHeight * 2) + (options.imageHeight) - 24 + options.topOffset + 'px'
          });
        }
      }
    },
    
		//stops the animation
    stop: function() {
      var mainDiv = $(this).find(".sliderImageContainer");

      return this.each(function() {
        var mt = mainDiv.data('slideInterval');
        if (mt) {
          clearInterval(mt);
        }

        var cd = mainDiv.data('cloneDiv');
        if (cd) {
          cd.remove();
        }

        var type = mainDiv.data('type');
        if (type == 'slideLeft') {
          mainDiv.find('.sliderImageContainerInner').stop(true, true).css({
            'margin-left': '0px'
          });
        }

        var dst = mainDiv.data('delayStartTimeout');
        if (dst) {
          clearTimeout(dst);
        }

        if (type == 'fade' || type == 'tv') {
          mainDiv.find('.sliderImage').each(function(it) {

            mainDiv.find('.tvStaticSmall').css({
              'opacity': 0.0
            });

            if (it == 0) {
              $(this).css({
                'z-index': 600,
                opacity: 1.0
              });
            } else {
              var rzi = Math.round(500 / (mainDiv.find('.sliderImage').length - 1));

              $(this).css({
                'z-index': (it * rzi),
                opacity: 0.0
              });
            }
          });
        }

        if (type == 'slideDown') {
          var totalLength = mainDiv.find('.sliderImage').length;
          var imHeight = mainDiv.find('.sliderImage:first img').height();
          var totalHeight = imHeight * totalLength;
          //mainDiv.find('.sliderImageContainerInner').css({'margin-top' : (-totalHeight * 2) + (imHeight) + 10 + 'px'});
          var regDiv = mainDiv.find('.sliderImages');
          regDiv.css({
            'margin-top': '0px'
          });

          var resetPos = ( - totalHeight) + (imHeight) - 1;

          //mainDiv.find('.sliderImageContainerInner').css({'margin-top' : (-totalHeight * 2) + (options.imageHeight) - 5 + 'px'});
          mainDiv.find('.sliderImageContainerInner').css({
            'margin-top': resetPos + 'px'
          });
        }

      });
    }
  };

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

})(jQuery);
