var voiteArr = [];

Array.prototype.in_array = function(p_val) {
    for(var i = 0, l = this.length; i < l; i++)  {
        if(this[i] == p_val) {
            return true;
        }
    }
    return false;
}

function getXmlHttp() 
{
	var xRequest=null;
	if (window.XMLHttpRequest) 
	{
		// Mozilla/Safari
		xRequest=new XMLHttpRequest();
	}
	else if (typeof ActiveXObject != "undefined")
	{
		xRequest=new ActiveXObject
		// Internet Explorer
		("Microsoft.XMLHTTP");
	}
	
	return xRequest;
}

/* ответ на комментарий */

function answerComm(commId, userName, userId)
{
	document.getElementById('userForAns').innerHTML    = (userName == '' && (userId == '' || userId == 0)) ? "[Аноним]" : "<a href='/mypage.html?user="+userId+"'>"+userName+"</a>";
	document.getElementById('ansToUser').style.display = 'block';
	document.getElementById('ansCheck').value          = commId;
	document.getElementById('ansCheck').checked        = true;
	
	document.getElementById('usid').value = (userId == '' || userId == 0) ? 0 : userId;
}

/* Добавление комментария */

function Answer(type)
{
	var text=document.getElementById('text_textarea').value;
	var post_id=document.getElementById('post_id').value;
	var holywar_id=document.getElementById('holywar_id').value;
	var session_id_form=document.getElementById('session_id_form').value;
	var id=document.getElementById('id_form').value;
	var news_id=document.getElementById('news_id_form').value;
	var str=document.getElementById('strn').value;
	var hidden=document.getElementById('hidden').value;
	
	var ans_id = (document.getElementById('ansCheck').checked == true) ? document.getElementById('ansCheck').value : 0 ;
	var usid   = (document.getElementById('ansCheck').checked == true) ? document.getElementById('usid').value : 0 ;
	
	if(session_id_form==0)
	{
		var cap=document.getElementById('cap').value+'.jpg';
		var cap_real=document.getElementById('cap_real').value;
		var email=document.getElementById('form_email').value;
		var nick=document.getElementById('form_nick').value;
		var params = 'text=' + encodeURIComponent(text) + '&holywar_id=' + encodeURIComponent(holywar_id) + '&post_id=' + encodeURIComponent(post_id) + '&hidden=' + encodeURIComponent(hidden) + '&r=' + Math.random() + '&session_id=' + encodeURIComponent(session_id_form) + '&type=' + encodeURIComponent(type) + '&id=' + encodeURIComponent(id) + '&news_id=' + encodeURIComponent(news_id) + '&ans_id=' + encodeURIComponent(ans_id) + '&usid=' + encodeURIComponent(usid) + '&str=' + encodeURIComponent(str) + '&nick=' + encodeURIComponent(nick) + '&email=' + encodeURIComponent(email);
	}
	else
	{
		var cap=0;
		var cap_real=0;
		var email='e';
		var nick='n';
		var params = 'text=' + encodeURIComponent(text) + '&holywar_id=' + encodeURIComponent(holywar_id) + '&post_id=' + encodeURIComponent(post_id) + '&hidden=' + encodeURIComponent(hidden) + '&r=' + Math.random() + '&session_id=' + encodeURIComponent(session_id_form) + '&type=' + encodeURIComponent(type) + '&id=' + encodeURIComponent(id) + '&news_id=' + encodeURIComponent(news_id) + '&ans_id=' + encodeURIComponent(ans_id) + '&usid=' + encodeURIComponent(usid) + '&str=' + encodeURIComponent(str);
	}
	
	if(cap!=cap_real)
	{
		document.getElementById ('for_answer').innerHTML="<p class='red'>Неверно введен код подтверждения</p>";
	}
	else
	{
		if(text=='' || nick=='' || email=='')
		{
			document.getElementById ('for_answer').innerHTML="<p class='red'>Пожалуйста, заполните все поля</p>";
		}
		else
		{
			document.getElementById ('for_answer').innerHTML="Loading...";
			document.getElementById ('send_message_button').disabled=true;
			
			var xmlhttp=getXmlHttp();
			xmlhttp.abort();
			xmlhttp.open('POST', '/client_files/comments/comments.php', true);
			xmlhttp.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
			
			xmlhttp.onreadystatechange = function() {
			  if (xmlhttp.readyState == 4) {
				 if(xmlhttp.status == 200) 
				 {
					document.getElementById ('send_message_button').disabled=false;
					 var data = eval("(" + xmlhttp.responseText + ")");
					 document.getElementById ('for_answer').innerHTML=data.title;
					 
					 if(data.newid!='')
					 {
						 var d = new Date();
						 
						 if(session_id_form==0)
						 {
							if(ans_id!=0) {
								var newSearch          = (window.location.search != '') ? window.location.search+"&n="+d.getTime(): "?n="+d.getTime();
								var location = window.location.pathname+newSearch+"#"+data.newid;
							}
							else {
								var location = window.location.pathname+"?n="+d.getTime()+"#"+data.newid; 
							}
							
							document.location.href='/session.php?mail='+data.mail+'&password='+data.password+'&last='+location;
						 }
						 else {
							if(ans_id!=0) {
								var newSearch          = (window.location.search != '') ? window.location.search+"&n="+d.getTime(): "?n="+d.getTime();
								document.location.href = window.location.pathname+newSearch+"#"+data.newid;
							}
							else {
								document.location.href = window.location.pathname+"?n="+d.getTime()+"#"+data.newid; 
							}
						}
					 }
				 }	
			  }
			};
			xmlhttp.send(params);
		}
	}
}

