/**
 * @author Andrew Abramov (http://forgiving.ru/)
 * @copyright BRIGHTSIDE studio (http://bright-side.ru/)
 */

function selectSpeed(speed) {
    return $.browser.msie ? 0 : speed;
}

jQuery.preventDefaultEvent = function(e, options) {
    var options = jQuery.extend({
        shift:1,
        ctrl:1,
        alt:1,
        meta:1
    }, options); 
    var href = e.currentTarget.getAttribute('href');
    if(((options.shift && e.shiftKey)
        || (options.alt && e.altKey)
        || (options.ctrl && e.ctrlKey)
        || (options.meta && e.metaKey))
        && href && href.indexOf('#') != 0
        && href.indexOf('javascript:') != 0
    ) return true;
    e.preventDefault();
    return false;
}

jQuery.fn.whenLoadContent = function(callback) {
    var current = $(this);
    var images = current.find('img');
    var backgroundImages = current.find('[style]');

    images = clear($.unique(images.each(function(index) {
        images[index] = images[index].src;
    })));
    
    backgroundImages = clear(backgroundImages.each(function(index) {
        backgroundImages[index] = $(backgroundImages[index]).css('background-image')
        .replace('url(', '').replace(')', '').replace('none', '')
        .replace('"', '').replace('"', '');
    }));
    
    $.when(isImagesLoad(images), isImagesLoad(backgroundImages)).done(callback);
    return this;
    
    function clear(arr) {
        return $.grep(arr, function(element) {
            return '' == element || 'initial' == element ? false : true;
        });
    }
    
    function isImagesLoad(arraySrc) {
        return isAbstractLoad(arraySrc, imageProcessing);
    }
    
    function imageProcessing(value, key, logical, deferred) {
        img = new Image();
        img.onload = function() {
            doneOne(key, logical, deferred);
        }
        img.src = value;
    }
    
    function isAbstractLoad(arr, callback) {
        var d = $.Deferred();
        if (0 == arr.length) {
            d.resolve();
        } else {
            var logical = new Array(arr.length);
            
            for (key in arr) {
                logical[key] = false;
            }
            
            for (key in arr) {
                callback(arr[key], key, logical, d);
            }
        }
        return d;
    }
    
    function doneOne(key, logical, deferred) {
        logical[key] = true;
        if (isComplete(logical)) {
            deferred.resolve();
        }
    }
    
    function isComplete(logical) {
        for (key in logical) {
            if (true != logical[key]) {
                return false;
            }
        }
        return true;
    }
};

