function getBodyScrollTop()
{
  return self.pageYOffset || (document.documentElement && document.documentElement.scrollTop) || (document.body && document.body.scrollTop);
}
function getDocumentHeight()
{
	return (document.body.scrollHeight > document.body.offsetHeight)?document.body.scrollHeight:document.body.offsetHeight;
}


$(document).ready(function(){
	$("div.show").click(function () {
    $('div.show').css( {backgroundPosition: '0 0'} );
	if (a==0) {
      $("#pic").hide("slow");
	  $('div.show').css( {backgroundPosition: '0 -13px'} );
	  $.cookie("pos", 0);
	  a=1;
	}else{
	  $("#pic").show("slow");
	  $('div.show').css( {backgroundPosition: '0 0'} );
	  $.cookie("pos", 1);
	  a=0;
	};
    });
	
	//закрытие формы логина
    $(".login .ccv").click(function(){
      $(".login").animate( { marginTop:"-100%" }, 800 );
      $("#overlay") .animate( { opacity:".0" }, 500 )
	  				.hide("slow");
		$("a.open-login").removeAttr('href');
		$("a.open-login").attr({ 
          href: "login.html",
          title: "Login"
        });
	});
	
	//закрытие формы регистрации
	$(".login2 .ccv").click(function(){
    $(".login2").animate( { marginTop:"-100%" }, 800 );
    $("#overlay") .animate( { opacity:".0" }, 500 )
				  .hide("slow");
	$("a.open-registration").removeAttr('href');
	$("a.open-registration").attr({ 
        href: "register.html",
        title: "Register"
		});
	});
	
	//раскраска табличек в #content с классом .zebra
	$("#content table.zebra tr").each(colorize); // передаем в each функцию colorize
	function colorize(index)
	{
	  if(index % 2 == 1)       // index является индексом текущего элемента в коллекции
	    $(this).toggleClass("odd");
	}

});

//показываем форму логина и прячем ссылку href="login.html"
/*$(document).ready(function(){
    $(".open-login").click(function(e){
	$(".open-login a").removeAttr('href');
	$(".open-login a").attr({href: "#", title: "Enter"});
	  $("#overlay").show()
	  			   .animate( { opacity:".8" }, 500 );
	  $(".login").css( {display: "block"} );
      $(".login")
	  			.animate( { marginTop:"50px" }, 800 );
			//	.animate( { marginTop:"30px" }, 100 )
			//	.animate( { marginTop:"50px" }, 80 );

	e.preventDefault();
    });

});*/

//показываем форму регистрации и прячем ссылку href="register.html"
$(document).ready(function(){
    $(".open-registration").click(function(e){
	$(".open-registration a").removeAttr('href');
	$(".open-registration a").attr({href: "#", title: "Enter"});
	 $("#overlay").css( {height:"1050px"} );
	  $("#overlay").show()
	  			   .animate( { opacity:".8" }, 800 );
	  $(".login2").css( {display: "block"} );
	  	  $("#overlay").show()
      $(".login2")
//      	  .animate({height: "show"}, 300);

	  			.animate( { marginTop:getBodyScrollTop()+50 }, 800 );
				//.animate( { marginTop:"30px" }, 100 )
				//.animate( { marginTop:"50px" }, 80 );

	e.preventDefault();
    });

});

