$(document).ready(function(){
	dictum();	
	SpamAnimation.init();	
	fancyfeast();
	submenu();
	Fancyform.init();
	doublehover();
});
//double hover
function doublehover(){
		$(".cont_menu .menu_stripe,.images").hover(
				function(){
					$(this).parent().addClass("active");					
				},
				function(){
					$(this).parent().removeClass("active");
				});		
}
//----- Общие настройки---------------------------------------------------------
SESS_ID = '';
if (window.location.toString().match(/SESS_ID=(\d+)/))
    SESS_ID = RegExp.$1;
/**
 * Выполняет Ajax запрос с xml-ответом
 * @param {Object} data Данные
 * @param {Function} handler Обработчик
 */
getXML = function(data, handler) {
    if (SESS_ID)
        data['SESS_ID'] = Ctmol.SESS_ID;
    $.post('/ajax/', data, handler, 'xml');
}
textContent = function(xml) {
    var cnt;
    if (xml.text != undefined) {
      cnt = xml.text;
    } else if (xml.textContent != undefined) {
      cnt = xml.textContent;
    } else {
      cnt=xml.firstChild.nodeValue;
    }
    return cnt;
}
//Фэнсибокс по ссылке "написать письмо"
Fancyform = function(){
	
	function show(xml){
		if(xml){
			var template = xml.getElementsByTagName("template")[0];
			if(template){
				$.fancybox(textContent(template),{titleShow: false});
				$("form").submit(function(){send(this); return false;});								  
			}
		}
	}
	
	function send(form){
		var params ={iface: "mail_form"};
		
		var $form=$(form);
		
		var errorFlag = false;
		
		$form.find('.p').removeClass('error');
		var $fields = $form.find('input, textarea');
		for (var i = 0; i<$fields.length; i++){
			var $f = $fields.eq(i), $p = $f.parent();
			if(($f.attr('name'))&&($f.attr('name')!='__BACK')){
				var val = $f.val().trim();
				params[ $f.attr('name') ] = val;
				if(($p.hasClass('need-field')) && (val == '')){
					$p.addClass('error');
					errorFlag = true;
				}
			}
		}
		if(!errorFlag){
			$.fancybox.showActivity();
			getXML(params,function(xml){answer(xml); });
		}
	}
	function answer(xml){
		if(xml){
			var template = xml.getElementsByTagName("template")[0];
			if(template){
				$.fancybox(textContent(template),{titleShow: false});
			}
		}
	}
	
	return{
		init: function(){
			$(".click_form").click(function(){				
				$.fancybox.showActivity();
				getXML({iface: "mail_form",
								_action: "get"},function(xml){show(xml); });
				return false;})
			}
		}
}();

//Фэнсибокс по ссылке "подробнее"
function fancyfeast(){
	$(".paper_cont li").each(function(){
		var $this = $(this);
		var cont = $this.find(".hidden_cont").html();		
		$this.find("a.click_link").click(function(){	
			$.fancybox({ 					
					'content' : "<div class='text marg'>"+cont+"</div>",
					'autoDimensions' :false,
					'scrolling' :'auto',
					'width' :680,
					'height':440
				});				
			return false;	
		})
	})
}
//Анимация меню в шапке
function submenu(){
	$(".head_menu li .sub_menu").hide();
	$(".head_menu li").each(function(){		
		$(this).hover(
		function(){
			$(this).find(".sub_menu").show();
		}, 
		function(){
			$(this).find(".sub_menu").hide();
		});
	});
}
//Анииация высказыванинй
function dictum(){
	$(".dictum span").css({'display':'none'})
	window.setTimeout(animate,4000);
	function animate(){
		$(".dictum span.words")
		.css({			
			'margin-left':'260%',
			'display':'block'
		})
		.animate({		 
		'margin-left':'-=260%'},1000,function(){ 
			$(".dictum span.author")
			.css({'margin-top':'-14px','display':'block'})
			.animate({'margin-top':'+=21px'},1000, 'linear');});		
		}	
}
//Анимация скрытого контента по нажатию на ссылку.
function hide_show(){	
	$(".paper_cont li a.click_link").each(function(){
		var $this = $(this);		
		$this.click(function(){
				if($this.hasClass("active")){
							$(this.parentNode).find(".hidden_cont").slideUp("slow", function(){				
								$(this.parentNode).find(".click_link").html("подробнее");
								$(this.parentNode).find(".click_link.active").removeClass("active");
							}) 			
				}
				else{
					$(this.parentNode).find(".hidden_cont").slideDown("slow", function(){				
						$(this.parentNode).find(".click_link").html("скрыть");
						$this.addClass("active");
					})	
				}
			return false;
		});
	})		
}

//Анимация спама над меню
SpamAnimation = function(){

	var $anim = $();
	function setup(){		
		$anim.find("div").each(function(){						
			var $this = $(this);
			this.adv_block = $this.find(".adv_block");
			this.sp_height = this.adv_block.find(".second_part").height();
			this.adv_block.find(".second_part").height(0);			
			$this.hover(function(){					
					var div  = this;					
					this.adv_block.find(".second_part").stop().animate({height:div.sp_height},400,'swing');
				},
				function(){					
					this.adv_block.find(".second_part").stop().animate({height:0},400,'swing');
					
				})
			});		
		}
		return{
			init: function(){
				$anim = $(".cont_menu");
				if($anim.length>0){					
					setup();					
				}
			}
		}
}();



// Полезные функции-утилиты	
/**
 * pngFix для IE
 *
 */