jQuery.fn.brightWorkMenu = function(options) {
    var options = jQuery.extend({
        visibleNumber: 10,
        speed: 100,                 
        appearanceSpeed: 'slow',    
        scrollingShift: 2,          
        tabs: 'ul.tabs li',              
        items: '.items',
        scrollable: '.scrollable',  
        prev: '.prev',        
        next: '.next',
        preview: '.previews',
        inactive: 'inactive',
        eyeTitle: '',
        eyeActiveTitle: '',
        bestTitle: '',
        bestActiveTitle: ''
    }, options); 
    
    var menu = $(this);
    var tabs = $(options.tabs, this);
    var eye = tabs.filter('.eye').attr('title', options.eyeTitle);
    var best = tabs.filter('.best').attr('title', options.bestTitle);
    tabs = tabs.not(eye).not(best);
    var pages = getPages();
    var scrollable = $(options.scrollable, this);
    var prevHandler = $(options.prev, this);
    var nextHandler = $(options.next, this);
    
    var tabIndex = 0;
    
    tabs.bind('select', function(event, newIndex) {
        if (undefined == newIndex) {
            newIndex = 0;
        }
        tabs.eq(tabIndex).removeClass('now');
        tabs.eq(newIndex).addClass('now');
    });
    
    prevHandler.bind('review_prev', function() {
        var page = pages[tabIndex];
        if(!tabs.eq(tabIndex).hasClass('disabled')) {
            prevHandler.show();
        }
        if (page.currentElementIndex > 0) {
            prevHandler.removeClass(options.inactive);
        } else {
            prevHandler.addClass(options.inactive);
        }
    }).bind('resize_prev', function() {
        prevHandler.stop().animate({'margin-left': (pages[tabIndex].width - prevHandler.width()) / 2});
    });
    
    nextHandler.bind('review_next', function() {
        if(!tabs.eq(tabIndex).hasClass('disabled')) {
            nextHandler.show();
        }
        var page = pages[tabIndex];
        var number = eye.hasClass('selected') ? $('li.preview', page.elements).size() : best.hasClass('selected') ? $('li.best', page.elements).size() : page.number;
        var visible = getVisibleElementsNumber(number);

        if (page.currentElementIndex < number - visible) {
            nextHandler.removeClass(options.inactive);
        } else {
            nextHandler.addClass(options.inactive);
        }
    }).bind('resize_next', function() {
        nextHandler.stop().animate({'margin-left': (pages[tabIndex].width - nextHandler.width()) / 2});
    });
    
    menu.bind('resize_menu', function(event, pageIndex) {
        if (undefined == pageIndex) {
            pageIndex = 0;
        }
        var lastPage = pages[tabIndex];
        var currentPage = pages[pageIndex];
        var currentHeight = eye.hasClass('selected') ? currentPage.miniHeight : best.hasClass('selected') ? currentPage.miniBestHeight : currentPage.height;
        lastPage.elements.hide();
        currentPage.elements.show();        
        
        scrollable.stop().animate({height: currentHeight}, {duration: options.appearanceSpeed,
            easing: 'easeOutExpo'});
        tabIndex = pageIndex;
        menu.triggerHandler('review_handle');
    }).bind('review_handle', function(event, pageIndex) {
        prevHandler.triggerHandler('review_prev');
        nextHandler.triggerHandler('review_next');
    }).bind('select_page', function(event, pageIndex) {
        if (undefined == pageIndex) {
            pageIndex = 0;
        }
        tabs.triggerHandler('select', pageIndex);
        menu.triggerHandler('resize_menu', pageIndex);
        
        //tabIndex = pageIndex;

        prevHandler.triggerHandler('resize_prev');
        nextHandler.triggerHandler('resize_next');
    }).bind('move_page', function(event, number) {
        var page = pages[tabIndex];
        var shifnNumber = page.currentElementIndex;
        page.setCurrentElementIndex(page.currentElementIndex + number);
        shifnNumber -= page.currentElementIndex;
        
        page.elements.stop().animate({'top' : (-page.currentElementIndex * page.elementHeight)}, {duration: options.speed * Math.abs(shifnNumber), easing: 'easeInOutCirc'});
        
        menu.triggerHandler('review_handle');
    }).bind('lift', function(event, number) {
        menu.triggerHandler('move_page', [-number]);
    }).bind('lower', function(event, number) {
        menu.triggerHandler('move_page', [number]);
    }).bind('turn_on_prewiew_filter', function(event) {
        for (key in pages) {
            pages[key].noPreviewElements.hide();
            if (pages[key].noPreviewElements.size() == pages[key].number) {
                tabs.eq(key).addClass('disabled');
                if(tabIndex == key) {
                    prevHandler.hide();
                    nextHandler.hide();
                }
            } else {
                tabs.eq(key).removeClass('disabled');
            }
        }
        var page = pages[tabIndex];
        page.setCurrentElementIndex(0);
        page.elements.stop().animate({'top' : 0}, {duration: 0});
        menu.triggerHandler('resize_menu', tabIndex);
        eye.attr('title', options.eyeActiveTitle);
    }).bind('turn_off_prewiew_filter', function(event) {
        for (key in pages) {
            pages[key].noPreviewElements.show();
            tabs.eq(key).removeClass('disabled');
            prevHandler.show();
            nextHandler.show();
        }
        menu.triggerHandler('resize_menu', tabIndex);
        eye.attr('title', options.eyeTitle);
    }).bind('turn_on_best_filter', function(event) {
        for (key in pages) {
            pages[key].noBestElements.hide();
            if (pages[key].noBestElements.size() == pages[key].number) {
                tabs.eq(key).addClass('disabled');
                if(tabIndex == key) {
                    prevHandler.hide();
                    nextHandler.hide();
                }
            } else {
                tabs.eq(key).removeClass('disabled');
            }
        }
        var page = pages[tabIndex];
        page.setCurrentElementIndex(0);
        page.elements.stop().animate({'top' : 0}, {duration: 0});
        menu.triggerHandler('resize_menu', tabIndex);
        best.attr('title', options.bestActiveTitle);
    }).bind('turn_off_best_filter', function(event) {
        for (key in pages) {
            pages[key].noBestElements.show();
            tabs.eq(key).removeClass('disabled');
            prevHandler.show();
            nextHandler.show();
        }
        menu.triggerHandler('resize_menu', tabIndex);
        best.attr('title', options.bestTitle);
    });
     
    tabs.click(function() {
        if ($(this).hasClass('disabled')) {
            return false;
        }
        var newIndex = $(this).index() - 2;
        menu.triggerHandler('select_page', newIndex);
    });
    
    eye.click(function() {
        if(best.hasClass('selected')) {
            menu.triggerHandler('turn_off_best_filter');
            best.removeClass('selected');
        }
        eye.toggleClass('selected');
        if (eye.hasClass('selected')) {
            menu.triggerHandler('turn_on_prewiew_filter');
        } else {
            menu.triggerHandler('turn_off_prewiew_filter');
        }
    });
    
    best.click(function() {
        if(eye.hasClass('selected')) {
            menu.triggerHandler('turn_off_prewiew_filter');
            eye.removeClass('selected');
        }
        best.toggleClass('selected');
        if (best.hasClass('selected')) {
            menu.triggerHandler('turn_on_best_filter');
        } else {
            menu.triggerHandler('turn_off_best_filter');
        }
    });
    
    prevHandler.click(function() {
        if (prevHandler.hasClass('inactive')) {
            return false;
        }
        menu.triggerHandler('lift', options.visibleNumber);
    });
    
    nextHandler.click(function() {
        if (nextHandler.hasClass('inactive')) {
            return false;
        }
        menu.triggerHandler('lower', options.visibleNumber);
    });
    
    scrollable.mousewheel(function (event, delta) {
        if ( delta > 0 ) {
            if (prevHandler.hasClass('inactive')) {
                return false;
            }
            menu.triggerHandler('lift', options.scrollingShift);
        }
        else if ( delta < 0 ) {
            if (nextHandler.hasClass('inactive')) {
                return false;
            }
            menu.triggerHandler('lower', options.scrollingShift);
        }
    });

    var anchor = window.location.hash.substring(1).toLocaleUpperCase();
    tabs.each(function() {
        var current = $(this);
        if(current.text().toLocaleUpperCase() == anchor) {
            tabIndex = current.index() - 2;
        }
    });

    if(0 == tabIndex) {
        for (key in pages) {
            $('li > a', pages[key].elements).each(function() {
                var current = $(this);
		        if(getUniqueName(current.attr('href').toLocaleUpperCase()) == anchor) {
                    current.parent().addClass('now');
                    tabIndex = key;
		        }
            });
        }
    }

    menu.triggerHandler('select_page', tabIndex);
    
    var firstWork = $('li', pages[tabIndex].elements).filter('.preview');
    if (!firstWork.filter('.now').length) {
        if (firstWork.length) {
        firstWork.eq(0).addClass('now');
	    } else {
	        for (key in pages) {
	            $('li', pages[key].elements).filter('.preview').eq(0).addClass('now');
	        }
	    }
    }
    
    return this;
    
    function Page(page) {
        this.elements;
        this.noPreviewElements;
        this.noBestElements;
        this.visibleElementsNumber;
        this.currentElementIndex;
        this.elementHeight;
        this.width;
        this.height;
        this.miniHeight;
        this.miniBestHeight;
        this.number;
        this.setCurrentElementIndex = function(index) {
            var number = eye.hasClass('selected') ? this.number - this.noPreviewElements.size() : best.hasClass('selected') ? this.number - this.noBestElements.size() : this.number;
            this.currentElementIndex = index > 0 ? index > (number - this.visibleElementsNumber) ? (number - this.visibleElementsNumber) : index : 0;
        }
        this.init = function(page) {
            this.elements = $(page);
            var elementList = $('li', this.elements);
            this.noPreviewElements = elementList.not('.preview');
            this.noBestElements = elementList.not(elementList.filter('.best'));
            this.number = elementList.size();
            this.visibleElementsNumber = getVisibleElementsNumber(this.number);
            this.currentElementIndex = 0;
            this.elementHeight = $.browser.msie ? 18 : elementList.height();
            this.height = this.elementHeight * this.visibleElementsNumber;
            this.miniHeight = this.elementHeight * getVisibleElementsNumber(this.number - this.noPreviewElements.size());
            this.miniBestHeight = this.elementHeight * getVisibleElementsNumber(this.number - this.noBestElements.size());
            this.width = callPageRealWidth(elementList);
            this.elements.hide();
        }
        
        this.init(page);
    }
    
    function getPages() {
        var items = $(options.items, menu);
        var pages = new Array(items.length);
        for (i = 0; i < items.length; i++) {
		    pages[i] = new Page(items.eq(i));
		}
        return pages;
    }
    
    function getVisibleElementsNumber(number) {
        return number < options.visibleNumber ? number : options.visibleNumber ;
    }
    
    function callPageRealWidth(elementsList) {
        var max = 0;
        var list = $('a', elementsList).toArray();
        for (key in list) {
            var currentWidth = $(list[key]).width();
            if (currentWidth > max) {
                max = currentWidth;
            }
        }
        return max + 10;
    }
    
    function getUniqueName(href) {
        var sub = href.charAt(href.length-1) == '/' ? href.substring(0, href.length-1) : href ;
        return sub.substring(sub.lastIndexOf('/') + 1);
    }
};

