/**
 * @author Yakubov Andrey
 */
$(function() {

var $input = $("#search");

var $link_field = $("#link_field");
	
    var KEY = {
        UP: 38,
        DOWN: 40,
        DEL: 46,
        TAB: 9,
        RETURN: 13,
        ESC: 27,
        COMMA: 188,
        PAGEUP: 33,
        PAGEDOWN: 34,
        BACKSPACE: 8
    };
	
	var timeout;
	
	var currentIndex = 0;
	
	$link_field.bind(($.browser.opera ? "keypress" : "keydown"), function(event) 
    {
		switch (event.keyCode) {
			case KEY.RETURN:			
                clearTimeout(timeout);
                timeout = setTimeout(onLinkAdd, 50);
				
				break;
		}
	});
	
    $input.bind(($.browser.opera ? "keypress" : "keydown") + ".autocomplete", function(event) 
	{
        switch (event.keyCode) {
		
			/*case KEY.UP:
			
			    if (currentIndex>0) 
				    currentIndex--;
                selectItem(currentIndex);				
				break;
				
			case KEY.DOWN:
			    var mx = parseInt($('#ev_count').val());
				
				if (mx<10)
				{
	                if (currentIndex<(mx-1))
	                    currentIndex++;					
				}
				else
				{
	                if (currentIndex<9)
	                    currentIndex++;					
				}				

                selectItem(currentIndex);				
				break;
				
			case KEY.RETURN:
			    if ($("#result_" + currentIndex + ">a").attr("href") != undefined) {
					document.location = ($("#result_" + currentIndex + ">a").attr("href"));
				}
			    break;
			*/	
			default:
			    currentIndex = 0;
                clearTimeout(timeout);
                timeout = setTimeout(onChange, 50);			    
			    break;
		}
	   });	  
});

function selectItem(index)
{
	/*$("#result_" + (index-1)).removeClass("searchactive");
	$("#result_" + (index+1)).removeClass("searchactive");
	$("#result_" + (index-1)).addClass("searchinactive");
    $("#result_" + (index+1)).addClass("searchinactive");
	
	$("#result_" + index).removeClass("searchinactive");
    $("#result_" + index).addClass("searchactive");	
	
	//$("#highlight").css("color", "#FFFFFF");
	
	//alert($("#highlight").size());*/
}

function onChange()
{
    lookup($("#search").val());	
}

function onLinkAdd()
{
	var str;
	if (document.location.href.indexOf('user') == -1) {
		addLink($("#link_field").val());
	}
	else
	{
		profileAddLink($("#link_field").val());
	}
}

function lookup(val)
{
	if (val.length <3)
	{
		$("#search_res").hide();
		return;
	}
	else
	{
	    JsHttpRequest.query(
	          "/search?request_mode=ajax",
	          {'query' : val, 'ajax_action' : 'search_query'},
	          function(result, errors) {
	             if(errors)
	             {
	                if(!production_flag){alert(errors);}
	             }
	             
	             if (result)
	             {
				 	result = result.replace(new RegExp("(?![^&;]+;)(?!<[^<>]*)(" + val.replace(/([\^\$\(\)\[\]\{\}\*\.\+\?\|\\])/gi, "\\$1") + ")(?![^<>]*>)(?![^&;]+;)", "gi"), "<span id='highlight'>$1</span>");
	                $("#search_res").html(result);
					$("#search_res").show();
					
					selectItem(0);
					//alert($("#search_res").html());
	             }
	          },
	          true
	      );		
	}
	
}

function hideSugg()
{
	setTimeout('$("#search_res").hide();', 200);
}

function trim (str) {
	if (str == null) return "";
	
	str = str.replace(/^\s+/, '');
	for (var i = str.length; --i >= 0;) {
		if (/\S/.test(str.charAt(i))) {
			str = str.substring(0, i + 1);
			break;
		}
	}
	return str;
}


function onTitleSelect(item, type)
{
    if (item.id!=-1)
    {
        document.location = "/" + type + "/" + item.id;
    }
}

