$(document).ready(function() {
  var dropdown_open = false;
  var sync = false;

  var regexString = "https?://" + location.host + ".*";
  var regex = new RegExp(regexString);
  $('#site-dropdown li a').not('#site-dropdown li#change-language a').each(function(){
    if ($(this).attr("href").match(regex)) {
      $(this).parent().remove();
    } else {
      $(this).attr("href", function(){
        var newHref = this;
        newHref += location.pathname.substr(1);
        return newHref;
      });
      $(this).click(function(){
         var today = new Date();
         var expireDate = new Date();
         expireDate.setDate(today.getDate() + 365);
         var cookieOptions = { expiresAt: expireDate } // , domain: '.mozy.com' }
         var country = $(this).attr("id").match(/^country-([A-Z]+)$/)[1];
         $.cookies.set("country", country, cookieOptions);
      });
    }
  });

  $('#site-dropdown li#change-language').click(
    function(e) {
      e.preventDefault();
      if (dropdown_open) {
        $(this).siblings().fadeOut('fast');
        dropdown_open = false;
      } else {
        siblings = $(this).siblings();
        siblings.fadeIn('fast');
        focus_last_sibling(siblings.eq(siblings.length-1));
        dropdown_open = true;
        sync = true;
      }
    }
  );

  var last_sibling_check_count = 0;
  function focus_last_sibling(last) {
    last_sibling_check_count++;
    if (last.css('display') != 'list-item' && last.style != null && last_sibling_check_count <= 5) {
      setTimeout(function(){ focus_last_sibling(last) }, 50);
      return;
    }
    window.scrollTo(0, document.body.scrollHeight);
  }

  $('ul#site-dropdown').hover(
    function() {
      $(this).children('li#change-language').addClass('hover-over');
    },
    function() {
      $(this).children('li').not('#change-language').fadeOut('fast', function() {
        $(this).siblings('li#change-language').removeClass('hover-over');
        dropdown_open = false;
      });
    }
  );
});
