$(document).ready(function()
	{

		$("#auth .button").click(function(){$("#auth .content").toggle();});
		$("#auth input[name='astroauth_login']").focus(function(){if(this.value=="Логин") this.value="";}).blur(function(){if(this.value=="") this.value="Логин";});
		$("#auth input[name='astroauth_pass']").focus(function(){if(this.value=="Пароль") this.value="";}).blur(function(){if(this.value=="") this.value="Пароль";});;
		$("#auth input[class='submit']").click(Register.checkData);
		Tip.init();

		// check domain
		$("#chk_go").parent().parent().submit(Cheker.go);
		markNewsAsRead();
		if($("#calendar").length)
			Interface.bindCalendar();

		for(var i=1;i<8;i++)
		{
			var img = new Image();
			img.src="/i/c/c"+i+".jpg";
		}
		if($("#dateCal").length)
			$("#dateCal").datepicker();
	}
);

function markNewsAsRead()
{
	if(document.location.pathname != "/")
		return;
	var news_ids=[];
	if($.cookie("readnews"))
	{
		news_ids=$.cookie("readnews").split(",");
		for(var i=0;i<news_ids.length;i++)
		{
			$("a#_n"+news_ids[i]).addClass("visited");
		}
	}
	news_ids=[];
	jQuery.each($(".news-item .content-block a"), function()
		{
			if (a = this.href.match(/(\d+)\.html/))
			{
				news_ids[news_ids.length] =a[1];
			}
		}
	);
	$.cookie("readnews", news_ids.join(","), { path: '/', expires: 366 });
}

var Interface = {

	init : function () 
	{
		//debugger;

		// Main menu
		$('#right-menu .inside .items>div')
			.mouseover(function() {
					$(this).addClass("over");
				})
			.mouseout(function() {
					$(this).removeClass("over");
				});

		// Tabs
		$('#tabs-content #currency').show();

		$('.right-block #tabs .tab')
			.click(function() {
					if (this.className == 'tab')
					{
						$('.right-block #tabs>div').attr('class', 'tab');
						$(this).attr('class', 'tab here');
						var name = $(this).attr('name');
						$('#tabs-content>div').hide();
						$('#' + name).show();
					}
				});

		// Search menu
		$('#top-menu>div')
			.click(function() {
					$('#top-menu>div').removeClass("here");
					$(this).addClass("here");
					$("#searchtype").val(this.id.replace("_t", ""));
					/*
					var cn = this.className;
					if (cn.indexOf('here') == -1) 
					{
						$('#top-menu>div').attr('class', 'item');
						$('#top-menu>div:last').attr('class', 'item has-dd');
						$(this).attr('class', cn + ' here');
					}
					*/
				});

		$('#top-menu>div:last .dropdown .item')
			.click(function() {
				var html = $('a', $(this)).html();
				$('#top-block').width(520);
				$('#additional').show();
				$('#additional').attr('class', 'item here');
				$('#additional a').html(html);
				$('#top-menu>div:last').attr('class', 'item has-dd');
				return false;
			});

		// toggles
		var issue = ['news-item', 'simple-box'];

		for (var i=0; i<=1; i++)
		{
			var is = issue[i];

			$('.'+is+' .button').unbind('click').bind('click', function() {

				var ni = $(this).parent().parent();
				var cl = ni.attr('class').replace(' open', '').replace(' close', '');

				if (ni.attr('class') == cl + ' open')
				{
					ni.attr('class', cl + ' close');
					$.cookie(ni.attr('id'), '0', {path: '/'});
					
					Interface.footer();

				}
				else
				{
					ni.attr('class', cl + ' open');
					$.cookie(ni.attr('id'), '1', {path: '/'});
					
					var url	= $('.url', ni).val();

					if (url != '0')
					{
						$.get(url, function(data) {

							$('.content-block', ni).html(data);
							$('.url', ni).val('0');
							Interface.footer();

						});
					}
					else
					{
						Interface.footer();
					}
				}

			});
		}		

		// Footer
		$('#footer').css({visibility: 'visible'});
		Interface.footer();

	},

	chItem : function (issue, url)
	{
		var ni = $('#' + issue);
		
		var height = $('.content-block', ni).height();
		$('.content-block', ni).html('<div class="loading">...</div>');
		$('.content-block', ni).height(height);

		$.get(url, function(data) {

			$('.content-block', ni).height('auto');
			$('.content-block', ni).html(data);
			
			Interface.footer();

		});

	},

	footer : function ()
	{
		var val = $.browser.msie ? 'height' : 'minHeight';
		if(navigator.appVersion.indexOf('MSIE 7') != -1 || navigator.appVersion.indexOf('MSIE 8') != -1){
			val = 'minHeight';
		}

		leftCol = document.getElementById('left-col');
		rightCol = document.getElementById('right-col');
	
		if(leftCol && rightCol)
		{
			leftCol.style[val] = rightCol.offsetHeight + 'px';
		}

	},

	bindCalendar : function()
	{
		$("#calendar .days a").unbind("click").click(
			function()
			{
				$("#calendar").animate({opacity:0.4}, 500);
				$.get("/calendar/?ajax&day="+this.id.replace('d', ''), function(data)
						{
							$("#calendar").html(data);
							$("#calendar").stop().animate({opacity:1}, 500);
							Interface.bindCalendar();
							return false;
						}
					);
				return false;
			}
		);
		return false;
	}
};

