jQuery.fn.paginator_for = function(params, ttl_pages, url) {
  var container = this.find('.list-wrapper');
  var spin = this.find(".spinner");
  var user_container;
  var activePage;
  var total_pages = ttl_pages - 1;
  var prev_button;
  var next_button;
  var show_dots;
  var url = url;

  var users = formatUsers(params.users);
  buildUI();

  function prevPage() {
    setPage(activePage - 1);
  }
  function nextPage() {
    setPage(activePage + 1);
  }
  function setPage(num) {
    if (num != activePage) {
      activePage = num;

      // show or hide left or right arrow if the page is first or last
      if (num == total_pages) {
        next_button.hide();
      } else {
        next_button.show();
      }
      if (num == 0) {
        prev_button.hide();
      } else {
        prev_button.show();
      }

			if (typeof users[num] === 'undefined') {
				spinner(true);
        $.ajax({
	  			url:url.replace(escape(":page"), num + 1),
					type:'GET',
					datatype:'json',
					success: function(req) {
						users[num] = req.users;
						appendUsers(users[num], num);
						spinner(false);
					},
				});
			} else {
				appendUsers(users[num], num);
			}
    }
  }

	function spinner(show) {
		if (show) {
			container.animate({opacity:0.25}, {duration:200});
			spin.show();
		} else {
			container.animate({opacity:1.0}, {duration:200});
			spin.hide();
		}
	}

  function appendUsers(list, num) {	
    user_container.html(createUsersLi(list));
    if (show_dots) {
      container.find('a.dot.current').removeClass('current');
      container.find("a.dot:eq("+num+")").addClass('current');
    }
	}

  function formatUsers(userlist) {
	  var users = new Array();
	  users[0] = userlist; 
    return users;
  }

  function buildUI() {
    var html = "";
    html += "<a class='list_btn prev' href='#'>&laquo;</a>";
    html += "<ul class='noList clearfix usersList'></ul>";
    html += "<a class='list_btn next' href='#'>&raquo;</a>";
    show_dots = total_pages > 0;
    if (show_dots) {
      html += "<div class='dots'>";
      for (var i = 0; i <= total_pages; i++) {
        html += " <a href='#' class='dot'>&bull;</a>";
      }
      html += "</div>"
    }
    container.html(html);
    user_container = container.find("ul.noList");

    prev_button = $(container).find("a.prev");
    prev_button.click(function() {
      prevPage();
      return false;
    });
    next_button = $(container).find("a.next");
    next_button.click(function() {
      nextPage();
      return false;
    });
    if (show_dots) {
      $(container).find("a.dot").click(function() {
        setPage($(container).find("a.dot").index($(this)));
        return false;
      });
    }

    setPage(0);
  }

  function createUsersLi(people) {
    var result = '';
    for (var i in people) {
      var person = people[i];
      result += '<li class="loading">';
      result += "<a class='qtip profile_list' rel='/" + person.login + "' href='/" + person.login + "' title='" + person.login + "'>"
      result += "<img class='avatar' src='" + person.avatar_url + "' alt='" + person.login + "' width='64' height='64' onLoad='$(this).parent().parent().removeClass(\"loading\")'/>"
      result += "</a>";
      result += '</li>';
    }
    return result;
  }
};

$.extend({
  getUrlVars: function(){
    var vars = [], hash;
    var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');
    for(var i = 0; i < hashes.length; i++)
    {
      hash = hashes[i].split('=');
      vars.push(hash[0]);
      vars[hash[0]] = hash[1];
    }
    return vars;
  },
  getUrlVar: function(name){
    return $.getUrlVars()[name];
  }
});

function prepareUserToolTips(parent){
  // тултипчик над чувачками
  if (!$.browser.msie) {
    $(parent).find('img.avatar[title]').not('.winner img.avatar[title], #menu img, .widgetsContainer img').bt({
      positions:["top","right"],
      animate:true,
      distance:-10,
      shadow:false,
      strokeWidth:1,
      strokeStyle:'#bbb',
      wrapperzIndex: 11000,
      fill:'rgb(245,245,245)',
      cssStyles: {width:"auto"},
      offsetParent: 'body'
    })
  }
}
function updateUserToolTips(elements){
  if (!$.browser.msie) {
    $(elements).each(function(){
      var str = '#'+$(this).attr('id');
      $(str).find('img.avatar[title]').not('.winner img.avatar[title], #menu img, .widgetsContainer img').bt({
        positions:["top","right"],
        animate:true,
        distance:-10,
        shadow:false,
        strokeWidth:1,
        strokeStyle:'#bbb',
        wrapperzIndex: 11000,
        fill:'rgb(245,245,245)',
        cssStyles: {width:"auto"},
        offsetParent: 'body'
      })
    });
  }
}
$(document).ready(function(){
  $('.commentMeta .commenterLogin').click(function() {
    insert_login("<b>" + $(this).text() + "</b>");
    return false;
  });
  $('#clubMembersSwitch').click(function(){
    $('.clubMembersList').slideToggle(350);
    if(!$('#moderators').length){
      jQuery.ajax({
        url: 'http://' + document.location.host + document.location.pathname + '/info',
        type: 'get',
        success: function(request){
          $('.clubMembersList').addClass('done').html(request);
        }
      });
    }
  });
    
  $('.qtip[rel]:not("#menu .qtip, .widgetsContainer .qtip")').live('click', function(){
    var tip=new roundTip({
      header: $(this).find("img").attr('alt'),
      content: '<div class="tooltip_spinner"><img src="/images/spinner_light.gif" alt="Загрузка"/></div>',
      button: 'профиль',
      link: $(this).attr('rel'),
      id: 'userToolTip',
      remoteURL: $(this).attr('rel'),
      caller: $(this),
      onUpdate: function(){
        $('#'+this.id).find('dt a').hover(function(){
          $(this).parent().addClass('hover');
        },function(){
          $(this).parent().removeClass('hover');
        });
      }
    });
    tip.show();
    return false;
  });

  prepareUserToolTips('body');

  //chemoney tooltip TODO
  $('.sidebar .chemoney a, .sidebar .points a').hover(function(){
   $(this).parent().addClass('hover');
  }, function(){
   $(this).parent().removeClass('hover');
  });
  $('.chemoney').click(function(){
   return false; 
  });
   
  // FAQ TODO
  $(".faq").nextAll().hide();
  $(".faq").click(function() {
    $(this).nextAll().slideToggle(250);
    return false;
  });
  $(".close_all_faq").click(function() {
    $(".faq").nextAll(':visible').slideToggle(250);
    return false;
  });
  
  $('.flash-message').bt({
    contentSelector: "$(this).attr('title')",
    trigger: "none",
    positions: ["top"],
    animate: true,
    distance: -10,
    shadow: false,
    strokeWidth: 1,
    strokeStyle: '#000',
    fill: 'rgb(245,245,245)',
    cssStyles: {width: "auto"},
    cssClass: 'flashError',
    clickAnywhereToClose: false,
    shrinkToFit: true,
    offsetParent: 'body'
    });
  $('.flash-message').btOn();
});

function debit(amount, text) {
  $('.chebucksValue > span').text(parseInt($('.chebucksValue > span').text()) + parseInt(amount));
  if (text) {
    jQuery.noticeAdd({text: text, stayTime: 20000});
  }
  return false;
}
function credit(amount, text) {
  $('.chebucksValue > span').text(parseInt($('.chebucksValue > span').text()) - parseInt(amount));
  if (text) {
    jQuery.noticeAdd({text: text, stayTime: 20000});
  }
  return false;
}
function decPoints(amount, text) {
  $('.pointsValue span').text(parseInt($('.pointsValue span').text()) - parseInt(amount));
  if (text) {
    jQuery.noticeAdd({text: text, stayTime: 20000});
  }
  return false;
}
function incPoints(amount, text) {
  $('.pointsValue span').text(parseInt($('.pointsValue span').text()) + parseInt(amount));
  if (text) {
    jQuery.noticeAdd({text: text, stayTime: 20000});
  }
  return false;
}
function removePointsLink() {
  $('dt.points a').replaceWith('<span>Поинты:</span>');
  return false;
}

//set toolTips for achievements
var setAchTooltips = function(){
  $('.achTooltip').appendTo('body');
  $('.achTooltip h2:contains("-"), .achievment td:contains("-")').each(function(){
    var txt=$(this).html();
    txt = txt.replace('-','-&#8203;');
    $(this).html(txt);
  });
  $(".achievment").each(function(){
    $(this).tooltip({
      tip: $('.achTooltip')[$(".achievment").index(this)],
      effect: 'slide',
      position: 'bottom right',
      offset: [-100, 0]
    });
  });
};

