/**
 * jQuery hash change event
 *
 * Генерирует событие 'hashChange' (в контексте document)
 * и обеспечивает историю посещений для всех браузеров на любое изменение location.hash.
 * Пример использования: $(document).bind('hashChange', function(e, newHash){ ... });
 * Изменять location.hash можно любым способом, включая обычные ссылки (<a href="#bla">bla</a>).
 *
 * Copyright (c) 2009 Sergey Berezhnoy <veged mail ru>
 */
(function($){
    var $document = $(document),
        iframe,
        hash = '', // инициализируем пустым, чтобы учесть первоначальный хеш
        // считаем, что только IE нужно насильно записывать хистори (остальные сами справляются)
        needHistoryAdd = /MSIE/.test(navigator.userAgent),
        afterHistoryRead = false,
        afterHistoryAdd = false;

    // функция проверки изменения хеша, она же записывает хистори и вещает основное событие
    function check() {
        if (hash != (hash = document.location.hash)) {
            // если мы только что прочли из хистори, не надо туда записывать
            if (!afterHistoryRead && needHistoryAdd) historyAdd(hash);
            afterHistoryRead = false;
            $document.trigger('hashChange', [hash]);
            $.log('hashChange: ' + hash);
        }
        setTimeout(check, 42); // варварство из-за отсутствия полноценного события
    }

    // функция насильной записи в хистори через скрытый iframe
    function historyAdd(hash) {
        if (!iframe) iframe = $('<iframe style="display:none" src="javascript:false;"></iframe>').appendTo('body')[0];
        var d = iframe.contentDocument ||
            (iframe.contentWindow ? iframe.contentWindow.document : iframe.document);
        d.open();
        // можем позволить себе вольности с незакрытыми тегами, браузер достроит
        d.write('<html><head><title>' + document.title + '</title></head><body>'); // NOTE: потенциальная опасность с ескейпингом document.title
        d.write($('<div/>').append($('<div id="hashdiv"></div>').text(hash)).html()); // типа ради ескейпинга
        // приписываем в тело фрейма скрипт, который будет срабатывать при возвращении на него по хистори
        d.write(
            '<script>' +
                // портим объект window для связи между фреймами
                'window._hash = document.getElementById("hashdiv").innerText;' +
                'window.onload = parent._historyRead;' +
            '</script>'
        );
        afterHistoryAdd = true;
        d.close();
        $.log('historyAdd: ' + hash);
    }

    // для IE немного ускоряем обработку изменения хеша,
    // но поидее можно обойтись постоянно повторяющимся check()
    if ('onpropertychange' in document && 'attachEvent' in document) {
        document.attachEvent('onpropertychange', function(){
            if (event.propertyName == 'location') {
                check();
                $.log('onpropertychange: ' + document.location.hash);
            }
        });
    }

    if (needHistoryAdd) {
        // портим объект window, чтобы работало восстановление хистори через iframe
        window._historyRead = function(){
            console.log('try historyRead: ' + this._hash);
            // если мы только что добавили, читать не надо
            if (!afterHistoryAdd) {
                var newHash = this._hash;
                $.log('newHash: ' + newHash + ', currentHash: ' + document.location.hash);
                // без надобности не присваиваем, как минимум из-за звука "клака" в IE
                if (document.location.hash != newHash) {
                    afterHistoryRead = true;
                    document.location.hash = newHash;
                    console.log('historyRead: ' + newHash);
                }
            }
            afterHistoryAdd = false;
        };
    }

    $(function(){ setTimeout(check, 1) }); // запускаем постоянную проверку с задержкой, чтобы все успели начать слушать события

})(jQuery);



