Ascension Latorre

function isTouchDevice() {
  return "ontouchstart" in window;
}

var headerHeight;
var $html;
var $home;
var $collection;
var $philosophy;
var $theTeam;
var $manufacture;
var $latorreLife;
var $contact;
var $footer;
var mouseIsDown = false;
var $scrollTrack;
var getCurrentFirstPart;
var langPrefix;
var isIOS = IOSDetection.check();
var touchEnvironment = isTouchDevice();
var isFF = (navigator.userAgent.indexOf("Firefox") != -1);
var parallaxEnabled = !touchEnvironment;
var EXPANDED_HEADER_HEIGHT = 196;
var COLLAPSED_HEADER_HEIGHT = 142;

function updateHomeMargin() {
  if ($home) $home.css('margin-top', (isIOS ? EXPANDED_HEADER_HEIGHT : headerHeight) + 'px');
}

function showScrollBar() {
  if ($scrollTrack) {
    $html.animate({
      marginRight: '20px'
    }, {
      specialEasing: {
        marginRight: 'easeInOutCubic'
      },
      duration: 0
    });
    $('#scrollTrack').animate({
      width: '20px'
    }, {
      specialEasing: {
        width: 'easeInOutCubic'
      },
      duration: 0
    });
  }
}

function hideScrollBar() {
  if ($scrollTrack) {
    $html.animate({
      marginRight: '0px'
    }, {
      specialEasing: {
        marginRight: 'easeInOutCubic'
      },
      duration: 0
    });
    $('#scrollTrack').animate({
      width: '0px'
    }, {
      specialEasing: {
        width: 'easeInOutCubic'
      },
      duration: 0
    });
  }
}
var storedTitle;
(function($) {
  var $window;
  var $document;
  var windowHeight;
  var History;
  var $sections;
  var $navLinks;
  var $navHighlight;
  var $scrollbar;

  function init() {
/*isIOS = true;
		touchEnvironment = true;*/
/*isIOS = false;
		touchEnvironment = false;*/
    $html = $('html');
    $home = $('#home');
    $collection = $('#collection');
    $philosophy = $('#philosophy');
    $theTeam = $('#the-team');
    $manufacture = $('#manufacture');
    $latorreLife = $('#latorre-life');
    $contact = $('#contact');
    $footer = $('#wrapper > footer');
    $window = $(window);
    $document = $(document);
    windowHeight = $window.height();
    $window.resize(function() {
      windowHeight = $window.height()
    });
    headerHeight = $('body > header').height();
    updateHomeMargin();
    $sections = $('#wrapper > section');
    $navLinks = $('body > header > nav a');
    $navHighlight = $('#nav-highlight');
    $scrollbar = $('#scrollBar');
    $scrollTrack = $('#scrollTrack');

    var collItemContainer = $('#opened-coll-item');
    $("#the-team > .content > div > figure > .contents > .bio > .content").bulletProofScrollbar();
    $("#latorre-life > .content > div > figure > .contents .body").bulletProofScrollbar();

    $window.mousedown(function() {
      mouseIsDown = true;
/*if (scrollInterval)
			{
				clearInterval(scrollInterval);
				scrollInterval = undefined;
				scrollDest = currentScroll;
				animatingScroll = false;
				scrollingToElement = false;
			}*/
    });

    $document.bind('touchstart', function() {
      if (scrollInterval) {
        clearInterval(scrollInterval);
        scrollInterval = undefined;
        scrollDest = currentScroll;
        animatingScroll = false;
        scrollingToElement = false;
      }
    });

    $window.mouseup(function() {
      mouseIsDown = false;
    });

    History = window.History;
    storedTitle = $('head title').text();
    langPrefix = normalizeFirstPart(History.getState().hash) == 'es' ? 'es' : null;
    $window.bind('statechange', stateChangeHandler);
    $window.trigger('statechange');

    $window.scroll(scrollHandler);
    $window.keydown(keyDownHandler);

    $('#logo-strip > h1').click(function() {
      var $this = $(this);
      if ($this.css('cursor') != 'default') {
        CollectionGallery.close();
        TeamGallery.close();
        LatorreLife.close();
        navigateTo('/home');
      }
      return false;
    });

    $('#lang-selector a').click(function() {
      if (!$(this).hasClass('current')) {
        var newPath = normalizePath(History.getState().hash);
        if (!langPrefix) {
          newPath = '/es' + newPath
        };
        if (newPath == "") newPath = "/home";
        window.location = newPath;
      }
      return false;
    });
    $navLinks.bind('touchstart', pseudoLinkHandler);
    $navLinks.click(pseudoLinkHandler);
    $('#home aside a').bind('touchstart', pseudoLinkHandler);
    $('#home aside a').click(pseudoLinkHandler);

    if (parallaxEnabled) {
      $('#home').blockParallax();

      $philosophy.blockParallax();
      $philosophy.blockParallax('fixedBackground', 700);
      $philosophy.find('div.bg.philosophy-bg2').blockParallax('fixedBackground', 500);
      $philosophy.find('div.bg.philosophy-bg3').blockParallax('fixedBackground', 300);
      $philosophy.find('div.bg.philosophy-pic').blockParallax('fixedBackground', 100);

      function updatePicsXOffset() {
        var $pic = $philosophy.find('div.bg.philosophy-pic');
        var currentPositions = $pic.getBackgroundPosition().split(', ').join('').split(',');
        var newPositions = $pic.ieCompatibleOffset().left + "px " + currentPositions[0].split(' ')[1];
        $pic.css('background-position', newPositions);
      }
      $window.resize(updatePicsXOffset);
      updatePicsXOffset();
      //$philosophy.find('div.bg.philosophy-bg2').css('display', 'none');
      //$philosophy.find('div.bg.philosophy-bg3').css('display', 'none');
      //$philosophy.find('div.bg.philosophy-pic').css('display', 'none');

      $theTeam.blockParallax();
      $('#the-team > .content > div').blockParallax('css', 'margin-top', 50);
      $('#the-team > .content > div > aside').blockParallax('css', 'margin-top', -20);
      $('#the-team > nav').blockParallax('css', 'margin-top', -80);

      if (!isFF) {
        $manufacture.blockParallax();
        $manufacture.blockParallax('fixedBackground', 600);
        $('#manufacture > .content ').blockParallax('css', 'margin-top', $window.height() < 678 ? 300 : 450);

        $contact.blockParallax();
        $('#contact > .content').blockParallax('css', 'margin-top', 500);
      }

      $document.mousewheel(function(event, delta) {
        var customScroll = true;
        var html = $('html')[0];

        function checkObject(object) {
          if (object != html) {
            var overflow = $(object).css('overflow-y');
            if (overflow == 'auto' || overflow == 'scroll') {
              if (object.clientHeight < object.scrollHeight) {
                if ((delta < 0 && object.scrollTop < object.scrollHeight - object.clientHeight) || (delta > 0 && object.scrollTop > 0)) customScroll = false;
              }
            }
            if (customScroll) checkObject(object.parentNode);
          }
        }
        checkObject(event.target);
        if (customScroll) {
          if (collItemContainer.css('display') != 'block') {
            event.preventDefault();
            scroll(-250 * delta);
          }
        }
      });

      var $touchZone = $('html');
      var touchStartX;
      var touchStartY;
      var scrollStart;
      var speedMeterInterval;
      var lastY;
      var currentY;
      var speed;
      var THRESHOLD = 30;
      var ANGLE_THRESHOLD = Math.PI / 4;
      var dragStarted;

      function touchStartHandler(e) {
        if (!CollectionGallery.opened) {
          dragStarted = false; /*if (speedMeterInterval) { */
          clearInterval(speedMeterInterval); /*speedMeterInterval = undefined; }*/
          /*if (throwInterval) { */
          clearInterval(throwInterval); /*throwInterval = undefined; }*/
          $window.stop(true);
          $document.unbind('touchmove', touchMoveHandler);
          $document.unbind('touchend', touchEndHandler);
          var touch = e.originalEvent.touches[0];
          var pageY = -touch.clientY;
          touchStartX = -touch.clientX;
          touchStartY = currentY = lastY = pageY;
          scrollStart = (window.isIE ? document.documentElement.scrollTop : $window.scrollTop());
          $document.bind('touchmove', touchMoveHandler);
          $document.bind('touchend', touchEndHandler);
          speedMeterInterval = setInterval(checkSpeed, 1000 / 100);
        }
      }
      $touchZone.bind('touchstart', touchStartHandler);

      function touchMoveHandler(e) {
        e.preventDefault();
        var touch = e.originalEvent.touches[0];
        var pageX = -touch.clientX;
        var pageY = -touch.clientY;
        if (!dragStarted) {
          var angle = Math.atan2(pageY - touchStartY, pageX - touchStartX);
          var distance = Math.abs(pageY - touchStartY);
          if ((distance > THRESHOLD) && ((angle > ANGLE_THRESHOLD && angle < Math.PI - ANGLE_THRESHOLD) || (angle < -ANGLE_THRESHOLD && angle > -Math.PI + ANGLE_THRESHOLD))) {
            dragStarted = true;
            touchStartY = pageY;
          }
        }

        if (dragStarted) {
          e.preventDefault();
          $window.scrollTop(scrollStart + (pageY - touchStartY));
          currentY = pageY;
        }
      }

      function touchEndHandler(e) {
        clearInterval(speedMeterInterval);
        $document.unbind('touchmove', touchMoveHandler);
        $document.unbind('touchend', touchEndHandler);
        throwItems();
      }

      function checkSpeed() {
        speed = currentY - lastY;
        lastY = currentY;
      }

      var throwInterval;
      var FRICTION = .8;
      var HARD_FRICTION = .5;
      var ELASTIC = 1;
      var MIN_SPEED = .1;
      var MIN_SPEED_ELASCTIC = 1;
      var MAX_SCROLL = $window.height() - $window.height();

      function throwItems() {
        speed *= 2;
        throwInterval = setInterval(throwStep, 1000 / 20);
        MAX_SCROLL = $window.height() - $window.height();
      }

      function throwStep() {
        var currentScroll = (window.isIE ? document.documentElement.scrollTop : $window.scrollTop());
        speed *= FRICTION;
        $window.scrollTop(currentScroll + speed);
        if (Math.abs(speed) < MIN_SPEED) clearInterval(throwInterval);
      }
      HomeImage.startUpdating();
    } else {
      var $parallaxImage = $('#home .parallax-image');
      $parallaxImage.css('background-attachment', 'scroll');
      $parallaxImage.css('background-position', 'center center');

      $philosophy.css('background-attachment', 'scroll');
      $philosophy.find('div.bg.philosophy-bg2').css('background-attachment', 'scroll');
      $philosophy.find('div.bg.philosophy-bg3').css('background-attachment', 'scroll');
      $philosophy.find('div.bg.philosophy-pic').css('background-attachment', 'scroll');
      $manufacture.css('background-attachment', 'scroll');
      $html.css('overflow-y', 'scroll');
    }

    var showScrollbar = true;
    if (touchEnvironment) showScrollbar = false;

    if (showScrollbar) {

      $scrollTrack.mousedown(function(e) {
        if (e.currentTarget == e.target) {
          var windowHeight = $window.height();
          var htmlHeight = $.browser.msie ? $html[0].scrollHeight : $html.height();
          var maxScroll = htmlHeight - windowHeight;
          var barHeight = $scrollbar.height();
          var top = e.pageY - (window.isIE ? document.documentElement.scrollTop : $window.scrollTop()) - barHeight / 2;
          if (top < 0) top = 0;
          else if (top > windowHeight - barHeight) top = windowHeight - barHeight;
          var ratio = top / (windowHeight - barHeight);

          scrollTo(maxScroll * ratio);
        }
        return false;
      });

      function updateScrollbar() {
        var windowHeight = $window.height();
        var htmlHeight = $.browser.msie ? $html[0].scrollHeight : $html.height();
        var maxScroll = htmlHeight - windowHeight;
        var barRatio = windowHeight / htmlHeight;
        var barHeight = windowHeight * barRatio;
        $scrollbar.height(barHeight);
        barHeight = $scrollbar.height()
        var ratio = (window.isIE ? document.documentElement.scrollTop : $window.scrollTop()) / maxScroll;
        var top = ratio * (windowHeight - barHeight);
        $scrollbar.css('top', top + 'px');
      }
      $window.scroll(updateScrollbar);
      $window.resize(updateScrollbar);
      $scrollbar.mousedown(function(e) {
        $window.unbind('scroll', updateScrollbar);
        var startTop = Number($scrollbar.css('top').split('px').join(''));
        var startY = e.pageY - (window.isIE ? document.documentElement.scrollTop : $window.scrollTop());
        var maxTop = windowHeight - $scrollbar.height();
        var maxScroll = $html[0].scrollHeight - $window.height();

        if (window.isIE) $document.bind('mousemove', moveHandler);
        else $window.bind('mousemove', moveHandler);
        if (window.isIE) $document.bind('mouseup', upHandler);
        else $window.bind('mouseup', upHandler);

        function moveHandler(e) {
          var newY = e.pageY - (window.isIE ? document.documentElement.scrollTop : $window.scrollTop());
          var top = startTop + (newY - startY);
          if (top < 0) top = 0;
          else if (top > maxTop) top = maxTop;
          $scrollbar.css('top', top + 'px');
          scrollTo(top / maxTop * maxScroll);
          return false;
        };

        function upHandler(e) {
          if (window.isIE) {
            $document.unbind('mousemove', moveHandler);
            $document.unbind('mouseup', upHandler);
            $document.bind('scroll', updateScrollbar);
          } else {
            $window.unbind('mousemove', moveHandler);
            $window.unbind('mouseup', upHandler);
            $window.bind('scroll', updateScrollbar);
          }
        };
        return false;
      });
      updateScrollbar();
      showScrollBar();
    } else {
      $scrollTrack.remove();
      $scrollTrack = null;
    }

    BoxShadow.applyTo($('#collection > .content > div > figure'));
    BoxShadow.applyTo($('#latorre-life > .content > div > figure:not(.item-adder)'));

    if ($.browser.webkit) {
      $('h2, h3').each(function() {
        var $this = $(this);
        $this.append('<span class="after">' + $this.text() + '</span>');
      });
    }

    if (isIOS) {
      var $header = $('body > header');
      $header.css('position', 'absolute');
    }

    $window.resize(restoreHighlightPosition);

    var MIN_BOTTOM_PADDING = 0;
    var homeDefaultHeight = $home.height();
    var $homeAside = $home.find('.content > aside');
    var collectionDefaultHeight = $collection.height();
    var $collectionContent = $collection.children('.content');

    function updateSectionsHeight() {
/*var currentDistance = getCurrentSection().offset().top - (window.isIE ? document.documentElement.scrollTop : $window.scrollTop());
			var windowHeight = $window.height();
			
			var homeHeight = windowHeight - EXPANDED_HEADER_HEIGHT;
			if (homeHeight < homeDefaultHeight) homeHeight = homeDefaultHeight;
			$home.height(homeHeight);
			$homeAside.css('padding-top', (homeHeight - 118) / 2 + 'px');
			
			var collectionHeight = windowHeight - COLLAPSED_HEADER_HEIGHT + 3;
			if (collectionHeight < collectionDefaultHeight) collectionHeight = collectionDefaultHeight;
			$collection.height(collectionHeight);
			$collectionContent.css('margin-top', (collectionHeight - collectionDefaultHeight) / 2 + 'px');*/

      var newPadding = $window.height() - $footer.height() - COLLAPSED_HEADER_HEIGHT - $contact.height() + 3; // 3 pixels arbitrarios pero necesarios para que la costura de la sección quede escondida
      if (newPadding < MIN_BOTTOM_PADDING) newPadding = MIN_BOTTOM_PADDING;
      $contact.css('padding-bottom', newPadding + "px");
    }
    updateSectionsHeight();
    $window.resize(updateSectionsHeight);

    function disableSelectionForIE(target) {
      if (typeof target.onselectstart != "undefined") //IE route
      target.onselectstart = function() {
        return false
      }
    }

    $('#wrapper > section > nav > span').each(function() {
      disableSelectionForIE(this);
    });

    $('#logo-strip h1 a span').each(function() {
      disableSelectionForIE(this);
    });

    getCurrentFirstPart = function() {
      var State = History.getState();
      return normalizeFirstPart(State.hash);
    }


    // form
    var $form = $('#latorre-life > .content > div > .section-desc form');
    var $label = $form.find('.subscribe');
    var $field = $form.find('input[type=text]');
    var $submit = $form.find('input[type=submit]');
    var $checkboxBox = $form.children('.checkbox-box');
    var $checkbox = $checkboxBox.children('.checkbox');
    $checkboxBox.click(function() {
      $checkbox.toggleClass('checked');
    });
    $checkboxBox.children('a').click(function(e) {
      e.stopPropagation();
    });
    $submit.click(function() {
      var errorsFound = false;
      if (!validateEmail($field.attr('value'))) {
        errorsFound = true;
        $field.addClass('error');
      }
      if (!$checkbox.hasClass('checked')) {
        errorsFound = true;
        $checkbox.addClass('error');
      }

      if (!errorsFound) {
        $form.addClass('submitting');

        function success(data) {
          var success = Boolean(Number(data));
          if (success) {
            $form.children().animate({
              opacity: 0
            }, {
              queue: false,
              duration: 400,
              specialEasing: {
                opacity: 'easeInCubic'
              },
              complete: function() {
                $form.children().css('display', 'none');
                $form.removeClass('submitting');
                $form.children('p.success').css('display', 'block');
                $form.removeClass('submitting');
              }
            });
            $form.children('p.success').delay(500).animate({
              opacity: 1
            }, {
              queue: false,
              duration: 400,
              specialEasing: {
                opacity: 'easeOutCubic'
              }
            });
          } else error();
        }

        function error() {
          $form.children().animate({
            opacity: 0
          }, {
            queue: false,
            duration: 400,
            specialEasing: {
              opacity: 'easeInCubic'
            },
            complete: function() {
              $form.children().css('display', 'none');
              $form.removeClass('submitting');
              $form.children('p.error').css('display', 'block');
              $form.removeClass('submitting');
            }
          });
          $form.children('p.error').delay(500).animate({
            opacity: 1
          }, {
            duration: 400,
            specialEasing: {
              opacity: 'easeOutCubic'
            }
          });
        }
        var path = 'nl-subscription/' + $field.attr('value');
        if (langPrefix) path = langPrefix + "/" + path;
        path = '/?q=' + path;
        $.ajax({
          url: path,
          success: success,
          error: error,
          type: 'GET'
        });
      }

      return false;
    });

    function clearErrors() {
      $checkbox.removeClass('error');
      $field.removeClass('error');
    }
    $field.change(clearErrors);
    $field.click(clearErrors);
    $checkboxBox.click(clearErrors);

    function validateEmail(value) {
      var regExp = /^([A-Za-z0-9_\-\.])+\@([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/;
      return regExp.test(value);
    }

    function restoreForm() {
      $form.children().css('display', '');
      $form.children().css('opacity', '');
      $field.attr('value', '');
      return false;
    }
    $form.find('p.error a').click(restoreForm);
  }
  $(document).bind('preloaded', init);


  function onPageLoad() {
    if (touchEnvironment) $('body').addClass('touch');
    $('#scrollTrack').css('width', 0);
  }
  $(onPageLoad);

  function normalizePath(path) {
    path = path.split('?&_suid=')[0]
    if (langPrefix) path = path.split('/' + langPrefix).join('');
    path = path.split('/test').join('').split('#').join('').split('./').join('/');

    if (path.lastIndexOf('/') == path.length - 1) {
      return path.substr(0, path.length - 1);
    } else return path;
  }
  var justUpdatingHash = false;
  var updatingHashTimeout;
  var currentPath;

  function updateHash(path) {
    if (currentPath != normalizePath(path)) {
      justUpdatingHash = true;
      History.replaceState(null, storedTitle, langPrefix ? '/' + langPrefix + '/' + path : path);
      if (updatingHashTimeout) clearTimeout(updatingHashTimeout);
      updatingHashTimeout = setTimeout(function() {
        justUpdatingHash = false;
      }, 300);
    }
  }

  function navigateTo(path) {
    History.pushState(null, storedTitle, langPrefix ? '/' + langPrefix + path : path);
  }

  function stateChangeHandler() {
    var State = History.getState();
    currentPath = normalizePath(State.hash);
    if (!justUpdatingHash && !($.browser.msie && mouseIsDown)) {
      if (CollectionGallery.opened) CollectionGallery.closeImage();
      var firstPart = normalizeFirstPart(State.hash);
      navigateToSection(firstPart);
      var otherParts = getOtherParts(State.hash);
      if (otherParts.length) {
        switch (firstPart) {
        case 'latorre-life':
          var $figure = $('#latorre-life > .content > div > figure.item-' + otherParts[0]);
          if ($figure.length) LatorreLife.openItem($figure, false);
          break;
        }
      }
    }
    updateNavHighlight(normalizeFirstPart(State.hash));
  }

  function normalizeFirstPart(hash) {
    var parts = normalizePath(hash).split('/');
    parts.shift();
    var section = parts[0];
    if (section == "") section = "home";
    return section;
  }

  function getOtherParts(hash) {
    var parts = normalizePath(hash).split('/');
    parts.shift();
    parts.shift();
    if (langPrefix) parts.shift();
    return parts;
  }
  var navHighlightAnimateOptions = {
    duration: 500,
    specialEasing: {
      marginLeft: 'easeInOutCubic',
      opacity: 'easeInOutCubic'
    },
    queue: false
  }
  var $highlightLink;

  function updateNavHighlight(section) {
    $highlightLink = null;
    $navLinks.each(function() {
      if (!$highlightLink) {
        $this = $(this);
        if (normalizePath($this.attr('href')) == "/" + section) $highlightLink = $this;
      }
    });
    if ($highlightLink) {
      $navHighlight.animate({
        left: $highlightLink.position().left + Number($highlightLink.css('margin-left').split('px').join('')),
        width: $highlightLink.width(),
        opacity: 1
      }, navHighlightAnimateOptions);
    } else {
      $navHighlight.animate({
        opacity: 0
      }, navHighlightAnimateOptions);
    }
  }

  function restoreHighlightPosition() {
    $navHighlight.stop();
    if ($highlightLink) {
      $navHighlight.css({
        left: $highlightLink.position().left + Number($highlightLink.css('margin-left').split('px').join('')) + 'px',
        width: $highlightLink.width() + 'px',
        opacity: 1
      }, navHighlightAnimateOptions);
    } else $navHighlight.css('opacity', 0);
  }

  function navigateToSection(section) {
    var target;
    if (section == 'home' && touchEnvironment) target = $('body > header');
    else target = $('#' + section);
    if (target.length) scrollToElement(target);
  }

  function pseudoLinkHandler(e) {
    var $this = $(this);
    if ($this.css('cursor') != 'default') {
      CollectionGallery.close();
      TeamGallery.close();
      LatorreLife.close();
      navigateTo($this.attr('href'));
    }
    return false;
  }

  var scrollInterval;
  var scrollEase = .33;
  var currentScroll;
  var scrollDest;

  function checkScroll() {
    if (!scrollDest) {
      currentScroll = scrollDest = (window.isIE ? document.documentElement.scrollTop : $window.scrollTop());
    }
  }

  function scroll(difference) {
    checkScroll();
    scrollingToElement = false;
    scrollTo(scrollDest + difference);
  }

  function scrollToElement($target) {
    scrollingToElement = true;
    var top = $target.ieCompatibleOffset().top;
    var height = $target.height();

    var futureHeaderHeight;
    var offset;
    if ($target.attr('id') == 'home') {
      futureHeaderHeight = isIOS ? 0 : EXPANDED_HEADER_HEIGHT;
      offset = 0;
    } else {
      futureHeaderHeight = isIOS ? 0 : COLLAPSED_HEADER_HEIGHT;
      offset = 1;
      if ($target.children('.costura-hard').length) offset += 1;
      else if ($target.children('.costura-soft').length) offset += 3;
    }
    var scrollTarget;
    if (isIOS) {
      scrollTarget = height < 850 ? top + offset : top + height / 2 - (windowHeight) / 2;
    } else {
      scrollTarget = height < 850 ? top + offset - futureHeaderHeight : top - futureHeaderHeight + height / 2 - (windowHeight - futureHeaderHeight) / 2;
    }
    scrollTarget -= (isIOS ? 0 : headerHeight)
    scrollTarget += futureHeaderHeight
    scrollTo(scrollTarget);
  }
  var animatingScroll = false;
  var scrollingToElement = false;
  var speed = 0;
  var MAX_ACCELERATION = 25;

  function scrollTo(target) {
    animatingScroll = true;
    checkScroll();
    scrollDest = target;
    if (scrollDest < 0) scrollDest = 0;
    else if (scrollDest > $document.height() - windowHeight) scrollDest = $document.height() - windowHeight;

    if (!scrollInterval) scrollInterval = setInterval(function() {
      var scrollDiff = (scrollDest - currentScroll) * scrollEase;
      var way = scrollDiff / Math.abs(scrollDiff);
      speed += MAX_ACCELERATION * way;
      if (Math.abs(scrollDiff) > Math.abs(speed)) {
        scrollDiff = speed;
      } else {
        speed = scrollDiff;
      }
      currentScroll += scrollDiff;
      isAnimationStep = true;
      $window.scrollTop(currentScroll);
      isAnimationStep = false;
      if (Math.abs(currentScroll - scrollDest) < .5) {
        animatingScroll = false;
        scrollingToElement = false;
        currentScroll = scrollDest;
        clearInterval(scrollInterval);
        scrollInterval = undefined;
      }
    }, 1000 / 60);
  }

  function scrollHandler() {
    if (!animatingScroll) {
      scrollDest = currentScroll = (window.isIE ? document.documentElement.scrollTop : $window.scrollTop());
    }
    if (!scrollingToElement) {
      var $currentSection = getCurrentSection();
      updateHash($currentSection.attr('id'));
    }
  }

  function getCurrentSection() {
    var $nearestSection;
    var minDistance = 99999;
    $sections.each(function() {
      var $this = $(this);
      var top = $this.ieCompatibleOffset().top;
      var distance = Math.abs(currentScroll + (isIOS ? 0 : headerHeight) - top);
      if (distance < minDistance) {
        minDistance = distance;
        $nearestSection = $this;
      }
    });
    return $nearestSection;
  }

  function keyDownHandler(e) {
    var $newSection;
    var $currentSection;
    if (!CollectionGallery.opened) {
      switch (e.keyCode) {
      case 38:
        $currentSection = getCurrentSection();
        $newSection = $currentSection.prev();
        e.preventDefault();
        break;
      case 40:
        $currentSection = getCurrentSection();
        $newSection = $currentSection.next();
        e.preventDefault();
        break;
      }
      if ($newSection && $newSection.length > 0) {
        History.pushState(null, storedTitle, $newSection.attr('id'));
      }
    }
  }
})(jQuery)
function isTouchDevice() {
	return "ontouchstart" in window;
}

var headerHeight;
var $html;
var $home;
var $collection;
var $philosophy;
var $theTeam;
var $manufacture;
var $latorreLife;
var $contact;
var $footer;
var mouseIsDown = false;
var $scrollTrack;
var getCurrentFirstPart;
var langPrefix;
var isIOS = IOSDetection.check();
var touchEnvironment = isTouchDevice();
var isFF = (navigator.userAgent.indexOf("Firefox")!=-1);
var parallaxEnabled = !touchEnvironment;
var EXPANDED_HEADER_HEIGHT = 196;
var COLLAPSED_HEADER_HEIGHT = 142;
function updateHomeMargin()
{
	if ($home)
	$home.css('margin-top', (isIOS ? EXPANDED_HEADER_HEIGHT : headerHeight) + 'px');
}

function showScrollBar()
{
	if ($scrollTrack)
	{
		$html.animate({marginRight: '20px'}, {specialEasing: {marginRight: 'easeInOutCubic'}, duration: 0});
		$('#scrollTrack').animate({width: '20px'}, {specialEasing: {width: 'easeInOutCubic'}, duration: 0});
	}
}

function hideScrollBar()
{
	if ($scrollTrack)
	{
		$html.animate({marginRight: '0px'}, {specialEasing: {marginRight: 'easeInOutCubic'}, duration: 0});
		$('#scrollTrack').animate({width: '0px'}, {specialEasing: {width: 'easeInOutCubic'}, duration: 0});
	}
}
var storedTitle;
(function($) {
	var $window;
	var $document;
	var windowHeight;
	var History;
	var $sections;
	var $navLinks;
	var $navHighlight;
	var $scrollbar;
	function init()
	{
		/*isIOS = true;
		touchEnvironment = true;*/
		/*isIOS = false;
		touchEnvironment = false;*/
		$html = $('html');
		$home = $('#home');
		$collection = $('#collection');
		$philosophy = $('#philosophy');
		$theTeam = $('#the-team');
		$manufacture = $('#manufacture');
		$latorreLife = $('#latorre-life');
		$contact = $('#contact');
		$footer = $('#wrapper > footer');
		$window = $(window);
		$document = $(document);
		windowHeight = $window.height();
			$window.resize(function () {windowHeight = $window.height()});
		headerHeight = $('body > header').height();
		updateHomeMargin();
		$sections = $('#wrapper > section');
		$navLinks = $('body > header > nav a');
		$navHighlight = $('#nav-highlight');
		$scrollbar = $('#scrollBar');
		$scrollTrack = $('#scrollTrack');
		
		var collItemContainer = $('#opened-coll-item');
		$("#the-team > .content > div > figure > .contents > .bio > .content").bulletProofScrollbar();
		$("#latorre-life > .content > div > figure > .contents .body").bulletProofScrollbar();
		
		$window.mousedown(function()
		{
			mouseIsDown = true;
			/*if (scrollInterval)
			{
				clearInterval(scrollInterval);
				scrollInterval = undefined;
				scrollDest = currentScroll;
				animatingScroll = false;
				scrollingToElement = false;
			}*/
		});
		
		$document.bind('touchstart', function()
		{
			if (scrollInterval)
			{
				clearInterval(scrollInterval);
				scrollInterval = undefined;
				scrollDest = currentScroll;
				animatingScroll = false;
				scrollingToElement = false;
			}
		});
		
		$window.mouseup(function()
		{
			mouseIsDown = false;
		});
		
		History = window.History;
		storedTitle = $('head title').text();
		langPrefix = normalizeFirstPart(History.getState().hash) == 'es' ? 'es' : null;
		$window.bind('statechange', stateChangeHandler);
		$window.trigger('statechange');
		
		$window.scroll(scrollHandler);
		$window.keydown(keyDownHandler);
		
		$('#logo-strip > h1').click(function()
		{
			var $this = $(this);
			if ($this.css('cursor') != 'default')
			{
				CollectionGallery.close();
				TeamGallery.close();
				LatorreLife.close();
				navigateTo('/home');
			}
			return false;
		});
		
		$('#lang-selector a').click(function()
		{
			if (!$(this).hasClass('current'))
			{
				var newPath = normalizePath(History.getState().hash);
				if (!langPrefix)
				{
					newPath = '/es' + newPath
				};
				if (newPath == "") newPath = "/home";
				window.location = newPath;
			}
			return false;
		});
		$navLinks.bind('touchstart', pseudoLinkHandler);
		$navLinks.click(pseudoLinkHandler);
		$('#home aside a').bind('touchstart', pseudoLinkHandler);
		$('#home aside a').click(pseudoLinkHandler);
		
		if (parallaxEnabled)
		{
			$('#home').blockParallax();
			
			$philosophy.blockParallax();
			$philosophy.blockParallax('fixedBackground', 700);
			$philosophy.find('div.bg.philosophy-bg2').blockParallax('fixedBackground', 500);
			$philosophy.find('div.bg.philosophy-bg3').blockParallax('fixedBackground', 300);
			$philosophy.find('div.bg.philosophy-pic').blockParallax('fixedBackground', 100);
			function updatePicsXOffset()
			{
				var $pic = $philosophy.find('div.bg.philosophy-pic');
				var currentPositions = $pic.getBackgroundPosition().split(', ').join('').split(',');
				var newPositions = $pic.ieCompatibleOffset().left + "px " + currentPositions[0].split(' ')[1];
				$pic.css('background-position', newPositions);
			}
			$window.resize(updatePicsXOffset);
			updatePicsXOffset();
			//$philosophy.find('div.bg.philosophy-bg2').css('display', 'none');
			//$philosophy.find('div.bg.philosophy-bg3').css('display', 'none');
			//$philosophy.find('div.bg.philosophy-pic').css('display', 'none');
			
			$theTeam.blockParallax();
			$('#the-team > .content > div').blockParallax('css', 'margin-top', 50);
			$('#the-team > .content > div > aside').blockParallax('css', 'margin-top', -20);
			$('#the-team > nav').blockParallax('css', 'margin-top', -80);
			
			if (!isFF)
			{
				$manufacture.blockParallax();
				$manufacture.blockParallax('fixedBackground', 600);
				$('#manufacture > .content ').blockParallax('css', 'margin-top', $window.height() < 678 ? 300 : 450);
			
				$contact.blockParallax();
				$('#contact > .content').blockParallax('css', 'margin-top', 500);
			}
			
			$document.mousewheel(function(event, delta)
			{
				var customScroll = true;
				var html = $('html')[0];
				function checkObject(object)
				{
					if (object != html)
					{
						var overflow = $(object).css('overflow-y');
						if (overflow == 'auto' || overflow == 'scroll')
						{
							if (object.clientHeight < object.scrollHeight)
							{
								if
								(
									(delta < 0 && object.scrollTop < object.scrollHeight - object.clientHeight)
									||
									(delta > 0 && object.scrollTop > 0)
								)
								customScroll = false;
							}
						}
						if (customScroll) checkObject(object.parentNode);
					}
				}
				checkObject(event.target);
				if (customScroll)
				{
					if (collItemContainer.css('display') != 'block')
					{
						event.preventDefault();
						scroll(-250 * delta);
					}
				}
			});
			
			var $touchZone = $('html');
			var touchStartX;
			var touchStartY;
			var scrollStart;
			var speedMeterInterval;
			var lastY;
			var currentY;
			var speed;
			var THRESHOLD = 30;
			var ANGLE_THRESHOLD = Math.PI / 4;
			var dragStarted;
			function touchStartHandler(e) {
				if (!CollectionGallery.opened)
				{
					dragStarted = false;
					/*if (speedMeterInterval) { */clearInterval(speedMeterInterval); /*speedMeterInterval = undefined; }*/
					/*if (throwInterval) { */clearInterval(throwInterval); /*throwInterval = undefined; }*/
					$window.stop(true);
					$document.unbind('touchmove', touchMoveHandler);
					$document.unbind('touchend', touchEndHandler);
					var touch = e.originalEvent.touches[0];
					var pageY = -touch.clientY;
					touchStartX = -touch.clientX;
					touchStartY =
					currentY =
					lastY = pageY;
					scrollStart = (window.isIE ? document.documentElement.scrollTop : $window.scrollTop());
					$document.bind('touchmove', touchMoveHandler);
					$document.bind('touchend', touchEndHandler);
					speedMeterInterval = setInterval(checkSpeed, 1000/100);
				}
			}
			$touchZone.bind('touchstart', touchStartHandler);
			
			function touchMoveHandler(e) {
				e.preventDefault();
				var touch = e.originalEvent.touches[0];
				var pageX = -touch.clientX;
				var pageY = -touch.clientY;
				if (!dragStarted)
				{
					var angle = Math.atan2(pageY - touchStartY, pageX - touchStartX);
					var distance = Math.abs(pageY - touchStartY);
					if
					(
						(distance > THRESHOLD)
						&&
						(
							(angle > ANGLE_THRESHOLD && angle < Math.PI - ANGLE_THRESHOLD)
							||
							(angle < -ANGLE_THRESHOLD && angle > -Math.PI + ANGLE_THRESHOLD)
						)
					)
					{
						dragStarted = true;
						touchStartY = pageY;
					}
				}
				
				if (dragStarted)
				{
					e.preventDefault();
					$window.scrollTop(scrollStart + (pageY - touchStartY));
					currentY = pageY;
				}
			}
			
			function touchEndHandler(e) {
				clearInterval(speedMeterInterval);
				$document.unbind('touchmove', touchMoveHandler);
				$document.unbind('touchend', touchEndHandler);
				throwItems();
			}
			
			function checkSpeed()
			{
				speed = currentY - lastY;
				lastY = currentY;
			}
			
			var throwInterval;
			var FRICTION = .8;
			var HARD_FRICTION = .5;
			var ELASTIC = 1;
			var MIN_SPEED = .1;
			var MIN_SPEED_ELASCTIC = 1;
			var MAX_SCROLL = $window.height() - $window.height();
			function throwItems()
			{
				speed *= 2;
				throwInterval = setInterval(throwStep, 1000/20);
				MAX_SCROLL = $window.height() - $window.height();
			}
			
			function throwStep()
			{
				var currentScroll = (window.isIE ? document.documentElement.scrollTop : $window.scrollTop());
				speed *= FRICTION;
				$window.scrollTop(currentScroll + speed);
				if (Math.abs(speed) < MIN_SPEED)
				clearInterval(throwInterval);
			}
			HomeImage.startUpdating();
		}
		else
		{
			var $parallaxImage = $('#home .parallax-image');
			$parallaxImage.css('background-attachment', 'scroll');
			$parallaxImage.css('background-position', 'center center');
			
			$philosophy.css('background-attachment', 'scroll');
			$philosophy.find('div.bg.philosophy-bg2').css('background-attachment', 'scroll');
			$philosophy.find('div.bg.philosophy-bg3').css('background-attachment', 'scroll');
			$philosophy.find('div.bg.philosophy-pic').css('background-attachment', 'scroll');
			$manufacture.css('background-attachment', 'scroll');
			$html.css('overflow-y', 'scroll');
		}
		
		var showScrollbar = true;
		if (touchEnvironment) showScrollbar = false;
		
		if (showScrollbar)
		{
			
			$scrollTrack.mousedown(function(e)
			{
				if (e.currentTarget == e.target)
				{
					var windowHeight = $window.height();
					var htmlHeight = $.browser.msie ? $html[0].scrollHeight : $html.height();
					var maxScroll = htmlHeight - windowHeight;
					var barHeight = $scrollbar.height();
					var top = e.pageY - (window.isIE ? document.documentElement.scrollTop : $window.scrollTop()) - barHeight / 2;
					if (top < 0) top = 0;
					else if (top > windowHeight - barHeight) top = windowHeight - barHeight;
					var ratio = top / (windowHeight - barHeight);
					
					scrollTo(maxScroll * ratio);
				}
				return false;
			});
			function updateScrollbar()
			{
				var windowHeight = $window.height();
				var htmlHeight = $.browser.msie ? $html[0].scrollHeight : $html.height();
				var maxScroll = htmlHeight - windowHeight;
				var barRatio = windowHeight / htmlHeight;
				var barHeight = windowHeight * barRatio;
				$scrollbar.height(barHeight);
				barHeight = $scrollbar.height()
				var ratio = (window.isIE ? document.documentElement.scrollTop : $window.scrollTop()) / maxScroll;
				var top = ratio * (windowHeight - barHeight);
				$scrollbar.css('top', top + 'px');
			}
			$window.scroll(updateScrollbar);
			$window.resize(updateScrollbar);
			$scrollbar.mousedown(function(e)
			{
				$window.unbind('scroll', updateScrollbar);
				var startTop = Number($scrollbar.css('top').split('px').join(''));
				var startY = e.pageY - (window.isIE ? document.documentElement.scrollTop : $window.scrollTop());
				var maxTop = windowHeight - $scrollbar.height();
				var maxScroll = $html[0].scrollHeight - $window.height();
				
				if (window.isIE) $document.bind('mousemove', moveHandler);
				else $window.bind('mousemove', moveHandler);
				if (window.isIE) $document.bind('mouseup', upHandler);
				else $window.bind('mouseup', upHandler);
				function moveHandler(e)
				{
					var newY = e.pageY - (window.isIE ? document.documentElement.scrollTop : $window.scrollTop());
					var top = startTop + (newY - startY);
					if (top < 0) top = 0;
					else if (top > maxTop) top = maxTop;
					$scrollbar.css('top', top + 'px');
					scrollTo(top / maxTop * maxScroll);
					return false;
				};
				function upHandler(e)
				{
					if (window.isIE)
					{
						$document.unbind('mousemove', moveHandler);
						$document.unbind('mouseup', upHandler);
						$document.bind('scroll', updateScrollbar);
					}
					else
					{
						$window.unbind('mousemove', moveHandler);
						$window.unbind('mouseup', upHandler);
						$window.bind('scroll', updateScrollbar);
					}
				};
				return false;
			});
			updateScrollbar();
			showScrollBar();
		}
		else
		{
			$scrollTrack.remove();
			$scrollTrack = null;
		}
		
		BoxShadow.applyTo($('#collection > .content > div > figure'));
		BoxShadow.applyTo($('#latorre-life > .content > div > figure:not(.item-adder)'));
		
		if ($.browser.webkit)
		{
			$('h2, h3').each(function()
			{
				var $this = $(this);
				$this.append('<span class="after">' + $this.text() + '</span>');
			});
		}
		
		if (isIOS)
		{
			var $header = $('body > header');
			$header.css('position', 'absolute');
		}
		
		$window.resize(restoreHighlightPosition);
		
		var MIN_BOTTOM_PADDING = 0;
		var homeDefaultHeight = $home.height();
		var $homeAside = $home.find('.content > aside');
		var collectionDefaultHeight = $collection.height();
		var $collectionContent = $collection.children('.content');
		function updateSectionsHeight()
		{
			/*var currentDistance = getCurrentSection().offset().top - (window.isIE ? document.documentElement.scrollTop : $window.scrollTop());
			var windowHeight = $window.height();
			
			var homeHeight = windowHeight - EXPANDED_HEADER_HEIGHT;
			if (homeHeight < homeDefaultHeight) homeHeight = homeDefaultHeight;
			$home.height(homeHeight);
			$homeAside.css('padding-top', (homeHeight - 118) / 2 + 'px');
			
			var collectionHeight = windowHeight - COLLAPSED_HEADER_HEIGHT + 3;
			if (collectionHeight < collectionDefaultHeight) collectionHeight = collectionDefaultHeight;
			$collection.height(collectionHeight);
			$collectionContent.css('margin-top', (collectionHeight - collectionDefaultHeight) / 2 + 'px');*/
			
			var newPadding = $window.height() - $footer.height() - COLLAPSED_HEADER_HEIGHT - $contact.height() + 3; // 3 pixels arbitrarios pero necesarios para que la costura de la sección quede escondida
			if (newPadding < MIN_BOTTOM_PADDING)
			newPadding = MIN_BOTTOM_PADDING;
			$contact.css('padding-bottom', newPadding + "px");
		}
		updateSectionsHeight();
		$window.resize(updateSectionsHeight);
		
		function disableSelectionForIE(target){
			if (typeof target.onselectstart!="undefined") //IE route
				target.onselectstart=function(){return false}
		}
		
		$('#wrapper > section > nav > span').each(function()
		{
			disableSelectionForIE(this);
		});
		
		$('#logo-strip h1 a span').each(function()
		{
			disableSelectionForIE(this);
		});
		
		getCurrentFirstPart = function ()
		{
			var State = History.getState();
			return normalizeFirstPart(State.hash);
		}
		
		
		// form
		var $form = $('#latorre-life > .content > div > .section-desc form');
		var $label = $form.find('.subscribe');
		var $field = $form.find('input[type=text]');
		var $submit = $form.find('input[type=submit]');
		var $checkboxBox = $form.children('.checkbox-box');
		var $checkbox = $checkboxBox.children('.checkbox');
		$checkboxBox.click(function()
		{
			$checkbox.toggleClass('checked');
		});
		$checkboxBox.children('a').click(function(e)
		{
			e.stopPropagation();
		});
		$submit.click(function()
		{
			var errorsFound = false;
			if (!validateEmail($field.attr('value')))
			{
				errorsFound = true;
				$field.addClass('error');
			}
			if (!$checkbox.hasClass('checked'))
			{
				errorsFound = true;
				$checkbox.addClass('error');
			}
			
			if (!errorsFound)
			{
				$form.addClass('submitting');
				function success(data)
				{
					var success = Boolean(Number(data));
					if (success)
					{
						$form.children().animate({opacity: 0}, {queue: false, duration: 400, specialEasing: { opacity: 'easeInCubic'}, complete: function() {$form.children().css('display', 'none'); $form.removeClass('submitting'); $form.children('p.success').css('display', 'block'); $form.removeClass('submitting');}});
						$form.children('p.success').delay(500).animate({opacity: 1}, {queue: false, duration: 400, specialEasing: { opacity: 'easeOutCubic'}});
					}
					else error();
				}
				function error()
				{
					$form.children().animate({opacity: 0}, {queue: false, duration: 400, specialEasing: { opacity: 'easeInCubic'}, complete: function() {$form.children().css('display', 'none'); $form.removeClass('submitting'); $form.children('p.error').css('display', 'block'); $form.removeClass('submitting');}});
					$form.children('p.error').delay(500).animate({opacity: 1}, {duration: 400, specialEasing: { opacity: 'easeOutCubic'}});
				}
				var path = 'nl-subscription/' + $field.attr('value');
				if (langPrefix) path = langPrefix + "/" + path;
				path = '/?q=' + path;
				$.ajax({url: path, success: success, error: error, type: 'GET'});
			}
			
			return false;
		});
		function clearErrors()
		{
			$checkbox.removeClass('error');
			$field.removeClass('error');
		}
		$field.change(clearErrors);
		$field.click(clearErrors);
		$checkboxBox.click(clearErrors);
		function validateEmail(value)
		{
			var regExp = /^([A-Za-z0-9_\-\.])+\@([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/;
			return regExp.test(value);
		}
		function restoreForm()
		{
			$form.children().css('display', '');
			$form.children().css('opacity', '');
			$field.attr('value', '');
			return false;
		}
		$form.find('p.error a').click(restoreForm);
	}
	$(document).bind('preloaded', init);
	
	
	function onPageLoad()
	{
		if (touchEnvironment) $('body').addClass('touch');
		$('#scrollTrack').css('width', 0);
	}
	$(onPageLoad);
	
	function normalizePath(path)
	{
		path = path.split('?&_suid=')[0]
		if (langPrefix) path = path.split('/' + langPrefix).join('');
		path = path.split('/test').join('').split('#').join('').split('./').join('/');
		
		if (path.lastIndexOf('/') == path.length - 1)
		{
			return path.substr(0, path.length - 1);
		}
		else return path;
	}
	var justUpdatingHash = false;
	var updatingHashTimeout;
	var currentPath;
	function updateHash(path)
	{
		if (currentPath != normalizePath(path))
		{
			justUpdatingHash = true;
			History.replaceState(null, storedTitle, langPrefix ? '/' + langPrefix + '/' + path : path);
			if (updatingHashTimeout) clearTimeout(updatingHashTimeout);
			updatingHashTimeout = setTimeout(function() {justUpdatingHash = false;}, 300);
		}
	}
	function navigateTo(path)
	{
		History.pushState(null, storedTitle, langPrefix ? '/' + langPrefix + path : path);
	}
	function stateChangeHandler()
	{
		var State = History.getState();
		currentPath = normalizePath(State.hash);
		if (!justUpdatingHash && !($.browser.msie && mouseIsDown))
		{
			if (CollectionGallery.opened) CollectionGallery.closeImage();
			var firstPart = normalizeFirstPart(State.hash);
			navigateToSection(firstPart);
			var otherParts = getOtherParts(State.hash);
			if (otherParts.length)
			{
				switch(firstPart)
				{
					case 'latorre-life':
						var $figure = $('#latorre-life > .content > div > figure.item-' + otherParts[0]);
						if ($figure.length)
						LatorreLife.openItem($figure, false);
						break;
				}
			}
		}
		updateNavHighlight(normalizeFirstPart(State.hash));
	}
	function normalizeFirstPart(hash)
	{
		var parts = normalizePath(hash).split('/');
		parts.shift();
		var section = parts[0];
		if (section == "") section = "home";
		return section;
	}
	function getOtherParts(hash)
	{
		var parts = normalizePath(hash).split('/');
		parts.shift();
		parts.shift();
		if (langPrefix) parts.shift();
		return parts;
	}
	var navHighlightAnimateOptions =
	{
		duration: 500,
		specialEasing: {marginLeft: 'easeInOutCubic', opacity: 'easeInOutCubic' },
		queue: false
	}
	var $highlightLink;
	function updateNavHighlight(section)
	{
		$highlightLink = null;
		$navLinks.each(function()
		{
			if (!$highlightLink)
			{
				$this = $(this);
				if (normalizePath($this.attr('href')) == "/" + section)
				$highlightLink = $this;
			}
		});
		if ($highlightLink)
		{
			$navHighlight.animate({left: $highlightLink.position().left + Number($highlightLink.css('margin-left').split('px').join('')), width: $highlightLink.width(), opacity: 1}, navHighlightAnimateOptions);
		}
		else
		{
			$navHighlight.animate({opacity: 0}, navHighlightAnimateOptions);
		}
	}
	
	function restoreHighlightPosition()
	{
		$navHighlight.stop();
		if ($highlightLink)
		{
			$navHighlight.css({left: $highlightLink.position().left + Number($highlightLink.css('margin-left').split('px').join('')) + 'px', width: $highlightLink.width() + 'px', opacity: 1}, navHighlightAnimateOptions);
		}
		else $navHighlight.css('opacity', 0);
	}
	
	function navigateToSection(section)
	{
		var target;
		if (section == 'home' && touchEnvironment)
		target = $('body > header');
		else target = $('#' + section);
		if (target.length) scrollToElement(target);
	}
	function pseudoLinkHandler(e)
	{
		var $this = $(this);
		if ($this.css('cursor') != 'default')
		{
			CollectionGallery.close();
			TeamGallery.close();
			LatorreLife.close();
			navigateTo($this.attr('href'));
		}
		return false;
	}
	
	var scrollInterval;
	var scrollEase = .33;
	var currentScroll;
	var scrollDest;
	
	function checkScroll()
	{
		if (!scrollDest)
		{
			currentScroll =
			scrollDest = (window.isIE ? document.documentElement.scrollTop : $window.scrollTop());
		}
	}
	
	function scroll(difference)
	{
		checkScroll();
		scrollingToElement = false;
		scrollTo(scrollDest + difference);
	}
	
	function scrollToElement($target)
	{
		scrollingToElement = true;
		var top = $target.ieCompatibleOffset().top;
		var height = $target.height();
		
		var futureHeaderHeight;
		var offset;
		if ($target.attr('id') == 'home')
		{
			futureHeaderHeight = isIOS ? 0 : EXPANDED_HEADER_HEIGHT;
			offset = 0;
		}
		else
		{
			futureHeaderHeight = isIOS ? 0 : COLLAPSED_HEADER_HEIGHT;
			offset = 1;
			if ($target.children('.costura-hard').length)
			offset += 1;
			else if ($target.children('.costura-soft').length)
			offset += 3;
		}
		var scrollTarget;
		if (isIOS)
		{
			scrollTarget = height < 850 ? top + offset : top + height / 2 - (windowHeight) / 2;
		}
		else
		{
			scrollTarget = height < 850 ? top + offset - futureHeaderHeight : top - futureHeaderHeight + height / 2 - (windowHeight - futureHeaderHeight) / 2;
		}
		scrollTarget -= (isIOS ? 0 : headerHeight)
		scrollTarget += futureHeaderHeight
		scrollTo(scrollTarget);
	}
	var animatingScroll = false;
	var scrollingToElement = false;
	var speed = 0;
	var MAX_ACCELERATION = 25;
	function scrollTo(target)
	{
		animatingScroll = true;
		checkScroll();
		scrollDest = target;
		if (scrollDest < 0)
		scrollDest = 0;
		else if (scrollDest > $document.height() - windowHeight)
		scrollDest = $document.height() - windowHeight;
		
		if (!scrollInterval)
		scrollInterval = setInterval( function()
		{
			var scrollDiff = (scrollDest - currentScroll) * scrollEase;
			var way = scrollDiff / Math.abs(scrollDiff);
			speed += MAX_ACCELERATION * way;
			if (Math.abs(scrollDiff) > Math.abs(speed))
			{
				scrollDiff = speed;
			}
			else
			{
				speed = scrollDiff;
			}
			currentScroll += scrollDiff;
			isAnimationStep = true;
			$window.scrollTop(currentScroll);
			isAnimationStep = false;
			if (Math.abs(currentScroll - scrollDest) < .5)
			{
				animatingScroll = false;
				scrollingToElement = false;
				currentScroll = scrollDest;
				clearInterval(scrollInterval);
				scrollInterval = undefined;
			}
		}, 1000/60);
	}
	function scrollHandler()
	{
		if (!animatingScroll)
		{
			scrollDest = currentScroll = (window.isIE ? document.documentElement.scrollTop : $window.scrollTop());
		}
		if (!scrollingToElement)
		{
			var $currentSection = getCurrentSection();
			updateHash($currentSection.attr('id'));
		}
	}
	function getCurrentSection()
	{
		var $nearestSection;
		var minDistance = 99999;
		$sections.each(function()
		{
			var $this = $(this);
			var top = $this.ieCompatibleOffset().top;
			var distance = Math.abs(currentScroll + (isIOS ? 0 : headerHeight) - top);
			if (distance < minDistance)
			{
				minDistance = distance;
				$nearestSection = $this;
			}
		});
		return $nearestSection;
	}
	function keyDownHandler(e)
	{
		var $newSection;
		var $currentSection;
		if (!CollectionGallery.opened)
		{
			switch (e.keyCode)
			{
				case 38:
					$currentSection = getCurrentSection();
					$newSection = $currentSection.prev();
					e.preventDefault();
					break;
				case 40:
					$currentSection = getCurrentSection();
					$newSection = $currentSection.next();
					e.preventDefault();
					break;
			}
			if ($newSection && $newSection.length > 0)
			{
				History.pushState(null, storedTitle, $newSection.attr('id'));
			}
		}
	}
})(jQuery)