function showmenu(what) {
	var x = what.id;
	if(document.getElementById(x+"menu").style.display != "block"){
	document.getElementById(x+"menu").style.display = "block";
	}else{
	document.getElementById(x+"menu").style.display = "none";	
	}
}

function hideMenu()
{
    // document.getElementById("logomenu").style.display = "none";
    document.getElementById("searchmenu").style.display = "none";
}

function showSearchBar(type)
{
    if (type=='movie')
    {
        $('#search_movie').show();
        $('#search_book').hide();
        $('#search_travel').hide();
        
        $('#movie_s_span').show();
        $('#book_s_span').hide();
        $('#travel_s_span').hide();
    }
    else if (type=='book')
    {
        $('#search_book').show();
        $('#search_movie').hide();
        $('#search_travel').hide();
        
        $('#movie_s_span').hide();
        $('#book_s_span').show();
        $('#travel_s_span').hide();
    }
    else
    {
        $('#search_travel').show();
        $('#search_movie').hide();
        $('#search_book').hide();
        
        $('#movie_s_span').hide();
        $('#book_s_span').hide();
        $('#travel_s_span').show();
    }
    
    $('#search_form').attr({
        'action': '/'+type+'/add'
    });
} 

function getAuthForm()
{
    JsHttpRequest.query(
      	  "/?request_mode=ajax",
      	  {'ajax_action' : 'get_auth_form'},
      	  function(result, errors) {
             if(errors)
		     {
		     	if(!production_flag){alert(errors);}
		     }
             
             if (result)
             {
                $('#login_div').html(result);
             }
      	  },
      	  true
      );
}

function getRegistrationForm()
{
    JsHttpRequest.query(
      	  "/?request_mode=ajax",
      	  {'ajax_action' : 'get_reg_form'},
      	  function(result, errors) {
             if(errors)
		     {
		     	if(!production_flag){alert(errors);}
		     }
             
             if (result)
             {
                $('#login_div').html(result);
             }
      	  },
      	  true
      );
}

function registerUser(reg_form)
{
    JsHttpRequest.query(
      	  "/?request_mode=ajax",
      	  {'reg_form' : reg_form, 'ajax_action' : 'reg_user'},
      	  function(result, errors) {
             if(errors)
		     {
		     	if(!production_flag){alert(errors);}
		     }
             
             if (result) {
                 if (parseInt(result.error_status)) {
                     $('#warning').html('<li><b class="red">' + result.error_msg +'</b></li>');
                     $('#warning').show();
                 }
                 else {
                     document.location.reload();
                 }
             }
      	  },
      	  true
      );
}

function logoutUser()
{
    JsHttpRequest.query(
    	  "/?request_mode=ajax",
    	  {'ajax_action' : 'logout'},
    	  function(result, errors) {

    	  	 if(errors)
		     {
		     	if(!production_flag){alert(errors);}
		     }
		     else
		     	if(result)
		     	{
		     	    document.location.reload();
		     	}
    	  },
    	  true
      ); 
}

function authUser(auth_form)
{
    JsHttpRequest.query(
    	  "/?request_mode=ajax",
    	  {'auth_form' : auth_form,'ajax_action' : 'auth_user'},
    	  function(result, errors) {

    	  	 if(errors)
		     {
		     	if(!production_flag){alert(errors);}
		     }
             
             if (result) {
                 if (parseInt(result.error_status)) {
                     if (parseInt(result.error_status) == 1)
                     {
                         $('#err_login').show();
                         $('#err_pwd').hide();
                     }
                     else
                     {
                         $('#err_login').hide();
                         $('#err_pwd').show();
                     }
                 }
                 else {
                     document.location.reload();
                 }
             }
    	  },
    	  true
      );     
}

