function post() {};
post.vote = function(element, essenceType, essenceId, mark){
  var url = W_AJAX + 'poll.php';
  $.post(url,
    {
      type: "application/x-www-form-urlencoded",
      essenceType: essenceType,
      essenceId:  essenceId,
      mark:  mark
    },
    function(responseText) {
   	  if (navigator.userAgent.indexOf ("Opera") != -1) var arrInfo = eval('(' + responseText + ')');
    	else var arrInfo = JSON.parse(responseText);
      if(arrInfo['result'] == 'OK') {
        $(element).parent().find('p').removeClass('empty').html(arrInfo['average_mark']);
        var secondImg = $(element).parent().find("img[src!='" + $(element).attr('src') + "']");
        if($(secondImg).attr('src') == W_IMAGES + 'icons/up.gif')
        	$(secondImg).attr('src',  W_IMAGES + 'icons/upGrey.gif');
       	else
       		$(secondImg).attr('src',  W_IMAGES + 'icons/downGrey.gif');
      }
      else
        alert(arrInfo['err_text']);
    });
};

post.previewComment = function(element){
  var commentText = $( $('#' + $('#textCommentText').attr('id') + 'IFrame').document() ).find('body').html();
	$('#previewText').remove();
	$('#commentForm').prepend('<div id="previewText" style="margin:5px 0px 8px 0px;">' + commentText + '</div>');
};



post.createCommentHTML = function(arrComment) {
	$('#noComments').remove();
  var retText = '';
  retText += '<div class="comment" id="com_' + arrComment['ID_comment'] + '">';
  retText += '<div class="text_comment">';
    retText += '<div class="comInfo">';
    retText += '<p class="user"><a href="' + W_ABSPATH + 'user/' + arrComment['login'] + '"><img  src="' + W_IMAGES + 'essence/user/s_' + arrComment['pic_file'] + '" userId="' + arrComment['ID_user'] + '" alt="" /></a>';
    retText += '<a href="' + W_ABSPATH + 'user/' + arrComment['login'] + '" title="" class="commentAuthor">' + arrComment['last_name'] + ' ' + arrComment['first_name'] + '</a></p>';
      retText += '<p class="date">' + arrComment['creation'] + '</p>';
      //retText += '<p class="vote">0</p>';
    retText += '</div><br />';
    //retText += '<div class="clear"></div>';
		retText += '<div class="text">' + arrComment['text'] + '</div>';
		retText += '<div class="actions"><a href="/" onclick="post.moveFormToComment(this);return false;">Ответить</a></div>';
  retText += '</div>';
  retText += '</div>';
  return retText;
};

post.moveFormToComment = function(element) {
  //$(element).parent().parent().next().after($('#commentForm'));
  $('#previewText').remove();
  $(element).parent().after($('#commentForm'));
  $('#commentForm').find('div').eq(0).html('<textarea id="textCommentText" class="wysiwygComment" cols="50" rows="5" name="commentText" />');
  $('#subAddComment').remove();
  $('#subPreviewComment').remove();
  $('#commentForm').find('div').eq(0).after('<p><input class="button" type="submit" value="Предпросмотр" id="subPreviewComment" name="previewComment" onclick="post.previewComment();" /><input style="margin-left:10px;" class="button" type="submit" value="Опубликовать" id="subAddComment" name="addComment" onclick="post.submitComment();" /></p>');
  $('#textCommentText').wysiwyg({ debug : true, wysiwygType : 'comment' });
  var tempVal = $(element).parent().parent().parent().attr('id');
  tempVal = tempVal.substr(4);
  $('#inpRootComment').val(tempVal);
};

post.moveFormToRootComment = function() {
  $('#previewText').remove();
	$('#rootCommentHead').after($('#commentForm'));
  $('#commentForm').find('div').eq(0).html('<textarea id="textCommentText" class="wysiwygComment" cols="50" rows="5" name="commentText" />');
  $('#subAddComment').remove();
  $('#subPreviewComment').remove();
  $('#commentForm').find('div').eq(0).after('<p><input class="button" type="submit" value="Пердпросмотр" id="subPreviewComment" name="previewComment" onclick="post.previewComment();" /><input style="margin-left:10px;" class="button" type="submit" value="Опубликовать" id="subAddComment" name="addComment" onclick="post.submitComment();" /></p>');
  $('#textCommentText').wysiwyg({ debug : true, wysiwygType : 'comment' });
  $('#inpRootComment').val('');
};

post.selectType = function() {
	if ($('#Post_self').val() == 1) $('#sportDiv').hide();
	else  $('#sportDiv').show();
};

