//On Document Load
$(function (){
	//Checkbox init
	Custom.init();
	//SMS
	/*setInterval("checkNewSMS()",10000);
	setInterval("$('#sms_shuffle_div').html(sms_shuffle[Math.floor(Math.random()*sms_shuffle.length)] || '')",30);
	checkNewSMS();/**/
	sms_shuffle=[];
	$("#sms_data").mouseover(function(){
		$('.sms_chat').stop();$('.sms_chat').animate({height:'200px'},500);
	}).mouseout(function(){
		$('.sms_chat').stop();$('.sms_chat').animate({height:'30px'},500);
	});
	//End
	$("#rem_me").click(function(){
		if($(".auth input[name=remember]").val()!="on"){
			$(".auth input[name=remember]").val("on");
			$(".auth .checkbox").mouseup();
		}else{
			$(".auth input[name=remember]").val("off");
			$(".auth .checkbox").mouseup();
		}
	}).blur(function (){
		$("#rem_me").fadeOut('slow');
	}).focus(function (){$("#rem_me").stop();});
	
	$(".loginp[name=login_email]").focus(function (){
		$("#rem_me").css('display', 'block');
	}).blur(function (){
		$("#rem_me").fadeOut('slow');
	});
	//News
	for (x in all_news)
	{
		bind_new(all_news[x]);
	}
	function bind_new(a){
		$("#sp_"+a).mousedown(function(){
			if (isNaN(fulltextmark[a]) || fulltextmark[a]==0){
				$("#ntxt_"+a).animate({opacity: "show", height: "show" }, 200);
				fulltextmark[a]=1;
				$("#sp_"+a).text("Скрыть подробности");
			} else {
				$("#ntxt_"+a).animate({opacity: "hide", height: "hide" }, 200);
				fulltextmark[a]=0;
				$("#sp_"+a).text("Читать целиком");
			};
		});		
	}
	
	//LK menu
	function m_open(){
		$(this).parent().addClass("person_right_column");
		$(".person_right_column").before($(".person_left_column"));
		if($.browser.msie){
			$(".text2").css('overflow','visible');
		}
		$(".person_left_column").css("display", "block");
		$("#stock").remove();
		$("#menu_open").remove();
		$(".right_column_content").prepend("<div id=\"menu_close\" class=\"disab\" title=\"Свернуть меню\">-</div>");
		$("#menu_close").click(m_close);
	}
	
	function m_close(){
		$("body").append("<div id=\"stock\" style=\"display:none;\"></div>");
		$("#stock").append($(".person_left_column"));
		if($.browser.msie){
			$(".text2").css('overflow','visible');
		}
		$(".person_right_column").prepend("<div id=\"menu_open\" class=\"disab\" title=\"Развернуть меню\">+</div>");
		$("#menu_open").click(m_open);
		$(".person_right_column").removeClass("person_right_column");
		$("#menu_close").remove();
	}
	
	$("#menu_close").click(m_close);
	$("#menu_open").click(m_open);
	$("#menu_open").click();
});

var Ival='';
var sms_shuffle=new Array();
var fulltextmark = new Array();
var all_news = new Array();
var priv_msg='';

function reactivate(a,b){
	$.get(a+'reactivate.php', {id: b}, function (data){ $("#msg").html(data);});
}
//Ajax.js

var request = null;
var data = {};

function createRequest() {
     try {
          request = new XMLHttpRequest();
     } catch (trymicrosoft) {
          try {
               request = new ActiveXObject("Msxml2.XMLHTTP");
          } catch (othermicrosoft) {
               try {
                    request = new ActiveXObject("Microsoft.XMLHTTP");;
               } catch (failed) {
                    request = null;
               }
          }
     }
     if (request==null) {
          alert("Включите JavaScript");
     }
}