function sortComment()
{
    $('#progress_bar').show();
    JsHttpRequest.query(
    	  "/?request_mode=ajax",
    	  {'ajax_action' : 'sort_comm'},
    	  function(result, errors) {

    	  	 if(errors)
		     {
		     	if(!production_flag){alert(errors);}
		     }
             
             if (result) {
                $('#progress_bar').hide();
                $('#items_on_main').html(result);
                $('#toplinks').html("<span id='show_all'>\
                                    (<a href='javascript:void(0);' onclick='sortAll();'>показывать все просмотры</a>)</span>\
                                    <span id='show_comm'>\
                                    с комментарием</span>\
                                    <span id='show_rec'>\
                                    (<a href='javascript:void(0);' onclick='sortRec();'>рекомендованные</a>)</span>");
             }
    	  },
    	  true
      );     
}

function sortRec()
{
    $('#progress_bar').show();
     JsHttpRequest.query(
    	  "/?request_mode=ajax",
    	  {'ajax_action' : 'sort_rec'},
    	  function(result, errors) {

    	  	 if(errors)
		     {
		     	if(!production_flag){alert(errors);}
		     }
             
             if (result) {
                $('#progress_bar').hide();
                $('#items_on_main').html(result);
                $('#toplinks').html("<span id='show_all'>\
                                    (<a href='javascript:void(0);' onclick='sortAll();'>показывать все просмотры</a>)</span>\
                                    <span id='show_comm'>\
                                    (<a href='javascript:void(0);' onclick='sortComment();'>с комментарием</a>)</span>\
                                    <span id='show_rec'>\
                                    рекомендованные</span>");
             }
    	  },
    	  true
      );    
}


function sortAll()
{
    $('#progress_bar').show();
     JsHttpRequest.query(
    	  "/?request_mode=ajax",
    	  {'ajax_action' : 'sort_all'},
    	  function(result, errors) {

    	  	 if(errors)
		     {
		     	if(!production_flag){alert(errors);}
		     }
             
             if (result) {
                $('#progress_bar').hide();
                $('#items_on_main').html(result);
                $('#toplinks').html("<span id='show_all'>\
                                    >показывать все просмотры</span>\
                                    <span id='show_comm'>\
                                    (<a href='javascript:void(0);' onclick='sortComment();'>с комментарием</a>)</span>\
                                    <span id='show_rec'>\
                                    (<a href='javascript:void(0);' onclick='sortRec();'>рекомендованные</a>)</span>");
             }
    	  },
    	  true
      );    
}

function deleteComment(comment_id, type)
{
     if (!type || !comment_id) return;
    
     JsHttpRequest.query(
      	  "/" + type + "?request_mode=ajax",
      	  {'comment_id' : comment_id, 'ajax_action' : 'delete_comment'},
      	  function(result, errors) {
             if(errors)
		     {
		     	if(!production_flag){alert(errors);}
		     }
             
             if (result)
             {
                 document.location.reload();
             }
      	  },
      	  true
      ); 
}

function fieldOnFocus(field, hint)
{
    if (field.value == hint) {
		field.value = '';
		field.style.color = "#000000";
	}
}

function fieldOnBlur(field, hint)
{
     if (field.value == '') {
	 	field.value = hint;
		field.style.color = "#808080";
	 }
}

function toggleRecCheck()
{
    if ($('#is_rec').attr('checked') == true) 
        $('#is_rec').removeAttr('checked'); 
    else $('#is_rec').attr({'checked' : 'checked'}); 
}

function toggleEditRec(id, type)
{
     if ($('#is_rec_' + type +'_' + id).attr('checked') == true) 
        $('#is_rec_' + type +'_' + id).removeAttr('checked'); 
    else $('#is_rec_' + type +'_' + id).attr({'checked' : 'checked'});    
}

function toggleCommentForm(but_text)
{
    $('#plus_href').blur();
    if (but_text == '+')
    {
        $("#plus_href").html('-');
        $('#comment_box').slideDown('slow');
    }
    else
    {
        $("#plus_href").html('+');
        $('#comment_box').slideUp('slow');
    }
}

