(function($) {

    function scrollList() {
        var l = $(this),
            h = l.height(),
            k = 0,
            i = 0,
            is = l.children('li');


        is.each(function() {
            if (!i && this.offsetTop >= h)
                i = k;
            k++;
        });

        if (!i)
            return;

        var u = $('<span class="up"></span>').insertBefore(l),
            d = $('<span class="down"></span>').insertAfter(l),

        k = i = is.length - i;

        function sd() {
            if (k) {
                var m = l.append(l.children('li:first-child').remove());
                if (m.get(0).tooltip)
                    m.tooltip();
                k--;
            }
        }

        function su() {
            if (k < i) {
                var m = l.children('li:last-child').insertBefore(l.children('li:first-child'));
                if (m.get(0).tooltip)
                    m.tooltip();
                k++;
            }
        }

        u.click(su);
        d.click(sd);

        l.mousewheel(function(e, d) {
            e.preventDefault();
            e.stopPropagation();
            ((d > 0) ? su : sd)();
        });
    }

    $.fn.scrollList = function() {
        this.each(scrollList);
    };

})(jQuery);

(function($) {
    function scrollable() {
        var container = $(this),
            content = container.children('div.content').first();

        if (this.scrollable) {
            var scrollBar = container.children('.scrollBar'),
                scrollSlider = scrollBar.children('.scrollSlider');
            return this.updateScroll();
        } else {
            var scrollBar = $('<div class="scrollBar"></div>').appendTo(container),
                scrollSlider = $('<div class="scrollSlider"></div>').appendTo(scrollBar);

            container.addClass('scrollable');
        }

        scrollSlider.bind('selectstart', function(e) {
            e.preventDefault();
        });

        function getScroll() {
            return content.position().top;
        }

        function scrollBy(dy) {
            var visibleHeight = container.height(),
                actualHeight = content.height(),
                sy = Math.round((getScroll() + dy) / 16) * 16;
            sy = Math.min(0, Math.max(sy, visibleHeight - actualHeight));
            content.css({ top: Math.round(sy) + 'px' });
            updateScroll();
        }

        function updateScroll() {
            var visibleHeight = container.height(),
                actualHeight = content.height(),
                k = visibleHeight / actualHeight,
                dh = scrollSlider.outerHeight() - scrollSlider.height(),
                boundY = scrollBar.height() - scrollSlider.outerHeight();
            if (k >= 1) {
                scrollBar.hide();
            } else {
                scrollBar.show();
                var sy = Math.max(visibleHeight - actualHeight, getScroll());
                scrollBar.css({ height: visibleHeight + 'px' });
                scrollSlider.css({ height: (visibleHeight * k - dh) + 'px', top: Math.min(boundY, visibleHeight * Math.abs(sy / actualHeight)) + 'px' }, 500);
            }
        }

        scrollSlider.mousedown(function(e) {
            e.preventDefault();
            var hitY = e.pageY - scrollSlider.offset().top,
                actualHeight = content.height(),
                scrollBarHeight = scrollBar.height(),
                scrollBarY = scrollBar.offset().top,
                boundY = scrollBarHeight - scrollSlider.outerHeight(),
                doc = $(document);

            doc.mousemove(function(e) {
                var y = Math.max(0, Math.min(boundY, e.pageY - scrollBarY - hitY)),
                    sy = -(y / scrollBarHeight) * actualHeight;
                scrollSlider.css('top', y + 'px');

                content.css('top', Math.round(Math.round(sy / 16) * 16) + 'px');
            });

            doc.mouseup(function() {
                doc.unbind();
            });
        });

        content.mousewheel(function(e, d) {
            e.preventDefault();
            e.stopPropagation();
            scrollBy(d * 16);
        });

        this.updateScroll = updateScroll;
        this.scrollable = true;
        updateScroll();
    }

    $.fn.scrollable = function() {
        this.each(scrollable);
    };

})(jQuery);

