﻿/*
===================================
Global vars
===================================
*/
var external = false;

/*
===================================
On Dom Ready
===================================
*/

$jQuery(document).ready(function () {
  $jQuery('.ImageGalleryCarousel').infiniteImageCarousel();
  $jQuery('.Carousel').infiniteCarousel();

  //preventSelect();

  fixingTopMenu();
  easing();

  externalAnchorJump();
  sectionPosition();
  sectionPositionSubPageReturn();

  //pointerPosition();

  removeLink();
  rssFeeding();
  rolloverLinks();
  clickableSplash();
  clearInputField();
  evenHeights(4, '.SummaryList li');
  evenHeights('all', '.RelatedCases ul.List li');
  evenHeights('all', '.CarouselSpot ul.List li');
  animateLevelNavigation();
  addRoundedCorners();
  headerContraSectionMenu();
  decorateMainMenu();
  mainMenuWidth();
  hideEmptyContentTopBlock();
});

/*
===================================
Functions
===================================
*/

function sectionPosition() {
  $jQuery('.NavigationMainMenu a').click(function () {
    var MainNavPos = $jQuery('.NavigationMainMenu').offset().top;
    var url = $jQuery(this).attr('href');
    //alert(url);
    $jQuery(this).parent().parent().find('.Active').removeClass('Active');
    var thisHash = '#' + url.replace('/', '').replace('#', '');
    $jQuery(this).parent().addClass('Active');
    if (MainNavPos < 300) {
      $jQuery.scrollTo(thisHash, 500, { offset: { top: -100, left: 0} });
    } else {
      $jQuery.scrollTo(thisHash, 500, { offset: { top: -39, left: 0} });
    }
    return false;
  });
};

function sectionPositionSubPageReturn() {
  var HashInUrl = window.location.hash;
  if (HashInUrl) {
    if (HashInUrl != '#Cases') {
      $jQuery.scrollTo(HashInUrl, 500, { offset: { top: -39, left: 0} });
    }
    if(HashInUrl == '#Cases') {
      $jQuery.scrollTo(HashInUrl, 500, { offset: { top: -100, left: 0} });
    }
    //window.location.hash = '';
    //window.location.hash.replace('#', '');
    //window.location.pathname.replace('/', '');
  }
};



function easing() {
  $jQuery(".ImageGallerySpot .Image").lightBox();

  //Easing class
  $jQuery.easing.elasout = function (x, t, b, c, d) {
    var s = 1.70158; var p = 0; var a = c;
    if (t == 0) return b; if ((t /= d) == 1) return b + c; if (!p) p = d * .3;
    if (a < Math.abs(c)) { a = c; var s = p / 4; }
    else var s = p / (2 * Math.PI) * Math.asin(c / a);
    return a * Math.pow(2, -10 * t) * Math.sin((t * d - s) * (2 * Math.PI) / p) + c + b;
  };

  $jQuery.easing.easeInOutSine = function (x, t, b, c, d) {
    return -c / 2 * (Math.cos(Math.PI * t / d) - 1) + b;
  };

  $jQuery.easing.easeOutSine = function (x, t, b, c, d) {
    return c * Math.sin(t / d * (Math.PI / 2)) + b;
  };
};

function fadeOutOtherSections() {
  var thisSection = window.location.hash.substr(1);
  $jQuery('.Section:not(.Section' + thisSection + ')').css({ opacity: 0.2 });
  setTimeout(function () {
    $jQuery(window).scroll(function () {
      $jQuery('.Section').fadeTo('fast', 1.0);
    });
  }, 1000);

}

function externalAnchorJump() {
  fadeOutOtherSections();
}

function removeLink() {
  $jQuery('.NoLink a').css('cursor', 'default');
  $jQuery('.NoLink a .Title').css('color', 'inherit');

  $jQuery('.NoLink a').click(function (e) {
    e.preventDefault();
    $jQuery(this).css('cursor', 'default');
  });
};

function preventSelect() {
  $jQuery('.Carousel .Paging .Forward, .Carousel .Paging .Back').mousedown(function () {
    return false;
  });
};