function showEditComment(id, type, is_rec_txt, is_rec, comm_date, forget_text)
{
    // alert('#comm_text' + type +'_' + id);
    var opened_id = $('#opened_id').val();
    var opened_type = $('#opened_type').val();
    
    if (opened_id != "" && opened_type!="") {
        hideEditComment(opened_id, opened_type);
    }
	
	getEditForm(id, type, is_rec_txt, is_rec, comm_date, forget_text);
    
    // blur();
    $('#calendar_' + type +'_' + id).datepicker({ 
                            dateFormat: 'yy-mm-dd', 
                            firstDay: 1,
                            dayNamesMin: [js_dictionary.sunday_min, 
                                          js_dictionary.monday_min, 
                                          js_dictionary.tusday_min, 
                                          js_dictionary.wensday_min, 
                                          js_dictionary.thursday_min, 
                                          js_dictionary.friday_min,
                                          js_dictionary.saturday_min],
                            monthNames: [js_dictionary.january, 
                                         js_dictionary.february, 
                                         js_dictionary.march, 
                                         js_dictionary.april, 
                                         js_dictionary.may, 
                                         js_dictionary.june, 
                                         js_dictionary.july, 
                                         js_dictionary.august, 
                                         js_dictionary.september, 
                                         js_dictionary.october, 
                                         js_dictionary.november, 
                                         js_dictionary.december],
                            showButtonPanel: true,
                            closeText: 'x (Закрыть)' });
    $('#edit_comm_' + type +'_' + id).show();    
    $('#text_' + type +'_' + id).hide();
    $('#text_cust_' + id).hide();
    $('#links_' + type +'_' + id).hide();
    $('#comm_type_' + type +'_' + id).hide();
    $('#comm_date_' + type +'_' + id).hide();
    $('#comm_text_' + type +'_' + id).focus();
    
    $('#opened_id').val(id);
    $('#opened_type').val(type);
}

function getEditForm(id, type,is_rec_txt, is_rec, comm_date, forget_text)
{
	var form_str = "";
	
	switch(type) {
	case 'movie':
	    form_str+= '<div class="editbox blueeditbox" id="edit_comm_' + type + '_' + id +  '" style="width:640px; display:block;">';
		break;
    case 'book':
        form_str+= ' <div class="editbox greeneditbox" id="edit_comm_' + type + '_' + id +  '" style="width:640px; display:block;">';
        break;
	default: 
		form_str+= ' <div class="editbox blueeditbox" id="edit_comm_' + type + '_' + id +  '" style="width:640px; display:block;">';
    }
	
	var rec_input = "";
	
	if (is_rec == 1)
	{
		rec_input += '<input id="is_rec_' + type + '_' + id +  '" type="checkbox" class="checkbox" name="is_rec" checked="checked"/>';
	}
	else
	{
		rec_input += '<input id="is_rec_' + type + '_' + id +  '" type="checkbox" class="checkbox" name="is_rec"/>';
	}
	
    var cal_input = "";
    
    if (comm_date == '0000-00-00')
    {
        cal_input += '<input readonly="true" type="text" class="text" value="'+forget_text+'" id="calendar_' + type + '_' + id +  '" name="comment_date"/>';
    }
    else
    {
        cal_input += '<input readonly="true" type="text" class="text" value="'+comm_date+'" id="calendar_' + type + '_' + id +  '" name="comment_date"/>';
    }
	
	form_str += '<form method="post" id="edit_comm_form_' + type + '_' + id +  '" enctype="multipart/form-data" onsubmit="return false;">';
	
	form_str += '<div class="colleft">\
                    <div class="inner">\
                        <textarea rows="6" cols="50" style="color:#000000;" id="comm_text_' + type + '_' + id +  '">' + trim($("#text_"+type+"_"+id).html()) +'</textarea>\
                    </div>\
                </div>';
				
    form_str += '<div class="colright">\
	                <div class="inner">\
	                    <div class="calendarbox">'+
	                        cal_input+
	                    '</div>'+
	                        rec_input+ 
	                        '<span class="font10">(<a href="javascript:void(0);" onclick="toggleEditRec(' + id + ', \'' + type +'\');">' + is_rec_txt + '</a>)</span>'+	
	                '</div>\
	                <div class="loglink"><span class="font36">(<a href="javascript:void(0);" onclick="editComment(' + id + ', \'' + type +'\');">+ llog!</a>)</span></div>\
	            </div>';
	
	form_str +='</form>';
	
	form_str +='</div>';
	
	$("#edit_place_"+id).html(form_str);
}