jQuery.fn.brightController = function(options) {
    var options = jQuery.extend({
         menuButtons: '',
         background: '',
         newBackground: '',
         previewPanel: '',
         titleViewPanel: '',
         infoPanel: '',
         linkButton: '',
         preloadPanel: '#pre-load',
         scroll: '#scroll',
         imgPrefix: 'http://img.bright-side.ru',
         previewName: 'preview',
         previewFormat: '.png',
         titleName: 'title',
         titleFormat: '.png'
    }, options);
    
    var current = $(this);
    
    var screenResolution = defineScreenResolution();
    
    var menu = $(options.menuButtons);
    var background = $(options.background).css('z-index', 0);
    var backgroundContent = $('div.content', background).css({'bottom': 0, 'height': 'auto'});
    var newBackground = $(options.newBackground).css({'visibility': 'hidden', 'z-index': 1});
    var newBackgroundContent = $('div.content', newBackground).css({'bottom': 0, 'height': 'auto'});
    var preview = $(options.previewPanel).hide();
    var title = $(options.titleViewPanel);
    var info = $(options.infoPanel);
    var link = $(options.linkButton).addClass('hide');//.hide();
    var preload = $(options.preloadPanel);
    var scroll = $(options.scroll); 
    
    var titleImg = new Image();
    var previewImg = new Image();
    
    var isBusyBackground = false;
    var isBusyTitleImg = false;
    var isBusyPreviewImg = false;
    
    var centerX;
    var centerY;
    var maxLenght;
    
    titleImg.onload = function() {
        isBusyTitleImg = false;
        if (!isBusyBackground) {
            current.triggerHandler('show');
        }
    }
    
    previewImg.onload = function() {
        preview.attr('src', previewImg.src).triggerHandler('show');
    }
    
    current.bind('show', function() {
        menu.triggerHandler('illuminate');
        current.triggerHandler('place_new');
        current.triggerHandler('even_new');
        current.triggerHandler('resize');
        newBackground.fadeOut(0).css('visibility', 'visible')
        .fadeIn('normal' , function() {            
            var buf = background;
            background = newBackground;
            newBackground = buf;
            
            buf = backgroundContent;
            backgroundContent = newBackgroundContent;
            newBackgroundContent = buf;
                
            newBackground.attr('id', 'new').css({'visibility': 'hidden', 'z-index': 2});
            background.attr('id', 'general').css('z-index', 1);
            newBackgroundContent.css({'bottom': 0, 'height': 'auto'}).html(''); 
            
            current.triggerHandler('place');
            current.triggerHandler('even');
            scroll.triggerHandler('resize');
            scroll.triggerHandler('starting');
        });
        title.fadeOut(0).css('visibility', 'hidden').attr('src', titleImg.src)
        .css('visibility', 'visible').fadeIn(selectSpeed('fast'));
        scroll.triggerHandler('resize');
        preview.triggerHandler('hide');
        preload.fadeOut('fast', function() {
           link.removeClass('stop');//.show();
        });
    }).bind('reload', function(e, src) {
        link.addClass('stop').hide();
        preload.fadeIn('fast');
        isBusyBackground = true;
        $.get('/wallpaper.php', {work: src, size: screenResolution}).done(function(data) {
            $(data).whenLoadContent(function() {
                newBackgroundContent.html(data);
                if (!isBusyTitleImg) {
                    current.triggerHandler('show');
                }
                isBusyBackground = false;
            });
        });
    }).bind('place', function() {
        toCenter(backgroundContent, backgroundContent.children());
    }).bind('place_new', function() {
        toCenter(newBackgroundContent, newBackgroundContent.children());
    }).bind('even', function() {
        even($('#general'), $('div.content', '#general'), true);
    }).bind('even_new', function() {
        even($('#new'), $('div.content', '#new'), false);
    });
    
    menu.bind('select', function(e, selected) {
        menu.parent().removeClass('now');
        $(selected).parent().addClass('now');
    }).bind('illuminate', function(e, isDull) {
        var body = $('body');
        menu.parent().filter('.now').children().hasClass('dull') ? body.addClass('dull') : body.removeClass('dull');
    }).bind('reload', function(e, selected) {        
        selected = $(selected);
        var href = selected.attr('href');
        var li = selected.parent();
        var dateTitle = {
            name: li.data('name'),
            type: li.data('type'),
            description: li.data('description')
        };
        
        window.location.hash = '#' + getUniqueName(href.toLocaleLowerCase());
        if($.browser.mozilla) {
            $('<link href="'+ $('link[type="image/x-icon"]').remove().attr("href") +'" rel="shortcut icon" type="image/x-icon" />').appendTo('head');
        }
        
        current.triggerHandler('reload', href);
        title.triggerHandler('reload', href);
        info.triggerHandler('reload', dateTitle);
        link.triggerHandler('reload', href);
        menu.triggerHandler('select', selected);
    });
    
    current.bind('resize', function() {
        background.height($('#footer').offset().top - ($.browser.msie ? 0 : $('#news-stuff .slide').css('border-bottom-width').replace('px', '')));
        newBackground.height(background.height());
        current.triggerHandler('place');
        current.triggerHandler('place_new');
    });
    
    preview.bind('reload', function(e, src) {
        if (src == this.last) {
            preview.triggerHandler('show');
        } else {
            previewImg.src = options.imgPrefix + src + options.previewName + options.previewFormat;
        }
        this.last = src;
    }).bind('show', function() {
        if (!isBusyPreviewImg) {
            preview.stop(true, true);
            preview.fadeIn(selectSpeed('fast'));
        }
    }).bind('hide', function() {
        preview.stop(true, true);
        preview.fadeOut(selectSpeed('fast'));
    });
    
    title.bind('reload', function(e, src) {
        link.hide();
        preload.fadeIn('fast');
        isBusyTitleImg = true;
        title.parent().attr('href', src);
        titleImg.src = options.imgPrefix + src + options.titleName + options.titleFormat;
    });
    
    link.bind('reload', function(e, href) {
        link.attr('href', href);
    });
    
    info.bind('reload', function(e, date) {
        $('strong', info).text(date.name);
        $('em', info).text(date.type);
        $('p', info).text(date.description);
    });
    
    $(window).bind('calculate_center_point', function(){
        centerX = $(this).width() / 2;
        centerY = ($(this).height() / 2) - 25;
    }).bind('calculate_max_lenght', function(){
        maxLenght = Math.sqrt((Math.pow(centerX, 2) +  Math.pow(centerY, 2)));
        maxLenght *= 0.20;
    });
    
    menu.click(function(e) {
        if($.preventDefaultEvent(e)) return;
        if(!$(this).parent().hasClass('now')) {
            menu.triggerHandler('reload', this);
        }
        return false;
    }).hover(function() {
        isBusyPreviewImg = false;
        t = $(this);
        var href = t.attr('href');
        if (!t.parent().hasClass('now')) {
            preview.triggerHandler('reload', href);
        }
    }, function() {
        preview.triggerHandler('hide');
        isBusyPreviewImg = true;
    });
    
    $(window).resize(function() {
        current.triggerHandler('resize');
        $(window).triggerHandler('calculate_center_point');
        $(window).triggerHandler('calculate_max_lenght');
    }).mousemove(function(e) {
        if (link.hasClass('stop')) {
            return false;
        }
        var x = e.pageX;
        var y = e.pageY;
        if ($('#news-stuff .btn-slide').hasClass('active')) {
            if (y > $('#news-stuff').offset().top) {
                return false;
            }
        }

        var length = Math.sqrt((Math.pow(x - centerX, 2) +  Math.pow(y - centerY, 2)));
        var percent = 1 - (length / maxLenght);
        var percent = percent < 0? 0 : percent;
        var index = (7 - Math.round(7 * percent));

        if (index == 7) {
            link.addClass('hide').fadeOut('fast');
        } else if((index < 7) && (link.hasClass('hide'))) {
            link.fadeIn('fast');
            link.css('background-position', -224 * index + 'px 0px');
        } else {
            link.css('background-position', -224 * index + 'px 0px');
        }
    });

    background.triggerHandler('resize');
    menu.triggerHandler('reload', menu.parent().filter('.now').children());
    $(window).triggerHandler('calculate_center_point');
    $(window).triggerHandler('calculate_max_lenght');
    return this;
    
    function defineScreenResolution() {
        var height = screen.height;
        var resolution = 'normal';
        if (height <= 768) {
            resolution = 'small';
        } else if (height >= 1080) {
            resolution = 'big'
        }
        return resolution;
    }
    
    function toCenter(outside, inside) {
        var offset = (outside.width() - inside.width()) / 2;
        inside.css('margin-left', offset < 0 ? offset : 0);
    }
    
    function even(outside, inside, scrollRight) {
        var h, action;
        
        if (inside.height() <= outside.height()) {
            h = '100%';
            action = 'hide';
        } else {
            h = 'auto';
            action = 'show';
        }
        
        inside.css('height', h);
        if(scrollRight) scroll.triggerHandler(action);
    }
    
    function getUniqueName(href) {
        var sub = href.charAt(href.length-1) == '/' ? href.substring(0, href.length-1) : href ;
        return sub.substring(sub.lastIndexOf('/') + 1);
    }
};

