jQuery(function($) {
	$(document).ready(function(){
		//гармошка фака
		$(".faq dt span").live("click", function(){
			$(this).parent().toggleClass("open");
			$(this).parent().next().slideToggle();
			return false;
		});
	});
    var SOEX = {
        initialize: function() {
            Cufon.set('autoDetect', true);
			
            this.Top.initialize();
            this.TopMenu.initialize();
            this.Header.initialize();
            this.Footer.initialize();
            this.Banner.initialize();
            this.Main.initialize();
            this.SearchResults.initialize();
            this.Content.initialize();
            this.Forms.initialize();
            this.Map.initialize();
            this.Tabs.initialize();

            $('img').mousedown(function(event) {
                event.preventDefault();
            });
            if ($.cookie('footer-state') == 'hide') {
                this.Footer.hideSiteMap(0);
            }
            /*if ($.cookie('header-state') != 'show') {
                this.Header.hideHeader(0);
            }*/
            if ($.cookie('header-state') == 'hide') {
                this.Header.hideHeader(0);
            }

            this.IE7.initialize();
        },
		
        /* Top ****************************************************************/
        Top: {
            $this: null,

            initialize: function() {
                this.$this = $('#top');

                Cufon.replace(this.$this.find('.company .middle'));

                SOEX.Utils.inputPlaceHolder(this.$this.find('form.search input.place-holder'));
            }
        },

        /* Top Menu ***********************************************************/
        TopMenu: {
            $this: null,

            initialize: function() {
                this.$this = $('#top-menu');

                this.$this.find('> li:last').addClass('last-of-type');

                this.stretch();
                this.$this.find('> li > a').wrapInner('<span class="left"></span>').append('<span class="right"></span>');
                this.$this.find('> li > a span.left').css({position: 'absolute'}).textShadow('#384f49', 0, -1);

                this.initSubMenu();
            },

            stretch: function() {
                var menuWidth = this.$this.width();
                var arrLiPos = [];
                var liSumWidth = 0;
                var $liList = this.$this.find('> li');
                var liCount = $liList.length;

                for (var i = 0; i < liCount; i++) {
                    arrLiPos[i] = $($liList[i]).position().left;
                    liSumWidth += $($liList[i]).width();
                }

                var dWidth = (menuWidth - liSumWidth) / liCount;

                for (var i = 1; i < liCount; i++) {
                    arrLiPos[i] = Math.floor(arrLiPos[i] + dWidth * i);
                }
                arrLiPos[liCount] = menuWidth;

                for (var i = 0; i < liCount; i++) {
                    $($liList[i]).width(arrLiPos[i + 1] - arrLiPos[i]);
                }
            },

            initSubMenu: function() {
                Cufon.replace(this.$this.find('> li > ul > li > a'), {
                    textShadow: '0 -1px #fff',
                    hover: true
                });
                Cufon.now();

                var MAX_MENU_WIDTH = 250;
                var SLIDE_DURATION = 150;

                var $ulList = this.$this.find('> li > ul');

                $ulList.css({
                    visibility: 'hidden',
                    display: 'block'
                });

                $ulList.each(function() {
                    var $ul = $(this).width(MAX_MENU_WIDTH);
                    var $parentLi = $ul.closest('li');
                    var $parentUl = $parentLi.closest('ul');
                    var aMaxWidth = 0;

                    $ul.find('> li > a').each(function() {
                        aMaxWidth = Math.max(aMaxWidth, $(this).outerWidth());
                    }).css({
                        whiteSpace: 'normal',
                        float: 'none'
                    });

                    aMaxWidth *= 1.1;

                    $ul.width(Math.min(Math.max($parentLi.width(), MAX_MENU_WIDTH), Math.max($parentLi.width(), aMaxWidth)));

                    if ($ul.offset().left + $ul.width() > $parentUl.offset().left + $parentUl.width()) {
                        $ul.addClass('left');
                    }

                    $ul.find('> li:last').addClass('last-of-type');
                });

                $ulList.append('<div class="bg"><span class="left"></span><span class="right"></span></div>');

                $ulList.css({
                    display: 'none',
                    visibility: 'visible'
                });

                $ulList.parent('li').hover(function() {
                    var $ul = $(this).find('> ul');
                    if (!$ul.queue().length) {
                        $ul.slideDown(SLIDE_DURATION);
                    }
                }, function() {
                    $(this).find('> ul').slideUp(SLIDE_DURATION);
                }).mousemove(function() {
                    var $ul = $(this).find('> ul');
                    if (!$ul.queue().length) {
                        $ul.slideDown(SLIDE_DURATION);
                    }
                });
            }
        },

        /* Header *************************************************************/
        Header: {
            $this: null,
            textHeight: null,
            SWITCH_DURATION: 500,
            isAnimated: false,
            isIndex: false,

            initialize: function() {
                this.$this = $('#header');

                if ($('body#index').length) {
                    this.isIndex = true;
                    this.initIndexHeader();
                }
            },

            initIndexHeader: function() {
                Cufon.replace(this.$this.find('h1'), {textShadow: '0 -1px rgba(0, 0, 0, 0.45)'});
                Cufon.replace(this.$this.find('h2'));

                this.$this.find('.light-block ul li').textShadow('#fff', 0, 1);

                this.$this.find('.control .switch a.hide').click($.proxy(function() {
                    this.hideHeader();
                }, this));
                this.$this.find('.control .switch a.show').click($.proxy(function() {
                    this.showHeader();
                }, this));
            },

            hideHeader: function(duration) {
                duration = $.type(duration) === 'number' ? duration : this.SWITCH_DURATION;
                var EASING = 'swing';

                if (!this.isIndex || this.isAnimated) {
                    return;
                } else {
                    this.isAnimated = true;
                }

                var $h = this.$this;
                var $db = $h.find('.dark-block');
                var $lb = $h.find('.light-block');
                var $tc = $db.find('.text-container');

                this.textHeight = $tc.find('.text').outerHeight(true);
                $tc.css({height: this.textHeight + 'px'});

                $h.animate({height: '240px'}, duration, EASING, $.proxy(function() {
                    this.isAnimated = false;
                }, this));
                $h.find('.bg-dynamic img').animate({
                    top: '-44px',
                    left: '-152px'
                }, duration);
                $db.animate({
                    paddingTop: '-=7',
                    paddingBottom: '-=20'
                }, duration, EASING);
                $tc.animate({
                    height: 0,
                    opacity: 0
                }, duration, EASING);
                $lb.animate({right: '-=' + $lb.outerWidth()}, duration);
                this.$this.find('.switch .hide').fadeOut(duration / 2, $.proxy(function() {
                    this.$this.find('.switch .show').fadeIn(duration / 2);
                }, this));

                $.cookie('header-state', 'hide', {expires: 365});
            },

            showHeader: function(duration) {
                duration = $.type(duration) === 'number' ? duration : this.SWITCH_DURATION;
                var EASING = 'swing';

                if (!this.isIndex || this.isAnimated) {
                    return;
                } else {
                    this.isAnimated = true;
                }

                var $h = this.$this;
                var $db = $h.find('.dark-block');
                var $lb = $h.find('.light-block');
                var $tc = $db.find('.text-container');

                $h.animate({height: '472px'}, duration, EASING, $.proxy(function() {
                    this.isAnimated = false;
                }, this));
                $h.find('.bg-dynamic img').animate({
                    top: 0,
                    left: 0
                }, duration);
                $db.animate({
                    paddingTop: '+=7',
                    paddingBottom: '+=20'
                }, duration, EASING);
                $tc.animate({
                    height: this.textHeight + 'px',
                    opacity: 1
                }, duration, EASING, function() {
                    $tc.css({height: 'auto'});
                });
                $lb.animate({right: '+=' + $lb.outerWidth()}, duration);
                this.$this.find('.switch .show').fadeOut(duration / 2, $.proxy(function() {
                    this.$this.find('.switch .hide').fadeIn(duration / 2);
                }, this));

                $.cookie('header-state', 'show', {expires: 365});
            }
        },

        /* Main ***************************************************************/
        Main: {
            $this: null,

            initialize: function() {
                this.$this = $('#main');

                var padding;
                if (SOEX.Banner.$this.length) {
                    var $banner = SOEX.Banner.$this;
                    padding = parseInt(this.$this.css('padding-bottom')) + $banner.outerHeight() + parseInt($banner.css('bottom')) + 20;
                } else {
                    padding = parseInt(this.$this.css('padding-bottom')) + SOEX.Footer.$this.outerHeight() + 25;
                }
                this.$this.css({paddingBottom: padding + 'px'});
            }
        },

        /* Banner *************************************************************/
        Banner: {
            $this: null,

            initialize: function() {
                if (!$('#banner').length) {
                    this.$this = $([]);
                    return;
                }

                this.$this = $('#banner');
                this.$this.css({
                    bottom: (parseInt(this.$this.css('bottom')) + SOEX.Footer.$this.outerHeight()) + 'px'
                });
            }
        },

        /* Footer *************************************************************/
        Footer: {
            $this: null,
            siteMapHeight: null,
            SWITCH_DURATION: 500,
            isAnimated: false,

            initialize: function() {
                this.$this = $('#footer').animate();

                this.$this.find('.switch .hide a').click($.proxy(function() {
                    this.hideSiteMap();
                }, this));
                this.$this.find('.switch .show a').click($.proxy(function() {
                    this.showSiteMap();
                }, this));
            },

            hideSiteMap: function(duration) {
                duration = $.type(duration) === 'number' ? duration : this.SWITCH_DURATION;
                var EASING = 'swing';
                var $siteMap = this.$this.find('.site-map');

                if (this.isAnimated) {
                    return;
                } else {
                    this.isAnimated = true;
                }

                this.siteMapHeight = $siteMap.height();
                $siteMap.css({height: this.siteMapHeight + 'px'});
                $siteMap.find('> table').css({position: 'absolute'});

                $siteMap.animate({
                    height: 0,
                    opacity: 0
                }, {
                    duration: duration,
                    easing: EASING,
                    complete: $.proxy(function() {
                        this.isAnimated = false;
                    }, this)
                });

                SOEX.Banner.$this.animate({bottom: '-=' + this.siteMapHeight}, duration, EASING);
                SOEX.Main.$this.animate({paddingBottom: '-=' + this.siteMapHeight}, duration, EASING);
                this.$this.find('.switch .hide').fadeOut(duration / 2, $.proxy(function() {
                    this.$this.find('.switch .show').fadeIn(duration / 2);
                }, this));

                $.cookie('footer-state', 'hide', {expires: 365});
            },

            showSiteMap: function(duration) {
                duration = $.type(duration) === 'number' ? duration : this.SWITCH_DURATION;
                var EASING = 'swing';
                var $siteMap = this.$this.find('.site-map');

                if (this.isAnimated) {
                    return;
                } else {
                    this.isAnimated = true;
                }

                $siteMap.animate({
                    height: this.siteMapHeight + 'px',
                    opacity: 1
                }, {
                    duration: duration,
                    easing: EASING,
                    complete: $.proxy(function() {
                        $siteMap.find('> table').css({position: 'static'});
                        $siteMap.css({height: 'auto'});
                        this.isAnimated = false;
                    }, this)
                });

                SOEX.Banner.$this.animate({bottom: '+=' + this.siteMapHeight}, duration, EASING);
                SOEX.Main.$this.animate({paddingBottom: '+=' + this.siteMapHeight}, duration, EASING);
                this.$this.find('.switch .show').fadeOut(duration / 2, $.proxy(function() {
                    this.$this.find('.switch .hide').fadeIn(duration / 2);
                }, this));

                $.cookie('footer-state', 'show', {expires: 365});
            }
        },

        /* Search Results *****************************************************/
        SearchResults: {
            initialize: function() {
                var $bc = $('#content.search-results .result ul.breadcrumbs');
                $bc.find('li:last').addClass('last-of-type');
                $bc.find('li:not(:last)').after('<s>/</s>');
            }
        },

        /* Content ************************************************************/
        Content: {
            isIndex: false,

            initialize: function() {
                $('#content span.date').after('<s>|</s>');
                $('#content ul.pagination li.disabled a').attr('href', 'javascript: void(0)');
                $('#content-menu');

                if ($('body#index').length) {
                    this.isIndex = true;
                    this.initIndexContent();
                }
            },

            initIndexContent: function() {
                Cufon.replace('#main h2');

                $('#sidebar div.tabs .tabs-panel').slider({
                    btnPrev:         true,
                    btnNext:         true,
                    btnPrevText:     'Назад',
                    btnNextText:     'Далее',
                    pagination:      false,
                    autoSlide:       false,
                    sequentialSlide: true,
                    circular:        false
                });
            }
        },

        /* Forms **************************************************************/
        Forms: {
            initialize: function() {
                var $form = $('form');
                this.initRequiredLabels($form);
                this.initValidateHook($form);
                this.styleButton($form.find('button'));
                this.styleInput($('form.search input[type="text"]'));
            },

            initRequiredLabels: function($form) {
                $form.find('.required').each(function() {
                    var $el = $(this);
                    $('label[for="' + $el.attr('id') + '"]', $el.closest('form')).addClass('required');
                });
            },

            styleInput: function($input) {
                $input.wrap('<div class="input-type-text"></div>');
            },

            styleButton: function($button) {
                $button.filter('form table button').textShadow('#384f49', 0, -1);
            },

            initValidateHook: function($form) {
                $form.submit($.proxy(function(event) {
                    var $form = $(event.currentTarget);
                    $form.find('div.error-message').css({display: 'none'});
                    if (!this.validateForm($form)) {
                        $form.find('div.error-message').css({display: 'block'});
                        event.preventDefault();
                    }
                }, this));
            },

            validateForm: function($form) {
                var $rInputList = $form.find('textarea.required, input');
                $rInputList.removeClass('error');

                var $errorList = $([]);

                $rInputList.each(function() {
                    var $this = $(this);
                    var error = false;
                    var re = null;
                    if ($this.hasClass('required') && this.value == '') {
                        $errorList = $errorList.add(this);
                        return;
                    } else if ($this.filter('[id|="email"]').length) {
                        re = new RegExp(/^([a-zA-Z0-9]([a-zA-Z0-9]|[-_\.][a-zA-Z0-9])*@[a-zA-Z0-9]([a-zA-Z0-9]|-[a-zA-Z0-9])*\.[a-zA-Z0-9]([a-zA-Z0-9]|-[a-zA-Z0-9])*|\s*)$/);
                    } else if ($this.filter('[id|="password"]').length) {
                        re = new RegExp(/^([a-zA-Z0-9]{6,}|\s*)$/);
                    } else if ($this.filter('[id|="name"]').length) {
                        re = new RegExp(/^([a-zA-Zа-яА-Я]([a-zA-Zа-яА-Я]|[- ][a-zA-Zа-яА-Я])*|\s*)$/);
                    } else if ($this.filter('[id|="tel-prefix"]').length) {
                        re = new RegExp(/^([0-9]{0,5}|\s*)$/);
                    } else if ($this.filter('[id|="tel"], [id|="tel-international"]').length) {
                        var re = $this.filter('[id|="tel-international"]').length ? new RegExp(/^((\+?[0-9]{1,3}(\s*|-))?(\([0-9]{1,5}\)(\s*|-))?[0-9]([0-9]|(\s+|-)[0-9])*|\s*)$/) : new RegExp(/^([0-9]([0-9]|-[0-9])*|\s*)$/);
                        if (re.test(this.value)) {
                            var str = this.value.replace(/[-\(\)\s\+]/g, '');
                            if (this.value != '' && (str.length < 5 || str.length > 15)) {
                                error = true;
                            }
                        } else {
                            error = true;
                        }
                    }

                    if (re != null && !re.test(this.value)) {
                        error = true;
                    }

                    if (error) {
                        $errorList = $errorList.add(this);
                    }
                });

                $errorList.one('focus', function() {
                    $(this).removeClass('error');
                });

                if ($errorList.addClass('error').length) {
                    return false;
                } else {
                    return true;
                }
            }
        },

        /* Marked Map *********************************************************/
        Map: {
            $this: null,

            initialize: function() {
                if (!$('#map').length) {
                    this.$this = $([]);
                    return;
                }

                $('#map').markedMap({
                    leftMiddleImg: 'img/map/tooltip-left-middle.png',
                    rightMiddleImg: 'img/map/tooltip-right-middle.png',
                    fadeDuration: ($.browser.msie && $.browser.version < 9) ? 0 : 300
                });
            }
        },

        /* Tabs ***************************************************************/
        Tabs: {
            initialize: function() {
                var $tabs = $('div.tabs');

                $tabs.each(function(index) {
                    var $div = $(this);
                    var $aList = $div.find('> ul.tabs-navigation li a');
                    var $tabList = $div.find('> div.tabs-panel');
                    for (var i = 0; i < $aList.length; i++) {
                        var tabId = 'tab-' + index + '-' + i;
                        $($aList[i]).attr('href', '#' + tabId);
                        $($tabList[i]).attr('id', tabId);
                    }
                });

                $tabs.filter('.business-type').find('.tabs-panel').addClass('shadow-block').append('<div class="bg"><span class="top-left"></span><span class="top-right"></span><span class="bottom-left"></span><span class="bottom-right"></span></div>');
                $tabs.tabs({
                    fx: {opacity: 'toggle'},
                    show: function(event, ui) {
                        Cufon.replace($tabs.find('> ul.ui-tabs-nav > li > a'), {hover: true});
                        Cufon.replace($tabs.find('> ul.ui-tabs-nav > li > span'));
                    }
                });
                $("#expert").find("div.bg").empty();
            }
        },

        /* Utils **************************************************************/
        Utils: {
            inputPlaceHolder: function(selector) {
                $(selector).each(function() {
                    var $input = $(this);
                    var text = $input.attr('value');

                    $input.focusin(function() {
                        if ($input.attr('value') == text) {
                            $input.attr('value', '').removeClass('ph-active');
                        }
                    }).focusout(function() {
                        if ($input.attr('value') == '') {
                            $input.attr('value', text).addClass('ph-active');
                        }
                    }).addClass('ph-active');
                }).closest('form').submit(function(event) {
                    if ($(this).find('input.place-holder').hasClass('ph-active')) {
                        event.preventDefault();
                    }
                });
                return this;
            }
        },

        /* IE7 ****************************************************************/
        IE7: {
            initialize: function() {
                if (!($.browser.msie && $.browser.version == 7)) {
                    return;
                }

                $('#content-menu + #content').css({marginTop: 0});
            }
        }
    };

    SOEX.initialize();
});
