var ReportViewerPageMap = {
    '25': '26',
    '27': '28',
    '32': '33',
    '62': '63',
    '64': '65'
};

Element.implement({
    setClass: function(klass, enabled){
        return this[enabled ? "addClass" : "removeClass"](klass);
    },

    shim: function(options){
        options = $merge({
            'delay': 700,
            'styles':{
                'position': 'absolute',
                'left': 0,
                'top': 0,
                'right': 0,
                'bottom': 0,
                'background': '#fff',
                'opacity': .6,
                'z-index': 1000
            }
        }, options);
        var shim = this.retrieve('shim'),
            timer = this.retrieve('shimtimer');
        if (shim && shim.getParent() != this){
            shim.destroy();
            shim = null;
        }
        if (timer !== null){
            $clear(timer);
            if (shim)
                shim.destroy();
            shim = null;
        }
        if (!shim){
            if (this.getStyle('position') == 'static')
                this.setStyle('position', 'relative');
            shim = new Element('div',{
                'text': '',
                'styles':options.styles
            });
            timer = (function(){
                this.eliminate('shimtimer');
                shim.injectTop(this);
            }).delay(options.delay, this);
            this.store('shimtimer', timer).store('shim', shim);
        }
        return shim;
    },

    unshim: function(){
        var shim = this.retrieve('shim');
        $clear(this.retrieve('shimtimer'));
        if (shim && shim.getParent() != this){
            shim.destroy();
            this.eliminate('shim').eliminate('shimtimer');
        }
        return this;
    },

    shadowHint: function(options){
        options = $merge({
            'hint': this.get('title'),
            'class': 'shadow-hint'
        }, options);
        this.store('ShadowHintClass', options['class'])
        this.defaultValue = options.hint;
        this.addClass(this.retrieve('ShadowHintClass')).addEvents({
            'blur': function(){
                if (this.value == ''){
                    this.value = this.defaultValue;
                    this.addClass(this.retrieve('ShadowHintClass'));
                }
            },
            'focus': function(){
                if (this.value == this.defaultValue)
                    this.value = '';
                this.removeClass(this.retrieve('ShadowHintClass'));
            }
        });
        return this;
    }
});

function uniqid(){
    var x=0;
    return function(){
        return String(Math.floor(Math.random()*10000)) + '.' + (x++);
    }();
}

window.addEvent('domready',function(){
    Growl.Smoke = new Gr0wl.Smoke(ReportViewerOptions.relPrefix + 'css/images/smoke.png');
    Growl.Bezel = new Gr0wl.Bezel(ReportViewerOptions.relPrefix + 'css/images/bezel.png');
});