jQuery.fn.brightScrollBar = function(options) {
    var options = jQuery.extend({
        handle: '#handle'
    }, options);

    return this.each(function() {
        var current = $(this).hide();
        var handle = $(options.handle, this);
        
        current.bind('show', function() {
            current.show().addClass('enable');
        }).bind('hide', function() {
            current.hide().removeClass('enable');
        }).bind('resize_plate', function() {
            /*var newHeight = $(window).height() - current.css('margin-top').replace('px','')
                - current.css('margin-bottom').replace('px','') 
                - $('#footer-line').height() 
                - $('#work-name').height() 
                - $('#work-name').offset().top;
            var minHeight = handle.height() * 1.25;
            current.height(newHeight > minHeight ? newHeight : minHeight);
            scrollHeight = current.height() - handle.height();*/
            current.height(235);
            scrollHeight = current.height() - handle.height();
        }).bind('set_position_handle', function(event, shift) {
            handle.css({top: shift * (current.height() - handle.height()) / 100});
        }).bind('animate_handle', function(event, shift) {
            var value = shift * (current.height() - handle.height()) / 100;
            value = NaN == value ? 0 : value;
            if(value < 5) {
                value = 0;
            } else if (value > (current.height() - handle.height() - 5)) {
                value = current.height() - handle.height();
            }
            handle.stop(false, true).animate({top: value}, 'fast');
        });
        
        handle.draggable({
	        start: function() {
	            handle.addClass('active');
	        }, stop: function() {
	            handle.removeClass('active');
	        }, containment: current
	    });
    }); 
};