function hideEditComment(id, type)
{
    $('#edit_comm_' + type +'_' + id).hide();    
    $('#text_' + type +'_' + id).show();
    $('#text_cust_' + id).show();
    $('#links_' + type +'_' + id).show();
    $('#comm_type_' + type +'_' + id).show();
    $('#comm_date_' + type +'_' + id).show();
}

function editComment(id, type, comment_form)
{
    var text = $('#comm_text_' + type +'_' + id).val();
    
    var date = $('#calendar_' + type +'_' + id).val();
    
    var is_rec = $('#is_rec_' + type +'_' + id).attr('checked');

    JsHttpRequest.query(
      	  "/" + type + "?request_mode=ajax",
      	  {'comment_id' : id, 'text' : text, 'date' : date, 'is_rec' : is_rec, 'ajax_action' : 'edit_comment'},
      	  function(result, errors) {
             if(errors)
		     {
		     	if(!production_flag){alert(errors);}
		     }
             
             if (result)
             {
                 document.location.reload();
             }
      	  },
      	  true
      );     
}

function deleteLink(site)
{
    $("#" +site+"_li").remove();
    $("#" +site).remove();
}

function clearCache()
{
    JsHttpRequest.query(
      	  "/?request_mode=ajax",
      	  {'ajax_action' : 'clear_cache'},
      	  function(result, errors) {
             if(errors)
		     {
		     	if(!production_flag){alert(errors);}
		     }
             
             if (result)
             {
                 alert('Кэш словаря очищен!');
             }
      	  },
      	  true
      );  
}

/**
 * @author K. Kopachev
 */
function sayThanks( thanks_type, event_type, comment_id, to_user_id, a_tag )
{
	 if ( (thanks_type != 0 && thanks_type != 1) || !event_type || !comment_id || !to_user_id || !a_tag) {
		 return;
	 }
	 
	 // $('#progress_bar').show();
	 
	 JsHttpRequest.query(
	      	  "/?request_mode=ajax",
	      	  {
	      		'ajax_action' : 'say_thanks',
	      		'thanks_type' : thanks_type,
	      		'event_type'  : event_type,
	      		'comment_id'   : comment_id,
	      		'to_user_id'  : to_user_id
	      	  },
	      	  function(result, errors) {
	             if(errors)
			     {
			     	if(!production_flag){alert(errors);}
			     }
	             
	             if (result) {
	            	 
	            	 // $('#progress_bar').hide();
	            	 
	            	 elem = $(a_tag);
	            	 
	                 if (parseInt(result.error_status)) {
	                     $('#warning').html('<li><b class="red">' + result.error_msg +'</b></li>');
	                     $('#warning').show();
	                 }
	                 else {
	                     if ( thanks_type == 1 ) {
	                    	 elem.html('<i>- СПАСИБО</i>');
	                    	 elem.attr('onClick', "sayThanks(0, '" + event_type + "', " + comment_id + ", " + to_user_id + ", this )");
	                     } else {
	                    	 elem.html('<i>+ СПАСИБО</i>');
	                    	 elem.attr('onClick', "sayThanks(1, '" + event_type + "', " + comment_id + ", " + to_user_id + ", this )");
	                     }
	                 }
	             }
	      	  },
	      	  true
	      );
}

function inputMaskNumber(e)
{
	var ch = "0123456789";
	
	/*if (!e.charCode) k = String.fromCharCode(e.which);
	else k = String.fromCharCode(e.charCode);*/

	if (!e.charCode || e.charCode == 13) return;
	else var k = String.fromCharCode(e.charCode);
	
	if (ch.indexOf(k) == -1) e.preventDefault();
	if (e.ctrlKey&&k=='v') e.preventDefault();
		
}