function remove_fields(link) {
  $(link).prev("input[type=hidden]").val("1");
  $(link).closest("li").fadeOut(200);
}
function edit_fields(link) {
  expose=$('#descriptionBox').add($(link).closest('li')).expose({
    color: '#fff',
    opacity: 0.8,
    loadSpeed: 'fast',
    onBeforeClose: function(event){
      $('#descriptionBox').remove();
      linkExps=false;
    },
    api: true
  });
 
  var cont='<div id="descriptionBox"><div id="descHeader">&nbsp;</div><div id="descInner"><textarea id="descriptionArea" rows="3" cols="20">Напишите же сюда остроумный комментарий</textarea></div></div>';
  $('#descriptionBox').remove();
  var offset = $(link).closest('li').offset();
  $('body').append(cont);
  $('#descriptionBox').css({
    position: 'absolute',
    left: offset.left + $(link).closest('li').width() -6 + 'px',
    top: offset.top + 'px',
    display: 'none',
    zIndex: 10000
  });
  $('#descriptionArea').addClass('hint');
  $('#descriptionArea').focus(function(){
    if($(this).val()=='Напишите же сюда остроумный комментарий'){
      $(this).val('');
      $(this).removeClass('hint');
    }
  });
  var oldDesc = $(link).closest('li').find("input:hidden[id$='description']").val();
  if(oldDesc != ''){
    $('#descriptionArea').val(oldDesc);
    $('#descriptionArea').removeClass('hint');
  }
  $('#descriptionBox').append('<a href="#" id="saveDesc" title="сохранить">&nbsp;</a>');
  $('#saveDesc').click(function(){
    $(link).closest('li').find("input:hidden[id$='description']").val($('#descriptionArea').val());
    if(expose.isLoaded()){
      expose.close();
      $(link).closest('li').removeClass('active');
    }
    return false;
  });
  $('#descHeader').append('<a href="#" id="closeDesc" title="закрыть">&nbsp;</a>');
  $('#closeDesc').click(function(){
    if(expose.isLoaded()){
      expose.close();
      $(link).closest('li').removeClass('active');
    }
    return false;
  });
  $('#descriptionBox').fadeIn(200, function(){
    $('#descriptionArea').resizable({
      maxHeight: 300,
      minHeight: 100,
      minWidth: 210,
      maxWidth: 210,
      handles: 'se'
    });
  });
  $(link).closest('li').addClass('active');
  expose.load();
  linkExps=true;
  $('.photoPostImgCont .controls').hide();
}
var linkExps=false;
$(document).ready(function() {
  //make photo thumbnails sortable during post edit
  $(".photoPostImgCont.edit").sortable({
    items: 'li',
    tolerance: 'pointer',
    update: function(event, ui) {
      update_photo_pos();
    },
    start: function(event, ui) {
      ui.item.addClass('drag');
    },
    stop: function(event, ui) {
      ui.item.removeClass('drag');
    }
  });
  
  //adding hover controls and shadow
  $('.photoPostImgCont.edit li').hover(function(){
    if(!linkExps){
      $(this).addClass('hover');
      $(this).find('.controls').show();
    }
  },function(){
    $(this).removeClass('hover');
    $(this).find('.controls').hide();
  });
  $(".photo_field dt").disableSelection();

  set_photo_scroll($('.post'));

  //set big photo switch
  $(".photoPostImgCont li").live('click', function(){
    if($(this).hasClass('edit')) return false;
    $(this).siblings().removeClass('active');
    $(this).addClass('active');
    var url = $(this).find(".photoPostSmall").attr('rel');
    var urlFull = $(this).find(".photoPostSmall").attr('rel_full');
    var title = $(this).find(".photoPostSmall").attr('title');
    var photos=$(this).parents('.photos');
    var photo_big=$(photos).find('.bigImg img');
    if($(photo_big).attr('src') == url){
      return false;
    }
    $(photo_big).closest('.bigImg').fadeOut(function(){
      $(photo_big).closest('.photoWrapper').append('<img class="photoSpinner" src="/images/spinner_light.gif" />');
      $(photo_big).attr('src', url);
      $(photo_big).parent().attr('href', urlFull);
      $(photo_big).unbind('load').bind('load', function(){
        $(photos).find('.photoSpinner').remove();
        updatePhotoDims(photo_big);
        $(photo_big).closest('.bigImg').fadeIn(200);
      });
    });
    if($.trim(title) != ''){
      $(photos).find('.photoDesc').html(title).show();
    }else{
      $(photos).find('.photoDesc').hide();
      $(photos).find('.photoDesc').empty();
    }
    $(photo_big).attr('title', $(this).attr('title'));
  });
  set_photo_center($('.post'));
  $('.bigImg a').live('click', function(){
    $('#galleryBig').remove();
    $('body').append('<div id="galleryBig"><img id="galleryBigPic" src="'+$(this).attr('href')+'" style="visibility: hidden;"/><a id="galleryNext"><span>вперед</span></a><a id="galleryPrev"><span>назад</span></a></div>');
    $('#galleryBig').append('<div id="bigPhotoDescription"><div id="bigPhotoDescriptionText">'+$(this).parent().parent().next().html()+'</div></div>');
    $('#galleryBig').append('<img id="gallerySpinner" class="photoSpinner" src="/images/spinner_light.gif" />');
    var top = ($(window).height() - 200) / 2 + $(window).scrollTop();
    var left = ($(window).width() - 200) / 2 + $(window).scrollLeft();
    $('#galleryBig').css({
      width: 200,
      height: 200,
      background: '#fff',
      position: 'absolute',
      top: top,
      left: left,
      zIndex: 100000
    });
    $('#galleryBig').expose({
      color: '#fff',
      opacity: 0.8,
      loadSpeed: 'fast',
      onBeforeClose: function(event){
        $('#galleryBigPic').parent().remove();
      },
      api: true
    }).load();
    $('#galleryBigPic').load(function(){
      updateBigPhotoDims(this);
    });
    if(document.getElementById('galleryBigPic').complete){
      $('#galleryBigPic').trigger('load');
    }
    $('#galleryBigPic').click(function(){
      if($(this).parent().expose().isLoaded()){
        $(this).parent().expose().close();
      }
    });
    var scroll = $(this).closest('.photos').find('.photoCont');
    if(scroll.length == 1){
      scroll.data('si', $(this).closest('.photos').find('li').index($(this).closest('.photos').find('li.active')));
      switchImgNav(scroll.data('si'), scroll.find('img.photoPostSmall').length);
      $('#galleryPrev').unbind('click').click(function(){
        var scrollIndex = scroll.data('si');
        var images = scroll.find('img.photoPostSmall:eq('+(scrollIndex-1)+')')
        if(images.length){
          scrollIndex -= 1;
          scroll.data('si', scrollIndex);
          $('#bigPhotoDescription').fadeOut(200);
          $('#galleryBigPic').fadeOut(200, function(){
            if($('#gallerySpinner').length == 0){
              $('#galleryBig').append('<img id="gallerySpinner" class="photoSpinner" src="/images/spinner_light.gif" />');
            }
            $('#galleryBigPic').attr('src', $(images[0]).attr('rel_full'));
            $('#bigPhotoDescriptionText').html($(images[0]).attr('title'));
          });
        }
        switchImgNav(scrollIndex, scroll.find('img.photoPostSmall').length);
        return false;
      });
      $('#galleryNext').unbind('click').click(function(){
        var scrollIndex = scroll.data('si');
        var images = scroll.find('img.photoPostSmall:eq('+(scrollIndex+1)+')')
        if(images.length){
          scrollIndex += 1;
          scroll.data('si', scrollIndex);
          $('#bigPhotoDescription').fadeOut(200);
          $('#galleryBigPic').fadeOut(200, function(){
            if($('#gallerySpinner').length == 0){
              $('#galleryBig').append('<img id="gallerySpinner" class="photoSpinner" src="/images/spinner_light.gif" />');
            }
            $('#galleryBigPic').attr('src', $(images[0]).attr('rel_full'));
            $('#bigPhotoDescriptionText').html($(images[0]).attr('title'));
          });
        }
        switchImgNav(scrollIndex, scroll.find('img.photoPostSmall').length);
        return false;
      });
    }else{
      switchImgNav(0, 0);
    }
    return false;
  });
  $('#photoProgress').hover(function(){
    $('#photoProgress, #photoAdd').addClass('hover');
  },function(){
    $('#photoProgress, #photoAdd').removeClass('hover');
  });
  function switchImgNav(scrollIndex, imgTotal){
    if(scrollIndex == 0 || imgTotal == 0){
      $('#galleryPrev').addClass('disabled');
    }else{
      $('#galleryPrev').removeClass('disabled');
    }
    if(imgTotal - scrollIndex == 1 || imgTotal == 0){
      $('#galleryNext').addClass('disabled');
    }else{
      $('#galleryNext').removeClass('disabled');
    }
  }
});
function set_photo_scroll(objects){
  //set scrollable if where are enough photos
  $(objects).each(function(){
    var str = '#'+$(this).attr('id');
    if($(str).find(".photoScrollCont li").length > 5){
      $(str).find(".photoScrollCont .photoCont").each(function(){
        $(this).scrollable({
          nextPage: '.scroll.right',
          prevPage: '.scroll.left',
          size: 4,
          hoverClass: 'hover',
          onBeforeSeek: function(){
            $('a.scroll').blur();
          },
          keyboard: false,
          api: true
        });
      });
    }else{
      $(str).find('.photoPostImgCont li').hover(function(){
        $(this).addClass('hover');
      },function(){
        $(this).removeClass('hover');
      });
    }
  });
}
function set_photo_center(objects){
  $(objects).each(function(){
    var str = '#'+$(this).attr('id');
    $(str).find('.bigImg img').each(function(){
      if(this.complete){
        updatePhotoDims(this);
      }else{
        $(this).unbind('load').load(function(){
          $(this).parents().find('.photoSpinner').remove();
          updatePhotoDims(this);
          $(this).fadeIn(200);
        });
      }
    });
  });
}
function update_photo_pos(){
  $(".photoPostImgCont li input:hidden[id$='position']").each(function(){
    $(this).val($(".photoPostImgCont li input:hidden[id$='position']").index(this)+1);
  });
}
function updatePhotoDims(el){
  $(el).closest('.bigImg').css({
    marginTop: ($(el).closest('.photoWrapper').height()-$(el).closest('.bigImg').outerHeight())/2 + 'px',
    marginLeft: ($(el).closest('.photoWrapper').width()-$(el).closest('.bigImg').outerWidth())/2 + 'px'
  });
}
function updateBigPhotoDims(el){
  if($(el).outerHeight() > $(window).height()){
    $(el).css({
      height: $(window).height() - 20
    });
  }
  if($(el).outerWidth() > $(window).width()){
    $(el).css({
      width: $(window).width() - 20
    });
  }
  var width=$(el).outerWidth();
  var height=$(el).outerHeight();
  $('#galleryBig').stop().animate({
    width: width,
    height: height,
    top: ($(window).height() - height) / 2 + $(window).scrollTop(),
    left: ($(window).width() - width) / 2 + $(window).scrollLeft()
  },200, 'linear', function(){
    $('#gallerySpinner').remove();
    $('#galleryBigPic').css({visibility: 'visible'}).fadeIn(200);
    if($.trim($('#bigPhotoDescription').text()) != ""){
      $('#bigPhotoDescription').fadeIn(200);
    }
  });
}

//make outer links open in new tab/window
$(document).ready(function(){
  var regExp = /^(http|ftp|https):\/\/(?!(www\.)*cheloveche.ru).*$/;
  $('.postContent a, .commentContent a, .restrictBox a').each(function(){
    if(regExp.test($(this).attr('href'))){
      $(this).attr('target', '_blank');
    }
  });
});

//comment links
$(document).ready(function(){
  $('.mainBody').delegate('.commentsLink a.total, .commentsLink a.more, .conversationCount a.total, .conversationCount a.more', 'hover', function(){
    $(this).parent().toggleClass('hover');
  });
  $('.mainBody').delegate('.commentsLink span.new a, .conversationCount span.new a', 'hover', function(){
    $(this).parent().parent().toggleClass('hover_new');
  });
  $('.endless').delegate('.commentsCount a.more, .conversationCount a.more', 'hover', function(){
    $(this).parent().toggleClass('hover');
  });
});