jQuery.fn.brightScrollController = function(options) {
    var options = jQuery.extend({
        scroll: '#scroll',
        handle: '#handle',
        background: '#background',
        all: '',
        scrollFactor: 0.2,
        scrollBaseFactor: 2.5
    }, options);

    return this.each(function() {
        var current = $(this);
        var scroll = $(options.scroll);
        var handle = $(options.handle, this);
        var all = $(options.all);
        var offset = 100;
        
        current.bind('set_position', function(event, shift) {
            $(options.background).css({bottom: calcPosotion(shift)});
        }).bind('move_to', function(event, shift) {
            scroll.stop();
            if (scroll.hasClass('enable')) {
	            var bg = $(options.background);
	            bg.stop();
	            offset = shift > 0 ? shift < 100 ? shift : 100 : 0;
                offset = offset == 0 ? 1 : offset;
	            bg.animate({bottom: calcPosotion(offset)}, 'fast');
            }
        }).bind('starting', function(event) {
            if (scroll.hasClass('enable')) {
	            current.triggerHandler('move_to', 100);
                scroll.triggerHandler('animate_handle', offset);
            }
        }).bind('move_on', function(event, shift) {
            current.triggerHandler('move_to', offset + shift);
            scroll.triggerHandler('animate_handle', offset);
        }).bind('up', function(event) {
            current.triggerHandler('move_on', -calcShift());
        }).bind('down', function(event) {
            current.triggerHandler('move_on', calcShift());
        });
        
        scroll.bind('resize', function(event) {
            scroll.triggerHandler('resize_plate');
            current.triggerHandler('set_position_handle', offset);
        });
        
        all.mousewheel(function (event, delta) {            
            if (delta > 0) {
                current.triggerHandler('up');
            }
            else {
                current.triggerHandler('down');
            }
        });

        $('#view-work-btn').mousewheel(function (event, delta) {
            if (delta > 0) {
                current.triggerHandler('up');
            }
            else {
                current.triggerHandler('down');
            }
        });
        
        scroll.mousewheel(function (event, delta) {            
            if (delta > 0) {
                current.triggerHandler('up');
            }
            else {
                current.triggerHandler('down');
            }
        }).click(function(e) {
            if ((e.pageY > handle.offset().top) && (e.pageY < handle.offset().top + handle.height())) {
            } else {
                var y = e.pageY - scroll.offset().top - scroll.css('padding-top').replace('px','');
                y = y < 0 ? 0 : y;
                var position = y / scroll.height() * 100;
                current.triggerHandler('move_to', position);
                scroll.triggerHandler('animate_handle', offset);
            }
        });
        
        handle.draggable({
            drag: function(event, ui) {
                current.triggerHandler('move_to', ui.position.top / (scroll.height() - handle.height()) * 100);
                scroll.triggerHandler('set_position_handle', offset);
            }
        });
        
        $(window).resize(function() {
            scroll.triggerHandler('resize');
            current.triggerHandler('set_position', offset);
        });
    });
    
    function calcPosotion(shift) {
        return ($(options.background).height() - $(document).height()) * -(100-shift) / 100;
    }
    
    function calcShift() {
        return 100 / (options.scrollBaseFactor + (($(options.background).height() / $(document).height() - 1) / options.scrollFactor));
    }
};

