/*
 * jQuery Catalog Plugin
 * version: 1.00
 * @requires jQuery v1.2.2 or later
 *
 */
;(function($) {

$.catalogInit = function() {
  var is_first_run = ($.cookie('expanded_ids') == null);
  var category_cookie = function(id, value) {
    if (value == undefined && is_first_run) {
      //category_cookie(id, true);
      //return true;
      return false;
    }

    var list = $.cookie('expanded_ids') == null ? [''] : $.cookie('expanded_ids').split(',');
    var exist = false;

    for (var i = 0; i < list.length; i++) {
      if (list[i] == id) {
        exist = true; break;
      }
    }
    if (value == undefined) {
      return exist;
    }
    if (value && !exist) {
      $.cookie('expanded_ids', $.cookie('expanded_ids') + ',' + id, {path: '/', expires: 1, domain: '.setwatch.ru'});
    }
    if (!value && exist) {
      new_cookie = '';
      for (var i = 0; i < list.length; i++) {
        if (list[i] == id) {
          continue;
        }
        new_cookie = new_cookie + ',' + list[i];
      }
      $.cookie('expanded_ids', new_cookie, {path: '/', expires: 1, domain: '.setwatch.ru'});
    }
  }
  var category_click = function() {
    var id = $(this).attr('id').replace('cat', '');
    var subcats = $(this).parent().next('div.els');
    if ($(this).hasClass('opened')) {
      $(this).removeClass('opened');
      subcats.slideUp(500);
      category_cookie(id, false);
    } else {
      $(this).addClass('opened');
      subcats.slideDown(500);
      category_cookie(id, true);
    }
    return false;
  }
  var category_init = function() {
    var id = $(this).find('> div.tit > a').attr('id').replace('cat', '');
    var subcats = $(this).find('> div.els');
    if (subcats.length) {
      if (category_cookie(id)) {
        $(this).find('> div.tit > a').addClass('opened').click(category_click);
      } else {
        subcats.hide();
        $(this).find('> div.tit > a').removeClass('opened').click(category_click);
      }
      subcats.find('> div.el').each(category_init);
    }
  }

  var base = $('#catalog');
  base.find('div.el').each(category_init);
  base.removeClass('hidden');
};

})(jQuery);