(function($) {
    function tooltip() {
        var tooltip = $('#tooltip'),
            textfield = tooltip.children('div').first(),
            target = this,
            element = $(target),
            set = function(e) {
                tooltip.css({ display: 'block', top: e.pageY - tooltip.outerHeight() - 2 + 'px', left: e.pageX + 'px' });
            },
            unset = function(e) {
                tooltip.css('display', 'none');
                element.unbind('mousemove');
            };

        if (!this.tooltip)
            this.tooltip = element.attr('title');
        element.attr('title', '');

        element.mouseenter(function(e) {
            textfield.html(this.tooltip);
            element.unbind('mousemove').mousemove(set);
            set(e);
        });

        element.mouseleave(unset).mousedown(unset);
    }

    $.fn.tooltip = function() {
        this.each(tooltip);
    };

})(jQuery);

var init = function() {

    //loadFirebugConsole();

    var controllerURL = '/controller.php?path=',
        playerURL = 'http://longstory.ru/videoplayer.swf';

    var _body = $(document.body),
        frame = $('#frame'),
        body = $('#body'),
        header = $('#header'),
        content = $('#content'),
        curtain = $('#curtain'),
        sidebar = $('#sidebar'),
        footer = $('#footer'),
        scroll = $('#scroll'),
        scrollBar = $('#scrollBar'),
        scrollSlider = $('#scrollSlider'),
        scrollLeft = $('#scrollLeft'),
        scrollRight = $('#scrollRight'),
        lightbox = $('#lightbox'),
        productionMenu = $('#productionMenu'),
        eventMenu = $('#eventMenu'),
        hash = null,
        path = '',
        oldpath = '',
        swfid = null,
        swfembedding = null,
        opening = false;

    var getScroll = function() {
        return body.position().left;
    }

    var getVisibleWidth = function() {
        return frame.outerWidth();
    }

    var getActualWidth = function() {
        return curtain.offset().left + sidebar.outerWidth() - getScroll();
    }

    // Подгоняем размер и положение слайдера скроллбара под желаемые
    // cx - положение шторы (curtain) и sx - левый скролл
    var updateScroll = function(cx, sx, nofixScroll) {
        var visibleWidth = getVisibleWidth(),
            actualWidth = (cx == null) ? getActualWidth() : (header.outerWidth() + cx + sidebar.outerWidth()),
            k = visibleWidth / actualWidth;
        if (k > 1) {
            scroll.fadeOut();
            scrollTo(0);
        } else {
            scroll.fadeIn();
            var scrollBarWidth = scrollBar.width(),
                sx = Math.max(visibleWidth - actualWidth, (sx == null ? getScroll() : sx));
            scrollSlider.stop();
            scrollSlider.css({ width: scrollBarWidth * k + 'px', left: scrollBarWidth * Math.abs(sx / actualWidth) + 'px' });
            if (!nofixScroll)
                scrollTo(sx);
        }
    }

    var getCurtainPos = function() {
        return curtain.position().left;
    }

    var moveCurtainTo = function(x, callback) {
        if (x == null)
            x = content.width();     // 1 / Math.tan(61.8 * Math.PI / 180) = 0.5361952954590328
        curtain.animate({ left: x + 'px', fontSize: 0.5361952954590328 * x + 'px' }, 500, callback);
        updateScroll(x);
    }

    var moveCurtainBy = function(dx, callback) {
        moveCurtainTo(getCurtainPos() + dx, callback);
    }

    var scrollTo = function(x) {
        body.animate({ left: Math.min(0, Math.max(x, getVisibleWidth() - getActualWidth())) + 'px' }, 200);
        //curtain.css({ fontSize: (0.5361952954590328 * (curtain.position().left - x)) + 'px' });
    }

    var scrollBy = function(dx) {
        var x = Math.min(0, Math.max(getScroll() + dx, getVisibleWidth() - getActualWidth()));
        body.css({ left: x + 'px' });
        updateScroll(null, x, true);
    }

    scrollSlider.bind('selectstart', function(e) {
        e.preventDefault();
    });

    scrollSlider.mousedown(function(e) {
        e.preventDefault();
        var hitX = e.pageX - scrollSlider.offset().left,
            actualWidth = getActualWidth(),
            scrollBarWidth = scrollBar.width(),
            scrollBarX = scrollBar.offset().left,
            boundX = scrollBarWidth - scrollSlider.outerWidth(),
            doc = $(document);

        doc.mousemove(function(e) {
            var x = Math.max(0, Math.min(boundX, e.pageX - scrollBarX - hitX)),
                sx = -(x / scrollBarWidth) * actualWidth;
            scrollSlider.css('left', x + 'px');
            body.css('left', sx + 'px');
            //sidebar.append($('<div>' + (0.5361952954590328 * (curtain.position().left + sx)) + 'px</div>'));
            //curtain.css({ fontSize: (0.5361952954590328 * (curtain.position().left + sx)) + 'px' });
        });

        doc.mouseup(function() {
            doc.unbind();
        });
    });

    scrollLeft.mousedown(function() {
        scrollBy(60);
    });

    scrollRight.mousedown(function() {
        scrollBy(-60);
    });

    content.mousewheel(function(e, delta) {
        e.preventDefault();
        scrollBy(delta * 141);
    });

    function fitMenus() {
        $('.pages-menu').each(function() {
            var e = $(this),
                top = e.offset().top;
            if (top)
                e.css({ top: Math.round(-top / 2) + 'px' });
        });
    }

    $(window).resize(function() {
        updateScroll();
        //fitMenus();
    });

    var removeSWF = function() {
        if (swfid)
            swfobject.removeSWF(swfid);
        if (swfembedding)
            clearTimeout(swfembedding);
    }

    /* Функции для ширмы (wall), принцип работы и html-структуру см.
       в разделе Продакшн/Шоурил, Продакшн/Партнеры и т.д. */

    // Загрузка секции ширмы
    var loadSection = function(e, callback) {
        opening = true;
        var a = $(e),
            td = a.parents('td').first(),
            _td = td.get(0),
            tr = _td.parentNode,
            inner = td.children('.inner');

        if (tr.curr_a) {
            tr.curr_a.removeClass('selected');
            var curr_a = tr.curr_a.get(0);
            curr_a.opened = false;
            curr_a.href = curr_a._href;
        }

        tr.curr_a = a.addClass('selected');
        e._href = e.href;
        e.href = e.href.replace(/\/[^\/]+$/, '');
        e.opened = true;

        closeSection(tr, true, function() {
            $.get(controllerURL + e._href.substr(e._href.indexOf('#') + 1), {}, function(data) {
                 inner.html(data);
                 if ($.trim(data))
                     openSection(_td, callback);
                 else
                     opening = false;
            });
        });
    }

    // Сортировка секций ширмы
    var sortSections = function(tr) {
        var i = 1;
        $(tr).parents('.wall').find('td').each(function() {
            if (this.parentNode.className == 'open') {
                $(this).children('.head').removeClass('even').addClass((i % 2) ? '' : 'even');
                i++;
            }
        });
    }

    // Открытие секции ширмы
    var openSection = function(e, callback) {
        opening = true;

        var td = $(e),
            inner = td.children('.inner');
        if (!inner.length) {
            opening = false;
            return;
        }

        inner.css({ display: 'block' });

        var tr = e.parentNode,
            width = td.width(),
            innerWidth = inner.get(0).scrollWidth,
            currCurtainPos = getCurtainPos() - (tr.curr_td ? tr.curr_td[1].outerWidth() : 0),
            nextCurtainPos = currCurtainPos + innerWidth,
            head = td.children('.head').get(0),
            src = td.attr('onkeydown') ? td.attr('onkeydown')() : null;

        if (head.href) {
            head._href = head.href;
            head.href = head.href.replace(/\/[^\/]+$/, '');
        }

        closeSection(tr);
        e.opened = true;
        inner.find('tr').first().addClass('open');
        sortSections(tr);

        var even = src && $(head).hasClass('even');
        if (even)
            inner.addClass('even');

        inner.animate({ width: innerWidth + 'px' }, 500, function() {
            inner.css({ width: 'auto' });
            if (src)
                swfembedding = setTimeout(function() {
                    swfid = 'v' + Math.round(Math.random() * 10000);
                    inner.children('.player').append('<span id="' + swfid + '"></span>');
                    swfobject.embedSWF(playerURL, swfid, 699, 473, '9', false, { src: src[0], srcHD: src[1], info: src[2], progressbar_y: even ? 224 : 188 , close_url: head.href }, { allowfullscreen: true });
                }, 800);

            if (callback)
                callback();

            $(head).addClass('opened');
            opening = false;
        });

        moveCurtainTo(nextCurtainPos, !src ? null : function() {
            var center = inner.offset().left - getVisibleWidth() / 2 + innerWidth / 2 - getScroll();
            scrollTo(-center);
            updateScroll(null, -center);
        });

        tr.curr_td = [td, inner, width, currCurtainPos, head];
    }

    // Закрытие секции ширмы
    var closeSection = function(tr, moveCurtain, callback) {
        if (!tr.curr_td) {
            if (callback)
                callback();
            opening = false;
            return;
        }

        var curr_td = tr.curr_td,
            innerWidth = curr_td[1].outerWidth();

        curr_td[0].get(0).opened = false;
        curr_td[4].href = curr_td[4]._href;
        curr_td[1].find('tr').first().removeClass('open');
        sortSections(tr);

        removeSWF();
        if (moveCurtain)
            moveCurtainTo(getCurtainPos() - innerWidth);

        //curr_td[1].css({ maxWidth: curr_td[1].outerWidth() + 'px' });
        curr_td[1].animate({ width: '1px' }, 500, function() {
            curr_td[0].find('tr').each(function(i, tr) {
                if (tr.curr_td) {
                    tr.curr_td[4].href = tr.curr_td[4]._href;
                    tr.curr_td[1].css({ width: '1px', display: 'none' });
                    tr.curr_td[0].get(0).opened = false;
                    $(tr.curr_td[4]).removeClass('opened');
                    tr.curr_td = null;
                }
            });

            $(curr_td[4]).removeClass('opened');
            curr_td[1].removeClass('even');
            curr_td[1].css({ width: '1px', display: 'none' });

            if (callback)
                callback();
        });

        tr.curr_td = null;
    }

    /* Функции для пузырей (bubbles), принцип работы и html-структуру см.
       в разделе Режиссеры */

    // Открытие пузыря
    var openBubble = function(e) {
        opening = true;

        var dd = $(e),
            dl = dd.parent().get(0),
            set = dd.parents('.bubbles').get(0),
            inner = dd.find('.inner');
        dl.height = dl.height || dl.clientHeight;
        dl.width = dl.width || dl.clientWidth;
        var width = dd.width(),
            height = dd.height(),
            oWidth = dd.outerWidth(),
            oHeight = dd.outerHeight(),
            innerWidth = inner.outerWidth(),
            innerHeight = Math.min(set.clientHeight - dl.height, inner.outerHeight()),
            currCurtainPos = set.curr_dd ? set.curr_dd[5] : getCurtainPos(),
            nextCurtainPos = currCurtainPos - dl.width + Math.max(innerWidth, dl.width);
        dd.addClass('open');
        e.opened = true;
       // inner.css({ height: innerHeight - inner.outerHeight() + inner.height() + 'px' });

        var _height = innerHeight - inner.outerHeight() + inner.height(),
            preview = dd.find('.preview');
        if (preview.length)
            _height -= preview.outerHeight(true);

        var scrollable = dd.find('.scrollable');
        if (scrollable.length) {
            var scrollableHeight = _height - scrollable.outerHeight() + scrollable.height();
            if (l = scrollableHeight % 16) {
                scrollableHeight -= l;
                innerHeight -= l;
            }
            scrollable.css({ height: scrollableHeight  + 'px' });
            scrollable.scrollable();
        }
        closeBubble(set);
        dd.animate({ width: Math.max(width, innerWidth) + 'px', height: (height + innerHeight) + 'px' }, 500, function() {
            opening = false;
        });
        moveCurtainTo(nextCurtainPos);
        set.curr_dd = [dd, width, height, oWidth, oHeight, currCurtainPos];

    }

    // Закрытие пузыря
    var closeBubble = function(set, moveCurtain) {
        if (!set.curr_dd) {
            opening = false;
            return;
        }

        var curr_dd = set.curr_dd;
        curr_dd[0].removeClass('open');
        curr_dd[0].animate({ width: curr_dd[1] + 'px', height: curr_dd[2] + 'px' }, 500, function() {
            curr_dd[0].get(0).opened = false;
            opening = false;
        });
        if (moveCurtain)
            moveCurtainTo(curr_dd[5]);

        set.curr_dd = null;
    }

    $('#production-news').click(function(e) {
        var id = e.target.onkeydown,
            e = $(this);
        if (id) {
            $.get(controllerURL + 'production/news/' + id(), {}, function(data) {
                e.html(data);
            });
        }
    });

    $('#event-news').click(function(e) {
        var id = e.target.onkeydown,
            e = $(this);
        if (id) {
            $.get(controllerURL + 'event/news/' + id(), {}, function(data) {
                e.html(data);
            });
        }
    });

    /* Функции лайтбокса */
    var showLightBox = function(src) {
        var player = lightbox.children('.player');
        lightbox.css({ height: footer.offset().top + footer.outerHeight(true) + 'px' });
        lightbox.fadeIn();

        swfembedding = setTimeout(function() {
            swfid = 'v' + Math.round(Math.random() * 10000);
            player.append('<span id="' + swfid + '"></span>');
            swfobject.embedSWF(playerURL, swfid, 699, 473, '9', false, { src: src[0], srcHD: src[1], info: src[2], progressbar_y: 224, close_url: hash + '/close' }, { allowfullscreen: true });
        }, 800);

        player.unbind();
        player.click(function(e) {
            e.stopPropagation();
        });

        lightbox.unbind();
        lightbox.click(hideLightBox);
    }

    var hideLightBox = function() {
        removeSWF();
        lightbox.fadeOut();
    }

    /* Функции навигации по страницам */
    var loadPage = function(path, callback, method, data) {
        removeSWF();
        opening = true;
        moveCurtainTo(0, function() {
            method = method || 'get';
            $[method](controllerURL + path, data, function(data) {
                content.html(data);

                moveCurtainTo(null, function() {
                    if (callback)
                        callback();

                    opening = false;
                });
            });
        });
    }

    setInterval(function() {
        if (location.hash != hash) {
            if (opening)
                return;

            var newPath = location.hash.substr(1).replace(/(^\/+|\/+$)/g, '') || 'index';
            for (p in init)
                if (newPath.indexOf(p) == 0)
                    init[p](!path.indexOf(p), newPath.substr(p.length + 1).split('/'));

            path = newPath;
            hash = location.hash;
        }
    }, 10);

    function set(classNames) {
        _body.removeClass().addClass(classNames);
        //fitMenus();
    }

    // -----------------------------------------------------------------------

    init['index'] = function(inited, args) {
        set('_index');

        if (inited)
            return;

        var src = window.slideshowSrc,
            k = 0,
            n = 0,
            images = {},
            image,
            slideshow = $('#slideshow'),
            timeout = null;

        var showImage = function(tag) {
            clearTimeout(timeout);
            var curr = slideshow.children('img'),
                neue = images[tag].shift();
            images[tag].push(neue);

            if (curr.length) {
                curr.css('zIndex', '4');
                neue.css('zIndex', '1').appendTo(slideshow);
                curr.fadeOut(1000, function() {
                    hideImage(curr);
                    timeout = setTimeout(function() {
                        showImage(tag);
                    }, 1000);
                });
            } else {
                neue.fadeOut(0).appendTo(slideshow);
                neue.fadeIn(1000, function() {
                    timeout = setTimeout(function() {
                        showImage(tag);
                    }, 1000);
                });
            }

            var w = neue.width(),
                h = neue.height(),
                sw = slideshow.width(),
                sh = slideshow.height();

            if ((w / h) > (sw / sh))
                neue.css({'width': 'auto', 'height': '100%'});
        }

        var hideImage = function(image) {
            clearTimeout(timeout);
            (image || slideshow.children('img')).remove().fadeIn(0);
        }

        var imageLoaded = function() {
            images[this._tag].push($(this));
            if (!--n) {
                loadPage('index', function() {
                    set('_index _slideshow _slideshow_off');

                    var hide = function() {
                        set('_index _slideshow _slideshow_off');
                        hideImage();
                    };

                    $('#index a.production').mouseenter(function() {
                        set('_index _slideshow _slideshow_on');
                        showImage('production');
                    }).tooltip();

                    $('#index a.production').mouseleave(hide).mousedown(function() {
                        $(this).unbind();
                        hide();
                    });

                    $('#index a.event').mouseenter(function() {
                        set('_index _slideshow _slideshow_on');
                        showImage('event');
                    }).tooltip();

                    $('#index a.event').mouseleave(hide).mousedown(function() {
                        $(this).unbind();
                        hide();
                    });
                });
            }
        }

        for (i in src) {
            images[i] = [];
            n += k = src[i].length;
            while (k--) {
                image = document.createElement('IMG');
                image.src = src[i][k];
                image.onload = imageLoaded;
                image._tag = i;
            }
        }
    }

    init['production'] = function(inited, args) {
        set('_production');
    }

    init['production/showreel'] = function(inited, args) {
        set('_production _showreel');

        if (!inited) {
            return loadPage('production/showreel', function() {
                init['production/showreel'](true, args);
                var timepoint = $('#timepoint'),
                    setTimepoint = function() {
                        timepoint.stop();
                        var head = $(this);
                        if (head.hasClass('opened'))
                            timepoint.hide();
                        else {
                            timepoint.show();
                            timepoint.animate({ left: (head.offset().left + 54 - content.offset().left) + 'px' }, 100);
                        }
                    };

                content.find('#showreel td .head').mouseover(setTimepoint);
            });
        }

        var timepoint = $('#timepoint');
        if (args[0]) {
            section = document.getElementById(':' + args[0]);
            if (section) {
                if (section.opened) {
                    if (args[1]) {
                        section = document.getElementById(':' + args[0] + args[1]);
                        if (section && !section.opened) {
                            openSection(section);
                            timepoint.hide();
                        }
                    } else
                        closeSection($(section).find('tr').get(0), true);
                } else {
                    $('#productionMenu li.curr a').html('<span>' + (section.title || '') + '</span>');
                    timepoint.hide();
                    openSection(section, function() {
                        if (args[1]) {
                            section = document.getElementById(':' + args[0] + args[1]);
                            if (section && !section.opened)
                                openSection(section);
                        }
                    });
                }
            }
        } else {
            closeSection($('#showreel tr').get(0), true);
            $('#productionMenu li.curr a').html('');
        }
    }

    init['production/directors'] = function(inited, args) {
        set('_production _directors');
        if (!inited) {
            return loadPage('production/directors', function() {
                init['production/directors'](true, args);
                $('#directors .preview ul').scrollList();
                $('#directors .preview li').click(function() {
                    if (this.onkeydown)
                        showLightBox(this.onkeydown());
                }).tooltip();
            });
        }

        if (args[0]) {
            bubble = document.getElementById(':directors' + args[0]);
            if (bubble && !bubble.opened)
                openBubble(bubble);

            if (args[1] && args[1] == 'close') {
                hash = location.hash = hash.replace('/close', '');
                hideLightBox();
            }
        } else {
            closeBubble($('#directors').get(0), true);
        }
    }

    init['production/partners'] = function(inited, args) {
        set('_production _partners');
        if (!inited) {
            return loadPage('production/partners', function() {
                init['production/partners'](true, args);
                $('#partners ul').scrollList();
            });
        }

        if (args[0] && args[1]) {
            a = document.getElementById(':' + args[0] + ':' + args[1]);
            if (a) {
                if (a.opened) {
                    if (args[2]) {
                        section = document.getElementById(':' + args[0] + ':' + args[1] + ':' + args[2]);
                        if (section && !section.opened)
                            openSection(section);
                    } else
                        closeSection($(a).parents('td').find('tr').get(0), true);
                } else {
                    loadSection(a, function() {
                        if (args[2]) {
                            section = document.getElementById(':' + args[0] + ':' + args[1] + ':' + args[2]);
                            if (section && !section.opened)
                                openSection(section);
                        }
                    });
                }
            }
        } else {
            var a = $('#partners a.selected');
            if (a.length) {
                a.removeClass('selected');
                a.attr('href', a.get(0)._href);
                a.get(0).opened = false;
            }
            closeSection($('#partners tr').get(0), true);
        }
    }

    init['production/news'] = function(inited, args) {
        set('_production _news');
        if (!inited)
            return loadPage('production/news', function() {
                $('#news ul').scrollList();
                init['production/news'](true, args);
            });

        var list = $('#news ul'),
            entry = $('#news .entry');

        if (args[0]) {
            opening = true;
            $.get(controllerURL + 'production/news/' + args[0], null, function(data) {
                if ($.trim(data)) {
                    entry.html(data);
                    list.fadeOut(function() {
                        list.parent().addClass('opened');
                        entry.fadeIn(function() {
                            entry.children('.scrollable').scrollable();
                            opening = false;
                        });
                    });
                }
            });
        } else {
            opening = true;
            entry.fadeOut(function() {
                list.fadeIn(function() {
                    list.parent().removeClass('opened');
                    opening = false;
                });
            });
        }
    }

    init['production/about'] = function(inited, args) {
        set('_production _about');
        if (!inited)
            return loadPage('production/about', function() {
                $('#about div.container').scrollable();
            });
    }

    init['production/service'] = function(inited, args) {
        set('_production _service');
        if (!inited) {
            return loadPage('production/service', function() {
                init['production/service'](true, args);
            });
        }

        if (args[0]) {
            bubble = document.getElementById(':' + args[0]);
            if (bubble && !bubble.opened)
                openBubble(bubble);
        } else {
            closeBubble($('#service').get(0), true);
        }
    }

    init['production/feedback'] = function(inited, args) {
        if (!inited)
            return loadPage('production/feedback', function() {
                init['production/feedback'](true, args);
                set('_production _feedback');
            });
        else
            set('_production _feedback');

        $('#feedback').submit(function() {
            set('_production');
            loadPage('production/feedback', function() {
                init['production/feedback'](true, args);
            }, 'post', $(this).serialize());
        });
    }

    init['event'] = function() {
        set('_event');
    }

    init['event/video'] = function(inited, args) {
        set('_event _video');
        if (!inited) {
            return loadPage('event/video', function() {
                init['event/video'](true, args);
                var timepoint = $('#timepoint'),
                    setTimepoint = function() {
                        timepoint.stop();
                        var head = $(this);
                        if (head.hasClass('opened'))
                            timepoint.hide();
                        else {
                            timepoint.show();
                            timepoint.animate({ left: (head.offset().left + 54 - content.offset().left) + 'px' }, 100);
                        }
                    };

                content.find('#video td .head').mouseover(setTimepoint);
            });
        }

        var timepoint = $('#timepoint');
        if (args[0]) {
            section = document.getElementById(':' + args[0]);
            if (section) {
                if (section.opened) {
                    if (args[1]) {
                        section = document.getElementById(':' + args[0] + args[1]);
                        if (section && !section.opened) {
                            openSection(section);
                            timepoint.hide();
                        }
                    } else
                        closeSection($(section).find('tr').get(0), true);
                } else {
                    $('#eventMenu li.curr a').html('<span>' + (section.title || '') + '</span>');
                    timepoint.hide();
                    openSection(section, function() {
                        if (args[1]) {
                            section = document.getElementById(':' + args[0] + args[1]);
                            if (section && !section.opened)
                                openSection(section);
                        }
                    });
                }
            }
        } else {
            closeSection($('#video tr').get(0), true);
            $('#eventMenu li.curr a').html('');
        }
    }

    init['event/photo'] = function(inited, args) {
        set('_event _photo');
        if (!inited) {
            return loadPage('event/photo', function() {
                init['event/photo'](true, args);
                $('#photo ul').scrollList();
            });
        }

        if (args[0]) {
            a = document.getElementById(':' + args[0]);
            if (a && !a.opened) {
                loadSection(a, function() {
                    $('#photo .container').scrollable();
                });
            }
        } else {
            var a = $('#photo a.selected');
            if (a.length) {
                a.removeClass('selected');
                a.attr('href', a.get(0)._href);
                a.get(0).opened = false;
            }
            closeSection($('#photo tr').get(0), true);
        }
    }

    init['event/pricelist'] = function(inited, args) {
        set('_event _pricelist');
        if (!inited) {
            return loadPage('event/pricelist', function() {
                init['event/pricelist'](true, args);
            });
        }

        if (args[0]) {
            bubble = document.getElementById(':' + args[0]);
            if (bubble && !bubble.opened)
                openBubble(bubble);
        } else {
            closeBubble($('#pricelist').get(0), true);
        }
    }

    init['event/news'] = function(inited, args) {
        set('_event _news');
        if (!inited)
            return loadPage('event/news', function() {
                $('#news ul').scrollList();
                init['event/news'](true, args);
            });

        var list = $('#news ul'),
            entry = $('#news .entry');

        if (args[0]) {
            opening = true;
            $.get(controllerURL + 'event/news/' + args[0], null, function(data) {
                if ($.trim(data)) {
                    entry.html(data);
                    list.fadeOut(function() {
                        list.parent().addClass('opened');
                        entry.fadeIn(function() {
                            entry.children('.scrollable').scrollable();
                            opening = false;
                        });
                    });
                }
            });
        } else {
            opening = true;
            entry.fadeOut(function() {
                list.fadeIn(function() {
                    list.parent().removeClass('opened');
                    opening = false;
                });
            });
        }
    }

    init['event/about'] = function(inited, args) {
        set('_event _about');
        if (!inited)
            return loadPage('event/about', function() {
                $('#about div.container').scrollable();
            });
    }

    init['event/feedback'] = function(inited, args) {
        if (!inited)
            return loadPage('event/feedback', function() {
                init['event/feedback'](true, args);
                set('_event _feedback');
            });
        else
            set('_event _feedback');

        $('#feedback').submit(function() {
            set('_event');
            loadPage('event/feedback', function() {
                init['event/feedback'](true, args);
            }, 'post', $(this).serialize());
        });
    }
};

$(document).ready(init);

function switchLang(lang) {
    location.href = location.protocol + '//' + location.host + '/' + lang + location.hash;
    return false;
}