/* Редактирование биографии */

function Edit_bio(type)
{
	var text=document.getElementById('text_textarea').value;
	var title=document.getElementById('text_title').value;
	var session_ip_form=document.getElementById('session_ip_form').value;
	var session_id_form=document.getElementById('session_id_form').value;
	var pages_id_form=document.getElementById('pages_id_form').value;
	
	var cap=document.getElementById('cap').value+'.jpg';
	var cap_real=document.getElementById('cap_real').value;
	
	var params = 'text=' + encodeURIComponent(text) + '&session_ip=' + encodeURIComponent(session_ip_form) + '&hidden=1&r=' + Math.random() + '&session_id=' + encodeURIComponent(session_id_form) + '&type=' + encodeURIComponent(type) + '&title=' + encodeURIComponent(title) + '&pages_id=' + encodeURIComponent(pages_id_form);
	
	if(cap!=cap_real)
	{
		document.getElementById ('for_answer').innerHTML="<p class='red'>Неверно введен код подтверждения</p>";
	}
	else
	{
		if(text=='' || title=='')
		{
			document.getElementById ('for_answer').innerHTML="<p class='red'>Пожалуйста, заполните все поля</p>";
		}
		else
		{
			document.getElementById ('for_answer').innerHTML="Loading...";
			document.getElementById ('send_message_button').disabled=true;
			var xmlhttp=getXmlHttp();
			xmlhttp.abort();
			xmlhttp.open('POST', '/client_files/comments/edit.php', true);
			xmlhttp.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
			
			xmlhttp.onreadystatechange = function() {
			  if (xmlhttp.readyState == 4) {
				 if(xmlhttp.status == 200) 
				 {
					document.getElementById ('send_message_button').disabled=false;
					 var data = eval("(" + xmlhttp.responseText + ")");
					 document.getElementById ('for_answer').innerHTML=data.title;
				 }
			  }
			};
			xmlhttp.send(params);
		}
	}
}

/* добавить в избранное */

function toFavorites(session_id, links, title)
{
	document.getElementById ('forFavorites').innerHTML="Loading...";
	
	var params = 'title=' + encodeURIComponent(title) + '&session_id=' + encodeURIComponent(session_id) + '&hidden=1&r=' + Math.random() + '&link=' + encodeURIComponent(links);
	var xmlhttp=getXmlHttp();
	xmlhttp.abort();
	xmlhttp.open('POST', '/client_files/comments/favorites.php', true);
	xmlhttp.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
			
	xmlhttp.onreadystatechange = function() {
		if (xmlhttp.readyState == 4) {
			if(xmlhttp.status == 200) 
			{
				var data = eval("(" + xmlhttp.responseText + ")");
				if(data.error==0) {
					informationWindow(data.text, '#02a51d');
				}
				else {
					informationWindow(data.text, 'red');
				}
				
				document.getElementById ('forFavorites').innerHTML = "";
			}
		}
	};
	xmlhttp.send(params);
}

/* информационное окно */

function informationWindow(textWindow, BgColor)
{
	if($("div#informationWindow").css("opacity")==0) {
		$("div#informationWindow").text(textWindow).css({
			"top":$(document).scrollTop(), 
			"right":"0", 
			"backgroundColor":BgColor
		}).animate({"opacity":"1"}, 200).delay(1800).animate({"opacity":"0"}, 1200);
	}
}

/* голосование за комментарии */
	
function commVoite(voiteMark, voiteIp, voiteId, voiteType, voiteSpan, voiteLast)
{
	if(voiteArr.in_array(voiteId)) {
		informationWindow("Вы уже голосовали за этот комментарий", 'red');
	}
	else {
		var params = 'voiteMark=' + encodeURIComponent(voiteMark) + '&voiteIp=' + encodeURIComponent(voiteIp) + '&voiteId=' + encodeURIComponent(voiteId) + '&voiteType=' + encodeURIComponent(voiteType) + '&voiteLast=' + encodeURIComponent(voiteLast);
		var xmlhttp=getXmlHttp();
		xmlhttp.abort();
		xmlhttp.open('POST', '/client_files/comments/voite.php', true);
		xmlhttp.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
						
		xmlhttp.onreadystatechange = function() {
			if (xmlhttp.readyState == 4) {
				if(xmlhttp.status == 200) 
				{
					var data = eval("(" + xmlhttp.responseText + ")");
					if(data.error==0) {
						informationWindow(data.text, '#02a51d');
						document.getElementById(voiteSpan).innerHTML = (data.value>0) ? "+"+data.value: data.value;
						document.getElementById(voiteSpan).className = (data.value>0) ? "cVoiteGreen" : ((data.value<0) ? "cVoiteRed" : "cVoiteGray");
					}
					else {
						informationWindow(data.text, 'red');
					}		
					voiteArr.push(voiteId);
				}
			}
		};
		xmlhttp.send(params);
	}
}

