jQuery(function()
{
    var cur_id = '';
    var cur_link_title = '';

	$("#aoc_enter").click(function(){
		$("#enter_form").toggle(200);
		return false;
	});

	$("#utype").click(function(){
		if($(this).attr('checked') == true)
		{			$("#dp_reg").show();		}
		else
		{			 $("#dp_reg").hide();		}
	});

	// ------------- комментарии -----------------

    // привязка к каждой ссылке добавления/редактирования соотв. вызовов форм
    $("#comment_block a[id^='reply']").click(function(){    	unset_all_greys();		call_form(this);
    });
    $("#comment_block a[id^='edit']").click(function(){    	unset_all_greys();
		call_edit(this);
    });

    // Уничтожение формы, убирание всех подкрашиваний
    function unset_all_greys()
    {
        $("#comment_block a[id^='edit']").removeClass('grey');
    	$("#comment_block a[id^='reply']").removeClass('grey');
    	$("#comment_block div.reply").removeClass('grey');
    	$("#reply_table").parent().html("");
        $("#edit_table").parent().html("");    }

    function restore_name()
    {    	if(cur_id != '' && cur_link_title != '') {$("#" + cur_id).html(cur_link_title);}    }

    // вызов формы редактирования
    function call_edit(obj)
    {
        restore_name();
    	if(cur_id == $(obj).attr("id"))
    	{
    		cur_id = '';
    		cur_link_title = '';			unset_all_greys();
			return;    	}
    	var block = $(obj).parent().parent().find("div.reply:eq(0)");
    	cur_id = $(obj).attr("id");
    	cur_link_title = $(obj).html();
    	$(obj).html("закрыть");

        var id = $(obj).attr("rel");        var params = {act: 'comment_edit', id:id};
		$.ajax({
       	"url": "/ajax/comment.php",
       	"dataType": "html",
       	"type": "POST",
       	"cache": false,
       	"data": jQuery.param(params),
       	"beforeSend" : function(){
       			$(block).addClass('grey');
       			$(obj).addClass('grey');
       	        $(block).css('textAlign','center');
                $(block).html('<img src="/images/ajax-loader.gif" />');
       		},
       		"success": function(data){
       		    $(block).css('textAlign','left');
				$(block).html(data);
                edit_comment_send();
       		},
       		"error":function(){
        	alert("Server AJAX error");
       		}
      	});    }

    // вызов формы добавления комментария
    function call_form(obj)
    {
    	restore_name();
    	if(cur_id == $(obj).attr("id"))
    	{

    		if(cur_id != '') {$("#" + cur_id).html(cur_link_title);}
    		cur_id = '';
    		cur_link_title = '';
			unset_all_greys();
			return;
    	}
    	var block = $(obj).parent().parent().find("div.reply:eq(0)");
    	cur_id = $(obj).attr("id");
    	cur_link_title = $(obj).html();
    	$(obj).html("закрыть");

    	var id = $(obj).attr("rel");
    	var params = {act: 'reply_form',id:id};
		$.ajax({
       	"url": "/ajax/comment.php",
       	"dataType": "html",
       	"type": "POST",
       	"cache": false,
       	"data": jQuery.param(params),
       	"beforeSend" : function(){
       			$(block).addClass('grey');
       			$(obj).addClass('grey');
       	        $(block).css('textAlign','center');
                $(block).html('<img src="/images/ajax-loader.gif" />');
       		},
       		"success": function(data){
       		    $(block).css('textAlign','left');
				$(block).html(data);
				reply_comment_send();
       		},
       		"error":function(){
        		alert("Server AJAX error");
       		}
      	});    }

    // привязка к кнопке редактирования комментария, проверка на ошибки
    function edit_comment_send()
    {

		$("#send_edit").click(function(){			var msg = '';
            if($("#edit_usercomment").val() == '')
            {
                msg += '— Вы не ввели сообщение\n';
            }

            if(msg == '')
            {                var block = $(this).parent().parent().parent().parent().parent().parent();
                var params = {act: 'edit_send',id: $("#id_comment").val(), content: $("#edit_usercomment").val()}
                $.ajax({
       			"url": "/ajax/comment.php",
       			"dataType": "html",
       			"type": "POST",
       			"cache": false,
       			"data": jQuery.param(params),
       			"beforeSend" : function(){

       			},
       			"success": function(data){
       				if($(data).find("li").size() > 0)
       				{
						$("#reply_table").parent().html(data);
						edit_comment_send();
       				}
       				else
       				{
       				    $(block).find("div.txt:first").html(data);
	       				$("#edit_table").parent().html("");
	       				unset_all_greys();
	       				restore_name();
	       				cur_id = '';
       				}


       			},
       			"error":function(){
        		alert("Server AJAX error");
       			}
      			});            }
            else
            {            	msg = 'Ошибки заполнения:\n' + msg;
            	alert(msg);            }
		})    }

    // привязка к кнопке отправки комментария, проверка на ошибки
    function reply_comment_send()
    {

        $("#send_reply").click(function(){            var msg = '';
            if($("#reply_username").val() == '')
            {                msg += '— Вы не ввели имя\n';            }
            if($("#reply_usercomment").val() == '')
            {
                msg += '— Вы не ввели сообщение\n';
            }
            if(msg == '')
            {
            	var block = $(this).parent().parent().parent().parent().parent().parent().find("div.replies_list:eq(0)");
            	var params = {act: 'reply_send', id: $("#id_parent").val(), reply_username: $("#reply_username").val(),
            	reply_useremail: $("#reply_useremail").val(), reply_usercomment: $("#reply_usercomment").val()};                $.ajax({
       			"url": "/ajax/comment.php",
       			"dataType": "html",
       			"type": "POST",
       			"cache": false,
       			"data": jQuery.param(params),
       			"beforeSend" : function(){

       			},
       			"success": function(data){       				if($(data).find("li").size() > 0)
       				{						$("#reply_table").parent().html(data);
						reply_comment_send();       				}
       				else
       				{
	       				$(block).append(data);
	       				$(block).find("a[id^='reply']:last").click(function(){	       					call_form(this);
	       				});
	       				$(block).find("a[id^='reply']:last + a[id^='edit']").click(function(){
	       					call_edit(this);
	       				});
	       				$("#reply_table").parent().html("");
	       				unset_all_greys();
	       				restore_name();
	       				cur_id = '';       				}


       			},
       			"error":function(){
        		alert("Server AJAX error");
       			}
      			});            }
            else
            {            	msg = 'Ошибки заполнения:\n' + msg;
            	alert(msg);            }


        	return false;        });    }
    // ------------ /комментарии -----------------


});