//a lot of room
var showcase;
$(document).ready(function(){
  if($('#roomShop').length){
    if($('#roomShop').hasClass('character')){
      var shopMode='wear';
    }else{
      var shopMode='unit';
    }
    showcase = {
      init: function(initType){
        if(initType==undefined) var initType='full';
        //***set handlers***
        var inits ={
          depsList: function(){
            $('#depsList').empty();
            var tags = ['all'];
            for(m in showcase.config.tags[showcase.config.mode]){
              $('#depsList').append('<li class="'+m+' all">Все</li>');
              $('#depsList li:last').data('active', true);
              $('#depsList li:last').data('catTag', 'all');
              for(n in showcase.config.tags[showcase.config.mode][m]){
                var multiCatTag = false;
                if(typeof showcase.config.tags[showcase.config.mode][m][n] == 'object'){
                  for(nm in showcase.config.tags[showcase.config.mode][m][n]){
                    var className = m+' '+nm;
                    multiCatTag = showcase.config.tags[showcase.config.mode][m][n];
                  }
                }else{
                  var className = m+' '+showcase.config.tags[showcase.config.mode][m][n];
                }
                var textName = showcase.config.names[showcase.config.mode][m][n];
                $('#depsList').append('<li class="'+className+'">'+textName+'</li>');
                var lastLi=$('#depsList li:last');
                if(multiCatTag){
                  var catTag = multiCatTag;
                }else{
                  var catTag = showcase.config.tags[showcase.config.mode][m][n];
                }
                lastLi.data('catTag', catTag);
                var isActive = false;
                if(!multiCatTag && showcase.data[lastLi.data('catTag')] != undefined && showcase.data[lastLi.data('catTag')].length != 0){
                  isActive = true;
                }
                if(multiCatTag){
                  for(var nm in multiCatTag){
                    for(var j=0; j<multiCatTag[nm].length; j++){
                      if(showcase.data[multiCatTag[nm][j]] != undefined && showcase.data[multiCatTag[nm][j]].length != 0){
                        isActive = true;
                        break;
                      }
                    }
                  }
                }
                if(!isActive){
                  lastLi.addClass('inactive');
                  lastLi.data('active', false);
                }else{
                  lastLi.data('active', true);
                }
              }
            }

            //menu bg animations
            $('#depsList li').unbind('mouseenter mouseleave');
            $('#depsList li').hover(function(){
              if(!$(this).hasClass('active')){
                $(this).animate({backgroundColor: '#c2cdd3'}, {duration: 200, queue: false});
              }
            },function(){
              if(!$(this).hasClass('active')){
                $(this).animate({backgroundColor: '#ffffff'}, {duration: 600, queue: false});
              }
            });
            $('#depsList li').unbind('click').click(function(event){
              if(!$(this).hasClass('active') && $(this).data('catTag') && $(this).data('active')){
                if($(this).data('catTag')=='all'){
                  var catTag=$('#depsTabs li.active').data('tabTag');
                }else{
                  var catTag=$(this).data('catTag');
                }
                showcase.updateType(catTag);
                flash=document.getElementById('flashcontent');
                try{
                  if(typeof catTag == 'object'){
                    for(nm in catTag){
                      catTag=nm;
                    }
                  }
                  if(showcase.config.mode == 'unit'){
                    flash.setRoomKind(catTag);
                  }
                  if(showcase.config.mode == 'wear'){
                    flash.setWearKind(catTag);
                  }
                }catch(e){
                }
              }
              return false;
            });
          },
          pics: function(){
            //remove spinner on image load
            $('.showcaseList li > img').each(function(){
              if(this.complete){
                $(this).parent().addClass('loaded');
              }else{
                $(this).unbind('load').load(function(){
                  $(this).parent().addClass('loaded');
                });
              }
            });
            $('.showcaseList li').unbind('mouseenter mouseleave');
            $('.showcaseList li').hover(function(){
              if(!$(this).hasClass('active')){
                $(this).find('.showcaseInfo').fadeIn(400);
                $(this).find('.showcasePrice').fadeOut(200);
              }
            },function(){
              if(!$(this).hasClass('active')){
                $(this).find('.showcaseInfo').fadeOut(200);
                $(this).find('.showcasePrice').fadeIn(400);
              }
            });
          },
          scrollPageNum: function(){
            var scroll=$('#showcaseWrapper').scrollable();
            $('#showcasePageNum').html(scroll.getPageIndex()+1+' из '+scroll.getPageAmount());
            if(scroll.getPageAmount()==1){
              $('#showcasePageSW .next').addClass('disabled');
            }else if(scroll.getPageIndex()+1 != scroll.getPageAmount()){
              $('#showcasePageSW .next').removeClass('disabled');
            }
          },
          common: function(){
            
            //scrollable showcase
            var scroll = $('#showcaseWrapper').scrollable({
              size: 1,
              onSeek: function(){
                inits.scrollPageNum();
              },
              clickable: false,
              api: true,
              keyboard: false
            });
            $('#depsTabs').parent().removeClass();
            if(showcase.config.allowedTabs[showcase.config.mode].length == 3) {
              $('#depsTabs').parent().addClass('triple');
            }
            $('#depsTabs').parent().addClass(showcase.config.mode);

            $('#depsTabs').empty();
            
            for(n in showcase.config.allowedTabs[showcase.config.mode]){
              $('#depsTabs').append('<li class="'+showcase.config.allowedTabs[showcase.config.mode][n]+'">'+showcase.config.allowedTabsNames[showcase.config.mode][n]+'</li>');
              $('#depsTabs li:last').data('tabTag', showcase.config.allowedTabs[showcase.config.mode][n]);
            }

            $('#depsTabs li').unbind('click').click(function(){
              showcase.switchDeps($(this).data('tabTag'));
              return false;
            });
            $('#depsList, .showcaseDetails').disableSelection();

            $('#showcasePageSW .next, #showcasePageSW .prev').hover(function(){
              $(this).addClass('hover');
            },function(){
              $(this).removeClass('hover');
            });
            
            //set info link to display info window
            $('.showcaseList a.showcaseInfo').live('click', function(){
              showcase.expose();
              showcase.showInfoBox($(this).parent());
              return false;
            });
            
            //set item click to buy
            $('#showcaseMover li img').live('click', function(){
              showcase.flashBuy($(this).parent().attr('rel'), 1);
              return false;
            });
            
            $('#showcaseExpose, #showcaseInfoBox .dialogClose').live('click', function(){
              showcase.hideInfoBox();
              return false;
            });

            //store chebux
            showcase.data['chebux'] = parseInt($('.chebucksValue > span').text());
          },
          chebux: function(){
            $('.showcaseList .showcasePrice span').each(function(){
              if($(this).text != 'FREE' && parseInt($(this).text()) > parseInt(showcase.data['chebux'])){
                $(this).parent().addClass('toMuch');
                $(this).closest('li').addClass('disabled');
              }else{
                $(this).parent().removeClass('toMuch');
                $(this).closest('li').removeClass('disabled');
              }
            });
          }
        };
        if(initType=='full'){
          inits.depsList();
          inits.common();
        }
        else if(initType=='scrollUpdate'){
          inits.scrollPageNum();
          inits.pics();
        }
        else if(initType=='chebux'){
          inits.chebux();
        }
      },
      showInfoBox: function(parent){
        var object=showcase.data['all'][$(parent).attr('rel')];
        if(object){
          $(parent).addClass('active');
          $(parent).find('.showcaseInfo').fadeOut(200);
          $('#showcaseInfoBox').hide();
          var offset=$(parent).position();
          var offset2=$(parent).parent().parent().position();
          $('#showcaseInfoBox').css({
            top: offset.top+25+'px',
            left: offset.left+offset2.left+240+85+25+'px',
            zIndex: 9999
          });
          $('#showcaseInfoBox .dialogButton').unbind('mouseenter mouseleave');
          $('#showcaseInfoBox .dialogButton').hover(function(){
            $(this).addClass('hover');
          },function(){
            $(this).removeClass('hover');
          });

          $('#showcaseInfoBox .dialogButton a').unbind('click').click(function(){
            if(!$('#showcaseInfoBox .presentCheck').hasClass('checked')){
              showcase.flashBuy(object.id, parseInt($('#showcaseInfoBox .quantCounter .quant').html()));
              showcase.hideInfoBox();
            }else{
              if($('#presenteeName').val()=='' || $('#presenteeName').val()=='укажите получателя'){
                alert('укажите получателя подарка');
              }else{
                showcase.flashBuy(object.id, parseInt($('#showcaseInfoBox .quantCounter .quant').html()), $('#presenteeName').val(), $(this).parent().parent().find('textarea.presentText').val());
                showcase.hideInfoBox();
              }
            }
            return false;
          });
          $('#showcaseInfoBox .dialogHeader div').html(object.name);
          $('#showcaseInfoBox .detailsPrice div').html(object.price);
          $('#showcaseInfoBox .quantCounter .quant').html(1);
          $('#showcaseInfoBox .showcaseDesc').html(object.description);
          $('#showcaseInfoBox .showcaseBigPicImg').attr({
            'src': '/flash/libs/swf/'+showcase.config.picPath[showcase.config.mode]+'/'+object.kind+'/'+object.path+'.png',
            'alt': object.name
          });
          $('#showcaseInfoBox .showcaseBigPicFrame').attr({
            'alt': object.name
          });
          var ratingStyles=['zero', 'one', 'two', 'three', 'four', 'five'];
          $('#showcaseInfoBox .detailsRating div span').removeClass('one two three four five').addClass(ratingStyles[object.rating]);
          
          showcase.updateChebuxDis();
          
          //quantity
          if(showcase.config.mode=='wear'){
            $('.detailsQuantity').addClass('single');
            $('.detailsQuantity a').unbind('click').click(function(){
              return false;
            });
          }else{
            $('.detailsQuantity .quantCounter .quantLower').unbind('click').click(function(){
              if(parseInt($(this).next().html())!=1){
                $(this).next().html(parseInt($(this).next().html())-1);
              }
              $('#showcaseInfoBox .detailsPrice div').html(object.price*parseInt($(this).next().html()));
              showcase.updateChebuxDis();
              return false;
            });
            $('.detailsQuantity .quantCounter .quantHigher').unbind('click').click(function(){
              if(parseInt($(this).prev().html())!=5){
                $(this).prev().html(parseInt($(this).prev().html())+1);
              }
              $('#showcaseInfoBox .detailsPrice div').html(object.price*parseInt($(this).prev().html()));
              showcase.updateChebuxDis();
              return false;
            });
          }
          
          //present
          $('#showcaseInfoBox .presentCheck').removeClass('checked');
          $('#showcaseInfoBox .showcasePresent').hide();
          $('#showcaseInfoBox .presentCheck').unbind('click').click(function(){
            if(!$(this).hasClass('disabled')){
              $('#showcaseInfoBox .presentCheck').toggleClass('checked');
              if($(this).hasClass('checked')){
                $('#showcaseInfoBox .showcasePresent').show("blind", {direction:"vertical"}, 300);
              }else{
                $('#showcaseInfoBox .showcasePresent').hide("blind", {direction:"vertical"}, 300);
              }
            }else{
              jQuery.noticeAdd({text: 'На вашем счете недостаточно челобаксов для подарочка!', stayTime: 5000});
            }
            return false;
          });
          $('#presenteeName').addClass('hint').val('укажите получателя');
          $('#presenteeName').unbind('focus').focus(function(){
            if($(this).val()=='укажите получателя'){
              $(this).removeClass('hint').val('');
            }
          });
          $('#presenteeName').unbind('blur').blur(function(){
            if($(this).val()==''){
              $(this).addClass('hint').val('укажите получателя');
            }
          });
          $('.presentText').addClass('hint').val('напишите сопроводительный текст');
          $('.presentText').unbind('focus').focus(function(){
            if($(this).val()=='напишите сопроводительный текст'){
              $(this).removeClass('hint').val('');
            }
          });
          $('.presentText').unbind('blur').blur(function(){
            if($(this).val()==''){
              $(this).addClass('hint').val('напишите сопроводительный текст');
            }
          });
          $('#presenteeName').autocomplete('/user_suggest/', {
            autoFill: false,
            minChars: 2,
            delay: 400,
            highlight: false
          });
          $('#showcaseInfoBox').appendTo('#roomShop').fadeIn('200');
        }
      },
      hideInfoBox: function(){
        $('#presenteeName').unautocomplete();
        $('.ac_results').remove();
        $('#showcaseExpose, #showcaseInfoBox').fadeOut('400');
        $('.showcaseList li').removeClass('active');
        $('.showcaseList li').find('.showcasePrice:hidden').fadeIn(400);
      },
      expose: function(opacity, spinner){
        if(opacity==undefined) var opacity=0.85;
        if($('#showcaseExpose').length==0){
          var offset=$('#roomShop').offset();
          var expose=document.createElement('div');
          expose.id="showcaseExpose";
          $(expose).css({
            background: 'white',
            opacity: opacity,
            position: 'absolute',
            top: 0,
            left: 0,
            zIndex: 666,
            width: $('#roomShop').outerWidth(),
            height: $('#roomShop').outerHeight(),
            display: 'none'
          });
          if(spinner!=undefined && spinner){
            $(expose).append('<img src="/images/spinner_tool_tip.gif" style="position: absolute; left: 50%; top: 50%; margin-left: -17px; margin-top: -17px;" />');
          }
          $(expose).appendTo('#roomShop').fadeIn(200);
        }else{
          $('#showcaseExpose').show();
        }
      },
      loadData: function(){
        $.ajax({
          url: showcase.config.path[showcase.config.mode],
          dataType: 'json',
          success: function(data){
            showcase.data=showcase.prepareData(data);
            showcase.init();
            $('#showcaseExpose').hide(200).remove();
            $('#depsTabs li:first').trigger('click');
          },
          error: function(){
            alert('Не получилось загрузить данные. Попробуйте обновить страничку.');
          }
        });

      },
      switchDeps: function(tabTag){
        if(tabTag == undefined){
          if(showcase.config.mode == 'room'){
            tabTag = 1;
          }else{
            tabTag = 0;
          }
          tabTag = showcase.config.allowedTabs[showcase.config.mode][tabTag];
        }

        if(showcase.data != undefined){
          $('#depsTabs li').removeClass('active');
          $('#depsTabs li.'+tabTag).addClass('active');
          $('#depsList li').hide();
          $('#depsList .'+tabTag).show();
          $('#depsList li').removeClass('active');
          $('#depsList li:visible:first').trigger('click');
          flash=document.getElementById('flashcontent');
          try{
            if(showcase.config.mode == 'unit'){
              flash.setRoomDep(tabTag);
            }
            if(showcase.config.mode == 'wear'){
              flash.setWearDep(tabTag);
            }
          }catch(e){
          }
        }
      },
      updateType: function(catTag){
        var data = Array();
        if($.inArray(catTag, showcase.config.allowedTabs[showcase.config.mode]) != -1){
          catTag='all';
        }
        var tabTag=$('#depsTabs li.active').data('tabTag');
        if(typeof catTag == 'object'){
          for(var nm in catTag){
            for(var i=0; i<catTag[nm].length; i++){
              if(showcase.data[catTag[nm][i]] != undefined){
                data=data.concat(showcase.data[catTag[nm][i]]);
              }
            }
            var catTagName=nm;
          }
        }else{
          data=showcase.data[catTag];
          if(catTag=='all'){
            data=showcase.data[tabTag]['novelty'].concat(showcase.data[tabTag]['not_novelty']);
          }
          var catTagName=catTag;
        }
        if(data.length && $('#depsList li.'+catTagName).length){
          $('#depsList li').stop().removeClass('active').css({backgroundColor: '#ffffff'});
          $('#depsList li.'+catTagName).addClass('active').css({backgroundColor: '#000'});

          $('#showcaseWrapper').scrollable().seekTo(0);

          $('#showcaseMover').empty();
          $('#showcaseMover').append('<ul class="showcaseList">');
          for(i=0; i<data.length/12; i++){
            if(i) $('#showcaseMover').append('<ul class="showcaseList">');
            var len=12;
            if(data.length<12){ len=data.length; }
            else if(data.length-(12*(i+1))<0){len=data.length-(12*i);}
            var liStr = '';
            for(j=0; j<len; j++){
              if(data[j+i*12].price > showcase.data['chebux']){
                var className='showcasePrice toMuch';
              }else{
                var className='showcasePrice';
              }
              if(data[j+i*12].price==0){
                var price='FREE';
                var className='showcasePrice free';
              }else{
                var price=data[j+i*12].price;
              }
              if(data[j+i*12].bought){
                var bought='<img class="bought" src="/images/room/bought.png" alt="Куплено" title="Уже куплено" />';
                className="showcasePrice bought";
              }else{
                var bought='<span>'+price+'</span>';
              }
              liStr += '<li rel="'+data[j+i*12].id+'"><img title="'+data[j+i*12].name+'" src="/flash/libs/swf/'+showcase.config.picPath[showcase.config.mode]+'/'+data[j+i*12].kind+'/'+data[j+i*12].path+'_small.png"/><a href="#" class="showcaseInfo">&nbsp;</a><div class="'+className+'">'+bought+'</div></li>';
            }
            $('#showcaseMover .showcaseList:eq('+i+')').html(liStr);
          }
          showcase.init('scrollUpdate');
        }
      },
      prepareData: function(data){
        var new_data=Array();
        for (var i in showcase.config.allowedTabs[showcase.config.mode]){
          var tab = showcase.config.allowedTabs[showcase.config.mode][i];
          new_data[tab]=Array();
          new_data[tab]['novelty']=Array();
          new_data[tab]['not_novelty']=Array();
          new_data['all']=Array();
        }
        var tabTags=Object();
        for(var m in showcase.config.allowedTabs[showcase.config.mode]){
          var tab = showcase.config.allowedTabs[showcase.config.mode][m];
          tabTags[tab]=Array();
          var tags = showcase.config.tags[showcase.config.mode][tab];
          for(var j=0; j<tags.length; j++){
            if(typeof tags[j] == 'object'){
              for(obj in tags[j]){
                tabTags[tab] = tabTags[tab].concat(tags[j][obj]);
              }
            }else{
              tabTags[tab].push(tags[j]);
            }
          }
        }
        for(i=0; i<data.length; i++){
          if((data[i][showcase.config.mode].id != 185 && data[i][showcase.config.mode].id != 186 && data[i][showcase.config.mode].id != 187) || showcase.config.mode != 'wear'){
            var arr={
              id: data[i][showcase.config.mode].id,
              name: data[i][showcase.config.mode].name,
              novelty: data[i][showcase.config.mode].novelty,
              path: data[i][showcase.config.mode].path,
              price: data[i][showcase.config.mode].price,
              rating: data[i][showcase.config.mode].rating,
              kind: data[i][showcase.config.mode].kind,
              description: data[i][showcase.config.mode].description,
              color1: data[i][showcase.config.mode].color1,
              color2: data[i][showcase.config.mode].color2,
              align: data[i][showcase.config.mode].align,
              sex: data[i][showcase.config.mode].sex,
              colors: data[i][showcase.config.mode].colors,
              mode: data[i][showcase.config.mode].mode,
              level: data[i][showcase.config.mode].level,
              mask: data[i][showcase.config.mode].mask,
              age: data[i][showcase.config.mode].age,
              bought: data[i][showcase.config.mode].bought
            };
            if(!new_data[data[i][showcase.config.mode].kind]){
              new_data[data[i][showcase.config.mode].kind]=Array();
            }
            new_data[data[i][showcase.config.mode].kind].push(arr);
            new_data['all'][data[i][showcase.config.mode].id]=arr;
            var inTab=false;
            for (var o in showcase.config.allowedTabs[showcase.config.mode]){
              var tab = showcase.config.allowedTabs[showcase.config.mode][o];
              if($.inArray(data[i][showcase.config.mode].kind, tabTags[tab]) != -1){
                var inTab = tab;
                break;
              }
            }
            if(inTab){
              if(data[i][showcase.config.mode].novelty){
                new_data[inTab]['novelty'].push(arr);
              }else{
                new_data[inTab]['not_novelty'].push(arr);
              }
            }
          }
        };
        return new_data;
      },
      flashBuy: function(object, quantity, presentee, pr_message ){
        object=showcase.data['all'][object];
        if(parseInt(object.price)*quantity <= showcase.data['chebux']){
          if(pr_message == undefined) var pr_message='';
          if(!presentee){
            if(!object.bought){
              flash=document.getElementById('flashcontent');
              if(showcase.config.mode=='unit'){
                try{
                  flash.addRoomObject(object.id, object.price, quantity, object.kind, object.path, object.name, object.description, object.color1, object.color2, object.align);
                  showcase.data['chebux'] = showcase.data['chebux']-object.price;
                  showcase.init('chebux');
                }catch(e){
                  alert('Что-то сломалось в магазине комнаты. Попробуйте перезагрузить страничку.');
                }
              }else if(showcase.config.mode=='wear'){
                try{
                  flash.addAvatarObject(object.path, object.level, object.mode, object.mask, object.colors, object.age, object.name, object.id, object.sex, object.kind, object.price, 1);
                  showcase.data['chebux'] = showcase.data['chebux']-object.price;
                  showcase.init('chebux');

                }catch(e){
                  alert('Что-то сломалось в магазине персонажа. Попробуйте перезагрузить страничку.');
                }
              }
            }
          }else{
            var idName = showcase.config.mode+"_id";
            var data = {
              count: quantity,
              login: presentee,
              message: (pr_message == 'напишите сопроводительный текст') ? '' : pr_message
            };
            if(showcase.config.mode=='wear'){
              data.wear_id = object.id;
            }else{
              data.unit_id = object.id;
            }
            jQuery.noticeAdd({text: 'Подарочек упаковывается и&nbsp;отправляется.', stayTime: 5000});
            $.ajax({
              type: 'POST',
              url: '/users/'+presentee+'/'+showcase.config.giftPath[showcase.config.mode],
              data: data,
              success: function(data, textStatus, XMLHttpRequest){
                var code=$(data).find('code').text();
                if(code != undefined && code==0){
                  credit($(data).find('chebucks').text(), 'Подарочек отправлен! С твоего счета ' +spellNumeric('челобакс', $(data).find('chebucks').text(), 'списан')+'.');
                  showcase.data['chebux'] = showcase.data['chebux']-parseInt($(data).find('chebucks').text());
                  flash=document.getElementById('flashcontent');
                  try{
                    flash.updateBalance(parseInt($(data).find('chebucks').text()));
                  }catch(e){
                  }
                }else if(code != undefined && code==1){
                  jQuery.noticeAdd({text: 'Получатель подарочка не найден. Нет такого пользователя.', stayTime: 20000});
                }
                else if(code != undefined && code==1){
                  jQuery.noticeAdd({text: 'Нет никакого подарочка, %username%. Объект не найден.', stayTime: 20000});
                }
              },
              error: function(XMLHttpRequest, textStatus, errorThrown){
                jQuery.noticeAdd({text: 'Не получилось подарить подарочек. Что-то неведомое с сервером.', stayTime: 20000});
              },
              dataType: 'xml'
            });
          }
        }else{
          jQuery.noticeAdd({text: 'На вашем счете недостаточно челобаксов для покупки!', stayTime: 5000});
        }
        return false;      
      },
      updateChebuxDis: function(){
        if(parseInt($('#showcaseInfoBox .detailsPrice div').text()) + 1 <= showcase.data['chebux']){
          $('#showcaseInfoBox .presentCheck').removeClass('disabled');
        }else{
          if($('#showcaseInfoBox .presentCheck').hasClass('checked')){
            $('#showcaseInfoBox .presentCheck').click();
          }
          $('#showcaseInfoBox .presentCheck').addClass('disabled');
        }
      },
      updateBalance: function(amount){
        showcase.data['chebux']=showcase.data['chebux']+parseInt(amount);
        showcase.init('chebux');
        showcase.updateChebuxDis;
      },
      data: null,
      config: {
        allowedTabs: {
          unit: Array('furniture', 'renew'),
          wear: Array('image', 'cloth', 'misc')
        },
        allowedTabsNames: {
          unit: Array('Интерьер', 'Ремонт'),
          wear: Array('Имидж', 'Одежда', 'Разное')
        },
        tags: {
          unit: {
            renew: Array('wall', 'door', 'floor', 'window', 'back'),
            furniture: Array('san', 'appliance', 'table', 'sofa', 'skap', 'light', 'electro', 'decor', 'entertain')
          },
          wear: {
            image: Array({hairstyle: ['hair', 'crewcut']}, {beard_and_mustaches: ['beard', 'bristle']}, 'makeup', {figure_and_tattoo: ['figure', 'tattoo']}, 'glasses', {piercings: ['earrings', 'piercing']}),
            cloth: Array('shirt', {lower_cloths: ['pants', 'underpants']}, 'hat', {shoes_and_socks: ['shoes', 'socks']},  {accessories: ['neck', 'torso', 'waist', 'hands']}),
            misc: Array('hobby', 'food', 'pet')
          }
        },
        names: {
          unit: {
            renew: Array('Стены', 'Двери', 'Напольные покрытия', 'Окна', 'За окном'),
            furniture: Array('Сантехника', 'Бытовые приборы', 'Столы и тумбы', 'Стулья, кресла, диваны', 'Шкафы и комоды', 'Освещение', 'Электроника', 'Декоративные элементы', 'Развлечения')
          },
          wear: {
            image: Array('Прически', 'Усы и бороды', 'Макияж и грим', 'Фигура и татуировки', 'Аксессуары лица', 'Пирсинг'),
            cloth: Array('Верх одежды', 'Низ одежды', 'Головные уборы', 'Обувь',  'Аксессуары'),
            misc: Array('Интересы', 'Еда и напитки', 'Дружочки')
          }
        },
        path: {
          unit: '/units.json',
          wear: '/wears.json'
        },
        picPath: {
          unit: 'room',
          wear: 'avatar'
        },
        giftPath: {
          unit: 'unit_gift',
          wear: 'gift'
        },
        mode: shopMode
      }
    };
    //showcase.loadData();
  };
});
var switchStore = function(mode){
  if(mode == undefined) { mode = 'unit'; }
  if($('#roomShop:visible').length){
    $('#showcaseExpose').remove();
    $('#roomShop').hide("blind", {direction:"vertical"}, 200);
    showcase.data = false;
  }else{
    $('#roomShop').show("blind", {direction:"vertical"}, 200, function(){
      showcase.config.mode = mode;
      showcase.loadData();
    });
    showcase.expose(1,true);
  }
  return false;
};