var OpenID = (function($) {	
  var providers= {
	yandex: {
	  name: 'Яндекс',
	  label: 'Введите свой логин в Яндексе',
	  url: "http://%username%.ya.ru/"
	},
	google: {
	  name: 'Google',
	  label: 'Ввведите свой идентификатор в гугле',
	  url: 'https://www.google.com/accounts/o8/id'
	},
	livejournal: {
	  name: 'LiveJournal',
	  label: 'Введите своё имя в Livejournal.',
	  url: 'http://%username%.livejournal.com/'
	},
	yahoo: {   
	  name: 'Yahoo!',
	  url: 'http://yahoo.com/'
	},
	openid: {   
	  name: 'OpenID',
	  label: 'Введите свой OpenID.',
	  url: null
	},
	flickr: {     
	  name: 'Flickr',
	  label: 'Введите своё имя в Flickr.',
	  url: 'http://flickr.com/%username%/'
	},
	aol: {     
	  name: 'AOL',
	  label: 'Введите своё имя в системе AOL',
	  url: 'http://openid.aol.com/%username%/'
	},
	myopenid: {
	  name: 'MyOpenID',
	  label: 'Введите своё имя в системе MyOpenID',
	  url: 'http://%username%.myopenid.com/'
	},
	technorati: {    
	  name: 'Technorati',
	  label: 'Введите свой логин в Technorati',
	  url: 'http://technorati.com/people/technorati/%username%/'
	},
	wordpress: {
	  name: 'Wordpress',
	  label: 'Ведите свой логин на Wordpress.com',
	  url: 'http://%username%.wordpress.com/'
	},
	blogger: {
	  name: 'Blogger',
	  label: 'Введите идентификатор своего Blogger аккаунта',
	  url: 'http://%username%.blogspot.com/'
	},
	claimid: {
	  name: 'ClaimID',
	  label: 'Введите свой ClaimID идентификатор',
	  url: 'http://claimid.com/%username%'
	}
  };
  return { 
	providers: providers,
	helper_block: null,
	form: null,
	url_input: null,
	openid_block: null,
	default_openid: null,
	default_username: null,
	url: null,
	current: {
	  name: null,
	  label: null,
	  url: null
	},
	setProviders: function (providers, r) {
	  if(r==true && typeof providers == "object") this.providers = {};
	  this.providers = $.extend(this.providers, providers);
	  return this;
	}, 
	setHelperBlock: function (helper_block) {
	  this.helper_block = $(helper_block);
	  return this;
	},
	setForm: function (selector) {
	  this.form = (selector) ? $(selector): $('#openid_block form');
	  return this;
	},
	init: function(helper_block, form_selector) {
	  this.setHelperBlock(helper_block);
	  this.setForm(form_selector);
	  this.helper_block = $(helper_block);
	  this.showProviders(this.helper_block);
	  this.url_input = $('#id_openid_url');
	  this.openid_input_item = this.url_input.parent().parent();
	  this.url_input.before('<input type="text" name="username" value="" />');
	  this.username_input = this.openid_input_item.parent().find('input[name$="username"]').hide();
	  this.label = this.openid_input_item.find('label');
	  this.openid_block = $('#openid_block');
	  this.default_username =  $.cookie('username')||'';
	  this.default_openid = $.cookie('openid')||'openid';
	  if(this.default_openid)
	  {
		this.setCurrent(this.default_openid);
		this.showCurrent(as=false);
	  }
	  this.form.submit(function(){
		$.cookie('openid',OpenID.current.name);
		$.cookie('username', OpenID.username_input.val());
		if(OpenID.current.url.search('%username%') !=-1)
		{
		  OpenID.url_input.val(OpenID.current.url.replace('%username%', OpenID.username_input.val()));
		};
	  });
	  return this;
	},
	getProvider: function(name){
	  return this.providers[name] ? this.providers[name]:(function(providers){
		var c = 0;
		var a =[];
		for(var b in providers){
		  a[c]=b;
		  c++;
		};
		return providers[a[Math.round(Math.random()*a.length)]]})(this.providers);
	},
	showProviders: function (helper_block) { 
	  $.each(this.providers, function (i, v){
		var	button = $('<div class="button '+i+'">'+v.name+'</div>');
		button.click(function () {
		  helper_block.find('div.button').not(button).removeClass('active');
		  button.toggleClass('active');
		  if(OpenID.current.name == i){
			OpenID.showDefault();
		  }
		  else{
			OpenID.setCurrent(i);	  
			OpenID.showCurrent();
		  }
		});
		helper_block.append(button);
	  });
	  return this;
	},
	showDefault: function(){
	  this.setCurrent('openid');
	  this.label.html(this.providers['openid'].label);
	  this.url_input.focus().show().select();
	  this.username_input.hide();
	  return this;
	},
	showCurrent: function(as) {
	  var c = this.current;
	  if(as !== false) var as = true;
	  if(this.current.url == null){
		this.showDefault();
	  }
	  else if(this.current.url.search('%username%') !=-1)
	  {
		this.label.html(this.current.label);
		this.username_input.attr('class',this.current.name).val((this.username_input.val()!=='')?this.username_input.val():this.default_username).show().focus();
		this.url_input.hide();
	  }
	  else{
		this.label.html(this.current.label);
		this.username_input.hide();
		this.url_input.val(this.current.url).focus().show();
		if(as){
		  window.setTimeout(function(){OpenID.form.submit();}, 800)
		};

	  };
	  return this;
	},
	setCurrent: function(name) {
	  this.current = this.getProvider(name);
	  this.current.name = name;
	},
	unsetCurrent: function() {
	  this.url_input.show();
	  this.current = {
		label: null,
		name: null,
		url: null,
	  };
	  this.username_input.hide();
	}
  };
})(jQuery);