post.changeMarkSport = function() {
  var url = W_AJAX + 'tournaments';
  $('#Post_ID_match').remove();
  $('#Post_ID_tour').remove();
  $('#Post_ID_tournament').remove();
  $('#chooseSportBlock').after('<br /><select onchange="post.changeMarkTournament();" class="standardSelect" name="Post[ID_tournament]" id="Post_ID_tournament"><option selected="selected" value="0">- Убрать отметку -</option></select>');
  ajax.after('Post_ID_tournament', 'tournamentAjax');
  $.post(url,
    {
      type: "application/x-www-form-urlencoded",
      ID_sport: $('#ID_sub_sport').val()
    },
    function(responseText) {
    	ajax.remove('tournamentAjax');
   	  if (navigator.userAgent.indexOf ("Opera") != -1) var arrInfo = eval('(' + responseText + ')');
    	else var arrInfo = JSON.parse(responseText);
      if(arrInfo['result'] == 'OK') {
				var itemNumber = arrInfo['tournaments'].length;
				retText = '<option value="0">- Убрать отметку -</option>';
				for (var i = 0; i < itemNumber; i++) {
					retText += '<option value="'+arrInfo['tournaments'][i]['ID_tournament']+'">'+arrInfo['tournaments'][i]['tournament_name']+'</option>';
				}
				$('#Post_ID_tournament').html(retText);
      }
      else
        alert(arrInfo['err_text']);
    });
};


post.changeMarkTournament = function() {
  var url = W_AJAX + 'tours';
  $('#Post_ID_match').remove();
  $('#Post_ID_tour').remove();
  $('#Post_ID_tournament').after('<br /><select onchange="post.changeMarkTour();" class="standardSelect" name="Post[ID_tour]" id="Post_ID_tour"><option selected="selected" value="0">- Убрать отметку -</option></select>');
  ajax.after('Post_ID_tour', 'tourAjax');
  $.post(url,
    {
      type: "application/x-www-form-urlencoded",
      ID_tournament: $('#Post_ID_tournament').val()
    },
    function(responseText) {
    	ajax.remove('tourAjax');
   	  if (navigator.userAgent.indexOf ("Opera") != -1) var arrInfo = eval('(' + responseText + ')');
    	else var arrInfo = JSON.parse(responseText);
      if(arrInfo['result'] == 'OK') {
				var itemNumber = arrInfo['tours'].length;
				retText = '<option value="0">- Убрать отметку -</option>';
				for (var i = 0; i < itemNumber; i++) {
					retText += '<option value="'+arrInfo['tours'][i]['ID_tour']+'">Тур '+arrInfo['tours'][i]['sort_num']+'</option>';
				}
				$('#Post_ID_tour').html(retText);
      }
      else
        alert(arrInfo['err_text']);
    });
};

post.changeMarkTour = function() {
  var url = W_AJAX + 'matches';
  $('#Post_ID_match').remove();
  $('#Post_ID_tour').after('<br /><select class="standardSelect" name="Post[ID_match]" id="Post_ID_match"><option selected="selected" value="0">- Убрать отметку -</option></select>');
  ajax.after('Post_ID_match', 'matchAjax');
  $.post(url,
    {
      type: "application/x-www-form-urlencoded",
      ID_tournament: $('#Post_ID_tournament').val(),
      ID_tour: $('#Post_ID_tour').val()
    },
    function(responseText) {
    	ajax.remove('matchAjax');
   	  if (navigator.userAgent.indexOf ("Opera") != -1) var arrInfo = eval('(' + responseText + ')');
    	else var arrInfo = JSON.parse(responseText);
      if(arrInfo['result'] == 'OK') {
				var itemNumber = arrInfo['matches'].length;
				retText = '<option value="0">- Убрать отметку -</option>';
				for (var i = 0; i < itemNumber; i++) {
					retText += '<option value="'+arrInfo['matches'][i]['ID_match']+'">'+arrInfo['matches'][i]['team_name_1']+' - '+arrInfo['matches'][i]['team_name_2']+'</option>';
				}
				$('#Post_ID_match').html(retText);
      }
      else
        alert(arrInfo['err_text']);
    });
};

// функции для комментариев