jQuery.fn.slideHorizontal = function(options) {
    var options = jQuery.extend({
        panel: '.panel',
        handle: '.handle',
        direction: 'left',
        speed: 'normal'
    }, options);

    return this.each(function() {
        var current = $(this);
	    var panel = $(options.panel, this).hide();
	    var handle = $(options.handle, this);
        
        handle.mouseover(function() {
            panel.stop().show("slide", { direction: options.direction }, options.speed, function() {
                panel.css('left', 'left' == options.direction ? 23 : 'auto');
            });
        });
        
        current.mouseleave(function(){
            panel.stop().hide("slide", { direction: options.direction }, options.speed, function() {
                panel.css('left', 'left' == options.direction ? 23 : 'auto');
            });
        });
        
	    /*handle.mouseover(function() {
            panel.stop(false, true);
            panel.show("slide", { direction: options.direction }, options.speed);
	        return false;
	    });
	    
	    current.mouseleave(function(){
            panel.stop(false, true);
            panel.hide("slide", { direction: options.direction }, options.speed);
	        return false;
	    });*/
    }); 
};

jQuery.fn.brightNewsStuffPanel = function(options) {
    var options = jQuery.extend({
        panel: '.panel',
        handle: '.handle',
        speedUp: 400,
        speedDown: 250,  
        methodUp: 'easeOutExpo',
        methodDown: 'easeOutBack',
        linkButton: ''
    }, options);    
    
    return this.each(function() {
        var current = $(this);
        var panel = $(options.panel, this).hide();
        var handle = $(options.handle, this);
        //var link = $(options.linkButton).hide();
        
        handle.bind('open', function(){
            handle.stop();
            panel.slideDown({duration: options.speedUp, easing: options.methodDown});
            handle.addClass('active');
        }).bind('close', function(){
            handle.stop();
            panel.slideUp({duration: options.speedDown, easing: options.methodUp});
            handle.removeClass('active');
        }).click(function() {
	        if (handle.hasClass('active')) {
	            handle.triggerHandler('close');
	        } else {
	            handle.triggerHandler('open');   
	        }
	        return false;
	    });
        
        /*current.hover(function() {
            
        }, function() {
	        handle.triggerHandler('close');
	    });*/
    }); 
};

