var ids = {
    gallery  : 'studio'
    ,
    studio : 'gallery'
}
$(document).ready( function() {
    Menu.lM = $('.line-menu');
    Menu.lB = $('.line-bottom');
})
var Menu = {
    ready : false
    ,
    menuId : 0
    ,
    menuItem : ''
    ,
    showLocalMenu : false
    ,
    lang : AjE.lang
    ,
    horisontalScrollId : null
    ,
    insertShowMenuButton : function(where){
        if($('.openmenu').length <= 0){
            var html = String.format(SectionHtml.openmenu, AjE.lang);
            where.prepend(html);
        }
    }
    ,
    stopAnimation: false
    ,
    intervalIds : {}
    ,
    loadIds : {}
    ,
    selectedMenuItemId : ''
    //	Bind mouse over/out for .line-menu and click for .line-bottom
    ,
    lM: null
    ,
    lB: null
    ,
    currentSection : ''
    ,
    linesBind : function(){
        var lineMenu = $('.line-menu');
        var lineBottom = $('.line-bottom');
        Menu.lM = lineMenu;
        Menu.lB = lineBottom;
        Menu.insertShowMenuButton(lineMenu);
        $('.openmenu').show();//css('display', 'block');
        clearInterval(Menu.menuId);
        Menu.menuId = setInterval(function(){
            if($('.line-menu').height() >= 60){
                $('.line-menu .openmenu').remove();
            } else {
                Menu.insertShowMenuButton(lineMenu);
            }
        }, 3);
        lineMenu.unbind().hover(
            //				On mouse over
            function() {
                Menu.insertMenuSections($(this));
                $('.openmenu').hide();//css('display', 'none');
                $(this).animate({
                    height: Menu.lineMenu.maxHeight
                }, Menu.lineMenu.speedOnOver, function(){
                    $(this).find('#menu-items').fadeIn('fast');
                });
            },
            //				On mouse out
            function() {
                //					Hide menu items, then minimize menu
                if($(this).children().length > 0) {
                    $(this).stop('true', 'true').children().hide().parent().animate({
                        height: Menu.lineMenu.minHeight
                    }, Menu.lineMenu.speedOnOut, function(){
                        Menu.insertShowMenuButton($(this));
                        $('.openmenu').show();//css('display', 'block');
                    });
                } else {
                    $(this).animate({
                        height: Menu.lineMenu.minHeight
                    }, Menu.lineMenu.speedOnOut, function(){
                        Menu.insertShowMenuButton($(this));
                        $('.openmenu').show();//css('display', 'block');
                    });
                }
            }
            );//.trigger('mouseover');
        lineBottom.click(function(){
            //            location.href='http://'+document.location.host;
            location.hash = AjE.lang + '-' + lineBottom.attr('id');
            
        //			location.hash="";
        //			Menu.swapLines();
        });
    //		lineBottom.click(Menu.swapLines());
    }
    ,
    switchLines : function(){
    //		var selected	= $('.line-menu');
    //		var unselected	= $('.line-bottom');
    //		$('.content').fadeOut('slow', function(){
    //			$(this).css('background', 'none');
    //
    //		});
    }
    ,
    lineMenu : {
        topPosition			: -64
        ,
        maxHeight			: 64
        ,
        minHeight			: 25
        ,
        style				: 'line-menu'
        ,
        speedOnOver		: 500
        ,
        speedOnOut		: 400
        ,
        speedTopAndHide	: 1500
        ,
        backPosition		: '4,7% 0'
    }
    ,
    linesHidden : true
    ,
    lineBottom : {
        style				 : 'line-bottom'
        ,
        speedBottomAndHide : 1500
    }
    ,
    insertMenuSections : function( selected ) {
        //		if(selected.attr('id') == 'gallery') {
        AjE.checkLang();
        var ru = '';
        var en = '';
        function changeLanguage( changeTo ) {
            var hash = document.location.hash;
            document.location.hash = hash.replace( /(ru|en)-/g,changeTo+'-');
//            console.log( hash );
        }
        function changeLanguageToEn(){
            changeLanguage( 'en' );
        }
        function changeLanguageToRu(){
            changeLanguage( 'ru' );
        }
        if ( AjE.lang == 'ru' ) {
            en = 'activeLink';
            ru = 'inactiveLink';
            $('#ruLang').die();
            $('#enLang').die().live( 'click', changeLanguageToEn);
        } else {
            $('#enLang').die();
            $('#ruLang').die().live( 'click', changeLanguageToRu);
            ru = 'activeLink';
            en = 'inactiveLink';
        }

        var html = String.format( SectionHtml.menuItems[selected.attr('id')], AjE.lang, ru, en );

        if(selected.html() != html) {
            selected.html(html);
        //			if(Menu.selectedMenuItemId.length > 0){
        //				$('#'+Menu.selectedMenuItemId+' a').css('opacity', 0.5);
        //			}
        }
        $('#careers').hover(function(e){
            //			if($(this).find('#internship').css('display') != 'block'){
            //				$(this).fadeOut('fast', function(){
            //					$(this).find('#internship').css('display', 'block');
            //					$(this).fadeIn('fast');
            //				});
            //			}
            $(this).find('#internship').fadeIn('fast');
        },
        function(e){
            //			if($(this).find('#internship').css('display') == 'block'){
            //				$(this).fadeOut('fast', function(){
            //					$(this).find('#internship').css('display', 'none');
            //					$(this).fadeIn('fast');
            //				});
            //			}
            $(this).find('#internship').fadeOut('fast');
        });
        var opened = false;
        $('#gall').hover(function(e){
            if(!opened){
                $(this).fadeOut('fast', function(){
                    $(this).find('#gallhref').hide();//css('display', 'none');
                    $(this).css({
                        'height': '30px'
                    }).find('#gallnews').show();//css('display', 'block');
                    $(this).find('#history').css({
                        'display' : 'block'
                    });
                    $(this).fadeIn('fast');
                    opened = true;
                });
            }
        },
        function(e){
            if(opened){
                $(this).fadeOut('fast', function(){
                    $(this).find('#gallhref').show();//css('display', 'block');
                    $(this).find('#gallnews').hide();//css('display', 'none');
                    $(this).find('#history').hide();//css('display', 'none');
                    $(this).fadeIn('fast');
                    opened = false;
                });
            }
        });
        //		selected.find('a').hover(function(){
        //			$(this).animate({
        //				'opacity' : 0.5
        //			}, 'fast');
        //		}, function(){
        //			$(this).animate({
        //				'opacity' : 1
        //			}, 'fast');
        //		});
        var tempOpacity = 1;
        selected.find('a').hover(function(){
            tempOpacity = $(this).css('opacity');
            $(this).css('opacity', 0.5);
        }, function(){
            $(this).css('opacity', tempOpacity);
        });
    //		$('#gallerycareers').mouseout(function(e){
    //			if($(this).find('#galleryinternship').css('display') == 'block'){
    //				$(this).fadeOut('fast', function(){
    //					$(this).css('top', '0px').find('#galleryinternship').css('display', 'none');
    //					$(this).fadeIn('fast');
    //				});
    //			}
    //		});
    //		}
    }
    ,
    mainSelect : function( selected, unselected, language ) {
        var id = selected.attr('id');
        //		Unbind all handlers
        selected.unbind().html('');
        unselected.unbind().html('');
        //		Menu.gotoPage('#'+AjE.redirect[selected.attr('id')]);
        //		Move selected behind the top and change style
        selected.animate({
            top: this.lineMenu.topPosition
        }, this.lineMenu.speedTopAndHide, null, function(){
            selected.addClass(Menu.lineMenu.style).css({
                'background-image':'url(shared/images/'+id+'-big.png)'
            });
			
            Menu.insertMenuSections(selected);
            Menu.insertShowMenuButton(selected);
			
            //			Show selected
            selected.animate({
                top: '0'
            }, 'slow', null, function(){
                document.location.hash = language+'-'+AjE.redirect[id];
                Menu.ready = true;
                //				Bind hover handler
                selected.hover(
                    //						On mouse over
                    function() {
                        Menu.insertMenuSections($(this));
                        $('.openmenu').hide();
                        selected.animate({
                            height: Menu.lineMenu.maxHeight
                        }, Menu.lineMenu.speedOnOver, null, function(){
                            $('#menu-items').fadeIn('fast');
                        });
                    },
                    //						On mouse out
                    function() {
                        //							Hide menu items, then minimize menu
                        selected.stop('true', 'true').children().hide().parent().animate({
                            height: Menu.lineMenu.minHeight
                        }, Menu.lineMenu.speedOnOut);
                        Menu.insertMenuSections($(this));
                        $('.openmenu').show();
                    //							$('#menu-items').css('display', 'none').parent().stop( true, true ).css('background-position', Menu.lineMenu.backPosition).animate({
                    //								height: Menu.lineMenu.minHeight
                    //							}, Menu.lineMenu.speedOnOut);
                    }
                    );
            });
        });
		
        var bottomPosition = $(window).height() + this.lineMenu.maxHeight - unselected.height();
        //		Move unselected to bottom and hide
        unselected.animate({
            top:bottomPosition
        }, Menu.lineBottom.speedBottomAndHide, null, function(){
			
            //			Change class and show
            unselected.addClass(Menu.lineBottom.style).removeAttr('style').show().css({
                //                'display':'block'
                //                ,
                'background-image':'url(shared/images/'+unselected.attr('id')+'-small.png)'
            }).animate({
                bottom: 0
            });
        });
    }
	
    //	Swap line-menu and line-bottom
    ,
    swapLines : function(hash) {
        $('.content').fadeOut('slow', function(){
            $('.line-menu').css('top', 0).animate({
                top : '-25px'
            }, 'slow', function(){
                $(this).html('').addClass('invisible').addClass('line-bottom').removeClass('line-menu').removeAttr('style').css({
                    bottom : -$(this).height()
                    ,
                    'background-image' : 'url(shared/images/'+$(this).attr('id')+'-small.png)'
                    ,
                    display : 'block'
                }).removeClass('invisible').unbind();
            });
            var windowHeight = $(window).height() - $('.line-bottom').height();
            $('.line-bottom').css('top', windowHeight).animate({
                top: $(window).height()
            }, 'slow', function(){
                $(this).addClass('invisible').addClass('line-menu').removeClass('line-bottom').removeAttr('style').css({
                    top : '-25px'
                    ,
                    'background-image' : 'url(shared/images/'+$(this).attr('id')+'-big.png)'
                    ,
                    display : 'block'
                }).removeClass('invisible').unbind();
                //				Menu.linesBind();
                var windowHeight = $(window).height();
                //				var id = setInterval(function(){
                //					if(parseInt($('.line-menu').css('top')) < -20 && parseInt($('.line-bottom').css('top')) >= windowHeight){
                //						clearInterval(id);
                //						redirect();
                //					}
                //				},1);
                setTimeout(redirect, 300);
                //				$('.line-bottom').addClass('invisible').removeAttr('style').css('bottom', '-21px').css('display','block').removeClass('invisible');
                //				$('.line-menu').css('top', '-25px');
                function redirect(){
                    if( typeof hash == 'string') {
                        document.location.hash = hash;
                    } else {
                        document.location.hash = AjE.lang+'-'+AjE.redirect[$('.line-menu').attr('id')];
                    }
                }
            });
        });
    }
	
    //	Hiding line-menu and line-bottom
    ,
    hideLines : function(func) {
        Menu.ready = false;
        var lineMenu = $('div.line-menu');
        var lineBottom = $('div.line-bottom');
        var bottomPosition = $(window).height() + Menu.lineMenu.maxHeight - lineBottom.height();
        lineMenu.animate({
            top : Menu.lineMenu.topPosition
        }, Menu.lineMenu.speedOnOut);
        lineBottom.animate({
            top : bottomPosition
        }, Menu.lineMenu.speedOnOut, null, function(){
            lineMenu.removeClass('line-menu').addClass('line-bottom');
            lineBottom.removeClass('line-bottom').removeClass('line-menu');
            Menu.ready = true;
            Menu.linesHidden = true;
            try {
                func();
            } catch (e) {
            // TODO: handle exception
            }
        });
    }
    ,
    checkSection : function(hash){
        var result = false;
        var which = 2;
        if($.browser.msie){
            which = 1;
        }
        var newSection = hash.split(/(-|\/)/)[which];
        //        var newSection = hash.split(/^#*[a-z]{2}-(\w*)\//)[0].split('-')[1];
        if(Menu.currentSection){
            if(Menu.currentSection != newSection ){
                result = true;
                Menu.currentSection = newSection;
            }
        } else {
            Menu.currentSection = newSection;
        }
        //        alert(newSection);
        return result;
    }
    ,
    showLines : function(func) {
        //        alert(1);
        var lineMenu = $('.line-menu');
        var lineBottom = $('.line-bottom');
        Menu.lM = lineMenu;
        Menu.lB = lineBottom;
        function changeMenu() {
            var html = String.format(SectionHtml.menuItems[lineMenu.attr('id')], AjE.lang);
            lineMenu.html(html);
            Menu.lang = AjE.lang;
            Menu.insertShowMenuButton(lineMenu);
            if(lineMenu.height() > 50){
                $('#menu-items').fadeIn('slow');
            }
        }
        if( Menu.lang != AjE.lang ) {
            var menuItems = lineMenu.find('#menu-items');
            if (menuItems.css('display') != 'none') {
                menuItems.fadeOut('fast', function(){
                    changeMenu();
                });
            } else {
                changeMenu();
            }
        }
        if( Menu.stopAnimation ) {
            try {
                func();
            } catch (e) {
            // TODO: handle exception
            }
            //					Bind hover handler
            lineMenu.unbind('click');
            Menu.linesBind();
            Menu.stopAnimation = false;
        } else {
            $('.line-menu').animate({
                top: '0'
            }, 'slow', null, function(){
                try {
                    func();
                } catch (e) {
                // TODO: handle exception
                }
                //					Bind hover handler
                lineMenu.unbind('click');
                Menu.linesBind();
            });
        }
        lineBottom.animate({
            bottom: 0
        }, 'slow').click(function(){
            //			Menu.swapLines();
            //            location.href='http://'+document.location.host;
            });
    }
	
    //	Loads not main page.
    ,
    showMenuWithContent : function() {
        Menu.ready = true;
        var hash = document.location.hash;
        var id 	 = 'gallery';
        var unid = 'studio';
        if (hash.indexOf('studio') >= 0) {
            id	 = 'studio';
            unid = 'gallery';
        }
        var selected = $('#'+id);
        var unselected	= $('#'+unid);
        var bottomPosition = $(window).height() + this.lineMenu.maxHeight - unselected.height();
        selected.addClass(Menu.lineMenu.style).css({
            'background-image':'url(shared/images/'+id+'-big.png)'
        });
        selected.css({
            top: -25
            ,
            height:Menu.lineMenu.minHeight
            ,
            'display':'block'
        }).removeClass('lines').addClass(Menu.lineMenu.style);
        Menu.insertMenuSections(selected);
        $('#menu-items a').css('opacity', 1);
        //		$('#menu-items #'+Menu.selectedMenuItemId+' a').css('opacity', 0.5);
        Menu.insertShowMenuButton(selected);
        unselected.removeAttr('style').css({
            'display':'block'
            ,
            'background-image':'url(shared/images/'+unid+'-small.png)'
        }).removeClass('lines').addClass('line-bottom');
        Menu.gotoPage(hash);
    }
    ,
    gotoPage:function(hash){
        $(document).unbind('mousemove').unbind('mousewheel').mousewheel(function(event){
            event.preventDefault();
        }); //unbinding mousemove and mousewheel
        $(window).unbind('mousewheel');
        var part = hash.split(/^#*[a-z]{2}-(\w*)\//);
        part = part[1];
        var title = '';
        if(part == 'gallery'){
            if(AjE.lang == 'ru'){
                str = 'Галерея Марины Гисич';
            } else {
                str = 'Marina Gisich Gallery';
            }
        } else {
            if(AjE.lang == 'ru'){
                str = 'Дизайн-студия Марины Гисич';
            } else {
                str = 'Marina Gisich Design Studio';
            }
        }
        if(hash.length > 0) {
            AjE.checkLang();
            var action = AjE.urlToAction(hash);
            if ( $('.content').css('display')!='none' ) {

                $('.content').fadeOut('slow', function(){
                    
                    if($(this).css('background-image') != 'none') {
                        $(this).addClass('invisible').removeAttr('style').removeClass('invisible');
                    }
                });
            }
            //            $('.content').fadeOut( 300, function() {
            //            alert( hash );
            //            })
            if( Menu.checkSection(hash) ) {
                //                alert(1);
                //            }
                Menu.stopAnimation = true;
                var menuId = Menu.lM.attr('id');
                var bottomId = Menu.lB.attr('id');
                Menu.lM.animate({
                    top: -25
                }, 300);
                Menu.lB.animate({
                    bottom: -21
                }, 300, function() {
                    //                    try {
                    //                        alert(1)
                    if( $.browser.msie ) {
                        Menu.lM[0].style.removeAttribute('top');
                    } else {
                        Menu.lM[0].style.removeProperty('top');
                    }
                    //                    } catch (e) {}
                    //                    console.log( Menu.lM, Menu.lB );
                    //                    setTimeout( function() {
                    Menu.lM.css({
                        bottom: -21
                        ,
                        'background-image':'url(shared/images/'+menuId+'-small.png)'
                        ,
                        height : 21
                        ,
                        cursor : 'pointer'
                    }).html('').animate({
                        bottom: 0
                    }, 1000);
                    Menu.lB.css({
                        top: -25
                        ,
                        'background-image':'url(shared/images/'+bottomId+'-big.png)'
                        ,
                        height : 25
                        ,
                        cursor : 'default'
                    }).animate({
                        top: 0
                    }, 1000);
                    Menu.lB.removeClass('line-bottom').addClass('line-menu');
                    Menu.lM.removeClass('line-menu').addClass('line-bottom').unbind();
                    Menu.linesBind();
                //                    }, 300);
                    
                });
            }
            function showContent( data ){
                function continueLoading() {
                    var id = hash.split('/');
                    id = id[1];
                    //					$('#menu-items #'+id).css('opacity', 0.5);
                    Menu.selectedMenuItemId = id;
                    //					$('#menu-items a').css('opacity', 1);
                    //					$('#'+id+' a').css('opacity', 0.5);
                    Menu.showLines(function(){
                        $(window).unbind();
                        $('#slider').slider('destroy');
                        $().unbind('mousemove');
                        for(i in Menu.intervalIds){
                            clearInterval(Menu.intervalIds[i]);
                        }
                        for(i in Menu.loadIds){
                            clearInterval(Menu.loadIds[i]);
                        }
                        clearInterval(Menu.horisontalScrollId);
                        $('.content').addClass('invisible').removeAttr('style').hide().removeClass('invisible').html(data).fadeIn('slow', function(){
                            if($.browser.msie){
                                var cssText = $('.content')[0].style.cssText.replace(/FILTER:.; */ig,"");
                                $('.content')[0].style.setAttribute('cssText', cssText);
                            //                                $('.content *').each(function(index){
                            //                                    var cssText = this.style.cssText.replace(/FILTER:.; */ig,"");
                            ////                                    alert(this.style.cssText);
                            ////                                    this.style.setAttribute('cssText',cssText);
                            ////                                    if(console){
                            ////                                        console.log($(this).context);
                            ////                                    }
                            //    //                                alert($(element)[0].style.zIndex);
                            //                                }).click(function(){
                            //                                    var prop = this.style;
                            //                                    var str = '';
                            //                                    for(i in prop){
                            //                                        if(prop[i] != ' '){
                            //                                        str += i+':'+prop[i]+';\n\
                            //    ';
                            //                                        }
                            //                                    }
                            //                                    $(this).text(str);
                            ////                                    alert(str);
                            //                                });
                            }
                        });
                        if($('.content').html() == ''){
                            Menu.loadId = setInterval(function(){
                                if($('.content').html() == ''){
                                    $.get(action, {}, showContent, 'html');
                                } else {
                                    clearInterval(Menu.loadId);
                                }
                            }, 500);
                        }
                    });
                }
                if( data ) {
                    var menu = 'menuImages';
                    for(i in Images[menu]) {
                        Images[menu][i] = String.format(Images[menu][i], AjE.lang);
                    }
                    if(!Images.loaded[menu][AjE.lang]) {
                        AjE.checkImagesLoad(Images.menuImages, continueLoading, true);
                        Images.loaded[menu][AjE.lang] = true;
                    } else {
                        continueLoading();
                    }
                }
            }
            $.get(action, {}, showContent, 'html');
        }
    }
    ,
    initLocalMenu : function(classes){
        if($.browser.webkit){
            //            $(classes.menu).css('position', 'relative');
            $(classes.openbutton).css({
                'position':'static'
            });//.addClass('workingClone');
            //            $(classes.openbutton).clone().addClass('webkitDummy').css('position','static').appendTo(classes.container);
            setTimeout(function(){
                var button = $(classes.container).offset();
                //                $(classes.container).css('border', '1px solid #66a000');
                //                $(classes.menu+' ').css('background', '#fd002f');
                $(classes.openbutton).css({
                    'position':'fixed'
                    ,
                    'top':button.top
                    ,
                    'left':button.left
                });
                $(window).resize(function(){
                    var container = $(classes.container).offset();
                    $(classes.menu+' a').css({
                        'left':container.left
                    });
                    $(classes.openbutton).css({
                        'left':container.left
                    });
                });
            },300);
        }
        for( i in Menu.loadIds){
            clearInterval(Menu.loadIds[i]);
        }
        var clickOnMenu = false;
        $(classes.container).append('<a href="#" id="focusChecker"></a>');
        $('#focusChecker').blur(function(){
            if(Menu.showLocalMenu && !clickOnMenu){
                closeMenu();
            }
            clickOnMenu = false;
        });
        var id = 0;
        var speed = 0;
        Menu.showLocalMenu = false;
        var countLinesFromTop = 1;
        var centerLine = 3;
        var checked = $(classes.menu+' a[rel=checked]');
        var singleHeight = parseInt(checked.css('height'));
        //        classes.dynamicTitle = '.'+classes.dynamicTitle;
        //        var checkedStyle = $('a[rel=checked]').attr('style');
        var maxFontSize = parseInt(checked.css('font-size'));
        checked.addClass('checkeditem').css('display', 'inline');
        var checkedWidth = 500;
        var loadId = setInterval(function(){
            var tempWidth = checked.width();
            if(tempWidth > 0){
                checkedWidth = tempWidth+20;
                $(classes.dynamicTitle).css('margin-left', checkedWidth+'px');
                $(classes.container).css('width', checkedWidth+'px');
                clearInterval(loadId);
                clearInterval(Menu.loadIds[loadId]);
            }
            if($.browser.webkit){
                $(elements).css('display', 'none');
                var offset = $(classes.container).offset();
                checked.css({
                    'display':'inline'
                    ,
                    'position':'fixed'
                    ,
                    'top':offset.top
                    ,
                    'left': offset.left
                });
            }
        }, 10);
        Menu.loadIds[loadId] = loadId;
        var menuWidth = $(classes.container).css('width');
        $(classes.container).css({
            'width': checkedWidth+'px'
            ,
            'height':'40px'
        });
        $(classes.menu).css('width', menuWidth);
        if(classes.dynamicTitle){
            $(classes.dynamicTitle).css('margin-left', checkedWidth+'px');
        }
        var fontStep = 4;
        var maxheight = 8 * singleHeight;
        var elements = $(classes.menu).children();
        var checkedIndex = elements.index($(classes.menu+' a[rel=checked]')[0]);
        var checkedTop   = (checkedIndex > 0) ? checkedIndex * singleHeight: 0;
        var maxTop = (elements.length - countLinesFromTop - 6) * singleHeight;
        var current = checkedIndex + centerLine;
        var maxlength = 0;
        var length = 0;
        var noAnimation = false;
        if(elements.length <= 6 ){
            noAnimation = true;
        }
        elements.map(function(){
            if($(this).html().length > maxlength){
                maxlength = $(this).html().length;
            }
            length++;
        });
        //        var maxwidth = maxlength * 18;
        $(elements).css('font-size', maxFontSize);
        //        for(i=current; i>=0; i--){
        //            $(elements[i]).css('font-size', (maxFontSize - (current - i)*fontStep)+'px');
        //        }
        //        for(i=current; i<elements.length; i++){
        //            $(elements[i]).css('font-size', (maxFontSize + (current - i)*fontStep)+'px');
        //        }
        if(!$.browser.msie){
            checked.css('overflow','hidden');
        }
        if($.browser.opera){
            var containerWidth = $(classes.container).width() - 20;
        //            $(classes.container).css('background-color', '#005d00');
        }
        $(classes.menu).css({
            'top':'-'+checkedTop+'px'
            ,
            'height':maxheight+'px'
        //            ,
        //            'width':menuWidth+'px'
        });
        var pressed = null;
        function closeMenu(){
            $('.topmenushade, .bottommenushade').removeAttr('style');
            clearInterval(id);
            id = 0;
            $(classes.menu).css({
                'top': '-'+checkedTop+'px'
            //                    ,
            //                    'width':menuWidth
            });
            $(classes.container).css({
                'height':(singleHeight-2)+'px'
                ,
                'background':'none'
                ,
                'margin-top':'0px'
                ,
                'width':checkedWidth
            }).unbind('mouseover').unbind('mousemove');
            //            $(classes.container).removeClass('uparrow').addClass('downarrow').css('background-position', 'left center');
            if($.browser.opera){
                var containerWidth = $(classes.container).width() + 10;
                $(classes.container).width(containerWidth);
            }
            if(!$.browser.webkit){
                $(classes.openbutton).css('top','0px');
            }
            $(classes.openbutton).addClass('downarrow').removeClass('uparrow');
            Menu.showLocalMenu = false;
            //                var current = checkedIndex+3;
            $(elements).css({
                'font-size': maxFontSize
                ,
                'height' : singleHeight
            });
            checked.addClass('checkeditem').css('display','inline');
            if(!$.browser.msie){
                checked.css({
                    'overflow':'hidden'
                });
            }
            var closedMenuWidth = checked.width()+25;
            $(classes.dynamicTitle).css('margin-left', checkedWidth+'px');
            if($.browser.webkit){
                $(elements).css('display', 'none');
                var offset = $(classes.container).offset();
                checked.css({
                    'display':'inline'
                    ,
                    'position':'fixed'
                    ,
                    'top':offset.top
                    ,
                    'left':offset.left
                });
            }
        //            pressed.unbind('blur');
        }
        function toggleMenu(pressed){
            if(Menu.showLocalMenu){
                closeMenu();
            } else {
                //                pressed.unbind('blur');
                //                $(classes.container).removeClass('downarrow').addClass('uparrow').css('background-position', 'left 40px');
                $(classes.dynamicTitle).css('margin-left', checkedWidth+'px');
                checked.removeClass('checkeditem').css('display','block');
                if(!$.browser.msie){
                    checked.css('overflow', 'none');
                }
                var current = checkedIndex+centerLine-2;
                var localTop = -(countLinesFromTop*singleHeight-checkedTop);
                var localCur = current+2;
                if(current > length - 3){
                    localTop = maxTop;
                    localCur = length - 3;
                }
                if(noAnimation){
                    localTop = singleHeight;
                }
                //              =========== part from moving ============
                menutop = parseInt($(classes.menu).css('top'));
                //                menutop = $(classes.menu).position().top;
                //                alert(menutop+' '+$(classes.menu).position().top);
                if(menutop >= countLinesFromTop*singleHeight){
                    menutop = countLinesFromTop*singleHeight;
                } else
                if(menutop <= -maxTop){
                    menutop = -maxTop;
                } else {
                    menutop += singleHeight;
                }
                $(classes.menu).css('top', menutop);
                //           =============================================
                localCur = Math.round((-1)*menutop / singleHeight + countLinesFromTop+centerLine);
                var tmpsize = null;
                elements.each(function(i){
                    tmpsize = maxFontSize - Math.abs((localCur - i)*fontStep);
                    if( tmpsize <= 0 ) {
                        tmpsize = 1;
                    }
                    $(elements[i]).css(
                        'font-size', tmpsize
                        //                            ,'height': (tmpsize+7)+'px'
                        );
                    if(noAnimation){
                        $(elements[i]).css('height', (tmpsize+7));
                    }

                });
                $('.topmenushade, .bottommenushade').show();//css('display','block');

                $(classes.menu).css({
                    //                        'top': '-'+(localTop)+'px'
                    //                        ,
                    'width': menuWidth
                });
                if(!$.browser.webkit){
                    $(classes.openbutton).css('top',(countLinesFromTop*singleHeight));
                } else {
                    $(elements).css('display', 'block');
                    var top = $(classes.container).offset().top;
                    checked.css({
                        'display':'block'
                        ,
                        'position':'static'
                        ,
                        'top':'auto'
                        ,
                        'left':'auto'
                    });
                }
                $(classes.openbutton).removeClass('downarrow').addClass('uparrow');
                $(classes.container).css({
                    'height':maxheight+'px'
                    ,
                    'margin-top':-(countLinesFromTop*singleHeight)
                    ,
                    'background-color':'#000'
                    ,
                    'width' : menuWidth
                }).mousemove(function(e){
                    var obj = $(this).offset();
                    obj.height = $(this).height();
                    //                            obj.width = $(this).width();
                    var center = {
                        'y' : (obj.top + obj.height / 2)
                    //                                , 'x' : (obj.left + obj.width / 2)
                    }
                    //                            var mouseX =  e.pageX - center.x;
                    var howfar = e.pageY - center.y;
                    speed = -Math.floor(howfar / 20);
                }).mouseover(function(e){
                    var menutop = 0;
                    //                            var id = 0;
                    var i = 0;
                    //                            clearInterval(id);
                    var tmpsize = null;
                    if(id == 0 && !noAnimation){
                        id = setInterval(function(){
                            menutop = parseInt($(classes.menu).css('top'))+speed;
                            //                            manutop = $(classes.menu).position().top+speed;
                            if(menutop >= countLinesFromTop*singleHeight){
                                menutop = countLinesFromTop*singleHeight;
                            }
                            if(menutop <= -maxTop){
                                menutop = -maxTop;
                            }
                            $(classes.menu).css('top', menutop);
                            //                            alert($(classes.menu).position().top+' '+menutop);
                            var current = Math.round((-1)*menutop / singleHeight + countLinesFromTop+centerLine);
                            //                            $('.debugger').html(menutop+' '+current);
                            tmpsize = null;
                            elements.each(function(i){
                                tmpsize = maxFontSize - Math.abs((current - i)*fontStep);
                                if( tmpsize <= 0 ) {
                                    tmpsize = 1;
                                }
                                $(this).css({
                                    'font-size':tmpsize+'px'
                                //                                        ,'height':(tmpsize+7)+'px'
                                });
                            });
                        //                            for(i=current; i<elements.length; i++){
                        //                                $(elements[i]).css({
                        //                                    'font-size': (maxFontSize - Math.abs((current - i)*fontStep))+'px'
                        //                                });
                        //                            }
                        }, 10);
                        Menu.loadIds[id] = id;
                    }
                }).mouseout(function(e){
                    clearInterval(id);
                    id = 0;
                    for(i in Menu.loadIds){
                        clearInterval(Menu.loadIds[i]);
                    }
                });
                if($.browser.opera){
                    var containerWidth = $(classes.container).width() + 10;
                    $(classes.container).width(containerWidth);
                }
                //               alert($(classes.menu).offset().top);
                //                    pressed.blur(function(){
                //                        closeMenu();
                //                    });
                Menu.showLocalMenu = true;
            //                 alert($('.topmenushade').offset().top);
            }
        }
        if(elements.length > 1){
            $(classes.openbutton).removeAttr('href');
            $(classes.openbutton+', a[rel=checked]').mousedown(function(e){
                if(!Menu.showLocalMenu){
                    $('#focusChecker').focus();
                }
                e.preventDefault();
                pressed = $(this);
                toggleMenu(pressed);
            }).mouseup(function(e){
                e.preventDefault();
            }).click(function(e){
                e.preventDefault();
            });
            $(classes.menu+' a[rel!=checked]').mousedown( function(e) {
                clickOnMenu = true;
                if($(this).attr('rel') == 'checked'){
                    e.preventDefault();
                }
            }).mouseup(function(e){
                if($(this).attr('rel') == 'checked'){
                    e.preventDefault();
                }
            });
        //            $(classes.container).hover(function(){
        //                if(pressed){
        //                    pressed.unbind('blur');
        //                }
        //            }, function(){
        //                if(pressed){
        //                    pressed.blur(function(){
        //                        closeMenu();
        //                    });
        //                }
        //            });
        }
    }
};

$(document).ready(function(){
    //	Kill bad keys
    $(document).keypress(function(event){
        var key = event.keyCode;
        switch(key){
            case 32:
            case 33:
            case 34:
            case 35:
            case 36:
            case 38:
            case 40:
                //                    case 0:
                event.preventDefault();
                break;
        //        		default:alert(key);
        }
    });
});

var SectionHtml = {
    menuItems : {
        gallery : '<ul id="menu-items"><li id="artists"><a class="{0}" style="background-image:url(/shared/images/menu/{0}/artists-active.png" href="#{0}-gallery/artists/img"></a></li><li id=\"exhibitions\"><a class="{0}" style="background-image:url(/shared/images/menu/{0}/exhibitions-active.png" href="#{0}-gallery/exhibitions"></a></li><li id=\"gall\" style="margin-right: 2%"><a class="{0}" id="gallhref" style="background-image:url(/shared/images/menu/{0}/gallery-active.png);" href="#{0}-gallery/history/"></a><a class="{0}" id="history" style="margin-top: -1px; display: none; background-image:url(/shared/images/menu/{0}/history.png);" href="#{0}-gallery/history/"></a><a id="gallnews" class="{0}" style="margin-top: 7px; display: none; background-image:url(/shared/images/menu/{0}/news.png);" href="#{0}-gallery/news/list/"></a></li><li id=\"events\"><a class="{0}" style="background-image:url(/shared/images/menu/{0}/events-active.png" href="#{0}-gallery/events"></a></li><li id=\"press\"><a  class="{0}" style="background-image:url(/shared/images/menu/{0}/press-active.png)" href="#{0}-gallery/publications"></a></li><li id=\"contacts\"><a class="{0}" style="background-image:url(/shared/images/menu/{0}/contacts-active.png" href="#{0}-gallery/contacts"></a></li><li id=\"careers\" style="margin-right: 0; height: 30px;"><a class="{0}" style="background-image:url(/shared/images/menu/{0}/careers-active.png" href="#{0}-gallery/careers"></a><a id="internship" class="{0}" style="margin-top: 7px; display: none; left:-1px; position:absolute; background-image:url(/shared/images/menu/{0}/internship.png);" href="#{0}-gallery/internship"></a></li><li class="languageContainer"><span class="languageLink {1}" id="ruLang">рус</span>&nbsp;/&nbsp;<span id="enLang" class="languageLink {2}">en</span></li></ul>'
        //        gallery : '<ul id="menu-items"><li id="artists"><a class="{0}" style="background-image: url(/shared/images/menu/{0}/gallerymenu.png); background-position: 0 0; width: 80px; opacity: 1;" href="#{0}-gallery/artists/img"></a></li><li id=\"exhibitions\"><a class="{0}" style="background-image: url(/shared/images/menu/{0}/gallerymenu.png); background-position: -80px 0; width: 72px;" href="#{0}-gallery/exhibitions"></a></li><li id=\"gall\" style="margin-right: 2%"><a class="{0}" id="gallhref" style="background-image: url(/shared/images/menu/{0}/gallerymenu.png); background-position: -154px 0; width: 55px; " href="#{0}-gallery/history/"></a><a class="{0}" id="history" style="margin-top: -1px; display: none; background-image: url(/shared/images/menu/{0}/gallerymenu.png); background-position: -210px 0; width: 53px;" href="#{0}-gallery/history/"></a><a id="gallnews" class="{0}" style="margin-top: 7px; display: none; background-image: url(/shared/images/menu/{0}/gallerymenu.png); background-position: -264px 0; width: 54px;" href="#{0}-gallery/news/list/"></a></li><li id=\"events\"><a class="{0}" style="background-image: url(/shared/images/menu/{0}/gallerymenu.png); background-position: -319px 0; width: 60px;" href="#{0}-gallery/events"></a></li><li id=\"press\"><a  class="{0}" style="background-image: url(/shared/images/menu/{0}/gallerymenu.png); background-position: -380px 0; width: 86px;" href="#{0}-gallery/publications"></a></li><li id=\"contacts\"><a class="{0}" style="background-image: url(/shared/images/menu/{0}/gallerymenu.png); background-position: -467px 0; width: 66px;" href="#{0}-gallery/contacts"></a></li><li id=\"careers\" style="margin-right: 0; height: 30px;"><a class="{0}" style="background-image: url(/shared/images/menu/{0}/gallerymenu.png); background-position: -534px 0; width: 67px;" href="#{0}-gallery/careers"></a><a id="internship" class="{0}" style="margin-top: 7px; display: none; left:-1px; position:absolute; background-image: url(/shared/images/menu/{0}/gallerymenu.png); background-position: -602px 0; width: 86px;" href="#{0}-gallery/internship"></a></li></ul>'
        ,
        studio : '<ul id="menu-items" style="left: 39%; width: 61%;"><li id="projects"><a class="{0}" href="#{0}-studio/projects"></a></li><li id="art"><a class="{0}" href="#{0}-studio/art"></a></li><li id="stud"><a class="{0}" href="#{0}-studio/studio"></a></li><li id=\"press\"><a  class="{0}" style="background-image:url(/shared/images/menu/{0}/press-active.png)" href="#{0}-studio/publications/list"></a></li><li id="contacts"><a class="{0}" href="#{0}-studio/contacts" style="margin-right: 0;"></a></li><li id=\"careers\" style="margin-right: 0; height: 30px;"><a class="{0}" style="background-image:url(/shared/images/menu/{0}/careers-active.png" href="#{0}-studio/careers"></a><a id="internship" class="{0}" style="margin-top: 7px; display: none; left:-1px; position:absolute; background-image:url(/shared/images/menu/{0}/internship.png);" href="#{0}-studio/internship"></a></li><li class="languageContainer"><span class="languageLink {1}" id="ruLang">рус</span>&nbsp;/&nbsp;<span id="enLang" class="languageLink {2}">en</span></li></ul>'
    }
    ,
    openmenu : '<div class="openmenu" style="display: none; background:url(/shared/images/menu/{0}/showmenu.png);"></div>'
}
var Images = {
    menuImages : {
        projects	: 'menu/{0}/projects.png'
        ,
        art		: 'menu/{0}/art.png'
        ,
        studio		: 'menu/{0}/studio.png'
        ,
        press		: 'menu/{0}/press.png'
        ,
        contacts	: 'menu/{0}/contacts.png'
        ,
        artists		: 'menu/{0}/artists.png'
        ,
        exhibitions	: 'menu/{0}/exhibitions.png'
        ,
        gallery		: 'menu/{0}/gallery.png'
        ,
        events		: 'menu/{0}/events.png'
        ,
        careers		: 'menu/{0}/careers.png'
        ,
        internship	: 'menu/{0}/internship.png'
        ,
        news		: 'menu/{0}/news.png'
        ,
        history		: 'menu/{0}/history.png'
    }
    ,
    loaded : {
        menuImages : {
            ru : false
            ,
            en : false
        }
    }
}

var Scroll = {
    init : function(func){
        $(window).unbind('scroll');
        //		if(window.removeEventListener('wheel'))
        //			window.removeEventListener('wheel');
        if(window.opera){
            function wheel(event){
                var delta = 0;
                if(!event) event = window.event;
                event.preventDefault();
                if(event.wheelData){
                    delta = -event.wheelDelta/120;
                } else if(event.detail) {
                    delta = -event.detail/3;
                }
                var result = true;
                if(delta){
                    event.preventDefault();
                    try{
                        func(delta);
                    } catch(e){
                    }
                    result = false;
                }
                return result;
            }
            if(window.addEventListener)
                window.addEventListener('DOMMouseScroll', wheel, false);
            window.onmousewheel = document.onmousewheel = wheel;
        } else {
            $(window).mousewheel(function(e, delta){
                e.preventDefault();
                try{
                    func(delta);
                } catch(e){
                }
                return false;
            });
        }
    }
}