$(document).ready(function() {
    // validate signup form on keyup and submit
    var validator = $("#signupform").validate({
        rules: {
            co_url: {
                required: true,
                url: true,
                remote: "s.php"
            },
            username: {
                required: true,
                minlength: 4,
                remote: "users.php"
            },
            password: {
                required: true,
                minlength: 4
            },
            password_confirm: {
                required: true,
                minlength: 4,
                equalTo: "#password"
            },
            email: {
                required: true,
                email: true,
                remote: "emails.php"
            },
            dateformat: "required",
            terms: "required",
            description: {
                remote: "desc.php"
            },
    },
    messages: {
        co_url: {
            url: "Пожалуйста, введите корректный URL.",
            required: "Пожалуйста, введите URL.",
            minlength: "Please enter a valid email address",
            remote: jQuery.format("{0} используется")
        },
        username: {
            required: "Введите имя пользователя",
            minlength: jQuery.format("Введите больше {0} символов"),
            remote: jQuery.format("Пользователь {0} существует")
        },
        password: {
            required: "Введите пароль",
            minlength: jQuery.format("Введите больше {0} символов"),
            rangelength: jQuery.format("Пароль должен быть больше {0} символов")
        },
        password_confirm: {
            required: "Повторите пароль",
            minlength: jQuery.format("Введите больше {0} символов"),
            equalTo: "Не совпадает с паролем"
        },
        email: {
            email: "Введите правильный email адрес",
            required: "Введите правильный email адрес",
            minlength: "Введите правильный email адрес",
            remote: jQuery.format("{0} используется")
        },
        dateformat: "Choose your preferred dateformat",
        terms: " ",
        description: {
            remote: "HTML код в описании сайта запрещен"
        }
    },
    // the errorPlacement has to take the table layout into account
    errorPlacement: function(error, element) {
        if (element.is(":radio"))
            error.appendTo(element.parent().next().next());
        else if (element.is(":checkbox"))
            error.appendTo(element.next());
        else
            error.appendTo(element.parent().next());
    },
    // specifying a submitHandler prevents the default submit, good for the demo
    /*	submitHandler: function() {
    alert("submitted!");
    },*/
    // set this class to error-labels to indicate valid fields
    success: function(label) {
        // set &nbsp; as text for IE
        label.html("&nbsp;").addClass("checked");
    }
});

});
function open_mins(url)
{
window.open(url,
	"mywindow","location=1,status=1,scrollbars=1,width=500,height=300");
}

function open_q(url,q)
{
window.open(url,q,
	"mywindow","location=0,status=0,scrollbars=1,width=500,height=300");
};
   function createXMLHttp() {
        if(typeof XMLHttpRequest != "undefined") { // для браузеров аля Mozilla

          return new XMLHttpRequest();
        } else if(window.ActiveXObject) { // для Internet Explorer (all versions)
          var aVersions = ["MSXML2.XMLHttp.5.0", "MSXML2.XMLHttp.4.0",
                   "MSXML2.XMLHttp.3.0", "MSXML2.XMLHttp",
                   "Microsoft.XMLHttp"
                   ];
          for (var i = 0; i < aVersions.length; i++) {
            try { //
              var oXmlHttp = new ActiveXObject(aVersions[i]);

              return oXmlHttp;
            } catch (oError) {

            }
          }
          throw new Error("Невозможно создать объект XMLHttp.");
        }
      }
      
      /* Очень важная функция, обратите на неё внимание.
        Формирует строку запроса "name1=value1&name2=value2&name3...".
        Принимает один аргумент - ссылку на форму.
      */
        
      function getRequestBody(oForm) {
        var aParams = new Array();
        for(var i = 0; i < oForm.elements.length; i++) {
          var sParam = encodeURIComponent(oForm.elements[i].name);
          sParam += "=";
          sParam += encodeURIComponent(oForm.elements[i].value);
          aParams.push(sParam);
        }
        return aParams.join("&");
      }
      
      
      /* В этой ф-ции мы создаём объект XmlHttp, формируем запрос, инициализируем перехватчик состояний
        onreadystatechange, и посылаем наш запрос.
        
        Обратите внимание, что во втором аргументе метода open(..) мы передаём
        ссылку на oForm.action, это сделано как из соображений безопасности, так и ради
        того что-бы сценарий можно-было бы использовать для работы с несколькими страницами.
        
        Так-же, стоит отметить факт отправки дополнительного заголовка: "appilaction/x-www-form-urlencoded"
        Большинство языков (в том числе и PHP), требуют этого, для корректного выполнения
        синтаксического анализа пришедших данных. Этот момент очень важен.
        
      */
      
      function sendRequest() {
        var oForm = document.forms[0];
        var sBody = getRequestBody(oForm);
        var oXmlHttp = createXMLHttp();
        
        oXmlHttp.open("POST",oForm.action, true);
        oXmlHttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
        
        oXmlHttp.onreadystatechange = function() {
          if(oXmlHttp.readyState == 4) {
            if(oXmlHttp.status == 200) {
               saveResult(oXmlHttp.responseText);
            } else {
              saveResult("Ошибка: " + oXmlHttp.statusText);
            }
          }
        };
        
        oXmlHttp.send(sBody);
      }
      
      function saveResult(sText) {
        var sElem = document.getElementById("divStatus");
        sElem.innerHTML = sText;
        $('#divStatus').show('fast');
        
      }