var auth = (function($){
  return {
	auth_type: null,
	types: {
	  openid: null,
	  lap: null
	},
	tooglers:{
	  to_openid: null,
	  to_login: null,
	},
	init: function(oselector, lselector, deftype) {
	  window.location.hash = $.cookie('auth_type')||'#openid_block';
	  this.types.openid = (oselector) ? $(oselector): $('#openid_block');
	  this.types.lap = (lselector) ? $(lselector): $('#login_block');
	  $.each(this.types, function(n, v){
		v.hide();
	  });
	  $.log(window.location.hash);
	  $(document).bind('hashChange', function(e, newHash){
		$.each(auth.types, function(i, v){
		  v.hide();
		});
		$(newHash).show();
		$.cookie('auth_type', newHash);
	  });
	}
  };
})(jQuery);


var alerts = (function($) {
  return {
    box: null,
    init: function(){
      $('body').append($("<div>").attr('id','alerts_box'));
      alerts.box = $('#alerts_box');
      $.log("Всплывающие сообщения инициализированы");
	  return this;
    },
    show: function(message){
      var a = $("<div class=\"alert\">"+message+"</div>").appendTo(alerts.box).show();
      window.setTimeout(function(){a.fadeOut(1000);}, 2000);
      return this;
    }};
})(jQuery);


