I've modified your code. See inline comments. See the entire code here and the LIVE DEMO.
$('.subitems').hide();
// check cookie
checkCookie();
function checkCookie() {
// the cookie exists
if($.cookie('mainlevel')) {
var index = $.cookie('mainlevel');
$(".mainitem:eq(" + index + ")").find("ul").show();
}
}
// click on .mainitem
$('.mainitem').click(function() {
// get the index
var cookie = $(this).index();
// hide all subitems
$(".mainitem").find("ul").slideUp();
// toggle the ul that is in the clicked item
$(this).find('ul').toggle(function() {
// save the cookie
$.cookie('mainlevel', [cookie], { expires: 30 });
});
// toggle if change happend :: thanks @lolotron
if (previousValue != cookie) {
$(".mainitem").find("ul").slideUp();
$(this).find('ul').slideDown();
}
});