jQuery.fn.brightPreview = function(options) {
    var options = jQuery.extend({
        info: '.info'
    }, options);
    
    return this.each(function() {
        var current = $(this);
        var info = $(options.info, this).hide();

        current.hover(function() {
            info.stop(true, true).fadeIn('fast');
        }, function() {
            info.stop(true, true).fadeOut('fast');
        });
    }); 
};

jQuery.fn.extend({
    disableSelection : function() {
        this.each(function() {
            this.onselectstart = function() { return false; };
            this.unselectable = 'on';
        });
    },
    enableSelection : function() {
        this.each(function() {
            this.onselectstart = function() {};
            this.unselectable = 'off';
        });
    }
});

jQuery.fn.newWindowOpened = function(){   
    return this.each(function() {
        $(this).click(function() {
            return !window.open(this.href);
        });
    });
};

jQuery.fn.brightMenu = function() {   
    var html = $('html');
    var body = $('body');
    
    return this.each(function() {
        var current = $(this);
        var limit = current.offset().top;
        var menu = $('#menu');
        var menuElements = $('li', menu);
        var menuBtns = $('> a', menuElements);
        var plus = menuBtns.filter('.addthis_button');
        var nowIndex = menuElements.filter('.now').index();
        var before = menuElements.slice(0, nowIndex);
        var after = menuElements.slice(nowIndex + 1, menuElements.length);        
        
        current.data('last', false);
        
        menuBtns.not(plus).hover(function(){
            $(this).stop().animate({backgroundColor: '#BB225F'}, 'fast');
        }, function(){
            $(this).stop().animate({backgroundColor: '#20201E'}, 'fast');
        });

        plus.hover(function(){
            $(this).stop().animate({backgroundColor: '#20201E'}, 'fast');
        }, function(){
            $(this).stop().animate({backgroundColor: '#BB225F'}, 'fast');
        });
        
        
    });
};

