/*
 * 	Snapple Module 1.0 - jQuery plugin
 *	written by Mike Fey (Hello Monday)	
 *	http://hellomonday.com
 *
 *	Built for jQuery library
 *	http://jquery.com
 *
 *  Controls functionality
 *  for products page of snapple.com
 */
 (function($) {

  var methods = {
    init: function(options) {

      return this.each(function() {
        // default configuration properties
        var defaults = {
          productsViewed: false
        }

        var opts = $.extend(defaults, options);
        var mainDiv = $(this);
        var productObArray = [];
        var totalThumbWidth = 0;
        var thumbInfoHide = 0;
        var thumbMoveInt = 0;
        var thumbMoveDir = 'right';
        var leftOverThumbAmount = 0;
        var drinksTagArray = [];
        var flavorsTagArray = [];
        var adArray = [];
        var sortTerm = '';
        var curSortArray = [];
        var curInfoOb;
        var firstView = true;
        var productSelected = false;
        var switchTime = 300;
        var switchInt = 0;
        var isMobile = false;
        var isMoving = false;
        var isMovingTimeout = 0;
        var drinkOrder = ['drinks teas', 'drinks diet', 'drinks juice drinks', 'drinks 100% juiced', 'drinks water'];
        var flavorOrder = ['flavors original', 'flavors berry', 'flavors citrus', 'flavors fruit', 'flavors mixed fruit'];
        var dragStartPos = 0;
        var dragEndPos = 0;
        var amountDragged = 0;
        var dragRegisterAmount = 5;
        var curBrowser = navigator.userAgent.toLowerCase();
        var isSearch = false;

        //detect if the user is coming from a mobile browser
        if (curBrowser.indexOf('iphone') != -1 || curBrowser.indexOf('ipod') != -1 || curBrowser.indexOf('ipad') != -1 || curBrowser.indexOf('android') != -1 || curBrowser.indexOf('blackBerry') != -1) {
          isMobile = true;
        }

        mainDiv.find('.productBlock').each(function(ind) {

          var pOb = Object();
          pOb.thumb = $(this).find('.productThumb').html();
          pOb.large = $(this).find('.productLarge').html();
          pOb.title = $(this).find('.productTitle').html();
          pOb.desc = $(this).find('.productContent').html();
          pOb.nutritionFacts = $(this).find('.productNutritionFacts').html();
          pOb.ingredients = $(this).find('.productIngredients').html();
          var sizeArr = $(this).find('.productLarge').attr('class').split(' ');
          pOb.largeWidth = sizeArr[1].substr(4, sizeArr[1].length);
          pOb.largeHeight = sizeArr[2].substr(4, sizeArr[2].length);;
          pOb.largeUrl = $(this).find('.productLarge').html();
          pOb.ind = ind;
          if ($(this).attr('class').indexOf('mainProduct') != -1) {
            pOb.isMain = true;
          } else {
            pOb.isMain = false;
          }

          var tagArray = $(this).attr('class').split('~');

          for (var t = 0; t < tagArray.length; t++) {
            if (tagArray[t] == ' ' || tagArray[t] == '' || tagArray[t] == 'productBlock ') {
              tagArray.splice(t, 1);
            }
          }

          pOb.tagArray = tagArray;
          productObArray.push(pOb);

          for (var c = 0; c < tagArray.length; c++) {
            checkTagMatch(tagArray[c]);
          }

          $(this).remove();

        });

        $('#productLeftBtn').show();

        $('#productRightBtn').show();

        $('.productShelf').show();

        $('#productThumbContainer').show();

        //lay out thumbnails
        var thtml = '';
        for (var i = 0; i < productObArray.length; i++) {
          if (productObArray[i].isMain == true) {
            thtml += '<div class="oProductThumb mainProduct">' + productObArray[i].thumb + '</div>';
          } else {
            thtml += '<div class="oProductThumb">' + productObArray[i].thumb + '</div>';
          }
        }

        $('#productThumbContainerInner').html(thtml);
        $('#productThumbContainerInner').css({
          'left': '0px'
        });

        $('.oProductThumb').each(function(ind) {

          $(this).css({
            'left': (ind * 126) + 'px'
          });
          var tim = $(this).find('img');
          var tw = tim.attr('width');
          var tml = (63 - (tw / 2));
          tim.css({
            'margin-left': tml + 'px'
          });
          tim.attr('alt', productObArray[ind].title);

          totalThumbWidth = totalThumbWidth + (126);

          $(this).data('infoObject', productObArray[ind]);

          if (isMobile == false) {
            $(this).bind('mouseenter', productThumbOver);
            $(this).bind('mouseleave', productThumbOut);
          }

          $(this).bind('click', productThumbClick);
        });

        $('#productThumbContainerInner').css({
          'width': totalThumbWidth + 'px'
        });

        $('#pageContentWrapper').append('<div id="thumbHoverInfo"><div id="thumbHoverText"></div></div>');

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

        if (isMobile == false) {
          $('#productLeftBtn').bind('mouseenter', {
            btnType: 'left'
          },
          productArrowBtnOver);
          $('#productLeftBtn').bind('mouseleave', {
            btnType: 'left'
          },
          productArrowBtnOut);
          $('#productRightBtn').bind('mouseenter', {
            btnType: 'right'
          },
          productArrowBtnOver);
          $('#productRightBtn').bind('mouseleave', {
            btnType: 'right'
          },
          productArrowBtnOut);
        } else {
          $('#productLeftBtn').bind('click', {
            btnType: 'left'
          },
          productArrowBtnClick);
          $('#productRightBtn').bind('click', {
            btnType: 'right'
          },
          productArrowBtnClick);
        }

        var tagHtml = '';
        var allTags = [];
        
				//checks if a tag is already in the tag array and places
				//them in the DOM
        function checkTagMatch(mtch) {
          var matchFound = false;

          var tagCat = mtch.split(' ')[0];

          if (tagCat == 'drinks') {
            for (var i = 0; i < drinksTagArray.length; i++) {
              if (drinksTagArray[i] == mtch) {
                matchFound = true;
              }
            }
          }

          if (tagCat == 'flavors') {
            for (var ii = 0; ii < flavorsTagArray.length; ii++) {
              if (flavorsTagArray[ii] == mtch) {
                matchFound = true;
              }
            }
          }

          if (matchFound == false) {
            if (tagCat == 'drinks' && mtch != '') {
              drinksTagArray.push(mtch);
            }

            if (tagCat == 'flavors' && mtch != '') {
              flavorsTagArray.push(mtch);
            }
          }

          drinksTagArray = orderTags('drinks');
          flavorsTagArray = orderTags('flavors');
        }
        
				//orders the tags based on the order array
        function orderTags(type) {
          var ogArray = [];
          var compArray = [];
          var nArray = [];
          if (type == 'drinks') {
            ogArray = drinksTagArray;
            compArray = drinkOrder;
          }

          if (type == 'flavors') {
            ogArray = flavorsTagArray;
            compArray = flavorOrder;
          }

          for (var i = 0; i < compArray.length; i++) {
            for (var ii = 0; ii < ogArray.length; ii++) {
              if (ogArray[ii] == compArray[i]) {
                nArray.push(ogArray[ii])
              }
            }
          }

          return nArray;
        }

        var dthtml = '';
        for (var d = 0; d < drinksTagArray.length; d++) {
          dthtml += '<div class="productTagBtn ' + drinksTagArray[d] + '">' + capitalizeString(drinksTagArray[d].substr(7, drinksTagArray[d].length)) + '</div>';
        }

        var fthtml = '';
        for (var f = 0; f < flavorsTagArray.length; f++) {
          fthtml += '<div class="productTagBtn ' + flavorsTagArray[f] + '">' + capitalizeString(flavorsTagArray[f].substr(8, flavorsTagArray[f].length)) + '</div>';
        }

        tagHtml += '<div id="productTagMenu">';
        tagHtml += '<div class="tagCategory drinksTctg"><div class="tagTitle drinksTt"></div><div class="tagBtnBack"></div><div class="tagBtnCont">' + dthtml + '</div></div>';
        tagHtml += '<div class="tagCategory allTctg"><div class="tagBtnBack"></div><div class="tagBtnCont"><div class="productTagBtn all">All</div></div></div>';
        tagHtml += '<div id="pSearchContainer"><div id="psSubmitBack"></div><div class="tagTitle searchTt"><form id="prSearch" action="products.html"><div class="productSearch"><div id="psBg"></div><input id="psInput" name="psField" /><div id="psSubmitBack"></div><input id="psSubmit" type="submit" value="Find"></div></form></div>';

        tagHtml += '</div>';

        $('#overlayCloseButton').before(tagHtml);

        $('#psSubmitBack').css({
          opacity: 0.5
        });
        $('.drinksTctg').find('.tagBtnBack').css({
          'width': ($('.drinksTctg').find('.tagBtnCont').width() + 20) + 'px',
          opacity: 0.5
        });
        $('.flavorsTctg').find('.tagBtnBack').css({
          'width': ($('.flavorsTctg').find('.tagBtnCont').width() + 20) + 'px',
          opacity: 0.5
        });
        $('.allTctg').find('.tagBtnBack').css({
          'width': ($('.allTctg').find('.tagBtnCont').width() + 20) + 'px',
          opacity: 0.5
        });

        if (isMobile == false) {
          $('.productTagBtn, #psSubmit').bind('mouseenter', tagBtnOver);
          $('.productTagBtn, #psSubmit').bind('mouseleave', tagBtnOut);
        }

        $('.productTagBtn').bind('click', tagBtnClick);

        $('#prSearch').submit(function() {
          var cs = $('#psInput').val();
          $.address.value(encodeURI('/products/search/' + cs));
          return false;
        });
        
				//capitalizes a string
        function capitalizeString(str) {
          return str.replace(/(^|\s)([a-z])/g,
          function(m, p1, p2) {
            return p1 + p2.toUpperCase();
          });
        }
        
				//the rollover function for the tag buttons
        function tagBtnOver(e) {
          $(this).stop(true, true).animate({
            color: '#f6de4b'
          },
          {
            duration: 300,
            specialEasing: {
              color: 'easeOutSine'
            }
          });
        }
        
				//the rollout function for the tag buttons
        function tagBtnOut(e) {
          if ($(this).attr('class').indexOf('productTagBtnSelected') == -1) {
            $(this).stop(true, true).animate({
              color: '#fff'
            },
            {
              duration: 300,
              specialEasing: {
                color: 'easeOutSine'
              }
            });
          }
        }
        
				//the click function for the tag buttons
        function tagBtnClick(e) {
          if ($(this).attr('class') != 'productTagBtn all' && $(this).attr('class').indexOf('productTagBtnSelected') == -1) {
            var sortStr = $(this).attr('class').substr(14, $(this).attr('class').length);
            $.address.value(encodeURI('/products/sort/' + sortStr));
          } else {
            if ($(this).attr('class').indexOf('productTagBtnSelected') == -1) {
              $.address.value(encodeURI('/products'));
            }
          }
        }
        
				//the rollover function for the product thumbs
        function productThumbOver(e) {
          lpos = $(this).data('infoObject').ind * 126;

          var lp = $('#productThumbContainerInner').css('left');
          var offset = Number(lp.substr(0, lp.length - 2));

          if (isMoving == true) {
            if (thumbMoveDir == 'right') {
              offset = Math.floor(offset / 126) * 126;
            }

            if (thumbMoveDir == 'left') {
              offset = Math.round(offset / 126) * 126;
            }
          }

          $('#thumbHoverInfo').css({
            'margin-left': ((lpos - 11) + offset) + 'px'
          });

          $('#thumbHoverText').css({
            'margin-top': '40px',
            'font-size': '15px'
          });

          $('#thumbHoverText').html($(this).find('img').attr('alt'));

          clearTimeout(thumbInfoHide);
          $('#thumbHoverInfo').show();

          if (curBrowser.indexOf('msie 8.0') == -1 && curBrowser.indexOf('msie 7.0') == -1) {
            $('#thumbHoverInfo').css({
              opacity: 0.0
            });
          }

          $('#thumbHoverInfo').css({
            top: '215px'
          });

          var tHeight = $('#thumbHoverText').height();

          if (tHeight > 35) {
            $('#thumbHoverText').css({
              'font-size': '13px'
            });
          } else {
            $('#thumbHoverText').css({
              'font-size': '15px'
            });
          }

          tHeight = $('#thumbHoverText').height();
          var nmt = (30 - (tHeight / 2)) + 19;

          $('#thumbHoverText').css({
            'margin-top': nmt + 'px'
          });

          if (curBrowser.indexOf('msie 8.0') == -1 && curBrowser.indexOf('msie 7.0') == -1) {
            $('#thumbHoverInfo').stop(true, true).animate({
              opacity: 1.0,
              top: 195
            },
            {
              duration: 300,
              specialEasing: {
                opacity: 'easeOutSine',
                top: 'easeOutExpo'
              }
            });
          }
        }
        
				//the rollout function for the product thumbs 
        function productThumbOut(e) {

          clearTimeout(thumbInfoHide);

          if (curBrowser.indexOf('msie 8.0') == -1 && curBrowser.indexOf('msie 7.0') == -1) {
            $('#thumbHoverInfo').stop(true, true).animate({
              opacity: 0.0,
              top: 215
            },
            {
              duration: 500,
              specialEasing: {
                opacity: 'easeOutSine',
                top: 'easeOutExpo'
              }
            });
          } else {
            $('#thumbHoverInfo').hide();
          }


          thumbInfoHide = setTimeout(hideThumbInfo, 500);
        }
        
				//the click function for the product thumbs 
        function productThumbClick(e) {
          curInfoOb = $(this).data('infoObject');
          var shouldClick = true;
          if (amountDragged > dragRegisterAmount) {
            shouldClick = false;
          }
          if (shouldClick == true) {
            $.address.value('/products/' + encodeURI(curInfoOb.title));
          }
        }
        
				//hides the rollover "flag" for the product thumbs 
        function hideThumbInfo() {
          $('#thumbHoverInfo').hide();
        }
        
				//shows the thumb arrow buttons 
        function displayBtns(len) {
          if (len > 9) {
            $('#productLeftBtn').show();
            $('#productRightBtn').show();
          } else {
            $('#productLeftBtn').hide();
            $('#productRightBtn').hide();
          }
        }
        
				//the rollover function for the thumb arrow buttons
        function productArrowBtnOver(e) {
          clearInterval(switchInt);
          var dir = e.data.btnType;
          moveProductThumbs(dir);
          switchInt = setInterval(function() {
            moveProductThumbs(dir)
          },
          switchTime);
        }
        
				//the rollout function for the thumb arrow buttons
        function productArrowBtnOut(e) {
          clearInterval(switchInt);
        }
        
				//the click function for the thumb arrow buttons
        function productArrowBtnClick(e) {
          var dir = e.data.btnType;
          moveProductThumbs(dir);
        }
        
				//animates the product thumbnails
        function moveProductThumbs(dir) {
          thumbMoveDir = dir;

          clearTimeout(isMovingTimeout);
          isMoving = true;

          if (thumbMoveDir == 'left') {
            if (thumbMoveInt > 0) {
              thumbMoveInt--;
            }
          }

          if (thumbMoveDir == 'right') {
            if (thumbMoveInt < leftOverThumbAmount) {
              thumbMoveInt++;
            }
          }

          $('#productThumbContainerInner').stop(true, true).animate({
            left: -(thumbMoveInt * 126)
          },
          {
            duration: switchTime,
            specialEasing: {
              left: 'linear'
            }
          });

          isMovingTimeout = setTimeout(resetIsMoving, switchTime);

          checkButtons();
        }
         
				//called when the thumbnails stop moving
        function resetIsMoving() {
          isMoving = false;
        }
        
				//checks whether to disable the thumb arrows
        function checkButtons() {
          if (thumbMoveInt == leftOverThumbAmount) {
            $('#productRightBtn').css({
              opacity: 0.3
            });
          } else {
            $('#productRightBtn').css({
              opacity: 1.0
            });
          }

          if (thumbMoveInt == 0) {
            $('#productLeftBtn').css({
              opacity: 0.3
            });
          } else {
            $('#productLeftBtn').css({
              opacity: 1.0
            });
          }
        }

        adArray = $.address.value().split('/');
        if (adArray[0] == '') {
          adArray.splice(0, 1);
        }

        handleAddress();

        if (opts.productsViewed == false) {
          $.address.change(function(e) {
            adArray = e.value.split('/')
            if (adArray[0] == '') {
              adArray.splice(0, 1);
            }

            handleAddress();

          });
        }
        
				//parses the hash mark and calls the correct function
        function handleAddress() {
          if (adArray.length > 1) {
            if (adArray[1] == 'sort' || adArray[1] == 'search') {
              if (adArray[1] == 'search') {
                isSearch = true;
              }
              sortTerm = adArray[2];
              createSortArray(false);
              sortThumbs();
              firstView = false;
            } else {
              $('.oProductThumb').each(function(ind) {
                if (decodeURI(adArray[1]) == $(this).data('infoObject').title) {
                  curInfoOb = $(this).data('infoObject');
                  if (firstView === true) {
                    createSortArray(true);
                    showLargeProduct();
                  } else {

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

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


                    setTimeout(showLargeProduct, 300);
                  }
                }
              });

              firstView = false;

            }
          } else {
            if (adArray.length == 1 && adArray[0] == 'products') {
              createSortArray(true);
              sortThumbs();
            }
          }
        }
        
				//creates an array of product thumbs based on the search or tag click
        function createSortArray(includeAll) {
          curSortArray = [];
          totalThumbWidth = 0;
          amountDragged = 0;
          dragStartPos = 0;
          dragEndPos = 0;

          $('.oProductThumb').each(function(ind) {
            if (includeAll == false) {

              var tArr = $(this).data('infoObject').tagArray;

              if (isSearch == false) {
                if (jQuery.inArray(decodeURI(sortTerm), tArr) != -1) {
                  curSortArray.push($(this));
                } else {
                  if (curBrowser.indexOf('msie 8.0') == -1 && curBrowser.indexOf('msie 7.0') == -1) {
                    $(this).stop(true, true).animate({
                      opacity: 'hide'
                    },
                    {
                      duration: 500,
                      specialEasing: {
                        opacity: 'easeOutSine'
                      }
                    });
                  } else {
                    $(this).hide();
                  }
                }
              } else {
                var ttlArr = $(this).data('infoObject').title.split(' ');

                var ntArray = [];

                for (var s = 0; s < tArr.length; s++) {
                  tsa = tArr[s].split(' ');
                  for (var p = 0; p < tsa.length; p++) {
                    if (tsa[p] != 'drinks' && tsa[p] != 'flavors') {
                      ntArray.push(tsa[p]);
                    }
                  }
                }

                tArr = ntArray;

                for (var i = 0; i < ttlArr.length; i++) {
                  ttlArr[i] = ttlArr[i].toLowerCase();
                  tArr.push(ttlArr[i])
                }

                if (jQuery.inArray(decodeURI(sortTerm), tArr) != -1) {
                  curSortArray.push($(this));
                } else {
                  $(this).stop(true, true).animate({
                    opacity: 'hide'
                  },
                  {
                    duration: 500,
                    specialEasing: {
                      opacity: 'easeOutSine'
                    }
                  });
                }
              }
            } else {
              curSortArray.push($(this));
            }
          });

          for (var i = 0; i < curSortArray.length; i++) {
            curSortArray[i].data('infoObject').ind = i;
            totalThumbWidth = totalThumbWidth + (126);
          }

          if (isMobile == true) {
            setDragging();
          }

          calculateLeftover();
          displayBtns(curSortArray.length);
          checkButtons();

          isSearch = false;

          if (curSortArray.length == 0) {
            //alert('no results');
            }
        }
         
				//calculates how many "sets" of product thumbnails are shown at a time
        function calculateLeftover() {
          var thumbSetAmount = Math.ceil(curSortArray.length / 9);
          var extraAmount = (curSortArray.length % 9);
          var fullSetAmount = (curSortArray.length - extraAmount) / 9;
          leftOverThumbAmount = ((fullSetAmount - 1) * 9) + (extraAmount);

          $('#productLeftBtn').unbind();
          $('#productRightBtn').unbind();
          if (isMobile == false) {
            $('#productLeftBtn').bind('mouseenter', {
              btnType: 'left'
            },
            productArrowBtnOver);
            $('#productLeftBtn').bind('mouseleave', {
              btnType: 'left'
            },
            productArrowBtnOut);
            $('#productRightBtn').bind('mouseenter', {
              btnType: 'right'
            },
            productArrowBtnOver);
            $('#productRightBtn').bind('mouseleave', {
              btnType: 'right'
            },
            productArrowBtnOut);
          } else {
            $('#productLeftBtn').bind('click', {
              btnType: 'left'
            },
            productArrowBtnClick);
            $('#productRightBtn').bind('click', {
              btnType: 'right'
            },
            productArrowBtnClick);
          }
        }
        
				//animates the thumbs in that are contained in the sort
        function sortThumbs() {

          thumbMoveInt = 0;

          for (var i = 0; i < curSortArray.length; i++) {
            curSortArray[i].show();

            if (curBrowser.indexOf('msie 8.0') == -1 && curBrowser.indexOf('msie 7.0') == -1) {
              curSortArray[i].css({
                opacity: 0.0
              });
              curSortArray[i].stop(true, true).animate({
                opacity: 1.0,
                left: (i * 126)
              },
              {
                duration: 500,
                specialEasing: {
                  opacity: 'easeOutSine',
                  left: 'easeOutSine'
                }
              });
            } else {

              curSortArray[i].stop(true, true).animate({
                left: (i * 126)
              },
              {
                duration: 500,
                specialEasing: {
                  left: 'easeOutSine'
                }
              });
            }

          }

          var ptciPos;
          if (curSortArray.length >= 9) {
            ptciPos = 0;
          } else {
            ptciPos = 570 - ((curSortArray.length * 126) / 2);
          }

          $('#productThumbContainerInner').stop(true, true).animate({
            left: ptciPos
          },
          {
            duration: 500,
            specialEasing: {
              left: 'easeOutSine'
            }
          });

          $('.productTagBtn').each(function() {
            if (adArray.length > 1) {
              if ($(this).attr('class').indexOf(decodeURI(sortTerm)) != -1 && adArray[1] == 'sort') {
                $(this).addClass('productTagBtnSelected');
                $(this).css({
                  'color': '#f6de4b'
                });
              } else {
                $(this).removeClass('productTagBtnSelected');
                $(this).stop(true, true).animate({
                  color: '#fff'
                },
                {
                  duration: 300,
                  specialEasing: {
                    color: 'easeOutSine'
                  }
                });
              }
            } else {
              if ($(this).attr('class') == 'productTagBtn all') {
                $(this).addClass('productTagBtnSelected');
                $(this).css({
                  'color': '#f6de4b'
                });
              } else {
                $(this).removeClass('productTagBtnSelected');
                $(this).stop(true, true).animate({
                  color: '#fff'
                },
                {
                  duration: 300,
                  specialEasing: {
                    color: 'easeOutSine'
                  }
                });
              }
            }
          });

          if (productSelected == false)
          {
            $('#mainLoader').remove();
          }

        }
        
				//sets the thumbnail dragging for mobile devices
        function setDragging() {
          $('#productThumbBounds').remove();
          $('#productThumbContainerInner').draggable("destroy");

          if (curSortArray.length > 9) {
            $('#productThumbContainerInner').before('<div id="productThumbBounds"></div');
            $('#productThumbBounds').css({
              'position': 'absolute',
              'left': ( - totalThumbWidth + 1140) + 'px',
              'width': (totalThumbWidth + (totalThumbWidth - 1140)) + 'px',
              'height': '170px'
            });
            $('#productThumbContainerInner').draggable({
              containment: ('#productThumbBounds'),
              start: function(e) {
                dragStartPos = e.pageX;
              },
              stop: function(e) {
                dragEndPos = e.pageX;
                amountDragged = (dragStartPos - dragEndPos);
                if (amountDragged < 0) {
                  amountDragged = amountDragged * -1;
                }

                var ptclp = $('#productThumbContainerInner').css('left');
                var curPos = Number(ptclp.substr(0, ptclp.length - 2));
                thumbMoveInt = Math.round(curPos / 126) * -1;

                checkButtons();

                setTimeout(resetDragPos, 100);
              }
            }).addTouch();
          }
        }
        
				//resets drag calculation variables
        function resetDragPos() {
          amountDragged = 0;
          dragStartPos = 0;
          dragEndPos = 0;
        }
        
				//animate in large product image and info when clicked
        function showLargeProduct() {

          if ($('#mainLoader').length == 0) {
            $('body').append('<div id="mainLoader"></div>');
          }

          positionLoader();

          productSelected = true;

          $('#productLargeContainer').html('');

          var img = new Image();
          var imWidth = curInfoOb.largeWidth;
          var imHeight = curInfoOb.largeHeight;
          var imUrl = curInfoOb.largeUrl;

          $(img).load(function() {
            var lpPosL = (1220 - imWidth) + $('#pageContentWrapper').offset().left;
            var lpPosT = $('footer').position().top - imHeight - 85;

            $('#productLargeContainer').css({
              'left': lpPosL + 'px',
              'top': lpPosT + 'px'
            });
            $('#productLargeContainer').html(this);

            $('#productLargeContainer img').attr('width', imWidth).attr('height', imHeight);

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

              showProductInfo();

              $('#productInfoContainer').css({
                opacity: 0.0
              });
              $('#productInfoContainer').stop(true, true).animate({
                opacity: 1.0
              },
              {
                duration: 500,
                specialEasing: {
                  opacity: 'easeOutSine'
                }
              });
            } else {
              $('#productLargeContainer').show();
              $('#productInfoContainer').show();
              showProductInfo();
            }

            $('#mainLoader').remove();


          }).error(function() {

            }).attr('src', imUrl);

          firstView = false;
        }
        
				//show the product text when a thumbnail is clicked
        function showProductInfo() {

          var pis = '';

          pis += '<div class="productTitle">' + curInfoOb.title + '</div>';
          pis += '	<div class="productContent">' + curInfoOb.desc + '</div>';
          pis += '	<div class="nutritionInfoCont">';
          pis += '		<div class="nutritionBlock">';
          pis += '			<div class="nutritionHeader">Nutrition Facts for 8 fl oz:</div>';
          pis += '		    <div class="productNutritionFacts">' + curInfoOb.nutritionFacts + '</div>';
          pis += '		</div>';
          pis += '		<div class="ingredientsSep"></div>';
          pis += '		<div class="ingredientsBlock">';
          pis += '			<div class="ingredientsHeader">Ingredients:</div>';
          pis += '		<div class="productIngredients">' + curInfoOb.ingredients + '</div>';
          pis += '	</div>';
          pis += '</div>';

          $('#productInfoContainer').html(pis);

          setTimeout(scrollToProduct, 500);

          positionProductInfo();

        }
        
				//positions the product text
        function positionProductInfo() {
          var piB = $('footer').offset().top - 580;
          $('#productInfoContainer').css({
            'top': piB + 'px'
          });
        }
        
				//positions the preloader
        function positionLoader() {
          var tpos = ($(window).height() / 2) - 16;
          if ($(window).height() < 945) {
            tpos = (945 / 2) - 16;
          }

          var lpos = ($(window).width() / 2) - 32;
          if ($(window).width() < 1210) {
            lpos = (1210 / 2) - 32;
          }

          $('#mainLoader').css({
            'top': tpos + 'px',
            'left': lpos + 'px'
          });
        }
        
				//scrolls the page down when a product is clicked,
				//meant for smaller screens
        function scrollToProduct() {
          $(window)._scrollable();
          $(window).stop(true, true).scrollTo('max', 1000, {
            easing: 'easeInOutExpo',
            axis: 'y'
          });
        }

      });
    },
    
		//destroys the products page
    destroy: function() {
      $('#thumbHoverInfo').remove();

      $('#productLeftBtn').unbind();

      $('#productRightBtn').unbind();

      $('.oProductThumb').unbind();
      $('.oProductThumb').data(null);

      $('.productTagBtn').unbind();

      setTimeout(removeHtml, 500);

      function removeHtml() {
        $('#productTagMenu').remove();
        $('#productInfoContainer').html('');
        $('#productThumbContainerInner').css({
          'margin-left': '0px'
        });
        $('.oProductThumb').remove();
        $('#productThumbContainerInner').html('');
        $('#productLargeContainer').html('');
      }
    }
  };

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

})(jQuery);