function openGet(action,callback,param) {
     //$("#loading").style.display = "block";
     var url = "action="+action;
     createRequest();
     for (var i in param) {
          url += "&"+i+"="+param[i];
     }
     request.open("POST","/tmp/ajax.php",true);
     request.onreadystatechange = function() {
          if (request.readyState == 4) {
               //$("#loading").style.display = "none";
               //e("debug").value = request.responseText;
              // alert(request.responseText);
               eval(request.responseText);
               eval('('+callback+'(data));');
          }
     };
     request.setRequestHeader("Content-type", "application/x-www-form-urlencoded"); 
     request.setRequestHeader("charset", "utf-8");
     request.setRequestHeader("Content-length", url.length); 
     request.setRequestHeader("Connection", "close");
     request.send(url);
}
// JavaScript Document
function getClientHeight(divname) /*Удерживаем футер в ИЕ*/
{ 
if(document.documentElement.clientHeight){
	var n=document.documentElement;
	var of=0;
}else{ 
	var n=document.body;
	var of=-23;
}
  var myvar1=n.clientHeight; /* высота рабочей области*/
  var myvar2=n.scrollTop; /*скролирование*/
  var inpdiv=document.getElementById(divname); 
  return myvar1+myvar2-inpdiv.clientHeight+of; 
}

function close_content_window(name){
	$("#"+name+" .block_content").css("display","none");
	$("#"+name).animate({opacity: "hide"}, 300);
}

function show_content_window(name){
	$("#"+name).animate({opacity: "show"}, 300);
	$("#"+name+" .block_content").css("display","block");
}

function l(a){
	document.location.href=a;
}
function blocker(nId) {
	if ($(nId).css('display')!='block') {
		$(nId).css('display','block');
	} else {
		$(nId).css('display','none');
	}
}

function msg(block){
	var worck_area_y=$('.content').height();
	var worck_area_x=$('.content').width();
	var scrolly=-30;
	window.scroll(0, 0);
	if($('#welcome').css('display')!='none'){
		close_content_window('welcome');
	}
	if($('#main_msg_box').length>0){
		$('#main_msg_box div.block_content>*').css('display', 'none').insertAfter("#priv_msg");
		$('#priv_msg').remove();
		$('#main_msg_box').remove();
	};
	$('.content').append('<div id="main_msg_box"><div id="main_msg_box0" class="block_container" style="display: block;"><div class="block_line o_png"><div class="ln_left o_png"/><div class="ln_right o_png"/><div class="block_close" onclick="javascript:close_content_window(\'main_msg_box0\'); blocker(\'#main_msg_box\');"></div></div><div class="block_content"></div><div id="news_niz" class="block_line o_png"><div class="ln_left o_png"/>	<div class="ln_right o_png"/></div></div></div>');
	$(block).after('<div id="priv_msg"></div>').css('display', 'block').appendTo("#main_msg_box div.block_content");
	$('#main_msg_box').css(
		{
			left: parseInt(worck_area_x/2-300)+'px',
			top: parseInt(50)+'px'
		}
	);
	if($('#main_msg_box').height()+100>worck_area_y){
		$('.content').css('height', ($('#main_msg_box').height()+120)+'px');
	}
}

//SMS chat

function myescape(a){
	a.replace(/>/,"&gt;");
	a.replace(/</,"&lt;");
	return a;
}
function checkNewSMS() {
	openGet("sms","checkNewSMScallback",{});
}
function checkNewSMScallback (data) {
	var html = "";
	for (var i=0; i<data.sms.length; i++) {
		html += "<span style='font-size:15px'>&nbsp;</span>"+data.sms[i].date+" "+myescape(data.sms[i].name)+ " "+myescape(data.sms[i].msg)+"<br>";
	}
	$("#sms_data").html(html);
}