post.submitComment = function(element){
//	ajax.remove("ajaxAddComment");
//	ajax.after("subAddComment","ajaxAddComment");
//	$('#ajaxAddComment').css('marginTop', '10px');
	if($(element).attr("attrType") == "root"){
		var rootComment = "root";
	}
	else{
		var rootComment = $(element).parent().parent().parent().parent().parent().parent().parent().parent().attr('idComment');
	}
	var answerElement = $("div#comment_answer_"+rootComment);

	var essenceType = $(answerElement).attr('essenceTypeId');
  var essenceId = $(answerElement).attr('idEssence');
  var ID_first_root_comment = $(answerElement).attr('ID_first_root_comment');
//  var commentText = $( $('#' + $('#textCommentText_'+rootComment).attr('id') + 'IFrame').document() ).find('body').html(); // for wysiwyg
  var commentText = $('#textCommentText_'+rootComment).val(); // for textarea
  if(commentText == '<br>' || commentText == ''){
		alert("не передан текст");
	}
	else{

	//alert($(element).parent().html());
	//  var commentText = $(element).parent().find('textarea').html();
	//  var commentText = "тестовый текст";
		commentText = encodeURIComponent(commentText);
		var url = W_AJAX + 'comment/addComment';
	  $(element).attr('disabled', 'disabled');
	  $.ajax({
	    //ifModified: true,
	  	type: "POST",
	    url: url,
	    data: "Comment[essence_type]=" + essenceType + "&Comment[ID_essence]=" + essenceId + "&Comment[ID_first_root_comment]=" +
	    ID_first_root_comment + "&Comment[root_comment]=" + rootComment + "&Comment[text]=" + commentText + "&Comment[user_name]=" + $(answerElement).find("input#Comment_name").val() +
	    "&Comment[user_e_mail]=" + $(answerElement).find("input#Comment_e_mail").val() + "&Comment[kaptcha]=" + $(answerElement).find("input#Comment_kaptcha").val() + "&Comment[user_IP]=" + $(answerElement).find("input#comment_user_IP").val(),
	    success: function(responseText){
	//    	ajax.remove("ajaxAddComment");
	//		alert(responseText);
	    	if (responseText == '-!-') alert('Вы наказаны и не можете писать комментарии');
	    	else {

	    		if (navigator.userAgent.indexOf ("Opera") != -1) var arrInfo = eval('(' + responseText + ')');
		    	else var arrInfo = JSON.parse(responseText);
			    if(arrInfo['result'] == 'OK') {
			    	var appendToIfNotRoot = $('div.comment[@id="com_'+ arrInfo['rootCommentId'] + '"]');
			    	var appendToIfRoot = $('div#comments');

			    	if(arrInfo['rootCommentId'] != "root"){
	//		    		alert('not root');
	//		    		alert($(appendToIfNotRoot).parent().html());
			    		$(appendToIfNotRoot).append(arrInfo['comment']);
			    	}
			    	else{
	//		    		alert('root');
			    		$(appendToIfRoot).prepend(arrInfo['comment']);
			    		$("textarea#textCommentText_root").val('');
			    	}
			    	$("div.CommentsCount").find("h3").find("span").text($("div#comments").find("div.text_comment").size());
			    	$("table#typicalPageIconLinks").find("a#comments_count_and_link").text($("div#comments").find("div.text_comment").size());
			    	if($("#comments").find("#noComments"))
			    		$("#comments").find("#noComments").remove();



						$("body").find("div.comment_answer").each(function(){
							$(this).find(".closeAnswerForm").click(); // закрываем все открытые формы
						});

			    }
			    else {
			      alert(arrInfo['err_text']);
			      $(element).removeAttr('disabled');
			    }
	    	}
	    	$(element).removeAttr('disabled');
	    }
	  });
	}
};


post.viewFormToComment = function(element) {
  //$(element).parent().parent().next().after($('#commentForm'));
//  $('#previewText').remove();
	var commentId = $(element).attr("commentId");
//	alert(commentId);
	$("body").find("div.comment_answer").each(function(){
		if($(this).attr("idComment") != commentId){
			$(this).find(".closeAnswerForm").click(); // закрываем все открытые формы
		}
	});
	$(element).parent().parent().hide(); // скрываем ссылку Ответить
	$("div#comment_answer_"+commentId).show();
	$("div#comment_answer_"+commentId).find("form").show();
	$("div#comment_answer_"+commentId).find("form").find("textarea[@name='commentText']").val("");


};


post.closeFormToComment = function(element){
	var answerFormDiv = $(element).parent().parent().parent().parent().parent().parent().parent().parent();
	$(answerFormDiv).hide();
//	alert($(answerFormDiv).parent().attr("idComment"));
	$("body").find("a.commentAnswerLink[@commentid='" + $(answerFormDiv).attr("idComment") + "']").parent().parent().show();
	$("body").find("input#edit_comment_button_" + $(answerFormDiv).attr("idComment")).show();
	$(answerFormDiv).find("textarea#textCommentText_" + $(answerFormDiv).attr("idComment")).text('');
	$(answerFormDiv).find(".submitAnswerForm").attr("onClick" ,"post.submitComment(this); return false;");
	$("textarea#textCommentText_"+$(answerFormDiv).attr("idComment")).text('');
};



