﻿
jQuery.fn.exists = function () { return jQuery(this).length > 0; }

jQuery(document).ready(function () {

    var s = document.location.toString();
    var $NavIndicator = jQuery('#NavIndicator');
    jQuery("#mainNavigation li a").each(function () {
        var href = jQuery(this).attr("href");
        if (s.indexOf(href.toString()) != -1) {
            jQuery(this).addClass("selected");
        }
    });

    var hasSelectedNav = jQuery("#mainNavigation li a.selected").exists();
    var $selectedItem;
    var tranistionSpeed = 400;
    var hasClicked = false;


    if (hasSelectedNav) {
        $selectedItem = $("#mainNavigation li a.selected");
        var pos = $("#mainNavigation li a.selected").position();
        var navAdjustment = $("#mainNavigation li a.selected").outerWidth() / 2;
        var indicatorPos = pos.left + navAdjustment - 8;
        $NavIndicator.show().css('left', indicatorPos);
    };

    jQuery("#mainNavigation li a").hover(
          function () {
              $NavIndicator.show();
              if (hasSelectedNav) {
                  $selectedItem.removeClass('selected');
              }
              var newPosition = $(this).position().left + ($(this).outerWidth() / 2) - 8;
              $NavIndicator.stop().animate({ left: newPosition, opacity: 1 }, tranistionSpeed);
          },
          function () {
              if (!hasClicked) {
                  if (hasSelectedNav) {
                      $selectedItem.addClass('selected');
                      $NavIndicator.stop().animate({ left: indicatorPos, opacity: 1 }, tranistionSpeed);
                  } else {
                      $NavIndicator.stop().animate({ opacity: 0 }, tranistionSpeed);
                  }
              }

          }
        ).click(function () {
            hasClicked = true;
            jQuery(this).addClass('selected');
        });

});