$(document).ready(function() {
	
	$('#paginator_input').keypress(inputMaskNumber);
	
	$('#paginator_form').submit(function (e){
		var max_page = parseInt($('#paginator_page_count').val());
		var selected_page = parseInt($('#paginator_input').val());
		
		if ( selected_page > max_page ) {
			$('#paginator_input').val(max_page);
		}
			
	});
	
	
	
	$('.thanks_count_baloon').bt({
		contentSelector: "$(this).parent().find('span.baloon_content').html()",
		trigger: 'click',
		
		closeWhenOthersOpen : true,
		width : '115px',
		spikeGirth:       5,                    // width of spike
    	spikeLength:      7,
    	fill: '#000060',
    	strokeWidth:      0,
    	cornerRadius: 0,

  		cssStyles: {
  			//'background':'#000060 url(/skin/img/bg_help.gif) no-repeat scroll 0 0',
			'color':'#FFFFFF',
			'font-size':'10px',
			'padding':'5px'/*,
			'width':'115px'*/
		},
		positions: ['bottom', 'left']
	});
	
	setup_how_to_format_baloon();
	
	
	
});

function setup_how_to_format_baloon(elem) {
	
	var to_what;
	
	if ( !elem ) {
		to_what = '.how_to_format'
	} else {
		to_what = elem;
	}
	
	$(to_what).bt('<pre>&lt;b><b>Полужирный</b></b>\n\
&lt;i><i>Курсив</i>&lt;/i>\n\
&lt;u><u>Подчеркивание</u>&lt;/u>\n\
&lt;s><s>Зачеркивание</s>&lt;/s>\n\
&lt;a href="">Ссылка&lt;/a>\n\
</pre>',
		{
		
		trigger: 'click',
		closeWhenOthersOpen : true,
		width : '135px',
		spikeGirth:       5,                    // width of spike
    	spikeLength:      7,
    	fill: '#000060',
    	strokeWidth:      0,
    	cornerRadius: 0,
  		cssStyles: {
  			//'background':'#000060 url(/skin/img/bg_help.gif) no-repeat scroll 0 0',
			'color':'#FFFFFF',
			'font-size':'10px',
			'padding':'5px'/*,
			'width':'115px'*/
		},
		positions: ['bottom']
	});
	
}


function addLink(url)
{
	
	$('#link_add_error').hide();
	
     var curlinks = new Array();
    
     $('#links_form > li > input').each( function() {
                             curlinks[this.id] = this.value;
                          });
    
     JsHttpRequest.query(
      	  "/movie?request_mode=ajax",
      	  {'url':url, 'cur_links' : curlinks, 'ajax_action' : 'get_link'},
      	  function(result, errors) {
             if(errors)
		     {
		     	if(!production_flag){alert(errors);}
		     }
             
             if (result)
             {
                 if (result.error_status) {
                 	$('#link_add_error').html(result.error_msg);
                    $('#link_add_error').show();
                 }
                 else {
                     $('#links_form').html(result);
                     $("#link_field").val('');
                     $('#add_link').hide();
					 $('#add_link_li').hide();
					 $('#link_field').hide();
					 $('#edit_add_link').show();
                 }
             }
      	  },
      	  true
      );     
}




function addPostComment(post_id, parent_id, type, event_id)
{
	
	var text = '';
	
	if ( parent_id ) {
		
		text = $('#addcomment_form_' + type + '_' + parent_id).val();
		
	} else {
		
		text = $('#addpostcomment_form_' + type + '_' + post_id).val();
		
	}
	
	if ( $.trim(text).length == 0 ) {
		return;
	}
	
    JsHttpRequest.query(
      	  "/?request_mode=ajax",
      	  {'type':type, 'post_id':post_id, 'parent_id':parent_id, 'text' : text, 'ajax_action' : 'add_post_comment'},
      	  
      	  function(result, errors) {
             if(errors)
		     {
		     	if(!production_flag){alert(errors);}
		     }
             
             if (result)
             {
             	var reload = (document.location.pathname == '/'+type+'/'+event_id+'/'+post_id);
             	
                window.location = '/'+type+'/'+event_id+'/'+post_id+'#' + result.id;
                if ( reload ) {
                	window.location.reload(true);
                }
             }
      	  },
      	  true
      );
}

