$(document).ready(function(){
  $('ul#menu li a').each(function(i){
    if ($.cookie('sm-opened-link-' + i)){
			$(this).removeClass('collapsed').addClass('expanded').next().show();
		}else {
			$(this).removeClass('expanded').addClass('collapsed').next().hide();
		}
    if ($.cookie('sm-active-link-' + i)){
      $(this).addClass('active');
    }
  });
  $('ul#menu li a').each(function(i){
    var this_a_index = $('ul#menu li a').index($(this));
    if ($(this).next().is('ul')){
      // ссылка, раскрывающая подменю
      $(this).click(function(){
        if ($(this).next().css('display') == 'none'){
          $('ul#menu li a').each(function(other_a_index){
            if (other_a_index != this_a_index && $(this).next().is('ul')){
              $(this).next().slideUp(400, function(){
                $(this).prev().removeClass('expanded').addClass('collapsed');
                $.cookie('sm-opened-link-' + other_a_index, null, {expires: null, path: '/'});
              });
            }
          });
          $(this).next().slideDown(400, function(){
            $(this).prev().removeClass('collapsed').addClass('expanded');
            $.cookie('sm-opened-link-' + this_a_index, 'opened', {expires: null, path: '/'});
          });
        }else {
          $(this).next().slideUp(400, function(){
            $(this).prev().removeClass('expanded').addClass('collapsed');
            $.cookie('sm-opened-link-' + this_a_index, null, {expires: null, path: '/'});
          });
        }
      });
    }else {
      // обычная ссылка
      $(this).click(function(){
        if ($(this).parent('li').parent('ul').is('#menu')){
          $('ul#menu li a').each(function(other_a_index){
            if ($(this).next().is('ul')){
              $.cookie('sm-opened-link-' + other_a_index, null, {expires: null, path: '/'});
            }
          });
        }
        $('ul#menu li a').each(function(other_a_index){
          $.cookie('sm-active-link-' + other_a_index, null, {expires: null, path: '/'});
        });
        $.cookie('sm-active-link-' + this_a_index, 'clicked', {expires: null, path: '/'});
      });
    }
  });
});
