

function BlogImages()
{
	this.actions_path = "/actions/blogs_actions.php";
	this.names = {
		container: "#comment-image-chooser"
	};
	this.insert_callback = null;
	this.last_image_id = 0;
	this.is_busy = false;
	this.is_first_load = true;
	this.current_image_id  = "";
	//this.insert_images_limit = 3;
	this.image_inserted = 0;
	
	this.Init = function()
	{
		var obj = this;
		$(this.names.container + " .upload-field .submit-button").click(function(){
			obj.StartUpload();
		});
	};
	
	this.ShowWindow = function(data)
	{
		this.insert_callback = data.insert_callback;
		
		if (this.is_first_load)
		{
			this.GetImages();
			//var html = '';
			var dialog_params = 
			{
				width: 650,
				height: 500,
				modal: true,
				buttons: {
					"Закрыть": function() {
						$(this).dialog("close");
					}
				}
			};
			$(this.names.container).dialog(dialog_params);
			
			var obj = this;
			$(this.names.container).scroll(function(){
				if (isScrolledIntoView(obj.names.container, obj.names.container+" .load-images-trigger")) {
					obj.GetImages();
				}
			});
			
			$(this.names.container + " .images-list .image").live("mouseenter", function(){
				obj.ShowControls(this);
			}).live("mouseleave", function(){
				obj.HideControls(this);
			});
			$(this.names.container + " .images-list .image .add-control").live("click", function(){
				obj.OnInsertImage(this);
			});
			
			this.is_first_load = false;
		}
		
		$(this.names.container).dialog("open");
	};
	
	this.OnInsertImage = function(sender)
	{
		if (this.insert_callback != null)
		{
			var image = $(sender).parent().find("img"); // o_O
			this.image_inserted++;
			this.insert_callback({
				thumb_url: $(image).attr("src"),
				id: $(image).attr("id")
			});
		}
	};
	
	this.StartUpload = function()
	{
		if ($(this.names.container + " .upload-field .image-file").val() == "") {
			alert("Укажите файл.");
			return false;
		}

		$(this.names.container + " .upload-field .status").html("Загрузка...");
		$(this.names.container + " .upload-field .status").show();
		
		var upload_form = $(this.names.container + " .upload-field .upload-form");
		upload_form.submit();
		
		$(this.names.container + " .upload-field .image-file").attr("disabled", "disabled");
		$(this.names.container + " .upload-field .submit-button").attr("disabled", "disabled");
	};
	
	this.FinishUpload = function(data)
	{
		$(this.names.container + " .upload-field .status").html(data.Message.Text);
		
		if (data.Html) {
			$(this.names.container + " .images-list").prepend(data.Html);
		}
		
		$(this.names.container + " .upload-field .image-file").attr("disabled", "");
		$(this.names.container + " .upload-field .submit-button").attr("disabled", "");
	};
	
	this.GetImages = function()
	{
		if (this.is_busy) return;
		this.is_busy = true;
		var obj = this;
		$.ajax({
			url: this.actions_path,
			type: "GET",
			dataType: "json",
			data: {
				action: "get-user-images",
				first_image: this.last_image_id
			},
			success: function(data) {
				obj.OnGetImagesSuccess(data);
			}
		});
	};
	this.OnGetImagesSuccess = function(data)
	{
		if (data.Html) {
			$(this.names.container + " .images-list").append(data.Html);
		}
		if (data.IsLastPage == true) {
			$(this.names.container + " .load-images-trigger").hide();
			$(this.names.container).unbind("scroll");
		}
		this.last_image_id = data.LastImageId;
		this.is_busy = false;
	};
	
	this.ShowControls = function(sender)
	{
		$(sender).find(".add-control").fadeIn();
	};
	this.HideControls = function(sender)
	{
		$(sender).find(".add-control").fadeOut();
	};
}

function isScrolledIntoView(scolled_elem, elem)
{
	var docViewTop = $(scolled_elem).scrollTop();
	var docViewBottom = docViewTop + $(scolled_elem).height();
	
	var elemTop = $(elem).position().top;
	var elemBottom = elemTop + $(elem).height();
	
	return ((elemBottom >= docViewTop) && (elemTop <= docViewBottom));
}

