(function(exports, $) {
  var Footer = exports.Footer = {
    currentPage: '',
    initialize: function() {
      var self = this;

      $('li[data-page] a').click(function() {
        var pageId = $(this).parent().data('page');
        if ($('footer div.container').is(':hidden')) {
          self.openContent(pageId);
        } else {
          if ($('section#' + pageId).is(':hidden')) {
            self.switchContent(pageId);
          } else {
            self.closeContent();
          }
        }
        return false;
      });

      $('footer nav').click($.proxy(self.closeContent, self));

      // Use .hover class because of Chrome's weird behavior.
      // When a hovered element moves out of the pointer,
      // Chrome keep :hover for the element until the pointer moves.
      $('footer nav').hover(function() {
        $(this).addClass('hover');
      }, function() {
        $(this).removeClass('hover');
      });

      $('#logo-menu').click(function() {
        if ($('footer div.container').is(':hidden')) {
          $.scrollTo(0, 1000);
        }
      });

      $('section#join h3').click(function() {
        if ($('footer div.container').is(':hidden')) {
          self.openContent('more');
        } else {
          self.switchContent('more');
        }
        return false;
      });

      $(window).on('hashchange', $.proxy(self.navigateToLocation, self));
      // Wait a second to wait images loaded and styles applied to show the animation.
      setTimeout($.proxy(self.navigateToLocation, self), 1000);
    },
    openContent: function(pageId) {
      var self = this;

      _gaq.push(['_trackEvent', 'Nav', 'Open']);

      $('section#' + pageId).show();
      $('footer nav ul li[data-page="' + pageId + '"]').addClass('current');
      $('footer nav').addClass('open');
      $('footer div.container').slideDown(function() {
        self.saveLocation(pageId);
      });

      // Lock the background content
      var $html = $('html'),
          $window = $(window),
          scrollPosition = [$window.scrollLeft(), $window.scrollTop()];
      $html
        .data('previous-overflow', $html.css('overflow'))
        .data('scroll-position', scrollPosition)
        .css({ overflow: 'hidden' });
      $window.scrollLeft(scrollPosition[0]).scrollTop(scrollPosition[1]);
      $('.main').click($.proxy(self.closeContent, self));
    },
    switchContent: function(pageId) {
      var self = this;

      _gaq.push(['_trackEvent', 'Nav', pageId]);

      $('footer nav ul li.current').removeClass('current');
      $('footer nav ul li[data-page=' + pageId + ']').addClass('current');

      $('footer section:visible').fadeOut(function() {
        $('footer section').not('#' + pageId).stop();
        $('section#' + pageId).fadeIn(function() {
          self.saveLocation(pageId);
        });
      });
    },
    closeContent: function() {
      var self = this;

      _gaq.push(['_trackEvent', 'Nav', 'Close']);

      if ($('footer nav').hasClass('open') == false) return;

      $('footer nav').removeClass('open').removeClass('hover');

      $('footer nav ul li.current').removeClass('current');

      $('footer div.container').slideUp(function() {
        $('footer section').hide();

        self.saveLocation('');

        // Unlock the background content
        var $html = $('html'),
            scrollPosition = $html.data('scroll-position');
        $html.css({ overflow: $html.data('previous-overflow') });
        $(window).scrollLeft(scrollPosition[0]).scrollTop(scrollPosition[1]);
        $('.main').unbind('click');
      });
    },
    saveLocation: function(pageId) {
      this.currentPage = pageId;
      window.location.hash = '!/' + pageId;
    },
    navigateToLocation: function() {
      var pageId = window.location.hash.replace(/^#\!\//, '');

      // Navigate only if hash is changed manually.
      if (this.currentPage === pageId) return;

      if ($('footer div.container').is(':hidden')) {
        if (pageId) {
          this.openContent(pageId);
        }
      } else {
        if (pageId) {
          this.switchContent(pageId);
        } else {
          this.closeContent();
        }
      }
    }
  };
  
  var SignUpForm = exports.SignUpForm = {
    submitted: false,
    initialize: function(form) {
      var self = this;
      
      form.submit(function() {
        // Check required fields
        var errors = [];
        $.each(['name', 'email', 'where'], function(i, id) {
          if ($.trim($('input#' + id).val()) === "") {
            errors.push(id);
          }
        });
        $(this).find('input').removeClass('error');
        if (errors.length > 0) {
          $.each(errors, function(i, id) {
            $('input#' + id).addClass('error');
          });
          return false;
        }
        _gaq.push(['_trackEvent', 'Nav', 'form submission']);
        self.submitted = true;
      });

      // Put a hidden iframe for Google Form redirection hack.
      // The form submits with the hidden iframe and the main frame doesn't show Google Form page.
      // Also, the iframe's load event is hooked to show thank you message.
      var iframeName = 'hidden-iframe';
      this.createHiddenIframe(iframeName);
      form.attr({ target: iframeName });
    },
    createHiddenIframe: function(iframeName) {
      var self = this;
      
      $('<iframe />')
        .attr({ name: iframeName, id: iframeName })
        .hide()
        .prependTo('body')
        .load(function() {
          if (self.submitted) {
            $('section#more form p.submit').addClass('thanks').html('Thanks!');
          }
        })
        // On IE, dynamically created iframe needs to be set name explicitly on its contentWindow
        // in order to work as a form target.
        .get(0).contentWindow.name = iframeName;
    }
  };
  
  // Apply background images, set captions and add parallax effect.
  $.fn.injectContent = function(setting, contentTag) {
    if (setting.inertia === undefined) setting.inertia = 0.2;
    if (contentTag === undefined) contentTag = 'p';
    
    if ($.isMobile()) {
      var imageName = setting.bg.replace("\.", '_980.');
      var margin = 80;
    } else {
      var imageName = setting.bg.replace("\.", '_1900.');
      var margin = 150;
    }
    
    this.css({ backgroundImage: 'url("./images/' + imageName + '")' });
    var content = this.find('article ' + contentTag).html(setting.content);
    
    var paddingTop = setting.contentY;
    if (isNaN(paddingTop)) {
      if (setting.contentY === 'top') {
        paddingTop = margin;
      } else if (setting.contentY === 'middle') {
        paddingTop = (this.height() - content.height()) / 2;
      } else {
        paddingTop = this.height() - content.height() - margin;
      }
    }
    this.find('article').css({ paddingTop: paddingTop, textAlign: setting.contentX });
    this.parallax('50%', this.height() + this.offset().top - setting.initialPos / setting.inertia, setting.inertia, true);
  }
})(window, jQuery);

jQuery(function($) {
  // Footer
  if ($.isMobile()) {
    var pageId = window.location.hash.replace(/^#\!\//, '');
    if (pageId.length > 0) {
      window.location.hash = pageId;
    }
  } else {
    Footer.initialize();
  }
  
  // Sign up form
  SignUpForm.initialize($('footer section#more form'));
  
  // Background images, texts and geometries
  $('#front').injectContent(grayImages[0], 'h1');
  $('section.holder').each(function(i) {
    $(this).append($('<article><p></p></article>')).injectContent(colorImages[i]);
  });
  $('.cube .sprite').parallax('80%', 2000, 0.3, true);
  $('.dodecahedron .sprite').parallax('20%', 4400, 0.4, true);
  
  // Facebook and Twitter
  $('a.facebook').click(function() {
    _gaq.push(['_trackEvent', 'Share', 'facebook']);
    //var fb = window.open('http://www.facebook.com/sharer.php?s=100&p[url]=http://www.nomic.com&p[title]=nomic&p[images][0]=' ,'fb','width=550,height=450');
    var fb = window.open('http://www.facebook.com/sharer.php?s=100&p[url]=http://www.nomic.com&p[title]=' + escape('People are the soul of the economy.'), 'fb', 'width=550,height=450');
    return false;
  });
  $('a.twitter').click(function() {
    _gaq.push(['_trackEvent', 'Share', 'twitter']);
    var tw = window.open('http://twitter.com/?status=' + escape('People are the soul of the economy. http://nomic.com #personaleconomy'), 'tw','width=1024,height=600,scrollbars=yes');
    return false;
  });
  
  // Capture scroll position
  var $window = $(window);
  var scrollingStoppedEvent;
  $window.bind('scroll', function() { //when the user is scrolling...
    if (scrollingStoppedEvent) {
        clearTimeout(scrollingStoppedEvent);
    }
    scrollingStoppedEvent = setTimeout(function() {
      var pos = $window.scrollTop(); //position of the scrollbar
      _gaq.push(['_trackEvent', 'Scroll', 'stopped', 'position', pos]);
    }, 300);
  });
});