var comments = (function($){
  return {
	url: "/ajax/comments/",
	can_add: false,
	comment_form: null,
	init: function(url) {
	  this.url = url;
	  this.comment_form = $('#comment-form');
	  $.log(this.comment_form.find('.counter'));
	  this.comment_form.find('textarea').keypress(function(){
		var count = 300-$(this).val().length;
		if(count < 0)
		{
		  comments.comment_form.find('.counter').addClass('warning');
		}
		else
		{
		  comments.comment_form.find('.counter').removeClass('warning');
		}
		comments.comment_form.find('.counter').text(count);
	  });
	  $('a.comments-link').each(function(i,v){
		$(v).click(function(){
		  var a  = v.id.slice("comments-link-".length).split("-");
		  var type = a[0], id=a[1]; 
		  if(!$(v).hasClass('loaded')){
			$.ajax({
			  url: url,
			  type: "POST",
			  data: {
				type: type,
				object_id: id
			  },
              dataType: "json",
			  success: function(data){
				comments.render_comments(data, id, type);
				if($(v).hasClass('can-add')){
				  comments.show_form($(v).parent().parent().parent());
				  comments.comment_form.show().find('input').click(function(){
					$.ajax({
					  url: url,
					  type: "POST",
					  data: {
						type: type,
						object_id: id,
						action: "add",
						comment: comments.comment_form.find('textarea').val()
					  },
					  dataType: 'json',
					  success: function(new_data){
						comments.render_comments(new_data, id, type);
						if(new_data.length>0){
						  alerts.show('Комментарий успешно добавлен');
						}
						comments.comment_form.find('textarea').val('')
					  },
					  error: function(){
						alerts.show('Произошла непредвиденная ошибка');
					  }
					});
					$.log($(this));
					return false;
				  });
				}
				else
				{
				  if($('#question-'+$.questions.id).hasClass('closed')){
					alerts.show('Вопрос закрыт, нельзя добавлять комментарии.');
				  }
				  else{
					comments.show_login($(v).parent().parent().parent());
				  }
				}
			  },
			  error: function(){
				alerts.show('Что-то пошло не так');
			  }});
			$(v).text('скрыть комментарии').addClass('loaded');
		  }
		  else {
			$(v).text('показать комментарии').removeClass('loaded');
			$('#'+type+'-'+id+" .wrapper ul.comments").hide();
			comments.comment_form.hide();
		  }
		  return false;
		 });
	   });
	 },
	show_form: function(e){ 
	  this.comment_form.appendTo(e);
	  return this.comment_form;
	},
	show_login: function(e){
	  return $('<div/>').addClass('need-login-for-comment').appendTo(e).html('Вам необходимо <a href="/login/">авторизироваться</a> для комментирования');
	},
	render_comments: function(data, id, type){
	   if($('#'+type+'-'+id+" .wrapper ul.comments").length){
		 var com = $('#'+type+'-'+id+" .wrapper ul.comments").show().html('');
	   }
	   else
	   {
		 var com = $('<ul class="comments"></ul>').attr('id',type+"-comments-"+id).appendTo('#'+type+'-'+id+" .wrapper");
	   }
	   $.each(data, function(i,v){
		 comments.render_comment(v, type, id).appendTo(com);
	   });
	 },
	 render_comment: function(comment_data, type, id) {
	   return $('<li>').addClass('comment').attr('id', 'comment-'+comment_data.comment_id)
		 .html(
		   $('<div class="body">'+comment_data.body+'</div>')
			 .append('&nbsp;&mdash;&nbsp; <a href="'+comment_data.user_url+'">'+comment_data.user_name+'</a>'+'<abbr class="published" title="'+comment_data.add_date_timestamp+'">'+comment_data.add_date+'</abbr>')
			 .append(function(){
			   if(comment_data.can_delete =='true' || comment_data.can_delete==true){
				 return $('<a href="#" class="delete">&#x2715;</a>')
				   .click(function(){
					 $.ajax({
					   url: comments.url,
					   type: "POST",
					   dataType: "json",
					   data: {
						 type: type,
						 object_id: id,
						 comment_id: comment_data.comment_id,
						 action: "delete"
					   },
					   success: function(data){
						 $('#comment-'+comment_data.comment_id).fadeOut(1500);
					   },
					   error: function(error){
						 alerts.show('Что-то пошло не так');
					   }
					 });
					 return false;
				   });
			   }
			   else{
				 return;
			   }
			 }));
	 }
}})(jQuery);


