jQuery(function($) {
  var historyApiIsEnabled = $.isFunction(history.pushState);

  $(document).on('click', 'a', function(event) {
    var $link = $(this);

    var url = getUrl($link);

    if (isLocalUrl(url)) {
      event.preventDefault();
      updateUrl(url);
    }
  });

  function getUrl($link) {
    return $link.attr('href');
  }

  function isLocalUrl(url) {
    return (url.indexOf('http') != 0);
  }

  function updateUrl(url) {
    if (historyApiIsEnabled) {
      history.pushState(url, document.title, url);
    }
    else {
      location.hash = '!' + url;
    }

    updateContent(url);
  }

  if (historyApiIsEnabled) {
    $(window).on('popstate', function(event) {
      var path = location.pathname;
      updateContent(path);
    });
  }
  else {
    var lastPath = null;
    var INTERVAL = 100;

    setInterval(function() {
      // Get path from URI fragment.
      // ex) "#!/about" -> "/about"
      var path = location.hash.slice(2);
      if (path != lastPath) {
        updateContent(path);
        lastPath = path;
      }
    }, INTERVAL);
  }

  /**
   * @param {String} pathText Abs path to be shown. ex: "/about", "/web/123"
   */
  function updateContent(pathText) {
    var path = (pathText ? pathText.slice(1).split('/') : []);
    var name = path[0];

    /*
     * `g_Carousel` is an instance of iCarousel.
     * See `iCarousel.js` and http://zend.lojcomm.com.br/icarousel/
     */
    var id = ({
      'about':   1,
      'system':  2,
      'web':     3,
      'inquiry': 4,
      '': 0
    })[name] || 0;

    (function() {
      // undefined on first time
      if (g_Carousel) {
        g_Carousel.goTo(id);

        if (name == 'web') {
          showWebContent(path[1]);
        }
      }
      else {
        setTimeout(arguments.callee, 100);
      }
    }());
  }

  function showWebContent(id) {
    // BK: Ignore cloned elements by iCarousel.
    var $webContainer = $('[id=item_web]').eq(1);

    $webContainer.find('.results_area_list .current')
      .removeClass('current');

    var $item = $webContainer
      .find('.results_area_list a[href="/web/' + id + '"]')
        .closest('.results_area');
    if ($item.length > 0) {
      showWebSlideshow($webContainer, $item);
      $item.addClass('current');
    }
    else {
      hideWebSlideshow($webContainer);
    }
  }

  function showWebSlideshow($webContainer, $item) {
    $webContainer.find('.slideshow_content')
      .empty()
      .append($item.clone());
    $webContainer
      .addClass('slideshow_mode')
      .find('.slideshow').slideDown();

    var $list = $item.closest('.results_area_list');
    var left = $item.position().left - $list.position().left + $list.scrollLeft();
    $list.scrollLeft(left);
  }

  function hideWebSlideshow($webContainer) {
    $webContainer
      .removeClass('slideshow_mode')
      .find('.slideshow').slideUp()
        .find('.slideshow-content').empty();
  }

  // Show content when dom is ready.
  // (URI fragment will be checked automaticaly.)
  if (historyApiIsEnabled) {
    updateContent(location.pathname);
  }
});