function fixingTopMenu() {
  //Attach TopMenu to top of page on scroll
  var isSiteRoot = window.location.pathname == '/';
  if (isSiteRoot) {
    var standardHeaderRegion = $jQuery('.StandardHeaderRegion');
    var topHeader = standardHeaderRegion.offset().top;
    topHeader += $jQuery('.StandardHeaderRegion').height();

    $jQuery(window).scroll(function () {
      var y = $jQuery(this).scrollTop();
      // whether that's below the form
      if (y >= topHeader) {

        // if so, add the fixed class
        standardHeaderRegion.addClass('Locked');
      } else {
        // otherwise remove it
        standardHeaderRegion.removeClass('Locked');
      }
    });
  }

};

function rssFeeding() {
  // Select all elements that have an "RSS URL" attribute and have zRSSFeed display RSS content in them.
  var rssAnchors = $jQuery('.RssUrl');
  for (var i = 0; i < rssAnchors.length; i++) {
    var rssAnchor = rssAnchors[i];
    var rssFeedUrl = rssAnchor.href;
    $jQuery(rssAnchor).rssfeed(rssFeedUrl, { limit: 1, header: false, date: false });
  }
};

function rolloverLinks() {
  //RolloverLinks: Has to be done as a jQuery due to Chrome issues with mouseover
  $jQuery('.RolloverLinks img').hover(function () {
    var src = $jQuery(this).attr('src').replace('.', '-hover.');
    $jQuery(this).attr('src', src);
  }, function () {
    var hoverSrc = $jQuery(this).attr('src').replace('-hover.', '.');
    $jQuery(this).attr('src', hoverSrc);
  });
};

function clickableSplash() {
  $jQuery(this).click(function (event) {
    var target = $jQuery(event.target);
    if (target.is('.ImageTextSpot') && !target.is('.Section .ImageTextSpot') && !target.is('.RightColumn .ImageTextSpot')) {
      window.location = target.find('a').attr('href');
    }
  });
};

function clearInputField() {

  //Clear preentered value in input
  $jQuery('.SubscribeBox input').click(function () {
    var defaultValue = $jQuery(this).val();
    $jQuery(this).val('');
    $jQuery(this).focus(function () {
      if ($jQuery(this).val() == defaultValue)
        $jQuery(this).val('');
    });
    $jQuery(this).blur(function () {
      if ($jQuery(this).val() == '')
        $jQuery(this).val(defaultValue);
    });
  });
};

function evenHeights(elementsPerRow, selector) {
  //remove the non-javascript infused height
  $jQuery(selector).css('height', 'auto');

  //Assure same height in each row as the heighst element
  var maxHeight = 0, currentElements;

  if (elementsPerRow == 'all') {
    elementsPerRow = selector.length;
  }

  $jQuery(selector).each(function (elementIndex, element) {
    if (elementIndex % elementsPerRow == 0) {
      maxHeight = 0;
      currentElements = [];
    }
    currentElements.push(element);

    maxHeight = Math.max(maxHeight, $jQuery(this).height());

    //add Rss and abstract to the height if they exsist.
    if ($jQuery(this).find('.RssContainer').length > 0) {
      maxHeight += $jQuery(this).find('.RssContainer').height();
      if ($jQuery(this).find('.Abstract').html().length > 0) {
        maxHeight += $jQuery(this).find('.Abstract').height();
      } else {
        $jQuery(this).find('.Abstract').remove();
        maxHeight += 50;
      }
    }
    $jQuery(currentElements).height(maxHeight);
  });

  var carouselDiv = $jQuery(selector).parent().parent().parent();
  if (carouselDiv.attr('class') == 'Carousel') {
    carouselDiv.css('height', maxHeight + 21);
  }
  carouselDiv.find('.CaseContent, Content').css('height', maxHeight + 20);
};

function animateLevelNavigation() {
  //Shorten the link text if it is more then 40 character long
  $jQuery('.CaseTitle a').each(function () {
    var linkText = $jQuery(this).html();
    var lengthOfLink = linkText.length;
    if (lengthOfLink > 32)
      $jQuery(this).text(linkText.substring(0, 32) + '...');
  });

  //Levelnavigation
  $jQuery('.LevelNavigation .PreviousCase').hover(function () {
    var thisDiv = $jQuery(this);
    thisDiv.stop().animate({ width: 310 + 'px' }, 400);
    $jQuery('.NextCase .CaseTitle').css('display', 'none');
    $jQuery('.PreviousCase .CaseTitle').css('display', 'block');
    thisDiv.parent().find('.NextCase').stop().animate({ width: 39 + 'px' }, 400);

  }, function () {
    var thisDiv = $jQuery(this);
    thisDiv.stop().animate({ width: 39 + 'px' }, 400);
    thisDiv.parent().find('.NextCase').stop().animate({ width: 310 + 'px' }, 400);
    $jQuery('.PreviousCase .CaseTitle').css('display', 'none');
    $jQuery('.NextCase .CaseTitle').css('display', 'block');
  });

  $jQuery('.LevelNavigation .PreviousCase, .LevelNavigation .NextCase').hover(function () {
    $jQuery(this).find('label, a').css('color', '#d7ecf7');
  }, function () {
    $jQuery(this).find('label, a').css('color', '#fff');
  });

  $jQuery('.LevelNavigation .PreviousCase, .LevelNavigation .NextCase').click(function () {
    var link = $jQuery(this).find('a').attr('href');
    window.location = link;
  });
};