post.delitComment = function(element){
	var idComment = $(element).attr('idComment');
	var url = W_AJAX + 'remove/comment/'+ idComment;

	if(confirm("Вы действительно хотите удалить?")){
	  $.ajax({
	    //ifModified: true,
	  	type: "GET",
	    url: url,
	    success: function(responseText){
	    		if (navigator.userAgent.indexOf ("Opera") != -1) var arrInfo = eval('(' + responseText + ')');
		    	else var arrInfo = JSON.parse(responseText);
			    if(arrInfo['result'] == 'OK') {
			    	var comment = $("div#com_"+arrInfo['idComment']).find("div.text_comment[@attrId='"+arrInfo['idComment']+"']");
			    	if($("div#com_"+arrInfo['idComment']).find("div.comment").size()>0)
			    		$(comment).html("<p><b><i>Комментарий удален модератором</i></b></p>");
			    	else
			    		$("div#com_"+arrInfo['idComment']).remove();
			    	var commentsCount = $("div.CommentsCount").find("h3").find("span").text();
			    	commentsCount--;
			    	$("div.CommentsCount").find("h3").find("span").text(commentsCount);
			    	$("a#comments_count_and_link").text(commentsCount);
			    }
			    else {
			      alert(arrInfo['err_text']);
			      $(element).removeAttr('disabled');
			    }

	    }
		});
	}
};

post.editComment = function(element){
	var idComment = $(element).attr('idComment');
	var commentTextDiv = $("div.text_comment[@attrId='"+idComment+"']").find("div.text");
	$(element).hide();
	var comment = $("div#com_"+idComment);
	var divActions = $("div.text_comment[@attrId='"+idComment+"']").find("div.actions");

	var text = new String($(commentTextDiv).html());
	text = text.replace(/<br>/g, "\n");
	text = text.replace(/<BR>/g, "\n");
	$(divActions).find("textarea#textCommentText_"+idComment).text(text);
	$(divActions).find("a.commentAnswerLink").click();
//	alert("click(fn)" + $(divActions).find(".submitAnswerForm").attr("onclick"));
	$(divActions).find(".submitAnswerForm").attr("onClick", "post.submitEditComment(this); return false;");
//	alert("click(fn1)");


//	post.submitComment(this);return false;



};

post.submitEditComment = function(element){
	var idComment = $(element).parent().parent().parent().parent().parent().parent().parent().parent().attr('idComment');
//	alert(idComment);
//	var commentText = $( $('#' + $('#textCommentText_'+idComment).attr('id') + 'IFrame').document() ).find('body').html();
	var commentText = $('#textCommentText_'+idComment).val();
	commentText = encodeURIComponent(commentText);
	var url = W_AJAX + 'edit/comment/'+ idComment;

	  $.ajax({
	    //ifModified: true,
	  	type: "POST",
	    url: url,
	    data: "Comment[ID_comment]="+idComment+"&Comment[text]="+commentText,
	    success: function(responseText){
	    		if (navigator.userAgent.indexOf ("Opera") != -1) var arrInfo = eval('(' + responseText + ')');
		    	else var arrInfo = JSON.parse(responseText);
			    if(arrInfo['result'] == 'OK') {
			    	var comment = $("div#com_"+arrInfo['idComment']).find("div.text_comment[@attrId='"+arrInfo['idComment']+"']");
//			    	$(comment).find("div.text").text($( $('#' + $('#textCommentText_'+arrInfo['idComment']).attr('id') + 'IFrame').document() ).find('body').html()); // for wusiwyg
				var text = new String($('#textCommentText_'+arrInfo['idComment']).val());
			    	$(comment).find("div.text").html(text.replace(/\r\n|\r|\n/g, "<br />")); // for textaera
					$("body").find("div.comment_answer").each(function(){
						$(this).find(".closeAnswerForm").click(); // закрываем все открытые формы
					});
			    }
			    else {
			      alert(arrInfo['err_text']);
			    }

	    }
		});


};

post.goToRootCommentAnswer = function(){
	if($("div#rootCommentAnswerBlock").find("div.close").size() != 0 || $("div#rootCommentAnswerBlock").find("div.content").css("display") == "none")
		$("div#rootCommentAnswerBlock").find("div.header").find("img#rootCommentAnswerBlock_link").click();
	$("div#rootCommentAnswerBlock").find("div.close").attr("class", "content contentIn");
};

