(function($){
    var methods={
    
        init:function(options) {
            var _defaults = {
                    changeSlideTime:6000,
                    fadeOutTime:500,
                    active:true}, 
                
                _config=$.extend(_defaults, options),
                _self=this;
                
            _self.find('.active').siblings('div').hide();
            $(window).bind('load',function() {
                _self.find('.active').siblings('div').hide();
                });
                
            this.data('novemberSlideshow',{_config:_config,animation:false});
            
            if(_config.active)
                this.novemberSlideshow('start');
                
            },
            
        
        start:function() {
            var d=this.data('novemberSlideshow'),
                _this=this;
                
            d._config.active=true;
            
            d.timeout=setTimeout(function(){
                _this.novemberSlideshow('nextSlide');
                },d._config.changeSlideTime);
            
            this.data('novemberSlideshow',d);
            },
            
        
        stop:function() {
            var d=this.data('novemberSlideshow');
            d._config.active=false;
            clearTimeout(d.timeout);
            
            this.data('novemberSlideshow',d);
            },          
            
        
        nextSlide:function() {
            var d=this.data('novemberSlideshow'),
                _this=this,
                $active=this.find('.active'),
                $next;
                
            if($active.next('div').length==0)
                $next=this.find('div:first-child')
            else 
                $next=$active.next('div').eq(0);
                
            this.novemberSlideshow('gotoSlide',$next.index());
            
            if(d._config.active==true) {
                d.timeout=setTimeout(function(){
                    _this.novemberSlideshow('nextSlide');
                    },d._config.changeSlideTime);
                }
            
            },
            
        
        previousSlide:function() {
            var d=this.data('novemberSlideshow'),
                _this=this,
                $active=this.find('.active'),
                $next;
                
            if($active.prev('div').length==0)
                $next=this.find('div:last-child')
            else 
                $next=$active.prev('div').eq(0);
                
            this.novemberSlideshow('gotoSlide',$next.index());
            },
            
        
        gotoSlide:function(number) {
            var d=this.data('novemberSlideshow'),
                _this=this;
            
            if(!d.animation) {
                var $active=this.find('.active'),
                    $next=this.find('div').eq(number);
                    
                $active.siblings('div').hide();
                $active.show();
                $next.show();
                
                d.animation=true;
                $active.addClass('last-active');
                
                $next.css({opacity:0.0})
                    .addClass('active')
                    .animate({opacity:1.0},d._config.fadeOutTime,function() {
                        $active.removeClass('active last-active');
                        
                        d.animation=false;
                        _this.data('novemberSlideshow',d);
                        });
                
                $active.css({opacity:1.0})
                    .animate({opacity:0.0},d._config.fadeOutTime)
                    
                if(typeof(d._config.callback)!=='undefined')
                    d._config.callback(number);
                
                this.data('novemberSlideshow',d);
                return true;
                }
            else
                return false;
            }
        };
        
        
    $.fn.novemberSlideshow = function(method) {
        if (methods[method]) {
            return methods[method].apply(this,Array.prototype.slice.call(arguments,1));
            } else if (typeof method==='object' || !method) {
                return methods.init.apply(this,arguments);
                } else {
                    $.error('Method'+method+' does not exist on jQuery.tooltip');
                    }    
            
        };
        
    })(jQuery);