var ReportViewer = new Class({

    Implements: [Options, Events, Chain],

    options: {
        relPrefix: '', // can be set to '../'
        selectedClass: 'selected',
        callbackFn: $empty,
        zoom: null,
        page: null,
        numPages: null
    },

    initialize: function(page_el, menu_el, tools_el, crumbs_el, options){
        var self = this;
        this.setOptions(options);

        this.link = this.options.link; // default link options
        this.baseZoom = this.link.zoom;

        this.content = $(page_el);
        this.menu = $(menu_el);
        this.tools = $(tools_el);
        this.crumbs = $(crumbs_el);

        this.menuitems = new Hash();

        this.bound = {
            loadPage: function(ev){
                ev.stop();
                var el = $(ev.target);
                if (el.get('tag') != 'a')
                    el = el.getParent('a');
                this.load(this.parseLink(el.get('href')));
            }.bind(this),

            scrollTop: function(ev){
                ev.stop();
                new Fx.Scroll(document.body).toTop();
            },

            clickMenu: function(ev){
                ev.stop();
                var el = $(ev.target);
                if (el.get('tag') == 'img'){
                    this.openMenu(el.getParent('a').retrieve('link').page);
                } else {
                    this.load(this.parseLink(el.get('href')));
                }
            }.bind(this),

            emailPage: function(ev){
                ev.stop();
                var el = $(ev.target);
                if (el.get('tag') != 'a')
                    el = el.getParent('a');
                if (!el.hasClass('disabled')){
                    this.load(this.parseLink(el.get('href')));
                }
            }.bind(this),

            attachPrintBasket: this.attachPrintBasket.bind(this),

            printAll: function(ev){
                ev.stop();
                window.open($(ev.target).href);
            },

            attachEmailForm: function(){
                var content = this.content;
                this.content.getElement('form').addEvent('submit', function(ev){
                    ev.stop();
                    var form = this,
                        data = "ajax=1&" + this.toQueryString();
                    new Request.JSON({
                        method: 'post',
                        data: data,
                        url: this.get('action'),
                        onSuccess: function(data){
                            data = data || {};
                            self.formError(form, data.errors);
                            if (data.errors && data.errors.code){
                                Asset.image(self.options.relPrefix + 'securimage?sid=' + uniqid(), {
                                    'class': 'code'
                                }).replaces(form.getElement('img.code'));
                                $(form.elements['code']).set('value', '');
                            }
                            if (!data.errors && data.message){
                                self.message(data.message);
                                if (data.back)
                                    data.back = self.parseLink(data.back);
                                self.load($pick(data.back, 'index'));
                            }
                        }
                    }).send();
                });
                var el = this.content.getElement('form input[type!="hidden"], form textarea');
                if (el)
                    el.focus();
            }.bind(this),

            attachSearchForm: function(){
                this.content.getElements('a[href]').addEvent('click', this.bound.loadPage);
            }.bind(this),

            attachFeedbackForm: function(){
                var content = this.content;
                this.content.getElement('form').addEvent('submit', function(ev){
                    ev.stop();
                    var form = this,
                        data = "ajax=1&" + this.toQueryString();
                    new Request.JSON({
                        method: 'post',
                        data: data,
                        url: this.get('action'),
                        onSuccess: function(data){
                            data = data || {};
                            self.formError(form, data.errors);
                            if (!data.errors && data.message){
                                self.load(self.parseLink(data.back), {'scroll': false}).chain(function(){
                                    $(document.body).scrollTo($(document.body).getScroll().x, 0);
                                    self.message(data.message);
                                });
                            }
                        }
                    }).send();
                });
                var el = this.content.getElement('form input[type!="hidden"], form textarea');
                if (el)
                    el.focus();
            }.bind(this)
        };

        $$('#logo, #home2').addEvent('click', this.bound.loadPage);

        this.makeMenu();
        this.makeToolbar();

        this.updateUI();

        this.hm = {
            page: HistoryManager.register("page", [this.link.page],
                function(values){
                    var is_page = String(values[0]).match(/^\d+$/),
                        page = values[0],
                        query = values[2],
                        reload;
                    if (is_page)
                        page = parseInt(page, 10);
                    query = query ? Base64.decode(query) : null;
                    reload = (String(self.link.page) != String(page) || self.link.query != query);
                    self.init_page(reload);
                    if (reload)
                        self.load({'page': page, 'type': is_page ? 'page' : 'special', 'query': query});
                },
                function(values){
                    var result = 'page' + values[0];
                    if (values[2])
                        result += '-' + Base64.encode(values[2]);
                    return result;
                },
                'page([^-;]*)(-([^;]*))?'
            ),
            zoom: HistoryManager.register("zoom", [this.link.zoom],
                function(values){
                    var zoom = parseInt(values[0], 10);
                    if (String(self.link.zoom) != String(zoom) || (!self.link.zoom && zoom == self.baseZoom)){
                        self.zoom(zoom);
                    }
                },
                function(values){
                    return 'zoom'+values[0];
                },
                'zoom(\\d+)'
            )
        };

        // preload styles
        [80, 100, 120].each(function(zoom){
            if (zoom != this.baseZoom)
                new Asset.css(this.options.relPrefix + 'zoom' + zoom + '/style', {'id': 'zoomstyle' + zoom}).set('disabled', true);
        }, this);

        this.options.callbackFn.call(this);
    },

    init_page: function(reload){
        if (reload){
            this.content.set('html', '');
        } else {
            this.processLoad();
        }
        this.content.setStyle('visibility', 'visible');
        this.init_page = $empty;
    },

    attachPrintBasket: function(){
        var self = this;
        if (this.content.getElement('table')){
            this.content.getElement('.actions a:first-child').addEvent('click', this.bound.emailPage);
            this.content.getElements('.actions a')[1].addEvent('click', this.bound.printAll);
            this.content.getElements('table tbody tr').each(function(tr){
                var links = tr.getElements('a'),
                    link = this.parseLink(links[0].get('href'));
                links[0].addEvent('click', this.bound.loadPage);
                links[1].addEvent('click', this.bound.emailPage);
                links[3].addEvent('click', function(ev){
                    ev.stop();
                    new Request.JSON({
                        method: 'get',
                        data: {'ajax': 1, 'p': link.page},
                        url: 'printbasket/del',
                        onSuccess: function(data){
                            if (data){
                                var size = data ? ' (' + data.size + ')' : '';
                                $('viewbasket').getElement('span').set('text', 'view basket' + size);
                                tr.destroy();
                                /*if (tr.getParent()){
                                    new Fx.Tween(tr, {'duration': 250}).chain(function(){
                                        tr.destroy();
                                    }).start('height', tr.getHeight(), 0);
                                }*/
                                self.content.getElements('table tbody td:first-child').each(function(el, ind){
                                    el.set('text', String(ind+1));
                                });
                            } else {
                                alert('Error occured.\nPlease reload the page and try again.');
                            }
                        }
                    }).send();
                });
            }, this);
        }
        return this;
    },

    message: function(message, type, options){
        type = $pick(type, 'info');
        options = $merge({
            'duration': 7,
            'image': this.options.relPrefix + 'css/images/'+((type == "error") ? 'error' : 'info')+'.png',
            'title': (type == "error") ? "Error:" : "Information:",
            'text': message
        }, options);
        Growl.Bezel(options);
        return this;
    },

    formError: function(form, errors, options){
        options = $merge({
            'key': 'error-message',
            'className': 'error-message',
            'starSelector': 'input[type="submit"]'
        }, options);
        form.getElements('span.' + options.className).setStyle('display', 'none');
        $each(errors || {}, function(value, key){
            var el = (key == '*') ? form.getElement(options.starSelector) : $(form.elements[key]),
                msg = el.retrieve(options.key),
                label;
            if (el.id)
                label = form.getElement('label[for="' + el.id + '"]');
            if (!msg){
                msg = new Element('span', {'class': options.className});
                if (label)
                    label.adopt(msg);
                else
                    msg.injectAfter(el);
                el.store(options.key, msg);
                el.focus();
            }
            msg.setStyle('display', '').set('html', value);
        }, this);
    },

    parseLink: function(link){
        var result = {}, tmp;
        link = link.split('/');
        result.page = link.pop();
        result.zoom = link.pop();

        tmp = result.page.split('?', 2);
        result.page = tmp[0];
        result.query = tmp[1];

        //result.accessible = link.pop() == 'accessible';
        if (result.zoom){
            if (result.zoom == 'pdf'){
                result.zoom = null;
                result.page = this.options.relPrefix + 'pdf/' + result.page;
                result.type = 'pdf';
            } else if (result.zoom == 'printbasket'){
                result.zoom = null;
                result.page = 'printbasket/' + result.page;
            } else {
                var m = result.zoom.match(/zoom([0-9]+)/);
                result.zoom = parseInt(m ? m[1] : 100, 10);
            }
        }
        if (!result.type){
            if (result.page){
                tmp = result.page.match(/page([0-9]+)/);
                if (tmp){
                    result.page = parseInt(tmp[1], 10);
                    result.type = 'page';
                } else {
                    result.type = 'special';
                }
            } else {
                result.type = 'unknown';
            }
        }
        return result;
    },

    makeURL: function(link){
        var args = [];
        if (link.zoom && link.zoom != this.baseZoom){
            args.push( this.options.relPrefix + 'zoom' + link.zoom );
        }
        args.push( (link.type == 'page') ? 'page' + link.page : link.page );
        args = args.join('/');
        if (link.query)
            args += '?' + link.query;
        return args;
    },

    makeMenu: function(){
        var prefix = this.options.relPrefix + 'css/images/treg_';
        this.bullets = {
            regular:{
                closed: Asset.image(prefix+'b.gif'),
                open: Asset.image(prefix+'bt.gif')
            },
            selected:{
                closed: Asset.image(prefix+'r.gif'),
                open: Asset.image(prefix+'rt.gif')
            }
        };
        this.menu.getElements('a').each(function(el){
            var link = this.parseLink(el.get('href'));
            el.addEvent('click', this.bound.clickMenu);
            el.store('link', link).store('open', false);
            el.getParent('li').removeClass('open');
            this.menuitems[link.page] = el;
        }, this);
        //this.menu.getElements('li').removeClass('open');
        return this;
    },

    openMenu: function(page, selected, force){
        var el = this.menuitems[page],
            menu = el.getNext('ul'),
            open;
        selected = selected || this.link.page == page;
        if (menu){
            open = force || (menu.getStyle('display') != 'block');
            if (menu.id != 'mainmenu'){
                menu.setStyle('display', open ? 'block' : 'none');
                el.setClass('selected', selected);
                el.getElement('img').store('open', open).set('src', this.bullets[selected ? 'selected' : 'regular'][open ? 'open' : 'closed'].get('src'));
                el.getParent('li').setClass('open', open);
            }
        }
    },

    updateMenu: function(){
        var selected = this.options.selectedClass,
            el, ul, a;
        this.menu.getElements('a img').each(function(el){
            el.set('src', this.bullets.regular[el.retrieve('open') ? 'open' : 'closed'].get('src'));
        }, this);
        this.menu.getElements('.' + selected).removeClass(selected);
        if (this.link.type == 'page'){
            el = this.menuitems[this.link.page];
            if (el){
                el.addClass(selected);
                ul = el;
                while((ul=ul.getParent('ul'))){
                    if (ul.id == 'mainmenu')
                        break;
                    ul.setStyle('display', 'block');
                    a = ul.getPrevious('a');
                    if (a){
                        a.getParent('li').setClass('open', open);
                        a = a.getElement('img');
                        if (a) a.store('open', open).set('src', this.bullets.regular.open.get('src'));
                    }
                }
                el = el.getElement('img');
                if (el){
                    el.set('src', this.bullets.selected[el.retrieve('open') ? 'open' : 'closed'].get('src'));
                }
            }

            this.menu.getChildren('li').each(function(li){
                var menus = li.getChildren('ul');
                if (!menus.length || li.getElement('a.selected'))
                    return;
                menus.setStyle('display', 'none');
                li.getElement('a img').store('open', false).set('src', this.bullets.regular.closed.get('src'));
            }, this);
        }
        return this;
    },

    updateToolbar: function(){
        if (this.tools){
            this.tools.getElements('a.disabled').removeClass('disabled');
            if (this.link.type == 'special'){
                $$('#addbasket, #emailtofriend, #printpage').addClass('disabled');
            } else {
                $('emailtofriend').set('href', 'email?pages=' + this.link.page + '&back=page' + this.link.page);
            }
        }
        //~ $('feed').set('href', 'feedback?back=' + encodeURIComponent(this.makeURL(this.link)));
        return this;
    },

    specialTitle: function(page){
        if (page == 'email')
            return "Email page to friend";
        if (page == "printbasket")
            return "Print basket";
        if (page == "index")
            return "";
        return page.replace('_', ' ').replace(/^[a-z]/, function(match){
            return match.toUpperCase();
        });
    },

    updateCrumbs: function(){
        var el, links = [];
        this.crumbs.empty();
        if (this.link.page == 'index'){
            this.crumbs.set('html', '&nbsp;');
            return this;
        }
        if (this.link.type == 'special'){
            links.push([this.link, this.specialTitle(this.link.page)]);
        } else {
            el = this.menuitems[this.link.page];
            while (el){
                links.push([el.retrieve('link'), el.get('text').trim(), el.get('title')]);
                el = el.getParent('ul');
                if (el)
                    el = el.getPrevious();
            }
        }
        links.push([{'page': 'index', 'type': 'special'}, "Home"]);
        links = links.reverse();

        var last = links.pop();
        links.each(function(link){
            new Element('a', {
                'href': this.makeURL(link[0]),
                'title': link[2],
                'html': link[1]
            }).addEvent('click', this.bound.loadPage).inject(this.crumbs);
            new Element('span', {'html': '&nbsp;&nbsp;|&nbsp;&nbsp;'}).inject(this.crumbs)
        }, this);
        new Element('span', {
            'title': last[2],
            'html': last[1]
        }).inject(this.crumbs);
        return this;
    },

    makeToolbar: function(){
        var self = this;
        if (this.tools){
            this.related = this.tools.getElement('dl.related');
            if (!this.related)
                this.related = new Element('dl', {'class': 'related'}).adopt(
                    new Element('dt').set('html', 'Related links and downloads'),
                    new Element('dd').set('html', '')
                ).setStyle('display', 'none').injectTop(this.tools);

            this.downloads = this.tools.getElement('dl.downloads');
            if (!this.downloads)
                this.downloads = new Element('dl', {'class': 'downloads'}).adopt(
                    new Element('dt').set('html', 'Downloads'),
                    new Element('dd').set('html', '')
                ).setStyle('display', 'none').injectTop(this.tools);

            this.banner = this.tools.getElement('div.banner');
            if (!this.banner)
                this.banner = new Element('div', {
                    'class': 'banner',
                    'html': ''
                }).setStyle('display', 'none').inject(this.tools);

            var open = Cookie.read('RVToolOpen'),
                togglers = this.tools.getElements('dl>dt'),
                containers = this.tools.getElements('dl>dd');
            if (open)
                open = togglers.indexOf(this.tools.getElement('dl.' + open + '>dt'));

            this.toolAccordion = new Accordion(this.tools, togglers, containers, {
                display: false,
                duration: 250,
                show: open,
                alwaysHide: true,
                opacity: false,
                onActive: function(toggler, element){
                    Cookie.write('RVToolOpen', toggler.getParent().get('class'));
                },
                onBackground: function(toggler, element){
                    if (Cookie.read('RVToolOpen') == toggler.getParent().get('class'))
                        Cookie.dispose('RVToolOpen');
                }
            });
            this.tools.getElements('dl').setStyle('visibility', 'visible');

            this.tools.getElements('div.tools a').addEvent('click', function(ev){
                ev.stop();
                self.load(self.parseLink(this.get('href')));
            });
        }
        $('printpage').addEvent('click', function(ev){
            if (!this.hasClass('disabled'))
                window.print();
            return false;
        });
        $('addbasket').addEvent('click', function(ev){
            ev.stop();
            if (!this.hasClass('disabled')){
                new Request.JSON({
                    method: 'get',
                    data: {'ajax': 1, 'p': self.link.page},
                    url: 'printbasket/add',
                    onSuccess: function(data){
                        var size = data ? ' (' + data.size + ')' : '';
                        $('viewbasket').getElement('span').set('text', 'view basket' + size);
                    }
                }).send();
            }
        });
        $('emailtofriend').addEvent('click', this.bound.emailPage);
        $('viewbasket').addEvent('click', function(ev){
            ev.stop();
            if (!this.hasClass('disabled')){
                self.load({
                    'query': null,
                    'page': 'printbasket',
                    'type': 'special'
                });
            }
        });
        $$('#footer .links a').addEvent('click', this.bound.loadPage);
        $('feed').addEvent('click', function(ev){
            ev.stop();
            self.load(self.parseLink(this.get('href')));
        });
        $($('search').elements['q']).shadowHint({'hint': 'Search'});
        $('search').addEvent('submit', function(ev){
            ev.stop();
            self.load({
                'page': 'search',
                'type': 'special',
                'query': this.toQueryString()
            });
        });
        $$('#footer .size a').addEvent('click', function(ev){
            ev.stop();
            var link = self.parseLink($(ev.target).get('href'));
            self.zoom(link.zoom);
        });
        return this;
    },

    updateUI: function(){
        this.updateMenu();
        this.updateToolbar();
        this.updateCrumbs();
        return this;
    },

    zoom: function(zoom){
        if (this.link.zoom != zoom){
            if (this.loading){
                // postpone zoom after page loaded/failed
                return this.chain(this.zoom.bind(this, zoom));
            }
            this.link.zoom = zoom;
            if (this.hm)
                this.hm.zoom.setValue(0, zoom);
            // or in order to use page post-processing:
            //~ self.load({
                //~ 'zoom': zoom
            //~ });

            // update stylesheet
            var updated = false;
            $$('link[id^=zoomstyle]').each(function(style){
                if (style.id == 'zoomstyle' + this.link.zoom){
                    style.set('disabled', false);
                    updated = true;
                } else {
                    style.set('disabled', true);
                }
            }, this);

            if (!updated){
                new Asset.css(this.options.relPrefix + 'zoom' + this.link.zoom + '/style', {'id': 'zoomstyle' + this.link.zoom});
            }

            // update size of accordion active container
            this.tools.getElements('dl>dd').each(function(dd){
                var ddclone;
                if (dd.offsetHeight > 0){
                    ddclone = dd.clone(true);
                    ddclone.setStyles({
                        'height': 0,
                        'visibility': 'hidden',
                        'position': 'absolute',
                        'left': -1000,
                        'top': -1000
                    }).injectBottom(dd.getParent());
                    (function(){
                        dd.setStyle('height', ddclone.scrollHeight);
                        ddclone.destroy();
                    }).delay(300);
                }
            }, this);
        }
        return this;
    },

    load: function(link, options){
        var self = this;

        if (link.type == 'pdf'){
            window.open(link.page);
            return this;
        }

        if (this.loading){
            this.loading.cancel();
        }

        var shim = this.content.shim();

        options = $merge({
            scroll: true,
            onSuccess: $empty,
            onFailure: $empty
        }, options);
        link = $merge(this.link, link);

        if (ReportViewerPageMap[String(link.page)])
            link.page = ReportViewerPageMap[String(link.page)];

        var menu = this.menuitems[link.page];
        if (menu){
            menu = menu.getNext('ul');
            if (menu && menu.getStyle('display') == 'none'){
                this.openMenu(link.page, true);
            }
        }

        this.loading = new Request.HTML({
            method: 'get',
            data: {'ajax': 1},
            url: this.makeURL(link),
            evalScripts: true,
            update: this.content,
            onSuccess: function(tree, elements, html){
                self.content.unshim();
                var data = JSON.decode(this.xhr.getResponseHeader('X-JSON')) || {};

                self.fireEvent('load', [data]);
                options.onSuccess.call(self, data);
                self.options.callbackFn.call(self, data);
                self.loading = null;

                self.link.query = null;
                self.link = $merge(self.link, link);
                //self.hm.zoom.setValue(0, $pick(self.link.zoom, self.baseZoom));
                self.hm.page.setValues([self.link.page, null, self.link.query]);

                self.callChain();

                //self.content.empty();
                var newclass = 'col1 ' + data.contentclass;
                if (newclass != self.content.className)
                    self.content.className = newclass;
                var newid = 'rv-content' + (data.special ? '-special' : '');
                if (newid != self.content.id)
                    self.content.id = newid;
                $('colmask').className = 'colmask ' + data.columnclass;
                self.updateUI();
                //self.content.set('html', html);

                if (options.scroll){
                    new Fx.Scroll(document.body).toTop();
                }

                self.downloads.setStyle('display', data.downloads ? 'block' : 'none');
                if (data.downloads){
                    var dd = self.downloads.getElement('dd');
                    dd.setStyle('height', 0).set('html', data.downloads);
                    if (self.toolAccordion.previous == 0){
                        dd.setStyle('height', dd.scrollHeight);
                    }
                }

                self.related.setStyle('display', data.related ? 'block' : 'none');
                if (data.related){
                    var dd = self.related.getElement('dd');
                    dd.setStyle('height', 0).set('html', data.related);
                    if (self.toolAccordion.previous == 1){
                        dd.setStyle('height', dd.scrollHeight);
                    }
                }

                if (data.banner)
                    self.banner.set('html', data.banner);
                self.banner.setStyle('display', data.banner ? 'block' : 'none');

                self.processLoad();
            },
            onFailure: function(){
                self.content.unshim();
                options.onFailure.call(self);
                self.fireEvent('failure');
                self.loading = null;
                self.callChain();
            }
        }).send();
        return this;
    },

    processLoad: function(){
        switch(this.link.page){
            case 'email':
                this.bound.attachEmailForm();
                break;
            case 'printbasket':
                this.bound.attachPrintBasket();
                break;
            case 'feedback':
                this.bound.attachFeedbackForm();
                break;
            case 'search':
                this.bound.attachSearchForm();
                break;
        }
        this.content.getElements('a.linktotop').addEvent('click', this.bound.scrollTop);
        this.content.getElements('a.pagelink').addEvent('click', this.bound.loadPage);
        this.related.getElements('a.pagelink').addEvent('click', this.bound.loadPage);
    }

});


var reportViewer, ReportViewerOptions={};

window.addEvent('domready', function(){
    /*if (Browser.Engines.trident() == 4){
        $$('.col2 ul.menu li ul').setStyle('display', 'block');
        $pick($('rv-content'), $('rv-content-special')).setStyle('visibility', 'visible');
        return;
    }*/

    HistoryManager.initialize({stateSeparator: ':'});
    reportViewer = new ReportViewer($pick($('rv-content'), $('rv-content-special')), $('mainmenu'), $('tools'), $('header').getElement('div.crumbs'), ReportViewerOptions);
    HistoryManager.start();

    if (reportViewer.link.zoom == reportViewer.baseZoom && window.getWidth() < 1190){
        reportViewer.zoom(80);
    }

/*
    window.RemoveHighlight = function(){
        return $$("span.highlight").each(function(el){
            el.parentNode.replaceChild(el.firstChild, el).normalize();
        });
    };
*/

});
