/*
 * 	Snapple Memory Game 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) {

      // default configuration properties
      var defaults = {
        reset: false //whether to reset the game
      }
      var opts = $.extend(defaults, options);
      var clockTimer;
      var mainDiv = $(this);
      var seconds = 0;
      var minutes = 0;
      var numAccross = 5;
      var spaceX = 145;
      var spaceY = 160;
      var colInc = 0;
      var rowInc = 0;
      var factDivArray = [];
      var arrCount = 0;
      var factCapArray = [];
      var curClicked;
      var obPosArr = [];
      var animateInterval;
      var animateInterval2;
      var frameInt = 0;
      var frameInt2 = 0;
      var rotateInt = 0;
      var rotateInt2 = 0;
      var numMatched = 0;
      var firstClicked;
      var secondClicked;
      var clickInt = 0;
      var foundSpaceInt;
      var curBrowser = navigator.userAgent.toLowerCase();
      var timeOb = Object();
      var isMobile = false;
      if (curBrowser.indexOf('iphone') != -1 || curBrowser.indexOf('ipod') != -1 || curBrowser.indexOf('ipad') != -1 || curBrowser.indexOf('android') != -1 || curBrowser.indexOf('blackBerry') != -1) {
        isMobile = true;
      }

      return this.each(function() {

        if (opts.reset == false) {
          $('#realFactsGameResetBtn').bind('mouseenter', capOver);
          $('#realFactsGameResetBtn').bind('mouseleave', capOut);
          $('#realFactsGameResetBtn').bind('click', rbClick);

          mainDiv.data('timeOb', timeOb);

          clockTimer = setInterval(showTime, 1000);
          mainDiv.data('timer', clockTimer);

          createCapArray();
        } else {
          var to = mainDiv.data('timeOb');
          seconds = to.seconds;
          minutes = to.minutes;

          clockTimer = mainDiv.data('timer');
          clockTimer = setInterval(showTime, 1000);
          mainDiv.data('timer', clockTimer);
        }

      });
      
			//pics random caps from a list of all caps. The data in the DOM, spit out by
			//Wordpress 
      function createCapArray() {
        factDivArray = [];
        arrCount = 0;

        for (var i = 0; i < 9; i++) {
          var rnum = randomRange(322, $('.realfactExpandedBlock').length);
          if (checkDup($('.realfactExpandedBlock:eq(' + rnum + ')').find('.expandedFactNumber')) == false) {
            var cd = $('.realfactExpandedBlock:eq(' + rnum + ')');
            var cdCopy = $('.realfactExpandedBlock:eq(' + rnum + ')').clone(false, false);
            factDivArray.push(cd);
            factDivArray.push(cdCopy);
          }
        }

        factDivArray.sort(randOrd);

        layoutCaps();

      }
      
			//positions all caps
      function layoutCaps() {
        $('#realFactsGameCaps').html('');
        $('#realFactsGameMatchedCaps').html('');
        $('#realFactsGameMatchedNum').html('0');

        $('#realFactsGameFactTextCont').hide();
        var capHtml = '';
        colInc = 0;
        rowInc = 0;

        for (var i = 0; i < factDivArray.length; i++) {

          var xpos = colInc * spaceX;
          var ypos = rowInc * spaceY;

          if (colInc == numAccross) {
            colInc = 0;
            rowInc++;
          } else {
            colInc++;
          }

          capHtml += '<div class="rfGameCap rfgcIt' + (i + 1) + '" style="left:' + xpos + 'px;top:' + ypos + 'px;">';
          capHtml += '	<div class="rfgSeq"><img src="wp-content/themes/snapple/images/module_real_facts/real-facts-expanded-cap.png" /></div>';
          capHtml += '	<div class="rfgTop"><img src="wp-content/themes/snapple/images/module_real_facts/real-facts-expanded-cap-top.png" /></div>';
          capHtml += '	<div class="rfgcBlock"></div>';
          capHtml += '</div>';
        }

        $('#realFactsGameCaps').html(capHtml);

        factCapArray = [];
        $('.rfGameCap').each(function(ind) {

          if (curBrowser.indexOf('msie 8.0') == -1 && curBrowser.indexOf('msie 7.0') == -1) {
            $(this).css({
              opacity: 0.0
            });
            $(this).stop(true, true).delay((ind / 20) * 1000).animate({
              opacity: 1.0
            },
            {
              duration: 300,
              specialEasing: {
                opacity: 'easeOutExpo'
              }
            });
          }

          if (curBrowser.indexOf('msie 8.0') == -1 && isMobile == false) {
            $(this).bind('mouseenter', capOver);
            $(this).bind('mouseleave', capOut);
          }

          $(this).bind('click', capClick);

          $(this).data('htmlData', factDivArray[ind]);

          var ogPosOb = Object();
          ogPosOb.topPos = $(this).css('top');
          ogPosOb.leftPos = $(this).css('left');

          $(this).data('positionObject', ogPosOb);

          factCapArray.push($(this));

        });

      }
      
			//the rollover function for the caps
      function capOver(e) {
        if (curBrowser.indexOf('msie 8.0') == -1 && curBrowser.indexOf('msie 7.0') == -1) {
          $(this).stop(true, true).animate({
            opacity: 0.8
          },
          {
            duration: 200,
            specialEasing: {
              opacity: 'easeOutExpo'
            }
          });
        }
      }
       
			//the rollout function for the caps
      function capOut(e) {
        if (curBrowser.indexOf('msie 8.0') == -1 && curBrowser.indexOf('msie 7.0') == -1) {
          $(this).stop(true, true).animate({
            opacity: 1.0
          },
          {
            duration: 300,
            specialEasing: {
              opacity: 'easeOutSine'
            }
          });
        }
      }
      
			//the click function for the caps
      function capClick(e) {
        clearInterval(animateInterval);

        clickInt++;

        if (clickInt == 1) {
          firstClicked = $(this);
          $('#realFactsGameFactTextContSmall').css({
            'z-index': 805
          });
        }

        if (clickInt == 2) {
          secondClicked = $(this);
          $('#realFactsGameFactTextContSmall').css({
            'z-index': 790
          });
        }

        frameInt = 0;
        rotateInt = 0;
        curClicked = $(this);

        $(this).find('.rfgTop').hide();
        $(this).find('.rfgSeq').show();

        $(this).css({
          'z-index': '800'
        });
        var curClass = $(this).attr('class');

        $('.rfGameCap').each(function(ind) {
          if ($(this).attr('class') != curClicked.attr('class')) {
            $(this).css({
              'z-index': 400 + Math.round((300 / ($('.rfGameCap').length - 1)) * ind),
              'cursor': 'default'
            });
          }
          $(this).unbind();
        });

        $('#realFactsGameOverlay').css({
          'z-index': '885'
        });

        $('#realFactsPopup').css({
          'z-index': '890'
        });

        if (curBrowser.indexOf('msie 8.0') == -1 && curBrowser.indexOf('msie 7.0') == -1) {
          $(this).stop(true, true).css({
            opacity: 1.0
          });
        }

        $(this).stop(true, true).animate({
          width: 340,
          height: 330,
          top: 65,
          left: 260
        },
        {
          duration: 300,
          specialEasing: {
            width: 'easeOutExpo',
            height: 'easeOutExpo',
            top: 'easeOutExpo',
            left: 'easeOutExpo'
          }
        });

        $(this).find('.rfgSeq').find('img').stop(true, true).animate({
          width: 2070,
          height: 330,
          marginLeft: -1035
        },
        {
          duration: 300,
          specialEasing: {
            width: 'easeOutExpo',
            height: 'easeOutExpo',
            marginLeft: 'easeOutExpo'
          }
        });

        setTimeout(function() {
          animateInterval = setInterval(animateCapUp, 40)
        },
        300);

      }
      
			//plays the stop motion animation when a cap "spins" and scales up after clicked
      function animateCapUp() {
        frameInt++;
        var lPos = 0;

        switch (frameInt) {
        case 0:
          lPos = -1035;
          break;
        case 1:
          lPos = -690;
          break;
        case 2:
          lPos = -370;
          break;
        case 3:
          lPos = 0;
          break;
        default:
          lPos = -1035;
        }

        if (frameInt == 3) {
          rotateInt++;
          frameInt = 0;
          if (rotateInt == 2) {
            clearInterval(animateInterval);
            showFactText();
          }
        }

        curClicked.find('.rfgSeq').find('img').css({
          'margin-left': lPos + 'px'
        });

      }
      
			//shows the fact text after a cap animates up
      function showFactText() {

        $('#moduleOverlay').unbind('click');

        $(document).unbind('click');
        $(document).bind('click', capDown);

        $('#realFactsGameFactTextCont').show();
        $('#realFactsGameFactNum').html(curClicked.data('htmlData').find('.expandedFactNumber').html());
        $('#realFactsGameFactText').html(curClicked.data('htmlData').find('.expandedFactText').html());

        if (clickInt == 1) {
          $('#realFactsGameFactNumSmall').html(curClicked.data('htmlData').find('.expandedFactNumber').html());
          $('#realFactsGameFactTextSmall').html(curClicked.data('htmlData').find('.expandedFactText').html());
        }

        if (clickInt == 2) {
          checkMatch();
        }
      }
      
			//animates the cap down
      function capDown() {
        $('#realFactsGameFactTextCont').hide();
        clearInterval(animateInterval);
        $('.rfGameCap').each(function(ind) {
          $(this).unbind();
        });

        frameInt = 0;
        rotateInt = 0;

        if (clickInt == 2) {
          clickInt = 0;

          frameInt2 = 0;
          rotateInt2 = 0;
          animateInterval2 = setInterval(animateFirstCapBack, 40);

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

          animateInterval = setInterval(animateCapDown, 40);
        } else {
          animateFirstClickedDown();
        }

      }
      
			//animates a small cap that is already turned over back
      function animateFirstCapBack() {
        frameInt2++;
        var lPos = 0;

        switch (frameInt2) {
        case 0:
          lPos = 0;
          break;
        case 1:
          lPos = -135;
          break;
        case 2:
          lPos = -265;
          break;
        case 3:
          lPos = -410;
          break;
        default:
          lPos = 0;
        }

        if (frameInt2 == 3) {
          clearInterval(animateInterval2);
        }

        firstClicked.find('.rfgSeq').find('img').css({
          'margin-left': lPos + 'px'
        });
      }
      
			//completes the small cap animation
      function animateFirstClickedDown() {
        $('#moduleOverlay').unbind('click');
        $('#moduleOverlay').bind('click', resetOverlayClick);

        $(document).unbind('click');

        try {
          curClicked.stop(true, true).animate({
            width: 135,
            height: 135,
            top: curClicked.data('positionObject').topPos,
            left: curClicked.data('positionObject').leftPos
          },
          {
            duration: 200,
            specialEasing: {
              width: 'linear',
              height: 'linear',
              top: 'linear',
              left: 'linear'
            }
          });

          curClicked.find('.rfgSeq').find('img').stop(true, true).animate({
            width: 816,
            height: 130
          },
          {
            duration: 200,
            specialEasing: {
              width: 'linear',
              height: 'linear'
            }
          });

          setTimeout(resetCaps, 200);
          setTimeout(showSmallText, 200);
        } catch(err) {
          console.log(err);
        }

      }
      
			//shows the small cap text
      function showSmallText() {
        $('#realFactsGameFactTextContSmall').show();

        var curLeft = curClicked.data('positionObject').leftPos;
        curLeft = Number(curLeft.substr(0, curLeft.length - 2)) - 50;

        var curTop = curClicked.data('positionObject').topPos;
        curTop = Number(curTop.substr(0, curTop.length - 2)) + 230;

        $('#realFactsGameFactTextContSmall').css({
          'left': curLeft + 'px',
          'top': curTop + 'px'
        });
      }
      
			//animates the large cap down
      function animateCapDown() {
        frameInt++;
        var lPos = 0;

        switch (frameInt) {
        case 0:
          lPos = 0;
          break;
        case 1:
          lPos = -370;
          break;
        case 2:
          lPos = -690;
          break;
        case 3:
          lPos = -1035;
          break;
        default:
          lPos = 0;
        }

        if (frameInt == 3) {
          rotateInt++;
          frameInt = 0;
          if (rotateInt == 2) {
            clearInterval(animateInterval);
            setTimeout(completeAnimateDown, 40);
          }

        }

        curClicked.find('.rfgSeq').find('img').css({
          'margin-left': lPos + 'px'
        });
      }
      
			//resets all caps
      function resetCaps() {
        $('.rfGameCap').each(function(ind) {
          $(this).bind('mouseenter', capOver);
          $(this).bind('mouseleave', capOut);
          $(this).bind('click', capClick);
          if (curBrowser.indexOf('msie 8.0') == -1 && curBrowser.indexOf('msie 7.0') == -1) {
            $(this).css({
              opacity: 1.0
            });
          }
          $(this).css({
            'cursor': 'pointer'
          });
        });

        if (clickInt == 1) {
          firstClicked.unbind();
          firstClicked.css({
            'cursor': 'default'
          });
        }
      }
      
			//called when the large cap is done animating back to the grid
      function completeAnimateDown() {
        $('#moduleOverlay').unbind('click');
        $('#moduleOverlay').bind('click', resetOverlayClick);

        $(document).unbind('click');

        curClicked.find('.rfgTop').find('img').css({
          'width': '327px',
          'height': '330px'
        });
        curClicked.find('.rfgTop').show();

        curClicked.find('.rfgSeq').hide();
        curClicked.find('.rfgSeq').find('img').css({
          'margin-left': '-410px',
          'width': '816px',
          'height': '130px'
        });

        var tp = curClicked.data('positionObject').topPos;
        tp = Number(tp.substr(0, tp.length - 2));

        var lp = curClicked.data('positionObject').leftPos;
        lp = Number(lp.substr(0, lp.length - 2));

        curClicked.stop(true, true).animate({
          width: 135,
          height: 135,
          top: tp,
          left: lp
        },
        {
          duration: 200,
          specialEasing: {
            width: 'linear',
            height: 'linear',
            top: 'linear',
            left: 'linear'
          }
        });

        curClicked.find('.rfgTop').find('img').stop(true, true).animate({
          width: 129,
          height: 130
        },
        {
          duration: 200,
          specialEasing: {
            width: 'linear',
            height: 'linear'
          }
        });

        setTimeout(resetCaps, 200)

      }
      
			//returns a random order
      function randOrd() {
        return (Math.round(Math.random()) - 0.5);
      }
      
			//makes sure there are no duplicates in the random array
			//chosen for the game
      function checkDup(num) {
        var hasDup = false;
        for (var i = 0; i < factDivArray.length; i++) {
          if (factDivArray[i].find('.expandedFactNumber') == num) {
            hasDup = true;
          }
        }
        return hasDup;
      }
       
			//returns a random number within a range
      function randomRange(minNum, maxNum) {
        return (Math.floor(Math.random() * (maxNum - minNum + 1)) + minNum);
      }
      
			//the click funciton for the "reset" button
      function rbClick() {
        $('#moduleOverlay').unbind('click');
        $('#moduleOverlay').bind('click', resetOverlayClick);

        $(document).unbind('click');

        frameInt = 0;
        frameInt2 = 0;
        rotateInt = 0;
        rotateInt2 = 0;
        numMatched = 0;
        clickInt = 0;
        seconds = 0;
        minutes = 0;

        var to = mainDiv.data('timeOb');
        to.seconds = seconds;
        to.minutes = minutes;

        $('.rfGameCap').each(function(ind) {
          $(this).unbind();
        });

        $('#realFactsGameMatchedCaps').html('');
        $('#realFactsGameMatchedNum').html('0');

        var ct = mainDiv.data('timer');
        clearInterval(ct);

        clockTimer = setInterval(showTime, 1000);
        mainDiv.data('timer', clockTimer);

        $('#rft1').html('0');
        $('#rft2').html('0');
        $('#rft3').html('0');
        $('#rft4').html('0');

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

        createCapArray();
      }
      
			//checks to see if a cap matches the one that is already turned over
      function checkMatch() {
        if (firstClicked.data('htmlData').find('.expandedFactText').html() == secondClicked.data('htmlData').find('.expandedFactText').html() && firstClicked.attr('class') != secondClicked.attr('class')) {
          numMatched++;

          $('#moduleOverlay').unbind('click');
          $('#moduleOverlay').bind('click', resetOverlayClick);

          $(document).unbind('click');

          $('#realFactsGameFactTextContSmall').hide();
          $('#realFactsGameMatchedNum').html((numMatched * 2));
          addCapsToFound();

          if (numMatched == 9) {
            var mt = mainDiv.data('timer');
            if (mt) {
              clearInterval(mt);
            }
            var wonTime = $('#rft1').html() + $('#rft2').html() + ':' + $('#rft3').html() + $('#rft4').html();

            $('#realFactsGameOverlay').show();
            $('#realFactsGameOverlay').css({
              opacity: 0.8
            });

            $('#realFactsSignupText').hide();
            $('#realFactsPhone').hide();
            $('#realFactsTextHeader').hide();

            $('#realFactsStartHeader').hide();
            $('#realFactsStartText').hide();
            $('#realFactsGameStartBtn').hide();
            $('#realFactsGameContinueBtn').hide();

            $('#realFactsPopup').show();
            if (curBrowser.indexOf('msie 8.0') == -1 && curBrowser.indexOf('msie 7.0') == -1) {
              $('#realFactsPopup').css({
                opacity: 0.0
              });
              $('#realFactsPopup').stop(true, true).animate({
                opacity: 1.0
              },
              {
                duration: 2000,
                specialEasing: {
                  opacity: 'easeOutExpo'
                }
              });
            } else {
              $('#realFactsPopup').show().css({
                'visibility': 'visible'
              });
            }


            $('#realFactsGameOverlay').unbind();
            $('#realFactsGameOverlay').bind('click', wonRestart);

            $('#realFactsWonHeader').show();
            $('#realFactsWonText').show();
            $('#realFactsWonTime').show();
            $('#realFactsWonTime').html(wonTime);
            $('#realFactsGameReplayBtn').show();
            $('#realFactsGameReplayBtn').bind('click', wonRestart);

          }
        }
      }
      
			//restarts the game if the user has won
      function wonRestart() {
        $('#moduleOverlay').unbind('click');
        $('#moduleOverlay').bind('click', resetOverlayClick);

        $(document).unbind('click');
        $('#realFactsGameOverlay').unbind();

        $('#realFactsGameOverlay').hide();
        if (curBrowser.indexOf('msie 8.0') == -1 && curBrowser.indexOf('msie 7.0') == -1) {
          $('#realFactsPopup').stop(true, true).animate({
            opacity: 0.0
          },
          {
            duration: 1000,
            specialEasing: {
              opacity: 'easeOutExpo'
            }
          });
          setTimeout(function() {
            $('#realFactsPopup').hide();
          },
          1000)
        } else {
          $('#realFactsPopup').hide();
        }

        $('#moduleContent').snappleMemoryGame();

      }
      
			//when a match is found, adds the caps to the completed section
      function addCapsToFound() {
        $('.rfGameCap').each(function() {
          $(this).unbind();
        });

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

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

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

        } else {
          firstClicked.hide();
          secondClicked.hide();
          $('#realFactsGameFactTextCont').hide();
        }

        clickInt = 0;

        var leftInt = numMatched * 2;
        var leftStart = 0;
        if (numMatched > 5) {
          leftInt = (numMatched * 2) - 10;
          leftStart = 10;
        }

        var fcHtml = '';
        for (var i = 0; i < 2; i++) {

          var leftPos = (((leftInt + i) * 25) + leftStart) - 50;

          fcHtml += '<div class="realFactsGameMatchedCap" style="left:' + leftPos + 'px;">';
          fcHtml += '		<img src="wp-content/themes/snapple/images/module_real_facts/real-facts-expanded-cap-top.png" />';
          fcHtml += '		<div class="realFactsGameMatchedCapBlock"></div>';
          fcHtml += '</div>';
        }

        $('#realFactsGameMatchedCaps').append(fcHtml);

        setTimeout(resetCaps2, 300);

      }
      
			//resets the event handlers for all caps
      function resetCaps2() {
        clickInt = 0;

        $('.rfGameCap').each(function(ind) {
          $(this).bind('mouseenter', capOver);
          $(this).bind('mouseleave', capOut);
          $(this).bind('click', capClick);
          if (curBrowser.indexOf('msie 8.0') == -1 && curBrowser.indexOf('msie 7.0') == -1) {
            $(this).css({
              opacity: 1.0
            });
          }
          $(this).css({
            'cursor': 'pointer'
          });
        });

        firstClicked.remove();
        secondClicked.remove();
      }
      
			//manages the game timer 
      function showTime() {
        seconds = seconds + 1;
        if (seconds == 60) {
          seconds = 0;
          minutes = minutes + 1;
        }

        if (minutes == 100) {
          minutes = 0;
        }

        var minNum1;
        if (minutes < 10) {
          minNum1 = 0;
        } else {
          minNum1 = minutes.toString().substr(0, 1);
        }

        var minNum2;
        if (minutes < 10) {
          minNum2 = minutes;
        } else {
          minNum2 = minutes.toString().substr(1, 1);
        }

        var secNum1;
        if (seconds < 10) {
          secNum1 = 0;
        } else {
          secNum1 = seconds.toString().substr(0, 1);
        }

        var secNum2;
        if (seconds < 10) {
          secNum2 = seconds;
        } else {
          secNum2 = seconds.toString().substr(1, 1);
        }

        var to = mainDiv.data('timeOb');
        if (to) {
          to.seconds = seconds;
          to.minutes = minutes;
        }

        $('#rft1').html(minNum1);
        $('#rft2').html(minNum2);
        $('#rft3').html(secNum1);
        $('#rft4').html(secNum2);

      }
      
			//closes the game when the overlay is clicked
      function resetOverlayClick() {
        $.address.value('/');
        return false;
      }

    },
    
		//destroys the game
    destroy: function() {
      var mainDiv = $(this);
      return this.each(function() {
        var mt = mainDiv.data('timer');
        if (mt) {
          clearInterval(mt);
        }
      });
    }

  };
  
	//calls the proper method based on the string passed
  $.fn.snappleMemoryGame = function(method) {
    // Method calling logic
    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 + ' snappleMemoryGame');
    }
  };

})(jQuery);