$(document).ready(function(){
    var options = {
        splitter_cssOver:{'background':'#fff8e9'},
        splitter_cssOut:{'background':"url('/images/top_menu_splitter.jpg') no-repeat"},
        td_classOver:'active',
        min_height:130,
        left_shadow:1,
        right_shadow:16,
        sub_menu_margin: 50
    };
    
    /**
     * Variables
     */     
    var prev_splitter = null;
    var td = null;
    var tdWidth = null;
    var next_splitter = null;
    var combobox = null;
    var comboboxWidth = null; 
    var comboboxHeight = null;
    var addedWidth = null;
    var padding = null;
    var tableHeight = null;
    var tableWidth = null;
    var FisrtLeft = null;
    var offsetLeft = null;
    var sub_menu = null;
    var drop_down_menu = null;
    var width = null;
    active_promo=1;
    promo_times_shown=0;
    promo_timeout=8000;
    do_change_promo=true;
    
    //--------------------------
    
    //Верхнее меню
    $('#top_menu td > a').one('mouseover', onMenuOver);    
    
    function onMenuOver (){
        prev_splitter = $(this).parent().prev();
        prev_splitter.css(options.splitter_cssOver);
        
        td = $(this).parent();
        tdWidth = td.width();
        td.addClass(options.td_classOver);
        
        next_splitter = $(this).parent().next();
        next_splitter.css(options.splitter_cssOver);
        
        combobox = $(this).next();
        comboboxWidth = combobox.width();
        comboboxHeight = combobox.height();
        
        addedWidth = prev_splitter.width() + next_splitter.width();        
        padding = parseInt(combobox.css('padding-left')) + parseInt(combobox.css('padding-right')); 
        
        tableHeight = options.min_height > comboboxHeight ? options.min_height : comboboxHeight;
        tableWidth = comboboxWidth > tdWidth ? comboboxWidth : tdWidth + options.right_shadow + addedWidth;
        
        FisrtLeft = Math.floor( $('#top_menu td:first-child').offset().left );
        offsetLeft = Math.floor( td.offset().left );
       
        /**
         * Фейлфокс расчитывает координаты как дабл,
         * поэтому бывает что координаты например
         * в опере 486 а в мозиле 487,01 изза чего
         * меню смещается на одни пиксел
         */ 
        if($.browser.mozilla) {
            offsetLeft = td.offset().left - 0.2 > Math.floor( td.offset().left )
                            ? Math.floor( td.offset().left )
                            : Math.floor( td.offset().left ) - 1
        }
        
        left = offsetLeft - FisrtLeft;
        
        if( td.is('#top_menu td:last-child')) {
            left -= tableWidth - tdWidth - options.right_shadow - addedWidth;
        }
        
        combobox.children('table').css({
            'height': tableHeight,
            'width': tableWidth
        });
        
        combobox.css({
            'left': left - options.left_shadow,
            'margin-left': prev_splitter.width() * -1,            
            'top': td.height()
        });
        
        combobox.show();        
        
        td.one("mouseleave", function(e){
            prev_splitter.css(options.splitter_cssOut);
            $(this).removeClass(options.td_classOver);
            next_splitter.css(options.splitter_cssOut);
            combobox.hide();
            hideSubMenu();
            $(this).children('a').one('mouseover', onMenuOver);                        
        });
        
        combobox.find('.content ul.open_ul > li:not(".has_sub_menu")').find("a").unbind('mouseover');
        combobox.find('.content ul.open_ul > li:not(".has_sub_menu")').find("a").mouseover(hideSubMenu);

        sub_menu_container = combobox.find('.has_sub_menu');
        sub_menu = sub_menu_container.children('ul.sub_ul');    
        
        sub_menu_container.unbind('mouseover');
        sub_menu_container.find('a.sub_menu').one('mouseover', onSubmenuOver);
        
        drop_down_menu = combobox.children('table');
        width = drop_down_menu.width() + sub_menu.width() + options.sub_menu_margin;
        widthOut = drop_down_menu.width();
                
        sub_menu_container.find('a.sub_menu').mouseleave(function(e){
            $(this).unbind('mouseover');
            $(this).one('mouseover', onSubmenuOver);
        });
        
        sub_menu_container.find('ul.open_ul a').mouseover(function(e){
            hideSubMenu();
        });
        
        //Спрятать под-пункт меню
        function hideSubMenu() {
            sub_menu.css('display', 'none');
            sub_menu_container.children('span').css('display', 'none');
            sub_menu_container.children('a').css('text-decoration', 'underline');
            drop_down_menu.width(widthOut);
        }
        
        //Отобразить под-пункт меню
        function onSubmenuOver(){
            hideSubMenu();
            drop_down_menu.width(width);
            $(this).parent('li.has_sub_menu').children('span').css('display', 'inline');
            $(this).parent('li.has_sub_menu').children('a').css('text-decoration', 'none');            
            $(this).parent('li.has_sub_menu').children('ul.sub_ul').css('display', 'inline');
        }
        
    }
    
    searchInput();
    actionButton(".top_menu_btn");
    imagesSwap();
    checkboxGroup('seminar');
    
    if($('.menu ul.submenu li:last-child').hasClass('active')) {
     $('.menu ul.submenu li.active').parent('ul.submenu').parent('li').next('li').find('.text').css('border','0px');
     }
    
    //setTimeout("changePromo()",promo_timeout);
    var $promoSl=$('.animate-blocks .promo-blocks');
    if($promoSl.length>0)
        $promoSl.novemberSlideshow();
    $('.promo-arrow.left').click(function() {
        $promoSl.novemberSlideshow('stop');
        $promoSl.novemberSlideshow('previousSlide');
        });
        
    $('.promo-arrow.right').click(function() {
        $promoSl.novemberSlideshow('stop');
        $promoSl.novemberSlideshow('nextSlide');
        });
    
    $(window).load(function(){
        createShadow();
    });
         
     
    $('div.right_menu ul.menu li.clickable').click(function(e) {
        if(!e.ctrlKey) {
            href=$(this).find('.text a').attr('href');
            window.location=href;
            }
        }); 
    
});