function CommentImagesControl()
{
	this.images = [];	
	this.BlogImages = null;
	this.control_container = "";
	this.images_inserted = 0;
	this.images_limit = 10;
	this.current_image = "";
	
	this.Init = function(options)
	{
		this.BlogImages = new BlogImages();
		this.BlogImages.Init();
		
		var obj = this;
		this.control_container = options.control_container;
		$(this.control_container)
			.append('<a href="javascript:///">добавить изображения</a>')
			.append('<div class="message"></div><div class="images-list"></div>');
		$(this.control_container + " > a").click(function(){ obj.OnInsertClick(); });
		$(this.control_container + " .images-list .image").live("mouseenter", function(){
			obj.ShowControls(this);
		}).live("mouseleave", function(){
			obj.HideControls(this);
		});
		
		$(this.control_container + " .images-list .image .remove-control").live("click", function(){
			obj.RemoveImage(this);
		});
		
	};
	
	this.Reload = function()
	{
		$(this.control_container + " .images-list").html("");
		this.images = [];
		this.images_inserted = 0;
		this.current_image = "";
		this.CheckImagesCount();
	};
	
	this.GetImagesList = function()
	{
		var result = { "comment_images": [] };
		$(this.control_container + " .images-list .image img").each(function(){
			result.comment_images.push($(this).attr("src"));
		});
		return result;
	};
	
	this.ShowControls = function(sender)
	{
		$(sender).find(".remove-control").fadeIn();
	};
	this.HideControls = function(sender)
	{
		$(sender).find(".remove-control").fadeOut();
	};
	
	this.RemoveImage = function(sender)
	{
		this.images_inserted--;
		$(sender).parent().remove();
		this.CheckImagesCount();
	};
	
	this.OnInsertClick = function()
	{
		var obj = this;
		this.BlogImages.ShowWindow({
			insert_callback: function(data) {
				obj.InsertCallback(data);
			}
		});
	};
	this.InsertCallback = function(data)
	{
		this.images_inserted++;
		this.images.push(data);
		$(this.control_container + " .images-list").append('<div class="image"><img src="'+ data.thumb_url +'"><div class="remove-control">убрать</div></div>');
		this.CheckImagesCount();
	};
	
	this.CheckImagesCount = function()
	{
		if (this.images_inserted > this.images_limit) {
			$(this.control_container + " .message").html("Можно вставить не более 10 изображений.");
			$(this.control_container + " .message").show();
			$(this.control_container + " .message").css({ "color": "red", "font-weight": "bold" });
		} else {
			$(this.control_container + " .message").hide();
		}
	};
}




	var Blogs = 
	{		
		actionsPath : "/actions/blogs_actions.php",
		
		DeletePost : function(post_id)
		{
			var vars = "action=deletepost&postid="+ post_id;
			if (confirm("Удалить сообщение?") == false) return false;
			try {
				sendXmlHttpRequest("post", this.actionsPath, vars, function(jsHttp) 
				{
					eval("var json = " + jsHttp.responseText);
					if (json.Message.Type == "info") 
					{
						if (json.Result == true) 
						{
							alert("Сообщение удалено");
							location.reload(); 
						}
					} else {
						alert(json.Message.Type + ":\n" + json.Message.Text);
					}
				});
			} catch (e) {
				alert(e);
			}
		},
		
		DeleteBlogImage : function(image_id)
		{
			var vars = "action=deleteimage&imageid="+ image_id;
			if (confirm("Удалить изображение?") == false) return false;
			try {
				sendXmlHttpRequest("post", this.actionsPath, vars, function(jsHttp) 
				{
					eval("var json = " + jsHttp.responseText);
					if (json.Message.Type == "info") 
					{
						if (json.Result == true) 
						{
							document.getElementById("photo_list" + image_id).src = "/common/img/img_deleted.png";
							//location.reload(); 
						}
					} else {
						alert(json.Message.Type + ":\n" + json.Message.Text);
					}
				});
			} catch (e) {
				alert(e);
			}
		},
		
		RatePost : function(post_id, rate)
		{
			var vars = {
				"action": "rate",
				"postid": post_id,
				"rate": rate
			}
			try {
				sendXmlHttpRequest("post", this.actionsPath, xhParseParams(vars), function(jsHttp) 
				{
					eval("var json = " + jsHttp.responseText);
					if (json.Message.Type == "info") 
					{
						if (rate == 1)
							$("#post_votes_yes_" + post_id).html("+" + json.Votes);
						else
							$("#post_votes_no_" + post_id).html("-" + json.Votes);
						/*var str_rating = "";
						if (json["Rating"] > 0) 
							str_rating = "<span class=\"green_rating\">+"+json["Rating"]+"</span>";
						else if (json["Rating"] < 0) 
							str_rating = "<span class=\"red_rating\">"+json["Rating"]+"</span>";
						else
							str_rating = "<span class=\"gray_rating\">"+json["Rating"]+"</span>";
						document.getElementById("comment_rating_" + id).innerHTML = str_rating;*/
					} else {
						alert(json.Message.Type + ":\n" + json.Message.Text);
					}
				});
			} catch (e) {
				alert(e);
			}
		}
		
	}
	
	var BlogsPolls = 
	{
		actionsPath : "/actions/blogs_actions.php",
		
		GetAnswersCount: function() {
			return $("#answers_list div").length;
		},
		
		AddAnswer : function() {
			var answers_count = this.GetAnswersCount();
			if (answers_count >= 10) {
				alert("Можно добавить не более 10 ответов");
				return;
			}
			$("#answers_list").append('<div> &curren; <input maxlength="255" size="30" type="text" class="textbox" name="answers[]" value=""> <a class="small_link" href="javascript:///" onclick="BlogsPolls.RemoveAnswer(this);">удалить</a></div>');
		},
		
		RemoveAnswer : function(sender) {
			var answers_count = this.GetAnswersCount();
			if (answers_count <= 2) {
				alert("Ответов должно быть не менее 2");
				return;
			}
			$(sender).parent().remove();
		},
		
		Vote : function(post_id) {
			var answer = $("input[name='post_poll_answer_" + post_id + "']:checked").val();
			if (!answer) return;
			var vars = {
				"action": "polls-vote",
				"postid": post_id,
				"answer" : answer
			}
			try {
				sendXmlHttpRequest("post", this.actionsPath, xhParseParams(vars), function(jsHttp) 
				{
					eval("var json = " + jsHttp.responseText);
					if (json.Message.Type == "info") 
					{
						$("#post_poll_" + post_id).html(json.Html);
					} else {
						alert(json.Message.Type + ":\n" + json.Message.Text);
					}
				});
			} catch (e) {
				alert(e);
			}
		}
		
	}
	
	
	
	
	

