var start_opacity;
$(document).ready(function(){
	start_opacity = $("#shadow").css('opacity');
	
	//рандомная шапка
	var pos = Math.round( Math.random()*3 );
	if (pos == 3){ pos = 0;}
	$("#header").css("backgroundPosition","left -"+91*pos+"px");
	
	/* подвал */
	/* свежие тексты */
	$("#show_new_texts").click(function(){
		$("#new_texts").animate( {height: "326",top:"-326"}, "slow");
		//$("#push").animate( {height: "417"}, "slow");
	});

	$("#hide_new_texts").click(function(){
		$("#new_texts").animate( {height: "0",top:"0"}, "slow");
		//$("#push").animate( {height: "91"}, "slow");
	});
	
	/* карусель в подвале */
	$("#show_counters").click(function(){
		var width = $("#carousel").width();
		$("#razrabotka").animate( {"marginLeft": "-" + width}, "slow");
	});
	$("#hide_counters").click(function(){
		var width = $("#carousel").width();
		$("#razrabotka").animate( {"marginLeft": "0px"}, "slow");
	});
	
	/* уголки */
	$('input[type="text"], input[type="password"]').before('<div class="input_left"></div>').after('<div class="input_right"></div>');
	
	/* форма о проекте */
	$("#about_block").prepend('<div class="about_title_right"></div><div class="about_title_left"></div>').append('<div class="about_right"></div><div class="about_left"></div><div class="about_bottom"></div>');
	
	//таймер
	if ($(".timer").length>0) { timer = setInterval  ( "update_timer()", 1000 );}
	
	
	
	$('.show_about_block').click(function(){
		var w = $("#page").width();
		var h = $("#page").height();
		$("#shadow").width(w).height(h);

		
		var w_h = window.innerHeight;
		var b_h = $("#about_block").height();
		var b_w = $("#about_block").width();
		
		var top = (w_h - b_h) / 2;
		if ( top < 0 ){ top = 0;}
		 if (!top ) { top = 40;}
		
		$("#about_block").css("left", ((w-b_w)/2)+"px").css("top", top+"px").fadeIn("slow");
		
		 if ( jQuery.browser.msie){
			 if ( jQuery.browser.version < 8){
				$("#shadow").show();
				$("#about_block").show();
			 } else {
				$("#shadow").animate({'opacity':start_opacity},"slow");
				$("#about_block").animate({'opacity':start_opacity},"slow");
			 }
		 } else {
			$("#shadow").fadeIn("slow");
			$("#about_block").fadeIn("slow");
		 }
		 
		 return false;
	});
	
	$("#shadow").click(function(){
		 if ( jQuery.browser.msie){
			 if ( jQuery.browser.version < 8){
				$("#shadow").hide();
				$("#about_block").hide();
			 } else {
				$("#shadow").animate({'opacity':'0'},"slow");
				$("#about_block").animate({'opacity':'0'},"slow");
			 }
		 } else {
			$("#shadow").fadeOut("slow");
			$("#about_block").fadeOut("slow");
		 }
	});

	//проверка капчи
	$(".check").blur(function(){
		if ($(this).val().length < 6 ){
			$(this).parent().parent().find("[class^='icon']").attr("class","icon_error");
		}
	});
	 
	$(".check").keyup(function(){
		obj = this;
		if ($(this).val().length == 6 ){
			$.post("ajax.php", {action:"check_captcha",check:( $(this).val() )}, function(data){
				$(obj).parent().parent().find("[class^='icon']").attr("class","icon_"+data);
			});
		}
	});
	
	//проверка email
	$(".email").blur(function(){
		if ( $(this).val().length == 0 ){return false;}
		if ( isValidEmail( $(this).val() , true ) ){
			$(this).parent().parent().find("td.last").html('<div class="icon_ok"/>');
		} else {
			$(this).parent().parent().find("td.last").html('<div class="icon_error"/><p>Введите правильный адрес</p>');
		}
	});
	
	//проверка адреса
	$("#page_address").blur(function(){
		if ( $(this).val().length == 0 ){
			$(this).parent().parent().find("td.last").html('');
			$(this).parent().find("p").html("<br/>Ваш адрес: http://getpage.org/");
			return false;
		}
		obj = this;
		$.post("ajax.php", {action:"check_address",address:( $(this).val() )}, function(data){
			if (data.status == "ok"){
				$(obj).parent().parent().find("td.last").html('<div class="icon_ok"/>');
			} else {
				$(obj).parent().parent().find("td.last").html('<div class="icon_error"/><p><b>Такой адрес занят</b><br/>Введите другой</p>');
			}
			$(obj).val( data.address );
			$(obj).parent().find("p").html("<br/>Ваш адрес: http://getpage.org/"+$(obj).val() );
		}, "json");
	});
	
	$("#page_address").keyup(function(){
		$(this).parent().find("p").html("<br/>Ваш адрес: http://getpage.org/"+$(this).val() );
	});
	
	//проверка сообщения в обратной связи
	$("#message").blur(function(){
		if ( $(this).val().length<10 ){
			$(this).parent().parent().find("td.last").html('<div class="icon_error"></div><p>Введите более содержательное сообщение</p>');
		} else {
			$(this).parent().parent().find("td.last").html('<div class="icon_ok"></div>');
		}
	});
	//проверка имени в обратной связи
	$("#username").blur(function(){
		if ( $(this).val().length<2 ){
			$(this).parent().parent().find("td.last").html('<div class="icon_error"></div>');
		} else {
			$(this).parent().parent().find("td.last").html('<div class="icon_ok"></div>');
		}
	});
	
	
	//проверка перед отправкой формы на создание страницы
	$("#add_page_form, #feedback_form").submit(function(){
		if ( $(this).find(".icon_no, .icon_error").length>0  ) {
			$(this).find(".icon_no").attr("class","icon_error");
			$(this).find(".icon_no, .icon_error").fadeOut("slow",function(){
				$(this).fadeIn("slow");
			});
			return false;
		}
	});
	
	//для админа
	
	//удаление
	$("#admin_catalog .del").click(function(){
		if ( confirm("Страница будет безвозвратно удалена. Продолжить?") ){
			var obj = this;
			$.post("ajax.php",{action:"del_page",id: $(this).attr("href") }, function(data){
				if (data.status == "ok"){
					$(obj).parent().parent().slideUp("slow",function(){
						$(this).remove();
					});
				}
			},"json");
		}
		return false;
	});
	
	//просмотр
	$("#admin_catalog .page_link").click(function(){
		var obj = this;
		$.post("ajax.php",{action:"show_page",id: $(this).attr("href") }, function(data){
			if (data.status == "ok"){
				$(obj).parent().parent().removeClass("new");
				$(obj).parent().find("ul").remove();
				$(obj).after( data.content );
				$(obj).parent().find("ul").slideDown("slow");
			}
		},"json");
		return false;
	});
	
	$(".hide_ul").live("click",function(){
		$(this).parent().slideUp("slow",function(){
			$(this).remove();
		});
		return false;
	});
	
	if (CKEDITOR){
		CKEDITOR.replace( 'editor', { toolbar :[[ 'Bold', 'Italic', '-', 'NumberedList', 'BulletedList', '-', 'Link', 'Unlink' ]]}); 
	}
	
});

function isValidEmail (email, strict)
{
 if ( !strict ) email = email.replace(/^\s+|\s+$/g, '');
 return (/^([a-z0-9_\-]+\.)*[a-z0-9_\-]+@([a-z0-9][a-z0-9\-]*[a-z0-9]\.)+[a-z]{2,6}$/i).test(email);
}

function update_timer(){
		time = $(".timer").text( ).split(':');
		time = +time[0]*60 +(+time[1]);

		if (time>0) {time--;} else {clearInterval(timer);}

		min = Math.floor(time/60);
		sec = time - min*60;

		if (sec<10) {
			time = min+":0"+sec ;
		} else {
			time = min+":"+sec ;
		}

		$(".timer").text( time );
}