var updateAvatar = function(){
  var login = $('.sidebar img.avatar').attr('src');
  $('img.avatar[@alt="'+login+'"]').each(function(){
    var path = $(this).attr('src');
    path = path.replace(/(\d{10})$/, Math.round(new Date().getTime()/1000));
    $(this).attr('src', path);
  });
}

function spellNumeric(text, number, pretext){
  number = number+'';
  if(text == undefined || number == undefined) return false;
  if(text == 'человек'){
    if((number == 2 || number.substr(-1) == 2 || number.substr(-1) == 3 || number.substr(-1) == 4) && number != 12 && number.substr(-2) != 12 && number != 13 && number.substr(-2) != 13 && number != 14 && number.substr(-2) != 14){
      var text = 'человека';
    }else{
      var text =  'человек';
    }
  }
  if(text == 'челобакс'){
    if((number == 2 || number.substr(-1) == 2 || number.substr(-1) == 3 || number.substr(-1) == 4) && number != 12 && number.substr(-2) != 12 && number != 13 && number.substr(-2) != 13 && number != 14 && number.substr(-2) != 14){
      var text = 'челобакса';
      var atext = 'о';
    }else if ((number == 1 || number.substr(-1) == 1) && number != 11 && number.substr(-2) != 11){
      var text =  'челобакс';
      var atext = '';
    }else {
      var text =  'челобаксов';
      var atext = 'о';
    }
  }
  if(pretext){
    text = pretext+atext+' '+number+' '+text;
  }
  return text;
}

//qtip for sidemenu buttons
$(document).ready(function(){
  $('.btn_tooltip').appendTo('body');
  updateBlackTips('body');
});
function updateBlackTips(parent){
  $(parent).find(".sidebarMenu li a, .boxTitle .user_actions a, .clubButtons li a, #widgets_panel img, #widgetPanelSwitch, .socialButton a, .unsee").not('.modalDialog a').each(function(){
    var title=$(this).attr('title');
    var config = {
      tip: $('.btn_tooltip'),
      delay: '0',
      predelay: '300',
      position: 'top center',
      offset: [6, 5],
      onBeforeShow: function(){
        $('.btn_tooltip').empty().append('<div class="btn_tooltip_inner"><div class="btn_tooltip_text"><span>'+title+'</span></div></div>');
      },
      events: { 
        tooltip:  ""
      }
    };
    if (!$.browser.msie) {
      config.effect = 'fade';
    }
    $(this).tooltip(config);
  });
}

$(document).ready(function(){
  $('#chebucksTooltip').appendTo('body');
  $('#chebucksTooltip li').hover(function(){
    $(this).addClass('hover');
  }, function(){
    $(this).removeClass('hover');
  });
  var config = {
    tip: $('#chebucksTooltip'),
    delay: '0',
    predelay: '300',
    position: 'bottom center',
    api: true,
    events: {
      def: "click,none",
      tooltip: "mouseover"
      },
    offset: [3, 47]
  };
  if (!$.browser.msie) {
    config.effect = 'fade';
  }
  var api = $('.sidebar .chemoney a').tooltip(config);
  $('#chebucksTooltip .dialogClose').click(function(){
    api.hide();
    return false;
  });
});