var __sizingRegExp = /iesizing\-(\w+)/;
function fixPNG(element, sizing, force) {
    if ((Browser.isIE6) || (force)) {
        sizing = sizing || "crop";
        var sizingMatch = __sizingRegExp.exec(element.className)
        if (sizingMatch)
            sizing = sizingMatch[1];
        var url;
        if (element.tagName == "IMG") {
            if (/\.png$/.test(element.src)) {
                url = element.src;
                element.src = "/i/ie/e.gif";
            }
        } else {
            url = element.currentStyle.backgroundImage.match(/url\(["']?(.+\.png).*?["']?\)/i);
            if (url) {
                url = url[1];
                element.runtimeStyle.backgroundImage = "none";
            }
        }
        if (url)
            element.runtimeStyle.filter = "progid:DXImageTransform.Microsoft.AlphaImageLoader(src='" + url + "',sizingMethod='" + sizing + "')";
        else
            element.runtimeStyle.filter = "true";
    }
}
/**
 * Класс для обработки специфических функций браузера
 */
Browser = function() {
    var userAgent = navigator.userAgent.toLowerCase();
    var _ie = /msie/.test(userAgent) && !/opera/.test(userAgent);
    var _opera = /opera/.test(userAgent);
    var _old_ie = /MSIE (5\.5|6|7).+Win/.test(navigator.userAgent);
    var _webkit = /webkit/.test(userAgent);
    return {
        isOpera: _opera,
        isMSIE: _ie,
        isWebKit: _webkit,
        isIE6: _old_ie,
        /**
         * Определяет область с основной прокруткой
         * (в браузерах на WebKit она волшебным образом отличается
         */
        getScrollBody: function() {
            return (_webkit)
                ? document.body
                : document.documentElement;
        }
    }
}();

/*==============================================================*/


/* Показ картинки */
function showFBox(link) {
    if ((link) && (link.href)) {
        if (!link.__fbox) {
            link.__fbox = new FBox({
                animation: true,
                showOverlay: true,
                useLoaderAnim: false,
                loaderParams: {
                    animatioLength: 400,
                    animationStep: 50,
                    animationTime: 100
                },
                image: {
                    src: link.href,
                    comment: link.title
                },
                constraints: {
                    minWidth: 300,
                    minHeight: 300,
                    maxWidth: 750,
                    maxHeight: 550
                }
            })
        }
        link.__fbox.show();
        return false;
    }
    return true;
}
window.showFBox = showFBox;

/* ajax галерея */
var bigAjaxGallery = null;
function showAjaxGallery(el) {
    if (!bigAjaxGallery) {
        var gallery_id = el.href.split("?")[1].split("=")[1];
        bigAjaxGallery = new FBox({
            animation: true,
            imagesList: true,
            imagesListWidth: 80,
            useLoaderAnim: true,
            loaderParams: {
                animatioLength: 400,
                animationStep: 50,
                animationTime: 100
            },
            showOverlay: true,
            navigationButtons: true,
            navigationButtonsHover: false,
            ajax: {
                url: '/ajax/',
                iface: 'gallery',
                gallery_id: gallery_id
            },
            constraints: {
                minWidth: 470,
                minHeight: 465,
                maxWidth: 750,
                maxHeight: 550
            }
        });
    }
    bigAjaxGallery.show();
}
window.showAjaxGallery = showAjaxGallery;

function offset(el, to) {
    var tEl = to || document.documentElement;
    var left = 0;
    var top = 0;
    var sel = el;
    do {
        left += sel.offsetLeft;
        top += sel.offsetTop;
    } while ((sel = sel.parentNode) && (sel != tEl));
    return { left: left, top: top };
}


function multipleGalleries(){
    this.name = "MultiGallery";
    this.gallery = null;
    this.start();
}

/* Каталог галерей */
multipleGalleries.prototype = {
    start: function(){
        var self = this;
        $(".galleries .g-item").each(function(){
            var links = $(this).find("a.shg");
            if(links.length>0){
                $(links[0]).click(function(){
                    var gallery_id = this.href.split("?")[1].split("=")[1];
                    if(self.gallery){ self.gallery = null };
                    self.gallery = new FBox({
                            animation: true,
                            imagesList: true,
                            imagesListWidth: 80,
                            useLoaderAnim: true,
                            loaderParams: {
                                animatioLength: 400,
                                animationStep: 50,
                                animationTime: 100
                            },
                            showOverlay: true,
                            navigationButtons: true,
                            navigationButtonsHover: false,
                            ajax: {
                                url: '/ajax/',
                                iface: 'gallery',
                                gallery_id: gallery_id
                            },
                            constraints: {
                                minWidth: 470,
                                minHeight: 465,
                                maxWidth: 750,
                                maxHeight: 550
                            }
                        });
                    self.gallery.show();
                    return false;
                });
                $(links[1]).click(function(){
                    $(links[0]).trigger('click');
                    return false;
                })
            }
        });
    }
}
window.multipleGalleries = multipleGalleries;

/* Галерея в произвольном месте */
function Gallery(el,id){
    if((el)&&(id)){
        if(!el.__gallery){
            el.__gallery = new FBox({
                animation: true,
                imagesList: true,
                imagesListWidth: 80,
                useLoaderAnim: true,
                loaderParams: {
                    animatioLength: 400,
                    animationStep: 50,
                    animationTime: 100
                },
                showOverlay: true,
                navigationButtons: true,
                navigationButtonsHover: false,
                ajax: {
                    url: '/ajax/',
                    iface: 'gallery',
                    gallery_id: id
                },
                constraints: {
                    minWidth: 470,
                    minHeight: 465,
                    maxWidth: 750,
                    maxHeight: 550
                }
            });
        }
        el.__gallery.show();
        return false;
    }
    return true;
}
window.Gallery = Gallery;