var favorities = (function($){
  var statuses = [
	"Не авторизован",
	"Неверные параметры",
	"Вопрос удалён из избранного",
	"Вопрос добавлен в избранное"
  ]
  return {
	url: null,
	id: null,
	init: function(url, id){
	  this.url = url;
	  this.id = id;
	  $('div.favorite').find('.favorite-icon').click(function(){
		var icon = $(this);
		favorities.id = favorities.id || icon.parent().attr('id').slice('favorite-'.length);
		$.ajax({
		  dataType: "json",
		  url: favorities.url,
		  type: "POST",
		  data: {
			object_id: favorities.id,
			action: "favorite"
		  },
		  success: function(data){
			alerts.show(statuses[data.status]);
			if(data.status != 0 || data.status != 1){
			  if(icon.hasClass('favorited')){
				icon.html('&#x2729;');
				icon.removeClass('favorited');
			  }
			  else{
				icon.html('&#x272a;');
				icon.addClass('favorited');
			  }
			  icon.parent().find('.favorite-number').html(data.count);
			}
			$.log(data);
			return false;
		  },
		  error: function(){
			alerts.show('Что-то пошло нетак');
		  }
		});
		return  false;
	  });
	}
  }
})(jQuery);



var accepting = (function($){
  var statuses = [
	"Не авторизован",
	"Неверные параметры",
	"Нельзя одобрить свой ответ",
	"Сняли одобрение с ответа",
	"Привет кулхацкер! Нельзя одобрить чужой ответ",
	"Ответ успешно одобрен"
  ]
  return {
	url: null,
	id: null,
	init: function(url, id){
	  this.url = url;
	  var icons = $('div.accepting').find('.accept-icon');
		icons.click(function(){
		  var icon = $(this);
		  $.log(icon);
		  accepting.id =  icon.parent().attr('id').slice('accept-'.length);
		  $.ajax({
			dataType: "json",
			url: accepting.url,
			type: "POST",
			data: {
			  object_id: accepting.id,
			  action: "accept"
			},
			success: function(data){
			  alerts.show(statuses[data.status]);
			  switch (data.status){
			  case 3: 
				icons.removeClass('accepted');
				if(data.accepted!='none')
				{
			  	  icon.addClass('accepted');
				}
				break;
			  case 5: 
				icons.removeClass('accepted');
				icon.addClass('accepted');
				break;
			  }
			  
			  $.log(data);
			  return false;
			},
			error: function(){
			  alerts.show('Что-то пошло не так');
			}
		  });
		  
		  return  false;
		});
	}
  }
})(jQuery);


var voting = (function($){
  var statuses = [
	"Не авторизован",
    "Неверные параметры",
    "Вы не можете пока голосовать",
	"Вы не можете голосовать за свои вопросы",
    "Ваша репутация слишком мала, чтобы голосовать против",
    "Вы больше не можете изменить свой голос",
    "Лимит голосов на сегодня исчерпан",
	"Ваш голос принят",
  ]
  return {
	url: null,
	id: null,
	init: function(url, id){
	  this.url = url;
	  this.id = id;
	  var arrows = $('ul.voting').find('.up, .down');
	  arrows.click(function(){
		var arrow = $(this);
		var a = arrow.parent().parent().parent().attr('id').split('-');
		var content_type = a[0],  object_id = a[1];
		if(arrow.hasClass('up')){
		  vote = "up";
		}
		else if (arrow.hasClass('down'))
		{
		  vote = "down";
		}
		else {
		  alerts.show('Несуществующий тип голоса');
		}
		$.ajax({
		  dataType: "json",
		  url: voting.url,
		  type: "POST",
		  data: {
			object_id: object_id,
			type: content_type,
			action: "voting",
			score: vote
		  },
		  success: function(data){
			alerts.show(statuses[data.status]);
			switch (data.status){
			case 3: break;
			case 5: break;
			case 7: 
			  arrow.parent().attr('class', 'voting').addClass(data.voted+"-on");
			  arrow.parent().find('.score').html(data.score);
			  break;
			}

			$.log(data);
			return false;
		  },
		  error: function(){
			alerts.show('Что-то пошло не так');
		  }
		});
		return  false;
	  });
	}
  }
})(jQuery);


