var tags = {
	vote: function (brand_id, tag_url, rating, one)
	{
		var $tags = this;
		$.ajax({
			url: "/brands/voteTag/"+brand_id,
			type: "POST",
			dataType: "html",
			data: ({tag_url: tag_url, rating: rating, one: one}),
			success: function(data){
				$("#brandsVoting").html(data);
				if(one == 1) $tags.renew(brand_id);
			}
		});
		return false;
	},
	add: function (url, tags, place_id)
	{
		var $tags = this;
		$.ajax({
			url: url,
			type: "POST",
			cache: false,
			dataType: "json",
			data: ({tags: tags}),
			success: function(response){
				info.show("addTagsResponse", response);
				$tags.renew(place_id);
			}
		});
		return false;
	},
	renew: function (brand_id)
	{
		$("#tagsBrand")
		.effect("highlight", {}, 800)
		.load("/brands/getBrandTagCloud/"+brand_id);
	},
	toggle: function ()
	{
		$("#tagsSuggestForm").toggle();
	}
}

var core = {
	events: function ()
	{
		$('.tipsy').remove();
		$('.tip, .icon, .button[title!=""]').tipsy({gravity: 's'});
		$('.tipr').tipsy({gravity: 'w'});
		$('.tipl').tipsy({gravity: 'e'});

		$(".nav_block").unbind('click').click(function (){
			var elem = $(this);
			var hash = $(elem).attr('href');
			$.ajax({
				url: hash,
				cache: false,
				dataType: "html",
				success: function(data){
					$(elem).hide("fast").remove();
					$("#comments").append(data);
				}
			});
			return false;
		});
		
		tb_init('a.thickbox');
	}
}

var info = {
	show: function (divId, response)
	{
		$("#"+divId).empty();
		$.each(response, function(i, v) {
			$("#"+divId).append("<div class=\""+ v.type +"\">"+v.msg+"</div>");
			if(v.redirect != undefined) window.location = v.redirect;
			if(v.javascript != undefined) eval(v.javascript);
		});
	}
}

var comment = {
	init: function ()
	{
		$('.commentForm').submit(function() {
			$(this).ajaxSubmit({ 
				success: afterSubmitComment,
				resetForm: true
			});
			return false; 
		});
		function afterSubmitComment(response, status) {
			comment.commentSucess(response, status);
			return false;
		}
	},
	commentSucess: function (response, status)
	{
		$("#comments").prepend(response);
		$("#comments .highlight").effect("highlight", {}, 3000);
		$("#comments .highlight").removeClass("highlight");
		$('#commentForm').remove();
	},
	rate: function (brand_id, comment_id, rating)
	{
		$.ajax({
			url: "/brands/ajax_comment_rate/"+brand_id+"/"+comment_id,
			type: "POST",
			dataType: "html",
			data: ({rating: rating}),
			success: function(data){
			$("#comment_rating_"+comment_id).html(data);
			$("#comment_rating_actions_"+comment_id).remove();
			}
		});
	}
}

$(document).ready(function () {

	$("#loader").ajaxStart(
		function(){
			$(this).show();
	}).ajaxComplete(
		function(){
			$(this).hide();
		}
	);

	core.events();
	comment.init();
});