roundTip = function(options){
  this.options={
    id: 'roundTip',
    caller: 'body',
    button: 'кнопка',
    header: 'сообщение',
    content: 'Важное сообщение!',
    onClose: function(){},
    onConfirm: function(){},
    onInit: function(){},
    onUpdate: function(){},
    link: false,
    expose: false,
    remoteURL: false,
    offset: {left: 0, top: 0}
  };
  if(options != undefined){
    $.extend(this.options, options);
  }
  this.init = function(){
    $('#'+this.options.id).remove();

    var object=this;
  
    var div=document.createElement('div');
    div.id=this.options.id;
    div.className='modalDialog';
  
    var header=document.createElement('div');
    header.className='dialogHeader';
  
    var close=document.createElement('a');
    close.className='dialogClose';
    close.href='#';

    $(close).click(function(){object.close();return false;});
  
    var headText=document.createElement('div');
    $(headText).html(this.options.header);
  
    $(header).append(close);
    $(header).append(headText);
    $(div).append(header);

    var wrapper=document.createElement('div');
    wrapper.className='dialogContentWrapper'
  
    var content=document.createElement('div');
    content.className='dialogContent'
  
    $(content).html(this.options.content);
    $(wrapper).append(content);
    $(div).append(wrapper);
  
    var button=document.createElement('div');
    button.className='dialogButton';
    $(button).hover(function(){
      $(this).addClass('hover');
    },function(){
      $(this).removeClass('hover');
    });
  
    var confirm=document.createElement('a');
    $(confirm).text(this.options.button);
    if(this.options.link){
      confirm.href=this.options.link;
    }else{
      confirm.href='#';
      $(confirm).click(function(){object.confirm();return false;});
    }
  
    $(button).append(confirm);
    $(div).append(button);

    $('body').append(div);
  
    $(window).scroll(function(){object.updatePosition();});
    $(window).resize(function(){object.updatePosition();});
  
    if(this.options.remoteURL){
      jQuery.ajax({
        url: this.options.remoteURL,
        type: 'get',
        success: function(request){
          $('#'+object.options.id).find('.dialogContent').html(request);
          object.updatePosition();
          object.options.onUpdate();
        }
      });
    }
    this.options.onInit();
  }
  this.show = function(){
    this.updatePosition();
    $('#'+this.options.id).show();
    if(this.options.expose){
      this.exp = $('#'+this.options.id).expose({
        api: true,
        closeOnClick: false,
        closeOnEsc: false,
        color: '#fff',
        opacity: 0.8,
        zIndex: 10500
      });
      this.exp.load();
    }
    return false;
  }
  this.close = function(){
    this.options.onClose();
    this.hide();
  }
  this.hide = function(){
    $('#'+this.options.id).hide();
    if(this.exp && this.exp.isLoaded()){
      this.exp.close();
    }
  }
  this.confirm = function(){
    this.options.onConfirm();
    this.hide();
  }
  this.updatePosition = function(){
    var width=$('#'+this.options.id).outerWidth() - 6;
    var height=$('#'+this.options.id).outerHeight() - 6;
    if(this.options.caller == 'body'){
      $('#'+this.options.id).css({
        position: 'absolute',
        top: ($(window).height() - height) / 2 + $(window).scrollTop() + this.options.offset.top,
        left: ($(window).width() - width) / 2 + $(window).scrollLeft() + this.options.offset.left
      });
    }else{
      var offset=this.options.caller.offset();
      var top=offset.top;
      var left=offset.left;
      $('#'+this.options.id).css({
        position: 'absolute',
        top: parseInt((top + this.options.caller.height()/2) - height/2 + this.options.offset.top)+'px',
        left: parseInt((left + this.options.caller.width()/2) - width/2 + this.options.offset.left)+'px'
      });
    }
  }
  this.init();
}

