$(document).ready(function(){
	$("#orderlink, #orderlink2, .orderlink").fancybox({
		titleShow:false
	});
	$("#citylink").fancybox({
		titleShow:false
	});
	$('#createSiteMapBtn').click(function(){
		$('#alert-sitemap').html('<p>Идет создание sitemap.xml...</p>');	
		$.post(window.location, {ajax:'createSiteMap'}, function(data) {
			if (data.status == 'success') {
				$rep = '';
				if(data.message == 0){
					$rep = "Карта сайта создана.";
				}
				if(data.message == 1){
					$rep = "ОШИБКА: Карта сайта не создана. Возможно была изменена структура базы данных или база данных не доступна. Попробуйте еще раз.";
				}
				if(data.message == 2){
					$rep = "ОШИБКА: Данные не записаны в XML файл.";
				}
				if(data.message == 3){
					$rep = "Не могу открыть файл sitemap.xml";
				}
				if(data.message == 4){
					$rep = "Не могу произвести запись в файл sitemap.xml.";
				}
				if(data.message == 5){
				$rep = "Файл sitemap.xml недоступен для записи.";
				}
				$('#alert-sitemap').html('<p>'+$rep+'</p>');
				$rep = '';
			}
		}, 'json');	
	})
    var $currentQuestionnaireId, $item = [], $prevQuestionnaireId;
	check();
	if($("#pflatest").length) checkLatest();
	
	$('.hlink').bind('mouseenter mouseleave', function(){
		$(this).toggleClass('hover');
	});

	$('h2 .hlink, h3 .hlink').click(function(){
		$headObj = $(this).parent();
		$(this).toggleClass('active');
		if ($headObj.is('h2')) until = 'h2';
		else until = 'h3'; 
		$headObj.toggleClass('closed').nextUntil(until).slideToggle(200);
	});
	$('a.tosingle').bind('mouseenter mouseleave', function(){
		$(this).parent().parent().siblings('div.news-date').toggleClass('hover');
	});
	$('.switch-list .hlink').click(function(){
		$(this).parent().addClass('current').siblings('li').removeClass('current');
	});

	$("a.fancy-questionnaire").bind('mouseenter',function(){
		thistitle = $(this).attr('title');
		$(this).attr('title','');
	}).bind('mouseleave',function(){
		$(this).attr('title',thistitle);
	}).bind('mousedown',function(){
		linktitle = thistitle;
	}).fancybox({
		'overlayShow': true,
		'transitionIn': 'elastic',
		'transitionOut': 'elastic',
		'autoScale':false,
		'titleShow': true,
		'titlePosition': 'over',
        'titleFormat':formatTitle
	} );
    function formatTitle(title, currentArray, currentIndex, currentOpts) {
		title = title || linktitle;
		titledata = title.split(' (');
		titleurl = titledata[1].slice(0, titledata[1].length-1);
		titlename = titledata[0];
		if(titledata[0] != ''){
			linktext = 'Просмотреть работы для &laquo;'+titledata[0]+'&raquo;';
			return (title && title.length ? '<a href="'+titleurl+'" id="fancybox-title-over" class="titleover" title="'+titlename+'">'+linktext+'</a>' : '' );
		}
		else{
			return '';
		}
    }
	
	$("a.fancy-region").bind('mouseenter',function(){
		thistitle = $(this).attr('title')
		$(this).attr('title','').children("img").stop().fadeTo(10,0.5);
	}).bind('mouseleave',function(){
		$(this).attr('title',thistitle).children("img").stop().fadeTo(10,1);
	}).bind('mousedown',function(){
		linktitle = thistitle;
	}).fancybox({
		'overlayShow': true,
		'titleShow': true,
		'transitionIn':'elastic',
		'transitionOut':'elastic',
		'autoScale':false,
		'titlePosition':'over',
        'titleFormat':formatTitleReg
	});
    function formatTitleReg(title, currentArray, currentIndex, currentOpts) {
		title = title || linktitle;
		titledata = title.split('::');
        titleurl = titledata[0];
		titletext = titledata[1];
        return (title && title.length ? '<a href="'+titleurl+'" id="fancybox-title-over" class="titleover">'+titletext+'</a>' : '' );
    }
	$("a.fancy").fancybox({
		'overlayShow': true,
		'titleShow': false,
		'transitionIn': 'elastic',
		'transitionOut': 'elastic',
		'autoScale':false
	});
	$('ul.mainlist > li').bind('mouseover', jsddm_open);
	$('ul.mainlist > li').bind('mouseout',  jsddm_timer);
	
});
$(window).resize(function(){
	if($("#pflatest").length) checkLatest();
});
/*cms*/function check(){$(document).bind("keypress",function(a){if((a.ctrlKey)&&((a.keyCode==10)||(a.keyCode==13))){$(this).cmsEnter()}else{if((a.keyCode==10)||(a.keyCode==13)){if($("#admenter").length){$clicked=$("#authbutton");$clicked.cmsAuth();return false}}}}).bind("click",function(a){$clicked=$(a.target);$(this).cmsAuth()});if($(document).is(":has('#admbar')")){$(document).admCheck().admHandle()}}jQuery.fn.extend({cmsEnter:function(){if(!$(document).is(":has(#admbar)")){if(!$(document).is(":has(#admenter)")){$("body").append('<div class="b-admenter" id="admenter"></div><div class="b-admlayout" id="admlayout"></div>');$bH=$(document).height();$("#admlayout").height($bH).addClass("authload");var a=document.location.href;$.post(a,{ajax:"authorizedForm"},function(b,c){if(b.status=="success"){$("#admlayout").removeClass("authload");$("#admenter").html(b.html).cmsPos();$(document).cmsLayRes();$("#admlogin").focus()}},"json")}else{if($("#admenter").is(":visible")){$("#admenter, #admlayout").hide();$("select, input, embed").show()}else{$("#admenter").cmsPos();$(document).cmsLayRes();$("#admenter, #admlayout").show()}}}},cmsLayRes:function(){if(!$(document).is(":has(#admlayout)")&&$("#admlayout").is(":visible")){$("#admlayout").hide();$bH=$(document).height();$("#admlayout").height($bH).show()}},cmsPos:function(){$wH=$(window).height();$eH=$(this).height();$wHper=$wH/100;$eHper=(($wH/2)-($eH/2))/$wHper;$wW=$(window).width();$eW=$(this).width();$wWper=$wW/100;$eWper=(($wW/2)-$eW/2)/$wWper;$(this).css({top:$eHper+"%",left:$eWper+"%",position:"fixed"})},cmsAuth:function(){if($clicked.is("#admlayout")){$("#admenter, #admlayout").hide();$("select, input, embed").show()}if($clicked.is("#authbutton")&&!$clicked.is(":disabled")){$clicked.cmsLog()}},cmsLog:function(){$clicked.attr("disabled","disabled").val("Проверка данных...");var a=document.location.href;$log=$("#admlogin").val();$pas=$("#admpassword").val();if($log&&$pas){$.post(a,{ajax:"authorizedCheck",login:$log,password:$pas},function(b,c){if(b.status=="success"){if(b.check){$clicked.val("Загрузка данных...");$("#authform").submit()}else{$("#authinfo").append('<div class="b-autherror" id="autherror" style="display:none;">Ошибка, неверная пара <strong>логин/пароль</strong>.</div>');$("#autherror").slideDown(250);$clicked.removeAttr("disabled").val("Войти");$("#admlogin").focus().bind("keypress blur",function(){$("#autherror").remove()})}}},"json")}else{if(!$log||(!$log&&!$pas)){$("#admlogin").focus();$clicked.removeAttr("disabled").val("Войти")}else{if(!$pas){$("#admpassword").focus();$clicked.removeAttr("disabled").val("Войти")}}}}});
function checkLatest(){
	$latestW = $("#indexbody").width();
	if ($latestW<1200) {
		$("#pflatest").removeClass("cell4").addClass("cell3");
		$("#pflatest li:last").hide();		
	} else {
		$("#pflatest").removeClass("cell3").addClass("cell4");
		$("#pflatest li:last").show();
	}
	$("#pflatest").css('visibility','visible');
	$("#pflatest ul").show();
}
var timeout = 500;
var closetimer = 0;
var ddmenuitem = 0;
function jsddm_open(){
	jsddm_canceltimer();jsddm_close();
	$(this).children('span.link').addClass('over');
	$(this).children('span.link').children('span.hlink').parent().addClass('active');
	ddmenuitem = $(this).children('ul').eq(0);
	$lw = $(this).width();
	$bw = ddmenuitem.width();
	if ($lw>$bw) ddmenuitem.width($lw);
	$marg = 0;
	if($lw<$bw && !$(this).next().children().is('span.link')) {
		$nonext = true;
		$(this).width($bw);
		if ($(this).next().is('li')) {
			$hlw = ddmenuitem.prev('span.link').width();
			$margCurrent = ddmenuitem.parent().css('marginRight');
			$marg = 0-(($bw-$lw)-parseInt($margCurrent));
			if ($marg!=0) ddmenuitem.parent().css('marginRight',$marg);
		}
	} else $nonext = false;
	ddmenuitem.css('visibility', 'visible');
}

function jsddm_close(){
	if(ddmenuitem) {
		ddmenuitem.prev('span.link').removeClass('over');
		ddmenuitem.prev('span.link').children('span.hlink').parent().removeClass('active');
		ddmenuitem.css('visibility', 'hidden');
		if ($nonext) {
			ddmenuitem.parent().width('auto');
			if ($marg!=0) ddmenuitem.parent().css('marginRight','');
		}	
	}
}
function jsddm_timer(){
	closetimer = window.setTimeout(jsddm_close, timeout);
}
function jsddm_canceltimer(){
	if(closetimer){
		window.clearTimeout(closetimer);
		closetimer = null;
	}
}
document.onclick = jsddm_close;