function addRoundedCorners() {
  $jQuery('.Section .LeftColumn .Content').addClass('RoundedCorners');
};

function headerContraSectionMenu() {
  var maxWidth, widthOfSectionMenu, widthOfDocumentHeader;
  if ($jQuery('.Section').attr('class') == 'Section') {
    $jQuery('.SectionTopBlock').each(function () {

      maxWidth = $jQuery('.SectionTopBlock').width();
      widthOfSectionMenu = $jQuery('.SectionTopBlock .NavigationSectionMenu').width();
      widthOfDocumentHeader = $jQuery('.SectionTopBlock .DocumentHeader').width();

      if ((widthOfSectionMenu / maxWidth) > 0.6 || (widthOfDocumentHeader / maxWidth) > 0.6 || ((widthOfDocumentHeader + widthOfSectionMenu) / maxWidth) >= 0.95) {
        $jQuery('.SectionTopBlock .DocumentHeader').css('margin-top', '13px');
      }
    });
  }
  maxWidth = $jQuery('.BodyTopBlock').width();
  widthOfSectionMenu = $jQuery('.BodyTopBlock .NavigationSectionMenu').width();
  widthOfDocumentHeader = $jQuery('.BodyTopBlock .DocumentHeader').width();

  if ((widthOfSectionMenu / maxWidth) > 0.6 || (widthOfDocumentHeader / maxWidth) > 0.6 || ((widthOfDocumentHeader + widthOfSectionMenu) / maxWidth) >= 0.95) {
    $jQuery('.BodyTopBlock .DocumentHeader').css('margin-top', '13px');
  }
};

function decorateMainMenu() {
  var hash = window.location.hash;
  var isHash = hash != ' ';

  if (isHash) {
    $jQuery('.AnchorMainMenu ul').children().each(function () {
      var anchor = $jQuery(this).children(':first-child').attr('href');
      if (anchor.substr(1, 20) == hash) {
        $jQuery(this).addClass('Active');
      }
    });
  }
};

function mainMenuWidth() {
  //from default the mainmenu is 585, mainmenu ul is 352, and the servicemenu is 148
  var serviceWidth = $jQuery('.NavigationServiceMenu').width();
  var totalWidth = $jQuery('.NavigationMainMenu ul').width();

  var totalWidthLi = 0;
  $jQuery('.NavigationMainMenu ul li').each(function () {
    totalWidthLi += $jQuery('.NavigationMainMenu li').width() + 24;
  });

//  if (totalWidth > totalWidthLi) {
//    $jQuery('.NavigationMainMenu ul').css('width', totalWidthLi);
//  } else {
//    $jQuery('.NavigationMainMenu ul').css('width', totalWidth);
//  }
  if (serviceWidth > 148) {
    $jQuery('.NavigationMainMenu').css('width', 585 - (serviceWidth - 148));
  }
};

function hideEmptyContentTopBlock() {
  var thisContentTopBlock = $jQuery('.StandardBodyRegion .ContentColumn .ContentTopBlock');
  var str = thisContentTopBlock.html();
  str = $jQuery.trim(str);
  if (str.length == 0) {
    thisContentTopBlock.css('display', 'none');
  }
};


function ValidateLogin(e) {
  var loginEvent = new AnalyticsPageEvent("Login", "Login spot, login button pressed.");
  if ($jQuery('#Login').val() == "" || $jQuery('#Password').val == "") {
    alert('Both fields must be filled');
    e.preventDefault();
  }
  try {
    loginEvent.trigger();
  }
  catch (err) {
    alert("Error occured " + err);
  }
}