/* lottery */
$(document).ready(function(){
  $('.lotteryButton').not('.empty').click(function(){
    $(this).parent().parent().toggleClass('open');
    $(this).parent().parent().find('.lotteryWinners').slideToggle(350);
  }).hover(function(){
    $(this).addClass('hover');
  },function(){
    $(this).removeClass('hover');
  });
  $('.winnersWrapper').scrollable({
    size: 6
  }).navigator({
    navi: '.pages',
    naviItem: 'span'
  });
  $('.lotteryWrapper .pages span').html('&bull;');
  
  $('.winToolTip').appendTo('body');
  $('.lotteryWinners .winner a img').attr('title','');
  $('.lotteryWinners .winner a').each(function(){
    var config = {
      tip: $('.winToolTip:eq('+$('.lotteryWinners .winner a').index($(this))+')'),
      delay: '0',
      predelay: '300',
      position: 'top center',
      offset: [6, 3],
      events: { 
        tooltip:  ""
      }
    };
    if (!$.browser.msie) {
      config.effect = 'fade';
    }
    $(this).tooltip(config);
  });
  if(window.location.toString().search(/#lottery_open$/i) != -1){
    $("#wallOfFameTab a").trigger('click');
    $(".lotteryButton:first").trigger('click');
  }
});

/*widgets*/
function getWidget(obj, url) {
  var w=new cheWidget({
    target: obj,
    content: '<div class="spinner"><img src="/images/spinner_light.gif" alt="Загрузка"/></div>',
    remoteURL: url,
    onUpdate: function(){
      updateWidget(obj);
      updateWidgetsPositions();
    },
    onDelete: function(){
      checkWideWidget("#widgets");
      checkDelWidgets(obj);
      enableWSubmit();
    }
  });
}
function updateWidgetsPositions() {
  $('#widgets .widget').not('.hidden').each(function(){
    $(this).find('input.pos_y').val($(this).parent().find('.widget').index(this));
    $(this).find('input.pos_x').val($("#widgets .widgetsContainer").index($(this).closest('.widgetsContainer')));
  });
}
function updateWidget(obj) {
  prepareUserToolTips(obj);
  $(obj).find('.wpWrapper').not('.unitsWrapper').scrollable({
    size: 1,
    clickable: false
  }).navigator({
    navi: '.wpPages',
    naviItem: 'span'
  });
  $(obj).find('.wpWrapper.unitsWrapper').scrollable({
    size: 1,
    clickable: false
  });
  if($(obj).find('.wpPage').length > 1){
    $(obj).find('.wpPages span').html('&bull;');
  }
}
function checkNewWidgets(){
  $('#widgets .widget.new').each(function(){
    $(this).removeClass('new');
    getWidget($(this), $(this).attr('rel'));
    $(this).addClass("editable");
    $(this).find('.widgetHeader').disableSelection();
    checkMultiWidgets();
  });
}
function checkDelWidgets(obj){
  //TODO показать скрытые виджеты в панели
  checkMultiWidgets();
  addDummyWidget("#widgets");
}
function checkMultiWidgets(){
  $('#widgets_scroll .widget').not('.multiple').each(function(){
    if($('#widgets .widget.'+$(this).attr('id')).not('.hidden').length){
      $(this).appendTo('#widgets_list_temp');
    }
  });
  $('#widgets_list_temp .widget').each(function(){
    if(!$('#widgets .widget.'+$(this).attr('id')).not('.hidden').length){
      $(this).prependTo('#widgets_scroll');
    }
  });
  $('#widgets_list').scrollable().begin();
  if($('#widgets_scroll .widget').length < 5){
    $('#widgets_panel .wl_scroll').hide();
  }
  if($('#widgets_scroll .widget').length > 4){
    $('#widgets_panel .wl_scroll').show();
  }
}
function checkWideWidget(container, ui){
  $(container).find('.widget.wide').each(function(){
    var cols = $(container).find('.widgetsContainer').length;
    var cont=$(this).parent();
    var contIndex=$(container).find('.widgetsContainer').index(cont);
    var ind=$(this).parent().find('.widget').index(this);
    if(contIndex > cols-2){
      var target=$(container).find('.widgetsContainer:eq('+(contIndex-1)+')');
      if($(target).find('.widget').length < ind+1){
        $(target).append(this);
      }else{
        $(target).find('.widget:eq('+ind+')').before(this);
      }
    }
  });
  addDummyWidget("#widgets");
}
function addDummyWidget(container, ui){
  if($(container).find('.widget').length){
    $(container).find('.widget.dummy').remove();
    $(container).find('.widget.wide').not('.high').not('.hidden').not('.ui-sortable-helper').each(function(){
      var indexCorrected = $(this).prevAll('.widget').not('.new').not('.hidden').not('.high').not('.ui-sortable-helper').length+$(this).prevAll('.widget.high').not('.hidden').not('.ui-sortable-helper').length*2;
      var caller = $(this);
      $(this).parent().next().find('.widget').not('.new').not('.hidden').each(function(){
        var indexCorrectedNext = $(this).prevAll('.widget').not('.new').not('.hidden').not('.high').not('.ui-sortable-helper').length+$(this).prevAll('.widget.high').not('.hidden').not('.ui-sortable-helper').length*2;
        if(indexCorrected == indexCorrectedNext){
          $(this).before('<div class="widget dummy">&nbsp;</div>');
        }
        if($(this).hasClass('high') && indexCorrected == indexCorrectedNext+1){
          $(caller).before('<div class="widget dummy">&nbsp;</div>');
          indexCorrected += 1;
        }
      });
      var indexCorrectedNext = $(this).parent().next().find('.widget').not('.new').not('.hidden').not('.high').not('.ui-sortable-helper').length+$(this).parent().next().find('.widget.high').not('.hidden').not('.ui-sortable-helper').length*2;
      if(indexCorrected == indexCorrectedNext){
        $(this).parent().next().append('<div class="widget dummy">&nbsp;</div>');
      }
    });
  }
}
function switchWPanel(){
  $('#widgets_panel').slideToggle(250).toggleClass('open');
  if($('#widgets_panel').hasClass('open')){
    $("#widgets .widgetsContainer").sortable("enable");
    $("#widgets .widget").addClass("editable");
    checkMultiWidgets();
  }else{
    $("#widgets .widgetsContainer").sortable("disable");
    $("#widgets .widget").removeClass("editable");
  }
  checkNoWidgets();
}
function enableWSubmit(){
  $('#new_user_widget #widgets_panel').find('.submit input').attr('disabled', false);
  $('#new_user_widget #widgets_panel').find('.submit').removeClass('disabled');
}
function disableWSubmit(){
  $('#new_user_widget #widgets_panel').find('.submit input').attr('disabled', true);
  $('#new_user_widget #widgets_panel').find('.submit').addClass('disabled');
}
function checkNoWidgets(){
  if($('#widgets .widget').not('.hidden').length || $("#widgets_panel").hasClass('open')){
    $('#widgetsHint').fadeOut(200);
  }else{
    $('#widgetsHint').fadeIn(600);
  }
}
$(document).ready(function(){
  if($('#widgets').length){
    $('#new_user_widget').submit(function(){
      $('#widgets .widget').removeClass('editable');
      disableWSubmit();
    });
    disableWSubmit();
    $('#widgets .widget').each(function(){
      getWidget($(this), $(this).attr('rel'));
    });
    $('#widgetPanelSwitch').click(function(){
      switchWPanel();
      return false;
    });
    $("#widgets .widgetsContainer").sortable({
      handle: '.widgetHeader',
      connectWith: '#widgets .widgetsContainer',
      placeholder: 'widget PH',
      tolerance: 'pointer',
      appendTo: 'body',
      zIndex: 11000,
      stop: function(event, ui) {
        enableWSubmit();
        checkNewWidgets();
        checkWideWidget("#widgets");
        updateWidgetsPositions();
      },
      change: function(event, ui) {
        addDummyWidget('#widgets', ui);
      },
      over: function(event, ui) {
        addDummyWidget('#widgets', ui);
      },
      start: function(event, ui) {
        //setPHDims(ui);
        //addDummy('#widgetsWrapper', ui);
      },
      distance: 30
    });
    $("#widgets .widgetsContainer").sortable("disable");
    $("#widgets_panel .widget").draggable({
      connectToSortable: '#widgets .widgetsContainer',
      helper: 'clone',
      revert: false,
      appendTo: 'body',
      zIndex: 11000
    });
    $(".widgetHeader").disableSelection();
    $('#widgets_list').scrollable({
      size: 4,
      nextPage: '.wl_scroll.right',
      prevPage: '.wl_scroll.left'
    });
    $('.wl_scroll').hover(function(){
      $(this).addClass('hover');
    },function(){
      $(this).removeClass('hover');
    });
    addDummyWidget("#widgets");
    checkMultiWidgets();
    checkNoWidgets();
  }
});
cheWidget = function(options){
  this.options={
    parent: '#widgets',
    id: '',
    header: 'Загружаем виджет...',
    content: 'Загружаем...',
    onDelete: function(){},
    onInit: function(){},
    onUpdate: function(){},
    remoteURL: false
  };
  if(options != undefined){
    $.extend(this.options, options);
  }
  this.init = function(){
    var object=this;
    
    var div=document.createElement('div');
    div.className='widgetUI';
    
    var header=document.createElement('div');
    header.className='widgetHeader';
    
    var close=document.createElement('a');
    close.className='widgetClose';
    close.href='#';
    $(close).text('X');
    $(close).click(function(){object.del(); return false;});
    
    var closeDiv=document.createElement('div');
    closeDiv.className='widgetCloseDiv';
 
    var headText=document.createElement('div');
    headText.className='headText';
    $(headText).html(this.options.header);
    
    $(header).append(close);
    $(header).append(closeDiv);
    $(header).append(headText);
    $(div).append(header);

    var wrapper=document.createElement('div');
    wrapper.className='widgetContentWrapper'
    
    var content=document.createElement('div');
    content.className='widgetContent'
    
    $(content).html(this.options.content);
    $(wrapper).append(content);
    $(div).append(wrapper);
    
    var footer=document.createElement('div');
    footer.className='widgetFooter'
    $(footer).append('<div></div>');
    $(div).append(footer);
        
    $(this.options.target).html(div);

    var uid = new Date().getTime();
    if($(object.options.target).attr('id').indexOf('uwid') == -1){
      var uwid  = '';
      $(object.options.target).addClass($(object.options.target).attr('id'));
      var wid = $(object.options.target).attr('id').substr(4);
      $(object.options.target).attr('id', '');
    }else{
      var uwid = $(object.options.target).attr('id').substr($(object.options.target).attr('id').indexOf('uwid')+5);
      var re=/wid_(\d+)\s/i;
      var a = re.exec($(object.options.target).attr('class'));
      var wid = a[1];
    }
    
    $(object.options.target).append('<input class="widget_id" type="hidden" value="'+wid+'" name="user[user_widgets_attributes]['+uid+'][widget_id]" />');
    $(object.options.target).append('<input class="pos_y" type="hidden" value="'+($('#widgets .widget').length)+'" name="user[user_widgets_attributes]['+uid+'][y]" />');
    $(object.options.target).append('<input class="pos_x" type="hidden" value="0" name="user[user_widgets_attributes]['+uid+'][x]" />');
    $(object.options.target).append('<input class="u_widget_id" type="hidden" value="'+uwid+'" name="user[user_widgets_attributes]['+uid+'][id]" />');
    $(object.options.target).append('<input class="_del" type="hidden" value="" name="user[user_widgets_attributes]['+uid+'][_delete]" />');
    
    if(this.options.remoteURL){
      jQuery.ajax({
        url: this.options.remoteURL,
        type: 'get',
        success: function(request){
          var obj=$(object.options.target).find('.widgetContent');
          $(obj).html(request);
          $(object.options.target).find('.widgetHeader .headText').text($(obj).find('.title').text());
          $(obj).find('.title').remove();
          object.options.onUpdate();
        }
      });
    }
    this.options.onInit();
  }
  this.del = function(){
    if($(this.options.target).attr('id') == ''){
      $(this.options.target).remove();
    }else{
      $(this.options.target).find('input._del').val(1);
      $(this.options.target).addClass('hidden');
      this.hide();
    }
    this.options.onDelete();
  }
  this.hide = function(){
    $(this.options.target).hide();
  }
  this.init();
}

/* send forms by ctrl+enter */
$(document).ready(function(){
  $("#comment_comment").keypress(function(event){
    if ((event.keyCode == '13' || event.keyCode == '10') && event.ctrlKey) {
      $("#post_submit").click();
    }
  });
});

/* calendars */
$(document).ready(function(){
  if($('#dateSelector').length){
    $('#dateSelector').disableSelection();
    if($('#billingsWrap').length){
      calendar = new cheCalendar({
        target: '#billingsWrap',
        url: '/billing/'
      });
    }else if($('#eventsWrap').length){
      calendar = new cheCalendar({
        target: '#eventsWrap',
        url: '/event/'
      });
    }else{
      return false;
    }
  }
});
cheCalendar = function(options){
  this.options={
    currentDate: new Date(),
    prevDate: 0,
    target: '#billingsWrap',
    url: '/billing/'
  }
  this.init = function(options){
    this.currentDate = this.options.currentDate;
    this.currentDate.setHours(0);
    this.currentDate.setMinutes(0);
    this.currentDate.setSeconds(0);
    this.currentDate.setMilliseconds(0);
    $('#dateSelector').data('loading', false);
    $('#dateSelector').data('object', this);
    this.target=this.options.target;
    this.url=this.options.url;
    if(options){
      if(options.target){
        this.target=options.target;
      }
      if(options.url){
        this.url=options.url;
      }
    }
    obj = this;
    $('#calendarMonths td:eq('+this.month()+')').addClass('active');
    this.updateDays();
    $('.calendarDays td:eq('+(this.day()-1)+')').addClass('active');
    $('#calendarMonths td').click(function(){
      if(!$(this).hasClass('disabled')){
        $('#calendarMonths td').removeClass('active');
        $(this).addClass('active');
        obj.month($('#calendarMonths td').index($(this)));
        obj.updateDays();
      }
    });
    $('#calendarYearPrev').click(function(){
      obj.year('prev');
      $('#calendarYear').text(this.year());
      obj.updateDays();
      return false;
    });
    $('#calendarYearNext').click(function(){
      obj.year('next');
      $('#calendarYear').text(this.year());
      obj.updateDays();
      return false;
    });
  }
  this.year = function(year){
    if(year == undefined){
      return this.currentDate.getFullYear();
    }else if(year == 'prev'){
      this.prevDate = this.currentDate.valueOf();
      this.currentDate.setFullYear(this.currentDate.getFullYear()-1);
    }else if(year == 'next'){
      this.prevDate = this.currentDate.valueOf();
      this.currentDate.setFullYear(this.currentDate.getFullYear()+1);
    }else{
      this.prevDate = this.currentDate.valueOf();
      this.currentDate.setFullYear(year);
    }
    return this;
  }
  this.month = function(month){
    if(month == undefined){
      return this.currentDate.getMonth();
    }else{
      this.prevDate = this.currentDate.valueOf();
      this.currentDate.setMonth(month);
      return this;
    }
  }
  this.day = function(day){
    if(day == undefined){
      return this.currentDate.getDate();
    }else{
      this.prevDate = this.currentDate.valueOf();
      this.currentDate.setDate(day);
      return this;
    }
  }
  this.updateDays = function(){
    if(this.currentDate.valueOf() != this.prevDate){
      $('#monthDays').show();
      var tempDate = new Date(this.year(), this.month(), 1);
      var days = new String();
      while(tempDate.getMonth() == this.month()){
        if(tempDate.getDay() == 0 || tempDate.getDay() == 6){
          days += '<td class="dayOff"><span>'+tempDate.getDate()+'</span></td>';
        }else {
          days += '<td><span>'+tempDate.getDate()+'</span></td>';
        }
        tempDate.setDate(tempDate.getDate() + 1);
      }
      tempDate.setDate(tempDate.getDate() - 1);
      if($('#monthDaysScroller .monthDaysPage').length){
        if(this.currentDate.valueOf() < this.prevDate){
          $('#monthDaysScroller').prepend('<div class="monthDaysPage"><table class="calendarDays"><col></col><tbody><tr>'+days+'</tr></tbody></table></div>');
          $('#monthDays .monthDaysPage:first .calendarDays col:first').attr('span', tempDate.getDate()).attr('width', 100/tempDate.getDate()+'%');
          $('#monthDaysScroller').css({
            left: -620
          });
          $('#monthDaysScroller').animate({
            left: 0
          }, 400, function(){
            $('#monthDaysScroller .monthDaysPage:last').remove();
            $('#monthDaysScroller').css({
              left: 0
            });
          });
        }else{
          $('#monthDaysScroller').append('<div class="monthDaysPage"><table class="calendarDays"><col></col><tbody><tr>'+days+'</tr></tbody></table></div>');
          $('#monthDays .monthDaysPage:last .calendarDays col:first').attr('span', tempDate.getDate()).attr('width', 100/tempDate.getDate()+'%');
          $('#monthDaysScroller').css({
            left: 0
          });
          $('#monthDaysScroller').animate({
            left: -620
          }, 400, function(){
            $('#monthDaysScroller .monthDaysPage:first').remove();
            $('#monthDaysScroller').css({
              left: 0
            });
          });
        }
      }else{
        $('#monthDaysScroller').empty();
        $('#monthDaysScroller').append('<div class="monthDaysPage"><table class="calendarDays"><col></col><tbody><tr>'+days+'</tr></tbody></table></div>');
        $('#monthDays .monthDaysPage:last .calendarDays col:first').attr('span', tempDate.getDate()).attr('width', 100/tempDate.getDate()+'%');
        $('#monthDays').slideDown(300);
      }
      $('#monthDays td').click(function(){
        if(!$('#dateSelector').data('loading') && !$(this).hasClass('disabled')){
          var obj = $('#dateSelector').data('object');
          $('#dateSelector').data('loading', true);
          $('#monthDays td').removeClass('active');
          $(this).addClass('active');
          obj.day($(this).text());
          var height = 0;
            $(obj.target).children().each(function(){
              height += $(this).outerHeight(true);
            });
          $(obj.target).addClass('loading').css({
            height: height
          });
          $(obj.target).children().fadeOut(200);
          $.ajax({
            url: obj.url+obj.year()+"/"+parseInt(obj.month()+1)+"/"+obj.day(),
            method: 'get',
            success: function(data){
              if($.trim(data) == ''){
                $(obj.target).empty().append('<p>На этот день событий нет</p>');
              }else{
                $(obj.target).empty().append(data);
              }
              var height = 0;
              $(obj.target).children().each(function(){
                height += $(this).outerHeight(true);
              });
              $(obj.target).removeClass('loading').animate({
                height: height
              }, 200);
              $('#dateSelector').data('loading', false);
            }
          });
        }
      });
    this.checkFuture();
    }
  }
  this.checkFuture = function(){
    $('#calendarMonths td, .calendarDays td').removeClass('disabled');
    var year = parseInt($('#calendarYear').text());
    var today = new Date();
    if(this.year() > today.getFullYear()){
      $('#calendarMonths td').addClass('disabled');
    }else if(this.year() == today.getFullYear()){
      $('#calendarMonths td:gt('+today.getMonth()+')').addClass('disabled');
    }
    if(this.month() > today.getMonth()){
      $('.calendarDays td').addClass('disabled');
    }else if(this.month() == today.getMonth()){
      if(this.currentDate.valueOf() > this.prevDate){
        $('.calendarDays:last td:gt('+(today.getDate()-1)+')').addClass('disabled');
      }else{
        $('.calendarDays:first td:gt('+(today.getDate()-1)+')').addClass('disabled');
      }
    }
  }
  this.init(options);
}

/* tags */
$(document).ready(function(){
  if($('input#post_tag_list, input#club_tag_list, input#wear_tag_list').length){
    $('input#post_tag_list, input#club_tag_list, input#wear_tag_list').md_tags({
      containerClass: 'clearfix',
      autocomplete: '/tag_suggest/'
    });
  };
});

/* quotes */
var add_quote = function(event) {
  var selection = window.getSelection();
  if($(event.target).parents('.comment').find('.itemContent:first').length){
    if(!selection.isCollapsed && $(selection.anchorNode).parents('.commentContent:first')[0] != undefined && $(selection.anchorNode).parents('.commentContent:first')[0] == $(selection.focusNode).parents('.commentContent:first')[0]){
      var text = selection.toString();
      var comment_id = $(selection.anchorNode).parents('.comment').attr('id').substr(8);
    }else{
      var comment = $(event.target).parents('.comment').find('.commentContent:first .commentText').clone();
      $(comment).find('.quoteText, .quoteTR, .quoteTL, .quoteBT, .quoteBL, .commentMeta').remove();
      var text = $(comment).text();
      var comment_id = $(event.target).parents('.comment').attr('id').substr(8);
    }
    $('#comment_comment').val($('#comment_comment').val()+'<quote comment_id="'+comment_id+'">'+jQuery.trim(text.replace(/[\n\r\t]/g, ' ').replace(/\s{1,}/g, ' '))+'</quote>');
    $.scrollTo($('#comment_comment'), {
      axis: 'y',
      duration: 500
    });
  }
  if($(event.target).parents('.postBG').find('.restrict_box:first').length){
    if($(selection.anchorNode).parents('.restrict_box:first')[0] != undefined && $(selection.anchorNode).parents('.restrict_box:first')[0] == $(selection.focusNode).parents('.restrict_box:first')[0]){
      var text = selection.toString();
      $('#comment_comment').val($('#comment_comment').val()+'<quote>'+jQuery.trim(text.replace(/[\n\r\t]/g, ' ').replace(/\s{1,}/g, ' '))+'</quote>');
    }else{
      var text = $(event.target).parents('.postBG').find('.restrict_box:first').text();
      $('#comment_comment').val($('#comment_comment').val()+'<quote>'+jQuery.trim(text)+'</quote>');
    }
    $.scrollTo($('#comment_comment'), {
      axis: 'y',
      duration: 500
    });
  }
}
$(document).ready(function(){
  $("#new_comment").submit(function(){
    if($('#comment_comment').val() == ''){
      enableSubmit($("#new_comment"));
      return false;
    }
  });
});
$(document).ready(function(){
  $('.quote').disableSelection();
  $('.quoteLink.toComment a').click(function(event){
    event.preventDefault();
    $.scrollTo($(event.target).attr('href'), {
      axis: 'y',
      duration: 500,
      offset: {
        top: -50
      }
    });
    return false;
  });
});
var setCookie = function(){
  return false;
}
$(document).ready(function(){
  $('.sidebar .new_idea').click(function(){
    var tip=new roundTip({
      header: 'Новая идея',
      content: '<img src="/images/ideaTip.png" id="ideaTip" /><textarea rows="5" name="post[body]" id="post_body" cols="32"></textarea>',
      button: 'сохранить',
      id: 'ideaToolTip',
      caller: $(this),
      onConfirm: function(){
        if($('#ideaToolTip textarea').val() != ''){
          $('.sidebar .new_idea a').hide();
          $('.sidebar .new_idea').append('<img src="/images/spinner_light_small.gif"/>');
          jQuery.ajax({
            url: '/posts',
            type: 'post',
            data: {
              "post[body]": $('#ideaToolTip textarea').val(),
              "post[kind]": 'idea'
            },
            success: function(request){
              jQuery.noticeAdd({text: 'Идея сохранена', stayTime: 20000});
              $('.sidebar img.avatar').attr('bt-xtitle', $('.sidebar img.avatar').attr('alt')+": "+$('#ideaToolTip textarea').val());
              $('.sidebar .new_idea img').remove();
              $('.sidebar .new_idea a').show();
            }
          });
        }
        return false;
      },
      offset: {
        left: 60,
        top: 20
      }
    });
    tip.show();
    $('#ideaToolTip textarea').focus();
    return false;
  });
});

$(document).ready(function(){
  //login link
  $('#frontPageMenu #loginLink').click(function(){
    $('#frontPageMenu #login-form').slideToggle(300);
    return false;
  });
  $('#frontPageMenu #closeLoginForm').click(function(){
    $('#frontPageMenu #login-form').fadeOut(200);
    return false;
  });
  
  //login and password focus
  $("#frontPageMenu #login").focus(function () {
    if($(this).val()=='Логин'){
      $(this).val('')
    }
    $(this).css('color','#222');
  });
  $("#frontPageMenu #login").blur(function () {
    if($(this).val()=='' || $(this).val()=='Логин'){
      $(this).css('color','#B0B0B0').attr("value", "Логин");
    }
  });
  $("#frontPageMenu #password").before('<input type="text" value="Пароль" id="passHolder"/>');
  $("#frontPageMenu #passHolder").focus(function () {
    $(this).hide();
    $("#frontPageMenu #password").show().focus();
  });
  $("#frontPageMenu #password").blur(function () {
    if($(this).val()=='' || $(this).val()=='Пароль'){
      $(this).hide();
      $("#frontPageMenu #passHolder").show();
    }else{
      $("#frontPageMenu #passHolder").hide();
    }
  });
  $("#frontPageMenu #login").blur();
  $("#frontPageMenu #password").blur();
  
  //disable selections
  $('.sidebar, #page-header a, #page-header img').disableSelection();
});

//levenstein distance
function levenshtein(str1, str2) {
  var l1=str1.length, l2=str2.length;
  if (Math.min(l1, l2) === 0) {
    return Math.max(l1, l2);
  }
  var i=0, j=0, d = Array();
  for(i=0; i<=l1; i++){
    d[i]=[];
    d[i][0]=i;
  }
  for(j=0; j<=l2; j++){
    d[0][j]=j;
  }
  for(i=1; i<=l1; i++){
    for(j=1; j<=l2; j++){
      d[i][j] = Math.min(
        d[i-1][j]+1,
        d[i][j-1]+1, 
        d[i-1][j-1]+(str1.charAt(i-1)===str2.charAt(j-1) ? 0 : 1)
      );
    }
  }
  return d[l1][l2];
}
var goodMailServers = ["mail.ru", "gmail.com", "yandex.ru", "rambler.ru", "bk.ru", "list.ru", "inbox.ru", "ya.ru", "ukr.net", "yahoo.com", "tut.by", "pochta.ru", "i.ua", "bigmir.net", "inbox.lv", "ngs.ru", "hotmail.com", "gmail.ru", "meta.ua", "ua.fm", "km.ru", "nm.ru", "live.ru", "narod.ru"];
function checkGoodMail(obj){
  var mail = $(obj).val();
  if(mail.indexOf("@") > 0){
    var str = mail.substr(mail.indexOf("@")+1);
    var servers = Array();
    if($.inArray(str, goodMailServers) == -1){
      for(var i = 0; i < goodMailServers.length; i++){
        if(levenshtein(str, goodMailServers[i]) > 0 && levenshtein(str, goodMailServers[i]) <= 2){
          servers.push(mail.substr(0, mail.indexOf("@")+1)+'<b>'+goodMailServers[i]+'</b>');
        }
      }
      if(servers.length){
        var lastServer = servers.pop();
        if(servers.length == 0){
          var errorString = '<a class="changeMailServer" href="#">'+lastServer+'</a>';
        }else{
          var errorString = '<a class="changeMailServer" href="#">'+servers.join('</a>, <a class="changeMailServer" href="#">')+'</a> или <a class="changeMailServer" href="#">'+lastServer+'</a>';
        }
        $(obj).next('.goodMail').remove();
        $(obj).after('<p class="goodMail">Возможно, вы имели ввиду '+errorString+'?</p>');
        $(obj).next('.goodMail').find('.changeMailServer').click(function(){
          $(obj).val($(this).text());
          $(this).parents('.goodMail').remove();
          return false;
        });
      }
    }else{
      $(obj).next('.goodMail').remove();
    }
  }
  return false;
}
function answerSubmit(form){
  disableSubmit(form);
  $(form).parent().css({height: $(form).outerHeight()});
  if($.trim($(form).find('textarea').val()) == ""){
    jQuery.noticeAdd({text: "Придумайте какой-нибудь ответ, пожалуйста", stayTime: 20000});
    $(form).find('.submit').removeClass('disabled');
    $(form).find('.submit input').attr('disabled', false);
    return false;
  }
  $(form).fadeOut('fast');
  $(form).parent().addClass('loading');
  return true;
}
function disableSubmit(form){
  $(form).find('.submit').addClass('disabled');
  $(form).find('.submit input').attr('disabled', true);
}
function enableSubmit(form){
  $(form).find('.submit').removeClass('disabled');
  $(form).find('.submit input').attr('disabled', false);
}

$(document).ready(function(){
  checkMenuFix();
  checkInformersFix();
  $(window).scroll(function(){
    checkMenuFix();
    checkInformersFix();
  });
});
function checkMenuFix(){
  var top = 120;
  var scroll = $(window).scrollTop();
  if((top - scroll) <= 0){
    $('#header').addClass('fixed');
  }else{
    $('#header').removeClass('fixed');
  }
}
function checkInformersFix(){
  var top = 388;
  var scroll = $(window).scrollTop();
  if((top - scroll) <= 0){
    $('#informersFix').addClass('fixed');
  }else{
    $('#informersFix').removeClass('fixed');
  }
}
var livePage = $.getUrlVar("page") != undefined ? parseInt($.getUrlVar("page")) + 1 : 2;
function getCurrentSorts(){
  var sorts = Object();
  
  sorts.postKind = "all";
  if($('.postKind li.current a').hasClass('audio')){      sorts.postKind = "audio";}
  else if($('.postKind li.current a').hasClass('video')){ sorts.postKind = "video";}
  else if($('.postKind li.current a').hasClass('photo')){ sorts.postKind = "photo";}
  else if($('.postKind li.current a').hasClass('text')){  sorts.postKind = "text";}
  
  sorts.inClub = "all";
  if($('.inClub li.current a').hasClass('inBlogs')){      sorts.inClub = false;}
  else if($('.inClub li.current a').hasClass('inClubs')){ sorts.inClub = true;}
  
  sorts.sortMode = "byDate";
  if($('.sortMode li.current a').hasClass('byComments')){      sorts.sortMode = "byComments";}
  else if($('.sortMode li.current a').hasClass('byABC')){ sorts.sortMode = "byABC";}
  else if($('.sortMode li.current a').hasClass('byRating')){ sorts.sortMode = "byRating";}
  
  sorts.showMode = "diary";
  if($('.showMode li.current a').hasClass('list')){      sorts.showMode = "list";}
  else if($('.showMode li.current a').hasClass('thumbs')){ sorts.showMode = "thumbs";}
  
  return sorts;
}
function setSorts(container, sorts, caller){
  if(sorts.inClub == "all"){
    var blocksHide=$(container).find('.listBlock.dirtyHack'); //TODOgit
    var blocksShow=$(container).find('.listBlock');
  }
  
  if(sorts.postKind == "all"){
    var blocksShow = $(container).find('.listBlock.hidden');
  }
  else if(sorts.postKind == 'audio'){
    var blocksHide = $(container).find('.listBlock').not(':has(.listAudio)');
    var blocksShow = $(container).find('.listBlock:has(.listAudio)');
  }
  else if(sorts.postKind == 'video'){
    var blocksHide = $(container).find('.listBlock').not(':has(.listVideo)');
    var blocksShow = $(container).find('.listBlock:has(.listVideo)');
  }
  else if(sorts.postKind == 'photo'){
    var blocksHide = $(container).find('.listBlock').not(':has(.listPhoto)');
    var blocksShow = $(container).find('.listBlock:has(.listPhoto)');
  }
  else if(sorts.postKind == 'text'){
    var blocksShow = $(container).find('.listBlock').not(':has(.listAudio), :has(.listVideo), :has(.listPhoto)');
    var blocksHide = $(container).find('.listBlock:has(.listAudio, .listVideo, .listPhoto)');
  }
  
  if(sorts.inClub != "all"){
    if(blocksHide == undefined){
      var blocksHide = $(container).find('.listBlock[data_is_club='+sorts.inClub+']');
    }else{
      var blocksHideAdd = $(container).find('.listBlock[data_is_club='+sorts.inClub+']');
    }
  }
  
  blocksHide.filter('.hidden');
  blocksShow.filter('not(.hidden)');
  
  blocksShow.removeClass('hidden').stop().animate({opacity: 1},{ duration: 400 });
  blocksHide.addClass('hidden').stop().animate({opacity: 0},{ duration: 400 });
  
  if(blocksHideAdd){
    blocksHideAdd.addClass('hidden').stop().animate({opacity: 0},{ duration: 400 });
  }
  
  if(caller){
    if($(caller).hasClass('byDate')){
      var blocks = $(container).find('.listBlock').get();
      blocks.sort(function(a, b) { 
        var keyA = $(a).attr('data_created');
        var keyB = $(b).attr('data_created');
        return keyA - keyB;
      });
      $.each(blocks, function(i, block){
        $(container).prepend(block);
      });
    }
    if($(caller).hasClass('byABC')){
      var blocks = $(container).find('.listBlock').get();
      blocks.sort(function(a, b) { 
        var keyA = $(a).text().toUpperCase();
        var keyB = $(b).text().toUpperCase();
        if (keyA < keyB) return -1;
        if (keyA > keyB) return 1;
        return 0;
      });
      $.each(blocks, function(i, block){
        $(container).append(block);
      });
    }
    if($(caller).hasClass('byRating')){
      var blocks = $(container).find('.listBlock').get();
      blocks.sort(function(a, b) { 
        var keyA = parseInt($(a).find('.rating').attr('data_rating'));
        var keyB = parseInt($(b).find('.rating').attr('data_rating'));
        return keyA - keyB;
      });
      $.each(blocks, function(i, block){
        $(container).prepend(block);
      });
    }
    if($(caller).hasClass('byComments')){
      var blocks = $(container).find('.listBlock').get();
      blocks.sort(function(a, b) { 
        var keyA = parseInt($(a).find('.commentsCount').attr('data_comments'));
        var keyB = parseInt($(b).find('.commentsCount').attr('data_comments'));
        return keyA - keyB;
      });
      $.each(blocks, function(i, block){
        $(container).prepend(block);
      });
    }
  }
  if($("ul.showMode .current a").hasClass('thumbs')){
    $(container).masonry({
      singleMode: true,
      itemSelector: '.listBlock:not(.hidden)',
      animate: true,
      animationOptions: {
        duration: 200,
        queue: false
      }
    })
  }
}
$(document).ready(function(){
  $(".listSorts ul").hover(function(){
    var pos = $(this).find('li.current').position();
    $("#menu").not('.fixed #menu').css({
      zIndex: 900
    });
    $(this).css({
      top: -pos.top + 8 
    });
  }, function(){
    $("#menu").not('.fixed #menu').css({
      zIndex: 1000
    });
    $(this).stop();
    $(this).css({
      top: 0
    });
  });
  $(".listSorts ul a").click(function(){
    $(this).blur();
    if($(this).parent().hasClass('current') || $("#postLoader").data('loading') == true){
      return false;
    }
    $(this).closest('ul').find('li').removeClass('current');
    $(this).parent().addClass('current');
    var pos = $(this).parent().position();
    $(this).closest('ul').animate({
      top: -pos.top + 8 
    }, 100, 'swing');
    
    if(!$(this).closest('ul').hasClass('clubsSort') && !$(this).closest('ul').hasClass('questionsMode')){
      if($(this).closest('ul').hasClass('postKind') || $(this).closest('ul').hasClass('inClub') || $(this).closest('ul').hasClass('sortMode') || $(this).closest('ul').hasClass('showMode')){
        livePage = 1;
        $("#postLoader").data('stop', false);
        $('.endless').css({
          height: 'auto'
        }).animate({
          opacity: 0
        }, 200, function(){
          $('.endless .listBlock, .endless  .listPost, .endless .listPostBG, .endless .post, .endless .comment, .questionContainer').hide().remove();
          loadNextPage();
        });  
        return false;
      }
      setSorts($('.endless'), getCurrentSorts(), $(this));
      return false;
    }else{
      return true;
    }
  });
  if($('.endless').length && $('#postLoader').length){
    setSorts($('.endless'), getCurrentSorts());
  }
});
function loadNextPage(){
  $("#postLoader").removeClass('stop').addClass('loading');
  $("#postLoader").data('loading', true);
  var sorts = getCurrentSorts();
  var data = Object();
  if($('#clubsList').length && $('#categoryCloud').length){
    data.category = $('#categoryCloud li.selected').attr('id').substr(9);
    if($('.clubsSort li.current a').hasClass('posts')){
      data.order="posts"
    }
    else if($('.clubsSort li.current a').hasClass('subscribers')){
      data.order="subscribers"
    }
    else if($('.clubsSort li.current a').hasClass('creation')){
      data.order="creation"
    }
  }else{
    data.kind = sorts.postKind;
    data.scope = sorts.inClub == 'all' ? 'all' : (sorts.inClub ? 'club' : 'blog');
    data.order = sorts.sortMode;
    data.sm = sorts.showMode;
  }
  if($('#searchPage').length){
    data = Object();
    data.q=$.getUrlVar('q');
  }
  if($('#allComments').length){
    data = Object();
  }
  data.page = livePage;
  $.ajax({
    url: $('#socialLinks').length ? $('#sideMenu .showProfile a').attr('href')+'/blog' : '',
    data: data,
    success: function(data){
      if($.trim(data)==""){
        $("#postLoader").data('stop', true);
        $("#postLoader").data('loading', false);
        $("#postLoader").removeClass('loading').addClass('stop');
        return false;
      }else{
        livePage++;
        $('.endless').css({
          opacity: 1
        });
        
        $('.endless').removeClass('wider');
        if($(data).filter('.listBlock').length){
          $('.endless').addClass('wider');
        }
        $('.endless').append(data);

        if($(data).filter('.listPostBG').length){
          set_photo_scroll($(data).filter('.listPostBG').find('.post'));
          set_photo_center($(data).filter('.listPostBG').find('.post'));
        }
      
        if($(data).filter('.listBlock').length){
          $('.endless').masonry({
            singleMode: true,
            itemSelector: '.listBlock:not(.hidden)'
          });
        }
        var length = 1;
        if($('#clubsList').length){
          length = 6;
        }
        if($('#conversations').length){
          length = 20;
        }
        if($('#allComments').length){
          length = 30;
        }
        if($('#questions').length){
          length = 10;
        }
        if($(data).filter('.listPost, .post, .listBlock, .clubListBlock, .conversation, .listPostBG, .comment, .questionContainer').length < length){
          $("#postLoader").data('stop', true);
          $("#postLoader").removeClass('loading').addClass('stop');
          $("#postLoader").data('loading', false);
          return false;
        }
      }
      $("#postLoader").data('loading', false);
      $("#postLoader").removeClass('loading');
      $(window).scroll();
    },
    error: function(){
      alert('Не получилось загрузить данные. Попробуйте обновить страничку.');
      $("#postLoader").data('loading', false);
      $("#postLoader").css({visibility: 'hidden'});
    }
  });
  return false;
}

/* social */
$(document).ready(function(){
  if($('#socialLinks').length){
    $('#socialLinks a:not(li.current a)').live('click', function(){
      $("#socialLinks li").removeClass('current');
      $(this).parent().addClass('current');
      var currentItem = $('#socialMover .socialItem.'+$(this).text());
      
      if($(this).text() == "cheloveche"){
        $(".listSorts").animate({
          height: '46px',
        },200, function(){
          $(this).css({overflow: 'visible'});
        });
      }else{
        $(".listSorts").css({overflow: 'hidden'}).animate({
          height: 0,
        },200);
      }
      
      var content = currentItem.find(".content");
      if (content.size() > 0 && content.attr("rel") != "loaded") {
        content.addClass('loading');
        var url = window.location.pathname + "/timeline?who=" + $(this).text();
        content.load(url, function(text, status){
          if (status == "success") {
            content.removeClass('loading');
            content.attr("rel", "loaded");
            set_photo_scroll($(content).find('.post'));
            set_photo_center($(content).find('.post'));
          }else{
            content.removeClass('loading');
            alert("Загрузка данных не удалась");
          }
        });
      }

      var offset =currentItem.position();
      $('.socialItem').not(currentItem).animate({
        height: 400
      }, 200);
      currentItem.css({
        height: 'auto'
      })
      $('#socialMover').animate({
        left: 0-offset.left
      }, 400);
      
      return false;
    });
    $('#socialLinks li.current a').live('click', function(){
      return false;
    });
  }
});

/* users */
var usersPage = 2;
function loadNextUserPage(){
  $("#usersLoader").addClass('loading').data('loading', true);
  var data = Object();
  data.page = usersPage;
  $.ajax({
    url: '',
    data: data,
    success: function(data){
      if($.trim(data)==""){
        $("#usersLoader").removeClass('loading').data('stop', true).hide();
        return false;
      }else{
        usersPage++;
        $('.users_endless').css({
          opacity: 1
        });

        $('.users_endless').append(data);
        updateUserToolTips(data);

        var length = 42;
        
        if($(data).filter('li').length < length){
          $("#usersLoader").data('stop', true).hide();
          return false;
        }
      }
      $("#usersLoader").data('loading', false);
      $("#usersLoader").removeClass('loading');
      $(window).scroll();
    },
    error: function(){
      alert('Не получилось загрузить данные. Попробуйте обновить страничку.');
      $("#usersLoader").data('loading', false);
      $("#usersLoader").css({visibility: 'hidden'});
    }
  });
  return false;
}

/* arena */
function addArenaMessage(login, text, mode, self){
  if(mode == undefined){
    mode = 'normal'
  }else if(/^\/whisper .+ .+/.test(text)){
    mode = 'whisper'
  }
  if(self == undefined){
    self = false;
  }
  if(self && text == "/clear"){
    resetChat();
    return false;
  }
  if(self){
    var className = 'self';
  }else{
    var className = '';
  }
  if($.trim(text) != ''){
    if(mode == 'whisper'){
      if(self){
        text = text.substr(9);
        text = $.trim(text);
        var loginWhisper = text.substr(0, text.indexOf(" "));
        text = text.substr(loginWhisper.length);
        $('#arenaChatLogText').prepend('<div class="chatMessage whisper"><span class="chatLogin self">'+login+' </span><span class="whisperLogin"> прошептал</span> <span class="chatLogin">'+loginWhisper+':</span> <span class="chatText"></span></div>');
      }else{
        $('#arenaChatLogText').prepend('<div class="chatMessage '+className+' whisper"><span class="chatLogin">'+login+' </span><span class="whisperLogin">вам шепчет</span>: <span class="chatText"></span></div>');
      }
    }else{
      $('#arenaChatLogText').prepend('<div class="chatMessage '+className+'"><span class="chatLogin">'+login+':</span> <span class="chatText"></span></div>');
    }
    $('#arenaChatLogText .chatMessage:first .chatText').text(text);
    checkChatScroller();
  }
}
function chatCount(count){
  if(count == undefined){
    count=$('#chat_message').val().length;
  }
  if(!$('#arenaChatCount').data('count')){
    $('#arenaChatCount').data('count', 140);
  }
  if(count <= 140){
    $('#arenaChatCount').data('count', 140-count);
    $('#arenaChatCount').text($('#arenaChatCount').data('count'));
    return true;
  }else{
    return false;
  }
}
function checkChatInput(event){
  if(event.keyCode == 13){
    return false;
  }
  if(!chatCount($('#chat_message').val().length + 1)){
    event.preventDefault();
  }
}
function checkChatScroller(){
  if($('#arenaChatLogWrap').height() == 0 || $('#arenaChatLogText').height() < $('#arenaChatLogWrap').height()) {
    $('#arenaChatLogScroller .handle').css({
      height: '100%'
    });
    $('#arenaChatLog').addClass('noScroll');
  }else{
    var h = $('#arenaChatLogWrap').height() / $('#arenaChatLogText').height() * $('#arenaChatLogScroller').height();
    if(h < 20){
      h=20;
    }
    $('#arenaChatLogScroller .handle').css({
      height: h
    });
    $('#arenaChatLog').removeClass('noScroll');
  }
}
function scrollChat(){
  var o = $('#arenaChatLogScroller .handle').position();
  var t = o.top;
  var top = t / $('#arenaChatLogScroller').height() * $('#arenaChatLogText').height();
  $('#arenaChatLogText').css({
    top: -top
  });
}
function resetChat(){
  $('#arenaChatLogText').empty();
  $('#arenaChatLogText').css({
    top: 0
  });
  checkChatScroller();
};
function enableHTMLChat(){
  if($('#arenaChatWrap').length){
    $('#arenaChatWrap').show();
    resetChat();
  }
}
function disableHTMLChat(){
  if($('#arenaChatWrap').length){
    $('#arenaChatWrap').hide();
  }
}
$(document).ready(function(){
  $('#q').focus(function(){
    $(this).removeClass('empty');
    if($(this).val()=='Имперский поиск'){
      $(this).val('');
    }
  });
  $('#q').blur(function(){
    if($.trim($(this).val())==''){
      $(this).val('Имперский поиск');
      $(this).addClass('empty');
    }
  });
});

function updateInformers(){
  if($('#informersFix').length){
    $.ajax({
      url: '/widget/informers?' + (new Date().getTime()),
      success: function(data){
        if ($('#informersFix').hasClass('fixed')){
          var fix = true;
        }else{
          var fix = false;
        }
        if($.trim(data) != ""){
          $("#informersFix").replaceWith(data);
          updateBlackTips("#informersFix");
          if(fix){
            $('#informersFix').addClass('fixed');
          }
          return true;
        }else{
          return false;
        }
      },
      error: function(){
      }
    });
  }
}
$(document).ready(function(){
  if($('#informersFix').length){
    var infInterval = window.setInterval("updateInformers()", 30000);
  }
});
var startPage = $.getUrlVar("page") != undefined ? parseInt($.getUrlVar("page")) : 1;
function readAll(el){
  if(!$(el).hasClass('loading')){
    el.addClass('loading');
    var sorts = getCurrentSorts();
    var data = Object();
    data.kind = sorts.postKind;
    data.scope = sorts.inClub == 'all' ? 'all' : (sorts.inClub ? 'club' : 'blog');
    data.order = sorts.sortMode;
    data.end_page = livePage - 1;
    data.page = startPage;
    $.ajax({
      url: '/live/read_all',
      data: data,
      success: function(data){
        el.removeClass('loading');
        $('.commentsCount .new, .commentsLink .new').remove();
        $('.commentsCount a.more, .commentsLink a.more').removeClass('more').addClass('total');
      }
    });
  }
  return false;
}