//Registration
//Проверяет, все ли обязательные поля заполнены
function check_send() {
	mes='';
	p1=$("#p1").val();
	em=$("#email").val();
    if (
		($("#name").val()=="")|| ($("#email").val()=="")||($("#p1").val()=="")||($("#p2").val()=="") || ($("#ask1").val()=="")
	)
		mes=mes+'Необходимо заполнить обязательные поля\n';	
	
	else{
		if($("#name").val().length>16) mes=mes+ 'Максимальная длина имени 16 символов\n';
		if($("#ask1").val()=="") mes=mes+ 'Необходимо заполнить поле "откуда вы о нас узнали"\n';
		if((em.indexOf("@")<0) || (em.indexOf(".")<0) ) mes=mes+'Неверный email! \n';
		if(p1.length < 6) mes=mes+'Неверная длина пароля! \n';
	
//	if	(!(document.getElementById("sum0").value==document.getElementById("code").value))    
//	  mes=mes+'Неверный код защиты! \n';					
		if (!($("#p1").val()==$("#p2").val()))
			mes=mes+'Пароли не идентичны! \n';
		if($("#p1").val().length<4) mes=mes+ 'минимальная длина пароля 4 символа\n';
		if (!document.getElementById("ok").checked)  mes=mes+'Вам необходимо ознакомиться с правилами!';
	}
	if (mes!=="") { alert(mes) ;return false;}
	
	$("#registration").submit();
}

function ShowReg(){
	$("#regin").css("display","inline");
}
function ShowLog(){
	if ( $('#login_email').val() && $('#pwd').val() ){
//		    loginForm.submit();
	}  
	else {
		alert('Нужно ввести данные авторизации');
	}
}

function HideReg(){
	$("#regin").css("display","none");	
}

function closeRegWindow(){
	$('#popupForm').html('');
}

function key(event){
	if (event.keyCode==13) ShowLog();
}

function randomFunc() {
	document.getElementById('img').src ="?p=registration&kcaptcha="+Math.random();
}


//Функции бан системы
function emailSend(name, mail) {
	if ($('#textNet').val() != '') {
		var arg = new Object();
		arg.name = name;
		arg.mail = mail;
		arg.msg = $('#textNet').val();
		openGet('sendMailFromBanned','sendMailFromBanned_complete',arg);
		alert('Сообщение отправлено');
	} else {
		alert('необходимо заполнить поле, чтобы отправить e-mail');
	}
}

function sendMailFromBanned_complete() {
	document.getElementById('errAll').innerHTML = "Ваше письмо отослано";
}

//Adminstration page functions

function show_pv_msg(obj,name){
	$(".pv_msg").remove();
	var actor=$(obj).parent().parent().parent().find("td:first-child").html();
	$(obj).after("<div class='pv_msg' style='display:none;'>"+
"<form action='' method='post'><table>"+
"<tr><td colspan='2' style='cursor:move;' class='h'><b>Отправка сообщения администатору</b></td></tr>"+
"<tr><td class='h'>От:</td><td>"+name+"</td></tr>"+
"<tr><td class='h'>Кому:</td><td id='reciver'></td></tr>"+
"<tr><td class='h'>Тема:</td><td><input name='Subject' width='100%'></td></tr>"+
"<tr><td colspan='2' class='h'>Сообщение:</td></tr>"+
"<tr><td colspan='2'><textarea cols='43' rows=''4' name='txt'></textarea><br/>"+
"<input type='submit' name='send' value='Отправить'></input></td></tr>"+
"</table></form>"+
"</div>");
	$("#reciver").html("<input type='hidden' name='reciver' value='"+actor+"'>"+actor);
	blocker(".pv_msg");
	$(".pv_msg").draggable({handle: 'td'});
}

function cm(){
    $("#welcome .block_content").append("<div class='chat_notice' style='font-size: 1.4em;'><br/>Чат доступен только зарегистрированным пользователям!<br/>Пожалуйста, зарегистрируйтесь.</div>");
    setTimeout(function(){$(".chat_notice").hide(2000, function(){$(this).remove();})}, 7000);
}


//Cool checkbox
var checkboxHeight = "25";
var radioHeight = "25";
var selectWidth = "190";

/* No need to change anything after this */

document.write('<style type="text/css">input.styled { display: none; } select.styled { position: relative; width: ' + selectWidth + 'px; opacity: 0; filter: alpha(opacity=0); z-index: 5; }</style>');