function editPostComment(comment_id, type)
{
	
	if (!comment_id) {
		return;
	}
	
	var text = $('#editcomment_form_' + type + '_' + comment_id).val();
	
    JsHttpRequest.query(
      	  "/?request_mode=ajax",
      	  {'type':type,'comment_id':comment_id, 'text' : text, 'ajax_action' : 'edit_post_comment'},
      	  
      	  function(result, errors) {
             if(errors)
		     {
		     	if(!production_flag){alert(errors);}
		     }
             
             if (result)
             {
                window.location.reload(true);
             }
      	  },
      	  true
      );
}

function deletePostComment(comment_id, type)
{
     if (!type || !comment_id) return;
    
     JsHttpRequest.query(
      	  "/?request_mode=ajax",
      	  {'type':type,'comment_id' : comment_id, 'ajax_action' : 'delete_post_comment'},
      	  function(result, errors) {
             if(errors)
		     {
		     	if(!production_flag){alert(errors);}
		     }
             
             if (result)
             {
                 window.location.reload(true);
             }
      	  },
      	  true
      ); 
}

function closePostComment(close_type, comment_id, type, a_tag)
{
     if (!type || !comment_id) return;
    
     JsHttpRequest.query(
      	  "/?request_mode=ajax",
      	  {
      	  	'type':type,
      	  	'close_type' : close_type,
      	  	'comment_id' : comment_id, 
      	  	'ajax_action' : 'close_post_comment'},
      	  function(result, errors) {
             if(errors)
		     {
		     	if(!production_flag){alert(errors);}
		     }
             
             if (result)
             {
                 elem = $(a_tag);
	            	 
	             if (parseInt(result.error_status)) {
	                 $('#warning').html('<li><b class="red">' + result.error_msg +'</b></li>');
	                 $('#warning').show();
	             }
	             else {
	                 /*if ( close_type == 1 ) {
	                	 elem.html('&Oslash; открыть');
	                 	 elem.attr('onClick', "closePostComment(0, " + comment_id + ", '" + event_type + "', this )");
	                 } else {
	                	 elem.html('&Oslash; закрыть');
	                	 elem.attr('onClick', "closePostComment(1, " + comment_id + ", '" + event_type + "', this )");
	             	 }*/
	             	window.location.reload(true);
	             }
             }
      	  },
      	  true
      ); 
}

function closePost( close_type, comment_id, event_type, a_tag )
{
	 if ( (close_type != 0 && close_type != 1) || !event_type || !comment_id || !a_tag) {
		 return;
	 }
	 
	 //$('#progress_bar').show();
	 
	 JsHttpRequest.query(
	      	  "/?request_mode=ajax",
	      	  {
	      		'ajax_action' : 'close_post',
	      		'close_type' : close_type,
	      		'event_type'  : event_type,
	      		'comment_id'   : comment_id
	      	  },
	      	  function(result, errors) {
	             if(errors)
			     {
			     	if(!production_flag){alert(errors);}
			     }
	             
	             if (result) {
	            	 
	            	 //$('#progress_bar').hide();
	            	 
	            	 elem = $(a_tag);
	            	 
	                 if (parseInt(result.error_status)) {
	                     $('#warning').html('<li><b class="red">' + result.error_msg +'</b></li>');
	                     $('#warning').show();
	                 }
	                 else {
	                     if ( close_type == 1 ) {
	                    	 elem.html('&Oslash; открыть');
	                    	 elem.attr('onClick', "closePost(0, " + comment_id + ", '" + event_type + "', this )");
	                    	 $('#li_addpostcomment_'+event_type + '_' + comment_id).hide();
	                    	 $('#addpostcomment_'+event_type + '_' + comment_id).hide();
	                    	 $('.comment_add_li').hide();
	                    	 $('.addcomment').remove();
	                    	 
	                     } else {
	                    	 elem.html('&Oslash; закрыть');
	                    	 elem.attr('onClick', "closePost(1, " + comment_id + ", '" + event_type + "', this )");
	                    	 $('#li_addpostcomment_'+event_type + '_' + comment_id).show();
	                    	 $('.comment_add_li').show();
	                     }
	                 }
	             }
	      	  },
	      	  true
	      );
}