var removing = (function($){
  var statuses = [
	"Не авторизован",
    "Неверные параметры",
    "Недостаточно прав для удаления",
    "Пост уже был удалён, восстанавливаем",
    "Объект успешно удалён"
  ]
  return {
	url: null,
	init: function(url){
	  this.url = url;
	  var links = $('a.delete-post');
	  links.click(function(){
		$.log('Нажали').log(this);
		var a = $(this).attr('id').slice('delete-'.length).split('-');
		var content_type = a[0], id = a[1];
		$.log(content_type).log(id);
		$.ajax({
		  dataType: "json",
		  url: removing.url,
		  type: "POST",
		  data: {
			object_id: id,
			type: content_type,
			action: "remove"
		  },
		  success: function(data){
			alerts.show(data.message);
			if(data.status == 3){
			  $("#"+content_type+"-"+id).removeClass('deleted');
			}
			else if(data.status == 4){
			  $("#"+content_type+"-"+id).addClass('deleted');
			}
		  },
		  error: function(){}
		});
		return false;
	  });
	}
  }
})(jQuery);

var close = (function($){
  var statuses = [
	"Не авторизован",
    "Неверные параметры",
    "Недостаточно прав для закрытия",
    "Недостаточно прав для открытия",
    "Вопрос успешно закрыт",
	"Вопрос успешно открыт"
  ]
  return {
	url: null,
	reload_links: function(){},
	show_dialog: function(e){
	  $.log('Показываем диалог');
	  var close_button = button = $(e);
	  if(button.hasClass('close-post')){
		var a = $(e).attr('id').slice('close-'.length).split('-');
		var content_type = a[0], id = a[1];
		$('<div title="Выберите причину закрытия"/>').dialog({
		  autoOpen: false, 
		  position:'center',
		  modal: true,
		  width: '400px',
		  open: function(event, ui){
			var wrapper = dialog = $(this);
			$.ajax({
			  dataType: "json",
			  url: close.url,
			  type: "POST",
			  data: {
				object_id: id,
				type: content_type,
				action: "load"
			  },
			  success: function(data){
				var reasons_list = $('<ul/>').addClass('reasons_list');
				$.each(data.reasons, function(i,v){
				  reasons_list.append($('<li/>').addClass('reason').click(function(){
					$.ajax({
					  dataType: "json",
					  url: close.url,
					  type: "POST",
					  data: {
						object_id: id,
						type: content_type,
						action: "close",
						reason: v[0]
					  },
					  success: function(data){
						if(data.message){
						  alerts.show(data.message);
						}
						dialog.dialog('close');
						close_button.after($('<a/>').attr('id','reopen-question-'+id).addClass('reopen-post').click(function(){
						  close.show_dialog(this);
						}).html("открыть"));
						close_button.remove();
					  },
					  error: function(){}
					});
					return false;
				  }).html(v[1]));
				});
				wrapper.append(reasons_list);
			  },
			  error: function(){}
			});		
		  }
		}).dialog('open');
	  }
	  else if (button.hasClass('reopen-post')){
		var a = $(e).attr('id').slice('reopen-'.length).split('-');
		var content_type = a[0], id = a[1];
		$.ajax({
		  dataType: "json",
		  url: close.url,
		  type: "POST",
		  data: {
			object_id: id,
			type: content_type,
			action: "reopen"
		  },
		  success: function(data){
			if(data.message){
			  alerts.show(data.message);
			}
			close_button.after($('<a/>').attr('id','close-question-'+id).addClass('close-post').click(function(){
			  close.show_dialog(this);
			}).html("закрыть"));
			close_button.remove();
		  },
		  error: function(){}
		});
	  }
	  return false;
	},
	init: function(url){
	  this.url = url;
	  var links = $('a.close-post, a.reopen-post');
	  links.click(function(){
		close.show_dialog(this);
		return false;
	  });
	}
  }
})(jQuery);

