$(document).ready (function () {
	
	$.dialogMassage = function(option) {
		var option = $.extend({
			time:5000,
			speed:'slow',
			note:null,
			className:null,
			sticked:false,
			position:{top:0,right:0}
		}, option);
		var dialogMassage = $('#jquery-dialogMassage');
		if (!dialogMassage.length) {
			$('body').prepend('<div id="jquery-dialogMassage"></div>');
			var dialogMassage = $('#jquery-dialogMassage');
		}
		dialogMassage.css({'position':'fixed','z-index':500000}).css({right:'auto',left:'auto',top:'auto',bottom:'auto'}).css(option.position);
		var dialog = $('<div class="dialog"></div>');
		dialogMassage.append(dialog);
		if (option.className) dialog.addClass(option.className);
        dialog.html(option.note);
		if (option.dialoged) {
			var exit = $('<div class="exit"></div>');
			dialog.prepend(exit);
			exit.click(function(){
				dialog.fadeOut(option.speed,function(){
					$(this).remove();
				})
			});
		} else {
			setTimeout(function(){
				dialog.fadeOut(option.speed,function(){
					$(this).remove();
				});
			}, option.time);
		}
	};
	$.fn.showTree = function(o){
		var o = $.extend({
			closeFolders: false,
			classTree: null
		}, o);
		return $(this).each(function(){
			var tree = $(this);
			tree.addClass('jquery-tree').children('li:first').prepend('<div class="first"></div>');
			tree.children('li:last').addClass('last');
			tree.find('ul').each(function(){
				$(this).children('li:last').addClass('last');
			}).prev('a').addClass('folder');
			if (o.classTree) tree.addClass(o.classTree)
			tree.find('a.folder').before('<span class="show"></span>');
			tree.find('span').click(openTree);
			if (o.closeFolders) {
				tree.find('ul').hide();
			} else {
				tree.find('.folder').addClass('open').prev('span').addClass('minus');
			}
		});
		function openTree(){
			var button = $(this);
		   	var link = button.next();
			var files = link.next('ul');
			if (link.hasClass('open')) {
				files.hide();
			} else {
				files.show();
			}
			link.toggleClass('open');
			button.toggleClass('minus');
			return false; 
		}
	};
	
	$.fn.boxShadow = function(o){
		if (!o) return;
		var str = o.split(' '),
		x = parseInt(str[0]),
		y = parseInt(str[1]),
		blur = 0,
		color = '';
		if (str.length == 3) {
			color = str[2];
		} else {
			blur = parseInt(str[2]);
			color = str[3];
		}
		return $(this).each(function(){
			var box = $(this),
			off = box.offset();
			box.css({position:'relative',zIndex:1}).after('<div id="reloadssss"></div>').next()
			.css({
				width:box.width() + parseInt(box.css('padding-left')) + parseInt(box.css('padding-right')),
				height:box.height() + parseInt(box.css('padding-bottom')) + parseInt(box.css('padding-top')),
				position:'absolute',zIndex:0,backgroundColor:color,left:off.left + x - blur + 'px',top:off.top + y - blur + 'px'});
			if (blur) box.next().css('filter','progid:DXImageTransform.Microsoft.Blur(pixelradius=' + blur + ', enabled="true")');
		});
	};
	
	
	$.fn.boxItems = function() {
		var $i = $(this);
		
		$i.hover(
			function() {
				$i.html();
			},
			function() {
				
			}
		)
		
		
	}
	
	$('a.items-photos').boxItems();
	
	$.openDialog = function(id) {
		
		var $d = $('#'+id);
		var $h = $(window).height();
		var $w = $(window).width();
		var $hd = $d.height();
		var $wd = $d.width();
		var $right = ($w-$wd)/2;
		var $top = ($h-$hd)/2;
		
		$d.css({'right':$right});
		
		if($h < $hd) {
			$hd = $h-20;
			var $top = ($h-$hd)/2;
			$d.css({'height':$hd+'px','top':$top});
		}
		else {
			$d.css({'top':$top});
		}
	}
	
	$.openD = function( text_dialod, id, obj, cookies ) {
		if($('#'+id+'').length == 0) $('body').append($('<div/>').attr('id', id));
		var text_open_dialog = '<div class="'+id+'info"><a id="close-dialog-data" href="#close">Закрыть</a>'+text_dialod+'</div>';
		$('#'+id+'').append(text_open_dialog);
		$.openDialog(id);
		$('#'+id+'').find("a[href=#close]").click(function() {
			$('#'+id+'').hide('show');
			setTimeout(function(){$('#'+id+'').remove();}, 3000);
			if(cookies) $.cookie(''+id+'',true, obj);
			return false;
		});
	}
	
	$.openDialogFaq = function() {
		
		$('#FaqDialogSiteText').remove();
		
		$.openD('<h1>Обратная связь.</h1><div>Ваше имя:<input name="name">Почтовый ящик:<input name="email">Вопрос, пожелание:<textarea></textarea></div><div>Сообщение не будет отправлено если какое-то из полей заполнено неверно.</div><div><a href="#submit" class="input">Отправить</a></div>', 'FaqDialogSiteText', {path:'/'}, false);
		var $vot = $('#FaqDialogSiteText');
		
		$vot.find('a[href=#submit]').click(function(){
			var $text = $vot.find('textarea').val();
			var $name = $vot.find('input[name=name]').val();
			var $email = $vot.find('input[name=name]').val();
			
			if($text.length > 5 && $name.length > 2 && $email.length > 5) {
				$.post("voteajax.php",{'get':'faq','text':$text, 'email': $email, 'name': $name});
			}
				
			$('#FaqDialogSiteText').hide('show');
			
			return false;
		});
	}
	
	if(!$.cookie('openDialogHello')) {
		$(window).resize(function(){
			$.openDialog();
		});
		
		var $_text_open_dialog = ''
		+'<p>Уважаемые пользователи, предлагаем Вашему вниманию новую версию сайта (конструктивно новый сайт).</p>'
		+'<p>В данной версии Вам предлагаются следующие новинки:</p>'
		+'<ul>'
			+'<li>1. Разбивка по разделам стала намного удобнее. </li>'
			+'<li>2. Поиск по ключевому слову в нужной вам категории.</li>'
			+'<li>3. Личный кабинет</li>'
			+'<li>4. «Управление» своими объявлениями (например, снять объявление с публикации на сайте, вернуть или продлить).</li>'
		+'</ul>'
		+'<p>На этом мы не намерены останавливаться – будут разрабатываться новые возможности сайта с учетом ваших пожеланий, исправляться ошибки («<a href="#faq">обратная связь</a>»).</p>'
		+'<p>Мы с удовольствием выслушаем ваши предложения и замечания.</p>'
		+'<p>Спасибо, что <b>Вы</b> с нами!</p>'
		$.openD('<h1>Мы рады вас видеть на нашем новом сайте.</h1>'+$_text_open_dialog, 'openDialogHello', {path:'/','expires':365}, true);
	}
	
	if(!$.cookie('VoteDialogSite')) {
	
		var $text_vote = ''
		+'<div class="vote-vote">Вам нравится наш новый сайт?</div>'
		+'<div class="vote-input"><a href="#yeas">Да</a><a href="#no">Нет</a></div>';
		var $v = $('#vote-dialog-site');
		
		$v.html($text_vote);
		
		$v.find("a[href=#yeas]").click(function() {
			$.get("voteajax.php",{'get':'yeas'});
			$v.hide('show');
			setTimeout(function(){$v.remove();}, 3000);
			$.cookie('VoteDialogSite',true, {path:'/','expires':365});
			return false;
		});
		
		$v.find("a[href=#no]").click(function() {
			$.openD('<h1>Почему вам не понравился сайт?</h1><div><textarea></textarea></div><div><a href="#submit" class="input">Отправить</a></div>', 'VoteDialogSiteText', {path:'/'}, false);
			var $vot = $('#VoteDialogSiteText');
			$vot.find('a[href=#submit]').click(function(){
				
				var $text = $vot.find('textarea').val();
				
				if($text.length > 5) {
					$.post("voteajax.php",{'get':'to_text','text':$text});
				}
				
				$('#VoteDialogSiteText').hide('show');
				setTimeout(function(){$('#VoteDialogSiteText').remove();}, 3000);
				
				return false;
			});
			$.get("voteajax.php",{'get':'no'});
			$v.hide('show');
			setTimeout(function(){$v.remove();}, 3000);
			$.cookie('VoteDialogSite',true, {path:'/','expires':365});
			return false;
		});
	}
	else {
		$('#vote-dialog-site').remove();
	}
	
	$('a[href=#faq]').click(function(){
		$.openDialogFaq();
	});
	
	$('.category-all').showTree({closeFolders: true});

	
});