function showEditCommentForm(type, post_id, comment_id, event_id) {
	
	
	$('div.addcomment').remove();
	
	$('div.bt-wrapper').remove();
	
	var text = $('#item_original_text_'+comment_id).html(); 
	
	var comment_form = $('<div class="addcomment" id="editcomment_'+type+'_'+comment_id+'">\
		<span class="font36 fr">\
		(<a href="javascript:void(0);" onclick="editPostComment('+comment_id+', \''+type+'\')">+</a>) \
		</span> \
		<div class="addform"><textarea rows="5" cols="30" id="editcomment_form_'+type+'_'+comment_id+'">'+text+'</textarea></div> \
		<span class="font10">(<a href="#" class="how_to_format" onclick="return false;">? как форматировать</a>)</span> \
		</div>');
	
	$('#bottombar_'+type+'_' + post_id + '_' + comment_id).after(
	
		comment_form
	
	);
	
	setup_how_to_format_baloon(comment_form.find('.how_to_format'));
	
	
}

function showAddCommentForm(type, post_id, comment_id, event_id) {
	
	
	$('div.addcomment').remove();
	
	$('div.bt-wrapper').remove();
	
	var comment_form = $('<div class="addcomment" id="addcomment_'+type+'_'+comment_id+'">\
		<span class="font36 fr">\
		(<a href="javascript:void(0);" onclick="addPostComment('+post_id+', '+comment_id+', \''+type+'\', '+event_id+')">+</a>) \
		</span> \
		<div class="addform"><textarea rows="5" cols="30" id="addcomment_form_'+type+'_'+comment_id+'"></textarea></div> \
		<span class="font10">(<a href="#" class="how_to_format" onclick="return false;">? как форматировать</a>)</span> \
		</div>');
	
	$('#bottombar_'+type+'_' + post_id + '_' + comment_id).after(
		comment_form
	);
	
	setup_how_to_format_baloon(comment_form.find('.how_to_format'));
	
	
}

function sayThanksForComment(thanks_type, event_type, comment_id, to_user_id, a_tag ) {
	
	if ( (thanks_type != 0 && thanks_type != 1) || !event_type || !comment_id || !to_user_id || !a_tag) {
		 return;
	 }
	 
	 //$('#progress_bar').show();
	 
	 JsHttpRequest.query(
	      	  "/?request_mode=ajax",
	      	  {
	      		'ajax_action' : 'say_thanks_for_comment',
	      		'thanks_type' : thanks_type,
	      		'event_type'  : event_type,
	      		'comment_id'  : comment_id,
	      		'to_user_id'  : to_user_id
	      	  },
	      	  function(result, errors) {
	             if(errors)
			     {
			     	if(!production_flag){alert(errors);}
			     }
	             
	             if (result) {
	            	 
	            	 //$('#progress_bar').hide();
	            	 
	            	 elem = $(a_tag);
	            	 
	                 if (parseInt(result.error_status)) {
	                     $('#warning').html('<li><b class="red">' + result.error_msg +'</b></li>');
	                     $('#warning').show();
	                 }
	                 else {
	                     if ( thanks_type == 1 ) {
	                    	 elem.html('<i>- СПАСИБО!</i>');
	                    	 elem.attr('onClick', "sayThanksForComment(0, '" + event_type + "', " + comment_id + ", " + to_user_id + ", this )");
	                     } else {
	                    	 elem.html('<i>+ СПАСИБО!</i>');
	                    	 elem.attr('onClick', "sayThanksForComment(1, '" + event_type + "', " + comment_id + ", " + to_user_id + ", this )");
	                     }
	                 }
	             }
	      	  },
	      	  true
	      );	
	
}