///ОШИБКА ГДЕ ТО ЗДЕСЬ!
 $(document).ready(function() {
	// validate signup form on keyup and submit
	var validator = $("#mailform").validate({
		rules: {
			text: {
				required: true
			},
			username: {
				required: true,
				minlength: 4
			},
			password: {
				required: true,
				minlength: 4
			},
			password_confirm: {
				required: true,
				minlength: 4,
				equalTo: "#password"
			},
			email: {
				required: true,
				email: true
				
			},
			dateformat: "required",
			terms: "required"
		},
		messages: {
			text: {
				required: "Ну напишите что нибудь!."
			},
			username: {
				required: "Пожалуйста, представьтесь",
				minlength: jQuery.format("Введите больше {0} символов"),
				remote: jQuery.format("Пользователь {0} существует")
			},
			password: {
				required: "Введите пароль",
				minlength: jQuery.format("Введите больше {0} символов"),
				rangelength: jQuery.format("Пароль должен быть больше {0} символов")
			},
			password_confirm: {
				required: "Повторите пароль",
				minlength: jQuery.format("Введите больше {0} символов"),
				equalTo: "Не совпадает с паролем"
			},
			email: {
				email: "Введите правильный email адрес",
				required: "Введите правильный email адрес",
				minlength: "Введите правильный email адрес"
			},
			dateformat: "Choose your preferred dateformat",
			terms: " "
		},
		// the errorPlacement has to take the table layout into account
		errorPlacement: function(error, element) {
			if ( element.is(":radio") )
				error.appendTo( element.parent().next().next() );
			else if ( element.is(":checkbox") )
				error.appendTo ( element.next() );
			else
				error.appendTo( element.parent().next() );
		},
		// specifying a submitHandler prevents the default submit, good for the demo
		submitHandler: function() {
		//	alert("submitted!");
		
		//sendRequest();
$("#mailform").hide("fast");
		sendRequest();
		},
		// set this class to error-labels to indicate valid fields
		success: function(label) {
			// set &nbsp; as text for IE
			label.html("&nbsp;").addClass("checked");
		}
	});
	
});
//показываем форму логина и прячем ссылку href="login.html"
/*$(document).ready(function(){
    $(".open-login").click(function(e){
	$(".open-login a").removeAttr('href');
	$(".open-login a").attr({href: "#", title: "Enter"});
	  $("#overlay").show()
	  			   .animate( { opacity:".8" }, 500 );
	  $(".login").css( {display: "block"} );
      $(".login")
	  			.animate( { marginTop:"50px" }, 800 );
			//	.animate( { marginTop:"30px" }, 100 )
			//	.animate( { marginTop:"50px" }, 80 );

	e.preventDefault();
    });

});*/

$(document).ready(function(){
    $(".open-login").click(function(e){
	$(".open-login a").removeAttr('href');
	$(".open-login a").attr({href: "#", title: "Enter"});
	  $("#overlay").css( {height:"1050px"} );
	  $("#overlay").show()
	  			   .animate( { opacity:".8" }, 800 );
	  $(".login").css( {display: "block"} );
      $(".login")
	  			.animate( { marginTop:getBodyScrollTop()+50 }, 800 );
			//	.animate( { marginTop:"30px" }, 100 )
			//	.animate( { marginTop:"50px" }, 80 );

	e.preventDefault();
	});
	
	$("#close_btn").click(function(e){
		$("#overlay").css('display','none');
		$("#login_box").css('display','none');
	});
	
	$("#login_form").submit(function() {
	        // указываем класс process для div-а сообщений и плавно показываем его
	        $("#login_result").removeClass().addClass('process').text('Проверка....').fadeIn(1000);
	        // проверяем через AJAX имя пользователя пароль
	        $.post($("#login_form").attr('action'), { username:$('#username').val(),password:$('#passwordd').val(),rand:Math.random() } ,function(data) {
				if(data==1) {
					// логин верный
					$("#login_result").fadeTo(200,0.1,function() {
					$(this).html('Редирект.....').removeClass().addClass('success').fadeTo(900,1,
						function() {
							document.location='/stat/';
						});
					});
				} else {
					// логин неверный
					$("#login_result").fadeTo(200,0.1,function(){
						$(this).html('Логин неверен ...').removeClass().addClass('error').fadeTo(900,1);
					});
				}
			});
			return false;// отмена отправки формы (действие по умолчанию)
	});
});
function dSubmit(a)
	{
	el = document.forms[0].elements;
	for (i = 0; i < el.length; i++) 
	if (el[i].name=='radiobutton' && el[i].value==a) el[i].checked=true;

		document.forms[0].value=a;
		document.getElementById('reg').style.display='block';
document.forms['reg'].elements['regid'].value = a;
//document.forms['reg'].elements['email'].value = a;
//		alert(a);
	}