var Custom = {
	init: function() {
		var inputs = document.getElementsByTagName("input"), span = Array(), textnode, option, active;
		for(a = 0; a < inputs.length; a++) {
			if((inputs[a].type == "checkbox" || inputs[a].type == "radio") && inputs[a].className == "styled") {
				span[a] = document.createElement("span");
				span[a].className = inputs[a].type;

				if(inputs[a].checked == true) {
					if(inputs[a].type == "checkbox") {
						position = "0 -" + (checkboxHeight*2) + "px";
						span[a].style.backgroundPosition = position;
					} else {
						position = "0 -" + (radioHeight*2) + "px";
						span[a].style.backgroundPosition = position;
					}
				}
				inputs[a].parentNode.insertBefore(span[a], inputs[a]);
				inputs[a].onchange = Custom.clear;
				span[a].onmousedown = Custom.pushed;
				span[a].onmouseup = Custom.check;
				document.onmouseup = Custom.clear;
			}
		}
		inputs = document.getElementsByTagName("select");
		for(a = 0; a < inputs.length; a++) {
			if(inputs[a].className == "styled") {
				option = inputs[a].getElementsByTagName("option");
				active = option[0].childNodes[0].nodeValue;
				textnode = document.createTextNode(active);
				for(b = 0; b < option.length; b++) {
					if(option[b].selected == true) {
						textnode = document.createTextNode(option[b].childNodes[0].nodeValue);
					}
				}
				span[a] = document.createElement("span");
				span[a].className = "select";
				span[a].id = "select" + inputs[a].name;
				span[a].appendChild(textnode);
				inputs[a].parentNode.insertBefore(span[a], inputs[a]);
				inputs[a].onchange = Custom.choose;
			}
		}
	},
	pushed: function() {
		element = this.nextSibling;
		if(element.checked == true && element.type == "checkbox") {
			this.style.backgroundPosition = "0 -" + checkboxHeight*3 + "px";
		} else if(element.checked == true && element.type == "radio") {
			this.style.backgroundPosition = "0 -" + radioHeight*3 + "px";
		} else if(element.checked != true && element.type == "checkbox") {
			this.style.backgroundPosition = "0 -" + checkboxHeight + "px";
		} else {
			this.style.backgroundPosition = "0 -" + radioHeight + "px";
		}
	},
	check: function() {
		element = this.nextSibling;
		if(element.checked == true && element.type == "checkbox") {
			this.style.backgroundPosition = "0 0";
			element.checked = false;
		} else {
			if(element.type == "checkbox") {
				this.style.backgroundPosition = "0 -" + checkboxHeight*2 + "px";
			} else {
				this.style.backgroundPosition = "0 -" + radioHeight*2 + "px";
				group = this.nextSibling.name;
				inputs = document.getElementsByTagName("input");
				for(a = 0; a < inputs.length; a++) {
					if(inputs[a].name == group && inputs[a] != this.nextSibling) {
						inputs[a].previousSibling.style.backgroundPosition = "0 0";
					}
				}
			}
			element.checked = true;
		}
	},
	clear: function() {
		inputs = document.getElementsByTagName("input");
		for(var b = 0; b < inputs.length; b++) {
			if(inputs[b].type == "checkbox" && inputs[b].checked == true && inputs[b].className == "styled") {
				inputs[b].previousSibling.style.backgroundPosition = "0 -" + checkboxHeight*2 + "px";
			} else if(inputs[b].type == "checkbox" && inputs[b].className == "styled") {
				inputs[b].previousSibling.style.backgroundPosition = "0 0";
			} else if(inputs[b].type == "radio" && inputs[b].checked == true && inputs[b].className == "styled") {
				inputs[b].previousSibling.style.backgroundPosition = "0 -" + radioHeight*2 + "px";
			} else if(inputs[b].type == "radio" && inputs[b].className == "styled") {
				inputs[b].previousSibling.style.backgroundPosition = "0 0";
			}
		}
	},
	choose: function() {
		option = this.getElementsByTagName("option");
		for(d = 0; d < option.length; d++) {
			if(option[d].selected == true) {
				document.getElementById("select" + this.name).childNodes[0].nodeValue = option[d].childNodes[0].nodeValue;
			}
		}
	}
}

