$(document).ready(function(){
  
  function Categories(names, cur){
    var a = {};
    for(var i in names)
      a[i] = [];

    if(location.hash){
      var hash = location.hash.substring(1);
      for(var i in names){
        if(hash == i){
          cur = i;
          break;
        }
      }
    }

    this.add = function(n,item){
      a[n].push(item);
    }

    this.each = function(f){
      for(var i in a){
        for(var j in a[i]){
          var e = a[i][j];
          f(e,i,cur);
        }
      }
    }

    this.eachc = function(f){
      for(var i in a){
        f(i,names[i],cur);
      }
    }

    this.set = function(cur_){
      cur = cur_;
    }

  }

  function CategoriesView(cats){
    var holder = $('#phone_nav'),
        selected;

    cats.eachc(function(i,n,c){
      new Link(i,n,(c==i));
    });

    function Link(id,name,sel){
      var e = $('<a href="#'+id+'">'+name+'</a>');
      holder.append(e);
      this.e = e;
      if(sel){
        e.addClass('sel');
        selected = e;
      }
      e.click(function(){
        cats.set(id);
        selected.removeClass('sel');
        selected = e;
        e.addClass('sel');
        cats.each(showHide);
      });
    }
  }


  var cats = new Categories({
    iphone4 : 'Стикеры для iPhone 4',
    iphone5 : 'Стикеры для iPhone 5',
    iphone : 'Другие стикеры',
    oboi : 'Обои',
  },'iphone4');

  function showHide(e,curcat,selcat){
    if(curcat != selcat)
      e.hide();
    else
      e.show();    
  }


  var catse = new CategoriesView(cats);

  $('.booklet li').each(function(){
    var me = $(this),
      title = me.find('.title').text().toLowerCase();

    if(title.indexOf('стикер') == -1){
      cats.add('oboi',me);
    }
    else{
      if(title.indexOf('5') == -1){
        if(title.indexOf('4') == -1)
          cats.add('iphone',me);
        else
          cats.add('iphone4',me);
      }
      else
        cats.add('iphone5',me);
    }

    cats.each(showHide);

  });
});    