String.prototype.isEmail =function()
{
	var reg= /^([A-Za-z0-9_\-\.])+\@([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/;
	return reg.test(this);
};



var Register = {
	checkData : function()
	{
		return true;
		if(!$("#auth input[name='astroauth_login']").val().length<3 || $("#auth input[name='astroauth_pass']").val().length <3)
		{
			alert("Данные введены неверно");
			return false;
		}
	}
};

var Cheker = {
	go : function()
	{
		if($("#chk_domain:checked").length)
			Cheker.chk_domain($("#check_val").val());
		else if($("#chk_company:checked").length)
			return Cheker.chk_company();
		else
			alert("Выберите операцию");
		return false;
	},

	chk_domain : function(val)
	{
		if(val.length<3 || val.indexOf(".") == -1)
		{
			alert("Проверьте введенное имя");
			return;
		}
		$.get("/include/checkdomain.php", {domain:$("#check_val").val()}, function(data)
			{
				if(data == "registred")
					alert("Доменное имя зарегистрировано");
				else if(data == "free")
					alert("Доменное имя свободно");
				else
					alert("Ошибка проверки. Попробуйте позже.");
			}
		);
		return false;
	},

	chk_company : function()
	{
		return true;
	}
};

var Tip = {
	currId : null,
	cache : [],
	init : function()
	{
		$(".news-item .content-block a").mouseover(function()
			{
				Tip.currId=this.id.replace("_n", "");
				if(Tip.cache["c"+Tip.currId] != null)
				{
					Tip.showHint(Tip.cache["c"+Tip.currId]);
				}
				else
				{
					setTimeout("Tip.loadHint("+Tip.currId+")", 300);
				}
			}
		);
		$(".news-item .content-block a").mouseout(function(){Tip.currId=null;$("#news_hint").html("");$("#news_hint").css({left:"-1000px"})});
		$(".news-item .content-block a").mousemove(Tip.pos);
	},

	loadHint : function(id)
	{
		if(Tip.currId != id)
			return;
		$.get("/include/get_brief.php", {id:id}, function(data)
			{
				if(id == Tip.currId)
				{
					Tip.cache["c"+id] = data;
					Tip.showHint(data);
				}
			}
		);
	},
	
	pos :function(e)
	{
		if($("#news_hint").html())
			$("#news_hint").css({top:($.browser.msie?window.event.y+5+document.body.scrollTop+230:e.pageY+5)+"px",left:($.browser.msie?window.event.x+10+document.body.scrollLeft:e.pageX+10)+"px"});
	},
	
	showHint : function(data)
	{
		if(!data)
			return;
		$("#news_hint").html(data);
		if($.browser.mozilla)
		{
			$("#news_hint").css({left:(mouse_x+10)+"px",top:(mouse_y+5)+"px"});
		}
		if($.browser.msie)
		{
			document.getElementById("_n"+Tip.currId).fireEvent("onmousemove");
		}
	}
};


if($.browser.mozilla)
{
	window.onmousemove = init_xy;
};

function init_xy(e)
{
	mouse_x = e.pageX;
	mouse_y = e.pageY;
};

CalendarTip ={

	init : function()
	{
		
		$(".c li a").unbind("mouseover").mouseover(function()
			{
				CalendarTip.showHint(this);
			}
		);

		$(".c li a").unbind("mouseout").mouseout(function(){$("#news_hint").css({left:"-1000px"})});
		$(".c li a").unbind("mousemove").mousemove(CalendarTip.pos);
		
	},

	pos :function(e)
	{
		if ($("#news_hint").html())
			$("#news_hint").css({top:($.browser.msie ? Math.round(window.event.y)+30 : e.pageY-30)+"px", left:($.browser.msie ? window.event.x+10 : e.pageX+10)+"px"});

	},

	showHint : function(obj)
	{
		var s = parseInt(obj.rel) == 0 ? "Модерация" : "Одобрено";
		$("#news_hint #s").html(s);

		if($.browser.msie)
		{

			var td		= $(obj).parent().parent().parent();
			var html	= $("#news_hint").html();
			$("#news_hint").remove();

			td.createAppend(
				'div', {id:'news_hint'}, html
			);

			$("#news_hint").css({top:(Math.round(window.event.y)-30)+"px", left:(window.event.x+10)+"px"});

		} else
		{
			$("#news_hint").css({left:(mouse_x+10)+"px", top:(mouse_y+5)+"px"});
		}

	}

};

var Reg = {
	error: null,
	init: function()
	{
		$("#repass").blur(
			function()
			{
				if( ($("#pass").val() != $("#repass").val()) && $("#pass").val().length > 5 && /^[^--]+$/.test($("#pass").val()))
					$("#_repass .error").css({display:"block"});
				else
					$("#_repass .error").css({display:"none"});
			}
		);
		$("#repass").click(function(){$("#_repass .error").css({display:"none"});});
		$("#login").blur(
			function ()
			{
				if(this.value.length < 4 || !this.value.match(/^[A-Za-z0-9\.\_]+$/) || this.value.match(/\.$/))
				{
					$("#_login .error1").css({display:"block"});
					return false;
				}
				else
				{
					$("#_login .error1").css({display:"none"});
				}
				$.get("./?action=chklogin", {login:jQuery.trim(this.value)}, function(data)
					{
						if(parseInt(data))
						{
							$("#_login .error").css({display:"block"});
							$("#_login .msg").css({display:"none"});
						}
						else
						{
							$("#_login .error").css({display:"none"});
							$("#_login .msg").css({display:"block"});
						}
					}
				)
			}
		).click(
			function()
			{
				$("#_login .error").css({display:"none"});
				$("#_login .error1").css({display:"none"});
				$("#_login .msg").css({display:"none"});
			}
		);
		$("#btnreg").click(function(){return Reg.checkData();});
	},

	checkData : function()
	{
		$("#birthday").val($("#_y").val()+"-"+$("#_m").val()+"-"+$("#_d").val());
		$("#code").val("reguser");
		if($("#fio_surname").val().length <2 || $("#fio_name").val().length <2 || $("#fio_lastname").val().length <2)
		{
			alert("Укажите ФИО");
			return false;
		}
		if($("#pass").val() != $("#repass").val())
		{
			alert("Пароли не совпадают")
			return false;
		}
		if($("#pass").val().length <6 || !/^[^А-Яа-я]+$/.test($("#pass").val()) )
		{
			alert("Длина пароля должна быть минимум 6 символов");
			return false;
		}
		if(($("#login").val().length < 4) || !$("#login").val().match(/^[A-Za-z0-9\_\.]+$/))
		{
			alert("Логин должен быть минимум 4 символа и состоять только из английских букв");
			return false;
		}
		if($("#company").val().length <3)
		{
			alert("Укажите компанию");
			return false;
		}
		if($("#position").val().length <3)
		{
			alert("Укажите должность");
			return false;
		}
		if($("#country").val().length <3)
		{
			alert("Укажите страну");
			return false;
		}
		if($("#city").val().length <3)
		{
			alert("Укажите город");
			return false;
		}
		if(parseInt($("#_y").val())>2000)
		{
			alert("Дата рождения указана не верно");
			return false;
		}
		$("#regform").submit();
	}
};


var RegEdit = {
	error: null,
	init: function()
	{
		$("#repass").blur(
			function()
			{
				if( ($("#pass").val() != $("#repass").val()) && $("#pass").val().length > 5 && /^[^--]+$/.test($("#pass").val()))
					$("#_repass .error").css({display:"block"});
				else
					$("#_repass .error").css({display:"none"});
			}
		);
		$("#repass").click(function(){$("#_repass .error").css({display:"none"});});
		$("#btnreg").click(function(){return RegEdit.checkData();});
	},

	checkData : function()
	{
		$("#birthday").val($("#_y").val()+"-"+$("#_m").val()+"-"+$("#_d").val());
		$("#code").val("reguser");
		if($("#fio_surname").val().length <2 || $("#fio_name").val().length <2 || $("#fio_lastname").val().length <2)
		{
			alert("Укажите ФИО");
			return false;
		}
		
		if ($("#pass").val())
		{
			if($("#pass").val() != $("#repass").val())
			{
				alert("Пароли не совпадают")
				return false;
			}
			if($("#pass").val().length <6 || !/^[^А-Яа-я]+$/.test($("#pass").val()) )
			{
				alert("Длина пароля должна быть минимум 6 символов");
				return false;
			}
		}
		if($("#company").val().length <3)
		{
			alert("Укажите компанию");
			return false;
		}
		if($("#position").val().length <3)
		{
			alert("Укажите должность");
			return false;
		}
		if($("#country").val().length <3)
		{
			alert("Укажите страну");
			return false;
		}
		if($("#city").val().length <3)
		{
			alert("Укажите город");
			return false;
		}
		if(parseInt($("#_y").val())>2000)
		{
			alert("Дата рождения указана не верно");
			return false;
		}
		$("#regform").submit();
	}
};

/*
function AJAXgetDailyEvents(d,m,y,p,obj)
{
	$.get("", {action:"_AJAXgetDailyEvents", d:d, m:m, y:y, p:p, ajax:""}, function(data)
		{
			$(obj).parent().parent().find("UL").html(data);
			var cell = $(obj).parent().parent().parent();
			var rightStr = cell.find(".rightStr");
			var leftStr = cell.find(".leftStr");
			var page = parseInt(rightStr.attr("id").replace("pn", ""));
			page += p>=page?1:-1;
			rightStr.attr("id", "pn"+page);
			leftStr.attr("id", "pp"+(page-2));
			if(data.indexOf("lastpage") != -1)
			{
				$(cell).find(".rightStr").hide();
			}
			else
			{
				rightStr.show();
			}
			if(page > 2)
			{
				leftStr.show();
			}
			else
			{
				leftStr.hide();
			}
		}
	);
	return false;
}
*/
function AJAXgetDailyEvents(d,m,y,p,obj)
{
	$.get("", {action:"_AJAXgetDailyEvents", d:d, m:m, y:y, p:p, ajax:""}, function(data)
		{
			$(obj).parent().parent().find("UL").html(data);
			CalendarTip.init();
			var cell = $(obj).parent().parent().parent();
			var rightStr = cell.find(".rightStr");
			var leftStr = cell.find(".leftStr");
			var page = parseInt(rightStr.attr("id").replace("pn", ""));
			if(obj.id.indexOf("pp")!=-1)
			{
				rightStr.attr("id", "pn"+(page-1));
				leftStr.attr("id", "pp"+(page-3));
			}
			else
			{
				rightStr.attr("id", "pn"+(page+1));
				leftStr.attr("id", "pp"+(page-1));
			}
		}
	);
	return false;
}

Array.prototype.remove = function(from, to) {
  var rest = this.slice((to || from) + 1 || this.length);
  this.length = from < 0 ? this.length + from : from;
  return this.push.apply(this, rest);
};