jQuery.fn.brightFastAcquaintance = function(){    
    return this.each(function() {
        var current = $(this);
        var btns = $('a', current);
        $('img', btns).hide();
        
        btns.hover(function() {
            var t = $(this);
            
            $('img', t).stop(true, true).fadeIn('fast');
        }, function() {
            var t = $(this);
            
            $('img', t).stop(true, true).fadeOut('fast');
        });
    });
};

$(document).ready(function () {
    if (!($.browser.msie && 6 == $.browser.version)) {
        $('html').addClass('js');
        $('#new, #general, #logo, #menu, #submenu-block, #lang, #slide-work-menu, #work-name, ul.tabs, #kote img, #slide-work-menu div.works ul.items li a, #slide-work-menu div.works div.scrollable, #right-panel, #scroll, #handle, #fast-acquaintance, #news-stuff div.slide, #contacts .mail, #contacts .twitter, #contacts .youtube, #contacts .livejournal').disableSelection();
        $('#contacts a.twitter, #contacts a.youtube, #contacts a.livejournal').newWindowOpened();
        $('#menu-line').brightMenu();
        $('#slide-work-menu').brightWorkMenu({
            eyeTitle: 'Только с превью',
            eyeActiveTitle: 'Все работы',
            bestTitle: 'Лучшие работы',
            bestActiveTitle: 'Все работы'
        }).brightController({
		    menuButtons: '#slide-work-menu > div.works > div.scrollable > ul.items > li.preview > a',
			background: '#general',
			newBackground: '#new',
			previewPanel: '#slide-work-menu > img.previews',
			infoPanel: '#short-description',
			linkButton: '#view-work-btn'
	    });
        $('#scroll').brightScrollBar().brightScrollController({background: '#general > div.content', all: '#new, #general'});
	    $("#buttons .button-transporent.info").slideHorizontal({handle: 'img', direction: 'left'});
	    $('#fast-acquaintance').brightFastAcquaintance();
        $("#buttons .button-transporent.mirar").slideHorizontal({handle: 'img', direction: 'right'});
	    $('#news-stuff').brightNewsStuffPanel({panel: '#slide-panel', handle: '.btn-slide', linkButton: '#view-work-btn'});
        $("#works-priview > ins").brightPreview({info: 'ins.btn'});
    }
});