var interests = (function($){
  return {
	interesting: [],
	ignoring: [],
	prefix: 'tctctc-',
	init: function(url,ignoring, interesting){
	  interests.interesting = interesting;
	  interests.ignoring = ignoring;
	  interests.url = url;
	  interests.hightlight();
	  $('.interesting, .ignoring').each(function(i,v){
		var form = $(this);
		var tag_input = form.find('[type~=text]');
		var button = form.find('input[type~=button]');
		tag_input.keyup(function(event){
		  if(event.keyCode == 13){
			button.click();
		  }
		});
		button.click(function(){
		  var tag_name = tag_input.val();
		  if(form.hasClass('interesting')){
			type = 'interesting';
		  }
		  else if(form.hasClass('ignoring')){
			type = 'ignoring';
		  }
		  else {
			type = 'none'
		  };
		  $.ajax({
			dataType: "json",
			url: interests.url,
			type: "POST",
			data: {
			  type: type,
			  tag_name: tag_name,
			  action: 'add'
			},
			success: function(data){
			  alerts.show(data.message);
			  var tags = form.find('.tags').html('');
			  if(data.status == 2 || data.status == 3){
				$.each(data[type],function(i,v){
				  tags.append($('<span/>').addClass('tag_box').append($('<a/>').addClass('tag').attr({
					rel:'tag',
					href: v.url
				  }).html(v.name)).append($('<a/>').addClass('delete').attr('href','#').html('×').click(
					function(){
					  interests.remove_tag(this);
					  return false;
					}
				  )));
				});
				tag_input.val('');
				if(type == 'interesting'){
				  interests.hightlight_post(tag_name);
				}
				else if (type == 'ignoring'){
				  interests.hidepost(tag_name);
				}
			  }
			},
			error: function(req, status){
			  alerts.show('Произошла ошибка, попробуйте ещё раз');
			}
		  });
		  return false;
		});
		form.find('.tags .delete').click(
		  function(){
			interests.remove_tag(this);
			return false;
		  }
		);
	  });
	  
	},
	remove_tag: function(tag){
	  var tag_box = $(tag).parent();
	  var tag_name = tag_box.find('.tag').html();
	  var ibox = tag_box.parent().parent();
	  if(ibox.hasClass('interesting')){
		type = 'interesting';
	  }
	  else if(ibox.hasClass('ignoring')){
		type = 'ignoring';
	  }
	  else {
		type = 'none'
	  }
	  $.ajax({
		dataType: "json",
		url: interests.url,
		type: "POST",
		data: {
		  type: type,
		  tag_name: tag_name,
		  action: 'remove'
		},
		success: function(data){
		  alerts.show(data.message);
		  if(data.status == 4 || data.status == 5)
		  {
			tag_box.remove();
			interests.remove_hightlight(tag_name);
		  }
		},
		error: function(req, status){
		  alerts.show('Произошла ошибка, попробуйте ещё раз');
		}
	  });
	  return false;
	},
	hightlight: function(){
	  interests.interesting;
	  $.each(interests.interesting, function(i,v){
		interests.hightlight_post(v);
	  });
	  $.each(interests.ignoring, function(i,v){
		interests.hidepost(v);
	  });
	},
	hightlight_post: function(tag){
	  $('li.question .tags.'+interests.prefix+tag).parent().parent().addClass('interested_q').removeClass('ignored_q');
	},
	hidepost: function(tag){
	  var q = $('li.question .tags.'+interests.prefix+tag).parent().parent();
	  q.each(function(k,v){
		if(!$(v).hasClass('interested_q')){
		  $(v).addClass('ignored_q');
	  };
	  });
	},
	remove_hightlight: function(tag){
	  $('li.question .tags.'+interests.prefix+tag).parent().parent().removeClass('ignored_q').removeClass('interested_q');
	}
  }
})(jQuery);

(function($){
  $.questions = {};
})(jQuery);