/* голосование за холивар */

function vsVoite(voiteId, warId, firstDiv, secondDiv)
{
		var params = 'voiteId=' + encodeURIComponent(voiteId) + '&warId=' + encodeURIComponent(warId);
		var xmlhttp=getXmlHttp();
		xmlhttp.abort();
		xmlhttp.open('POST', '/client_files/comments/vs.php', true);
		xmlhttp.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');

                document.getElementById(firstDiv).innerHTML = '<div class="holyWait">обрабатываем</div>';
                document.getElementById(secondDiv).innerHTML = '<div class="holyWait">обрабатываем</div>';

		xmlhttp.onreadystatechange = function() {
			if (xmlhttp.readyState == 4) {
				if(xmlhttp.status == 200)
				{
					var data = eval("(" + xmlhttp.responseText + ")");
					if(data.error==0) {
						informationWindow(data.text, '#02a51d');
						document.getElementById(firstDiv).innerHTML = data.value1;
						document.getElementById(secondDiv).innerHTML = data.value2;
					}
					else {
						informationWindow(data.text, 'red');
						document.getElementById(firstDiv).innerHTML = '<div class="holyWait">ошибка</div>';
						document.getElementById(secondDiv).innerHTML = '<div class="holyWait">ошибка</div>';
					}
				}
			}
		};
		xmlhttp.send(params);
}

$(document).ready(function() {
	
	$("div#view_text").toggle(1);

	var voiteClick = 0;
	
	/* показ и скрытие кода для блога */
	
	$("a#blogLink").click(
		function(){
			if($("textarea#textForBlogArea").height()<10) {
				$("textarea#textForBlogArea").css({
					opacity: 1,
					height: 100,
					marginTop: '5px',
					marginRight: '0px', 
					marginBottom: '17px', 
					marginLeft: '0px'
				  });
			}
			else {
				$("textarea#textForBlogArea").css({
					opacity: 0,
					height: 1,
					marginTop: '0px',
					marginRight: '0px', 
					marginBottom: '0px', 
					marginLeft: '0px'
				  });
			}
		}
	);

	/* предварительный просмотр при редактировании биографии */
	
	$("div#showclose").hover(
		function(){ 
			$(this).css({"border-bottom":"1px solid #fefbf1", "cursor":"pointer"});
		},
		function(){ 
			$(this).css("border-bottom", "1px dashed #1b62b0");
		}
	);
	
	$("div#showclose").click(
		function(){
			if($("textarea#text_textarea").val()!='') {
				$("div#view_text").toggle(700);
			}
		}
	);
	
	/* */

	/* голосование за материал */
	
	$("img.hearts").mouseover(function(){
		$("span#voiteMark").text($("img#"+this.id).attr("alt"));
		$("img.hearts").slice(this.id,5).fadeTo(150, 0.4);
		$("img.hearts").slice(0,this.id).fadeTo(150, 1);
	});

	$("img.hearts").mouseout(function(){
		$("img#"+this.id).fadeTo(200, 1);
	});
	
	$("img.hearts").click(function(){
		if(voiteClick==1) {
			informationWindow("Вы уже голосовали за этот материал", 'red');
		}
		else
		{
			var params = 'voiteMark=' + encodeURIComponent(this.id) + '&voiteIp=' + encodeURIComponent($("span.voiteIp").attr("id")) + '&voiteId=' + encodeURIComponent($("span.voiteId").attr("id")) + '&voiteType=' + encodeURIComponent($("span.voiteType").attr("id"));
			var xmlhttp=getXmlHttp();
			xmlhttp.abort();
			xmlhttp.open('POST', '/client_files/comments/marks.php', true);
			xmlhttp.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
					
			xmlhttp.onreadystatechange = function() {
				if (xmlhttp.readyState == 4) {
					if(xmlhttp.status == 200) 
					{
						var data = eval("(" + xmlhttp.responseText + ")");
						if(data.error==0) {
							informationWindow(data.text, '#02a51d');
							document.getElementById ('voiteValue').innerHTML = data.value;
						}
						else {
							informationWindow(data.text, 'red');
						}
						
						voiteClick = 1;
					}
				}
			};
			xmlhttp.send(params);
		}
	});
	
	/* */
	
	/* удаление из избранного */
	
	$("div.delsno").mouseover(function(){
		$(this).addClass("delsyes");
	});

	$("div.delsno").mouseout(function(){
		$(this).removeClass("delsyes");
	});
	
	/* */


	/* форма авторизации */

	$("a#Enter").click(function(){
		$('.authForm').fadeIn(400);
	});

	$("a#formClose").click(function(){
		$('.authForm').fadeOut(400);
	});

	/*  */
})