/*function changePromo() {
    var promo_count=$('.promo-block').length;
    if(do_change_promo) {
        active_promo++;
        if (active_promo>promo_count) {
            active_promo=1;
            promo_times_shown++;
        }
        
        $('#menu_block ul.menu').find('td.text[name="block'+active_promo+'"]').trigger('click');
        do_change_promo=true;
        
        if(promo_times_shown<2)
            setTimeout("changePromo()",promo_timeout);
    }
}*/


function searchInput()
{
    
    //Переключение текста в инпуте
    var input = $('input.search_input');    
    input.each(function(){
        var defVal = $(this).val();
        $(this).click(function(){
            if( $(this).val() == defVal) {
                $(this).val('');
                $(this).css('font-style','normal');                
            }
        });
        $(this).focusout(function(){
            if( $(this).val() == '' ) {
                $(this).val(defVal);
                $(this).css('font-style','italic');
            } 
        });
    });
    
    //Вставка текста "например" в поле поиска
    $('#search_example').click(function(){
        $('#search_input').val($(this).text());
        $('#search_input').css('font-style','normal');      
    });
    
}


function actionButton(selector)
{
    
    //Кнопка в верхнем меню (Создать напиток)
    top_menu_btn = $(selector);
    top_menu_btn.mouseout(function(){
        $(this).css('background-position', "0");
    });
    top_menu_btn.mouseover(function(){
        $(this).css('background-position', -$(this).width());
    });
    top_menu_btn.mousedown(function(){
        $(this).css('background-position', -$(this).width()*2);
    });
    top_menu_btn.mouseup(function(){
        $(this).css('background-position', -$(this).width());
    });
    
}

function imagesSwap()
{
    
    var big_img = $('#big_img');
    var images = $('.small_images');
    
    images.click(function(e){
        
        images.each(function(){
            if( $(this).find(':first').hasClass('active') ) {
                $(this).find(':first').removeClass('active');
            }
        });
        
        var path = $(this).find('img').attr('src');
        path = path.replace('small', 'large');
        big_img.attr('src', path);
        
        $(this).find(':first').addClass('active');
        
        createShadow();
        
    });
}

function checkboxGroup(selector)
{
    
    var checkbox = $('#'+selector);
    
    checkbox.click(function(){
        
        if( checkbox.attr('checked')) {
            $('.'+selector).attr('checked', 'checked');
            //checkbox.addClass('inactive');
        } else {
            $('.'+selector).attr('checked', '');
            checkbox.removeClass('inactive');
        }
        
    });
    
     $('.'+selector).click(function(){
        checkbox.attr('checked', 'checked');
        checkbox.addClass('inactive');
        
        var all = true;
        var nothing = true;
        
        $('.'+selector).each(function(){
                
             if( !$(this).attr('checked') ) {
                all = false;
             }             
             else {
                nothing = false;
             }
             
        });
        
        if(all) {
            checkbox.removeClass('inactive');
        }
        
        if(nothing) {
            checkbox.removeAttr('checked');
            checkbox.removeClass('inactive');
        }
                    
     });
    
}

//Добавляет тень к правому боку картинки
function createShadow() {
    $('#right_shadow').height( $('#big_img').outerHeight() );    
    $('#right_shadow').height( $('.promo-block.first').outerHeight() );    
    $('#right_shadow').height( $('.block1 img').height() );    
}
