// XXX - Ugly override of Request.HTML

Class.refactor(Request.HTML, {
    success: function(text) {
        var options = this.options;
        var match = text.match(/<title[^>]*>([\s\S]*?)<\/title>/i);
        var title = (match) ? match[1] : null;

        match = text.match(/<body[^>]*>([\s\S]*?)<\/body>/i);
        var html = match[1];
        if (options.basedir) {
            html = html.replace(/ src="images\//g, ' src="'+options.basedir+'images/');
        }
        if (options.dummify) {
            html = html.replace(/ src="([^"]*)images\//g, ' src="$1images/dummy.png#');
        }
        if (match && options.update) document.id(options.update).empty().removeClass('mySpinner').set('html', html);

        this.onSuccess(title);
    }
});

// constants
var arenaWidth = 960,
    topArea = 100,
    underTop = 139,
    leftArea = 225,
    topWidth = 1168,
    maxFloat = 680,
    winSize = {x: 0, y: 0},
    openPos = {x: 0, y: 0};

var iFrameIdx = 0;

function href_type(href) {
    if (href == '/#') return 'internal';
    if (href == 'bag.html') return 'buy';
    if (href.substr(0,3) != '/#!') {
        if (/\.swf$/.test(href)) return 'swf';
        return 'external';
    }
    var match = /^\/#!(\w+)%7C/i.exec(href);
    if (match) return match[1];
    return 'ajax';
}

function ajax_href(href, height) {
    if (href.substr(0,3) != '/#!') return href;
    var initial = '/index.html?';
    if (height) initial += 'height=' + height + '&';
    return initial + '_escaped_fragment_=' + href.substr(3).replace(/^(\w+)%7C/i, '');
}

function blog_href(href) {
    href = decodeURIComponent(href).replace(/^\/#!/, '/').replace(/\|/g, '/');
    if (!/^\/bathroom/.test(href)) return href;
    href = href.replace(/^\/bathroom/, '/bathroom/blog').replace(/^\/bathroom\/blog\/blog/, '/bathroom/blog');
    if (/^\/bathroom\/blog\/./.test(href)) return href;
    return '/bathroom/';
}

var Float = new Class({
    Implements: Options,
    options: {
        content: '',
        manager: null,
        basedir: ''
    },
    initialize: function(options) {
        this.setOptions(options);
        var self = this.container = new Element('div.float');
        self.icon = new Element('div.floatIcon', {
            text: 'T'
        }).inject(self);
        self.titleBar = new Element('div.floatTitleBar').inject(self);
        self.close = new Element('div.floatClose', {
            text: 'x'
        }).inject(self.titleBar);
        self.minimize = new Element('div.floatMinimize', {
            text: '_'
        }).inject(self.titleBar);
        self.theTitle = new Element('div.floatTitle', {
            text: this.options.title
        }).inject(self.titleBar);
        var href = this.options.href;
        var type = this.options.type;
        var forceTitle = this.options.forceTitle;
        if (href && type == 'iframe') {
            self.content = new IFrame({
                    src: href,
                    id: 'ID' + (++iFrameIdx) + 'if',
                    'class': 'floatContent'
                }).inject(self);
            href = null;
        }
        else
            self.content = new Element('div.floatContent').inject(self);
        if (this.options.size) self.content.addClass('floatContent' + this.options.size);
        self.bottom = new Element('div.floatBottom').inject(self);
        self.resize = new Element('img.floatResize', {
            src: 'images/floatResize.gif'
        }).inject(self.bottom);
        [self.titleBar, self.close, self.minimize, self.resize].each(function(el) {el.addEvents({
                mouseenter: function () {
                    this.addClass('floatHover');
                    var p = this.getParent();
                    if (p) p.addClass('floatChildHover');
                },
                mouseleave: function () {
                    this.removeClass('floatHover');
                    var p = this.getParent();
                    if (p) p.removeClass('floatChildHover');
                }
            })
        });
        if (href) {
            var update = self.content;
            if (type == 'magazine' || type == 'magpage') {
                update.set('html', $('catalogue').get('html'));
                update = update.getElement('.catbox');
            }
            self.theTitle.set('text', this.options.title+'... loading');
            try { _gaq.push(['_trackPageview', href]); } catch (e) {}
            var sorry = function() {
                self.content.set('html', 'Currently there seems to be a problem with this page.<br />' +
                    'Please contact <a href="mailto:customerservice@slowfashionhouse.com>customer service</a> ' +
                    'if you need help.');
                floatManager.nix.delay(10000, floatManager, self);
                self.content.removeClass('mySpinner');
            };
            self.content.addClass('mySpinner');
            self.content.set('load', {
                update: update,
                basedir: this.options.basedir,
                url: href,
                evalScript: false,
                useSpinner: false,
                timeout: 10000,
                onTimeout: sorry,
                onFailure: sorry,
                onSuccess: function(title) {
                    if (!self.share)
                        self.share=new IFrame({
                            src: 'about:blank',
                            'class': 'floatShare',
                            scrolling: 'no',
                            frameborder: 0,
                            allowTransparency: 'true',
                            width: 50,
                            height: 21
                        }).inject(self.minimize, 'after');
                    setShare(this.options.url, self.share);
                    var winTitle = self.content.getElement('.winTitle');
                    if (winTitle) { title = winTitle.get('html'); document.body.addClass('products'); }
                    if (title && !forceTitle) self.theTitle.set('html', title);
                    else self.theTitle.set('text', self.theTitle.get('text').replace(/\.\.\. loading$/, ''));
                    setZoom(self.content);
                    if (type == 'magazine' || type == 'magpage') new CatManager(self.content, href);
                }
            }).load(); // load.delay(1000, self.content, href)
        }
        self.setStyle('visibility', 'hidden');
        if (this.options.stash) self.inject(this.options.stash);
        else self.inject($(document.body));
        self.makeDraggable({
            handle: self.titleBar,
            onComplete: this.setLimits.bind(this)
        });
        self.content.makeResizable({
            handle: self.resize,
            onComplete: this.setLimits.bind(this),
            onDrag: function () {
                var w = self.content.getSize().x;
                self.titleBar.setStyle('width', w);
                self.bottom.setStyle('width', w);
            }
        });
        self.close.addEvent('click', function() {
            floatManager.nix(self)
        });
        self.store('minimizer',
            new Fx.Elements([self.content, self.titleBar, self.bottom], {
                duration: 1000,
                link: 'cancel',
                onComplete: this.setLimits.bind(this)
            }));
        var unMinimize = self.unMinimizeFn = function() {
            self.titleBar.removeEvent('click', unMinimize);
            self.retrieve('minimizer').start(self.unMinimize);
            self.removeClass('floatMinimized');
        };
        self.minimize.addEvent('click', function(e) {
            e.stop();
            var s = self.content.getSize();
            self.unMinimize = {
                0: {
                    width: s.x,
                    height: s.y
                },
                1: {
                    width: s.x,
                    backgroundColor: '#FFF'
                },
                2: {
                    width: s.x,
                    height: self.bottom.getSize().y
                }
            };
            self.titleBar.addEvent('click', unMinimize);
            self.addClass('floatMinimized');
            self.retrieve('minimizer').start({
                0: {
                    width: 60,
                    height: 0
                },
                1: {
                    width: 60,
                    backgroundColor: '#C5CCC7'
                },
                2: {
                    width: 60,
                    height: 0
                }
            });
        });
        this.setLimits();
        self.set('reveal', {
            mode: 'both',
            onComplete: this.setLimits.bind(this)
        });
        self.hide();
        self.setStyle('visibility', 'visible');
        try { a2a.init('page') } catch (e) {}
        return this;
    },
    setLimits: function() {
        var size = this.container.getSize();
        var cont = this.container.content.getSize();
        var pos = this.container.getPosition('floats');
        var win = winSize;
        if (window.console) console.log(size, cont, pos, win);
        if (size.x > win.x) {
            cont.x -= size.x - win.x;
            this.container.content.setStyle('width', cont.x);
            size.x = win.x;
        }
        this.container.titleBar.setStyle('width', cont.x);
        this.container.bottom.setStyle('width', cont.x);
        if (size.y > win.y) {
            cont.y -= size.y - win.y;
            this.container.content.setStyle('height', cont.y);
            size.y = win.y;
        }
        if (pos.x > win.x - size.x) {
            pos.x = win.x - size.x;
            this.container.setPosition(pos);
        }
        if (pos.y > win.y - 20) {
            pos.y = win.y - 20;
            this.container.setPosition(pos);
        }
        this.container.retrieve('dragger').setOptions({
            limit: {
                x: [0, win.x - size.x],
                y: [0, win.y - 20]
            }
        });
        this.container.content.retrieve('resizer').setOptions({
            limit: {
                x: [100, win.x - pos.x - size.x + cont.x],
                y: [100, win.y - pos.y - size.y + cont.y]
            }
        });
    },
    setLayer: function(z) {
        this.container.setStyle('z-index', 1000 + z)
    },
    addPop: function(manager) {
        var object = this;
        this.container.addEvent('mousedown', function(){
            manager.pop(object);
        })
    },
    reveal: function() {
        if (this.container.hasClass('floatMinimized'))
            this.container.unMinimizeFn();
        else
            this.container.reveal();
    }
});

var FloatManager = new Class({
    Implements: Options,
    options: {
        stash: null
    },
    initialize: function(options) {
        this.setOptions(options);
        this.options.stash = this.options.stash ? $(this.options.stash) : $(document.body);
        this.stack = [];
        this.store = {};
        this.startX = this.startY = 50;
    },
    add: function(href, center) {
        if (!href) return;
        var type = href_type(href),
            key = type + ':' + href,
            add = this.store[key],
            frameType = type,
            frameHref = ajax_href(href, winSize.y - 36),
            size = '';
        if (type == 'daily' || type == 'press' || type == 'bathroom') {
            frameType = 'iframe';
            frameHref = blog_href(href);
            center = true;
        }
        else if (type == 'buy') {
            this.nixAll(type);
            frameType = 'iframe';
            size = 'Buy';
            center = true;
        }
        else if (type == 'magazine' || type == 'magpage') {
            size = 'Magazine';
        }
        if (!add) {
            add = new Float({
                stash: this.options.stash,
                type: frameType,
                href: frameHref,
                size: size
            });
            if (center)
                add.container.position({
                    relativeTo: 'floats',
                    position: 'centerTop',
                    edge: 'centerTop'
                });
            else {
                add.container.setStyles({
                    left: this.startX + openPos.x,
                    top: this.startY + openPos.y
                });
                this.startX += 50;
                this.startY -= 50;
                if (this.startY < 50) {
                    var sum = this.startX + this.startY + 70;
                    if (this.startY >= 40) this.startX += 50;
                    this.startY = this.startX + 10;
                    this.startX = sum - this.startY;
                }
                while (this.startY > 300) { this.startX += 50; this.startY -= 50 }
            }
        }
        if (key) this.store[key] = add;
        this.pop(add);
        add.addPop(this);
        add.reveal();
    },
    pop: function(top) {
        this.stack.erase(top).push(top);     // move to end
        this.stack.each(function(object, index){
            object.setLayer(index);
        })
    },
    atTop: function(obj) {
        return obj === this.stack.getLast();
    },
    setLimits: function() {
        this.stack.each(function(object){
            object.setLimits();
        });
    },
    nix: function(container) {
        var tfloat, key;
        Object.each(this.store, function(afloat, akey){
            if (afloat.container === container) {
                tfloat = afloat; key = akey
            }
        });
        if (key !== undefined) {
            delete this.store[key];
            this.stack.erase(tfloat)
        }
        container.nix(true)
    },
    nixAll: function(type) {
        var self = this;
        Object.each(this.store, function(tfloat, key){
            if (key.indexOf(type + ':') === 0) {
                delete self.store[key];
                self.stack.erase(tfloat);
                tfloat.container.nix(true)
            }
        })
    }
});

// pages below index are right 396z-/792w0 px, in view right 396/0 px, above are right 0w0/0z- px
var fxLeft = {
    '0': { // prev. right page div (1) z 0
        width: [396, 0],
        right: [0, 396]
    },
    '1': { // new left page div (2) z +
        width: [0, 396],
        right: [0, 396]
    }
// new right page div (3) z -
// width: 396
// right: 0
};
var setLeft = {
    '0': { // prev. right page div (1) z 0
        width: 0,
        right: 396
    },
    '1': { // new left page div (2) z +
        width: 396,
        right: 396
    }
// new right page div (3) z -
// width: 396
// right: 0
};
var resetLeft = {
    '0': { // prev. right page div (1) z 0
        width: 396,
        right: 0
    },
    '1': { // new left page div (2) z +
        width: 0,
        right: 0
    }
};
var fxRight = {
    '0': { // new left page div (0) z +
        width: [0, 396],
        right: [792, 396]
    },
    '1': { // new right page div (1) z 0
        width: [396, 396],
        right: [792, 0]
    }
// old left page div (2) z -
// width: 396
// right: 396
};
var resetRight = {
    '0': { // new left page div (0) z +
        width: 0,
        right: 792
    },
    '1': { // new right page div (1) z 0
        width: 396,
        right: 792
    }
};

var CatManager = new Class({
    Implements: Options,
    options: {},
    initialize: function(catalogue, href) {
        var listLeft = this.listLeft = [];
        var listRight = this.listRight = [];
        var linkLeft = this.linkLeft = [];
        var linkRight = this.linkRight = [];
        var leftRun = 0, rightRun = 0;
        var catright = catalogue.getElement('.catnav.right'), catleft = catalogue.getElement('.catnav.left');
        var catmright = catalogue.getElement('.catmag.right'), catmleft = catalogue.getElement('.catmag.left');
        var cathref,
            catstart = 0,
            match = /(.*-page-)(\d+)$/.exec(href);
        if (match) {
            cathref = match[1];
            catstart = match[2].toInt();
        }
        else cathref = href + '-page-';
        var pagehref = cathref.replace(/.*=/, '#!magpage|');
        var fxIndex = this.fxIndex = Math.round(catstart/2);
        if (window.console) console.log('Hi there!');
        var width = catalogue.getElement('.catdiv1 .catpage').getStyle('width').toInt();
        var height = catalogue.getElement('.catdiv1 .catpage').getStyle('height').toInt();
        catalogue.getElements('.catdiv').setStyles({width: width, height: height});
        catalogue.getElement('.catbox').setStyles({width: width * 2, height: height});
        var fxLeft = {
            '0': { // prev. right page div (1) z 0
                width: [width, 0],
                right: [0, width]
            },
            '1': { // new left page div (2) z +
                width: [0, width],
                right: [0, width]
            }
// new right page div (3) z -
// width: width
// right: 0
        };
        var setLeft = {
            '0': { // prev. right page div (1) z 0
                width: 0,
                right: width
            },
            '1': { // new left page div (2) z +
                width: width,
                right: width
            }
// new right page div (3) z -
// width: width
// right: 0
        };
        var resetLeft = {
            '0': { // prev. right page div (1) z 0
                width: width,
                right: 0
            },
            '1': { // new left page div (2) z +
                width: 0,
                right: 0
            }
        };
        var fxRight = {
            '0': { // new left page div (0) z +
                width: [0, width],
                right: [width*2, width]
            },
            '1': { // new right page div (1) z 0
                width: [width, width],
                right: [width*2, 0]
            }
// old left page div (2) z -
// width: width
// right: width
        };
        var resetRight = {
            '0': { // new left page div (0) z +
                width: 0,
                right: width*2
            },
            '1': { // new right page div (1) z 0
                width: width,
                right: width*2
            }
        };
        try { _gaq.push(['_trackPageview', href]); } catch (e) {}
        for (var i = 0; ; i += 2) {
            var leftDiv = catalogue.getElement('.catdiv' + i);
            var rightDiv = catalogue.getElement('.catdiv' + (i + 1));
            var leftDiv2 = catalogue.getElement('.catdiv' + (i + 2));
            var rightDiv2 = catalogue.getElement('.catdiv' + (i + 3));
            if (i == 2*fxIndex) {
                setSrc(leftDiv);
                setSrc(rightDiv);
            }
            if (leftDiv) {
                leftDiv.setStyles({
                    zIndex: i <= 2*fxIndex ? 100 - i : 100+i
                })
            }
            if (!(rightDiv && leftDiv2)) {
                if (fxIndex > i/2) {
                    fxIndex = i/2;
                    if (leftDiv) {
                        setSrc(leftDiv, true);
                        leftDiv.setStyle('display', 'block');
                    }
                }
                break;
            }
            rightDiv.setStyles({
                zIndex: 100-i-1
            });
            if (i == 0)
                linkRight[0] = getSrc(rightDiv);
            linkLeft[i/2+1] = getSrc(leftDiv2);
            linkRight[i/2+1] = getSrc(rightDiv2);
            (function() {
                var left = new Elements([leftDiv, rightDiv]);
                var right = new Elements(rightDiv2 ? [leftDiv2, rightDiv2] : [leftDiv2]);
                var change = leftDiv2, changeIdx = i + 2;
                var rightFx = new Fx.Elements([leftDiv, rightDiv], {
                    link: 'cancel',
                    duration: 1800
                }).addEvent('complete', function() {
                    if (--rightRun <= 0 && catright.mousing)
                        catright.fade(1);
                    if (rightRun <= 0 && catmright.mousing)
                        catmright.fade(1);
                    if (rightRun <= 0) {
                        setShare(cathref + (fxIndex*2));
                        window.location.hash = cathref.replace(/.*=/, '!magazine|') + (fxIndex*2);
                        curHash = window.location.hash;
                        try { _gaq.push(['_trackPageview', cathref + (fxIndex*2)]); } catch (e) {}
                    }
                    right.setStyle('display', 'none');
                    change.setStyle('zIndex', 100+changeIdx);
                });
                listRight[i / 2 + 1] = function() {
                    rightRun++;
                    rightFx.set(resetRight);
                    left.each(setSrc);
                    left.setStyle('display', 'block');
                    rightFx.start(fxRight);
                };
                var leftFx = new Fx.Elements([rightDiv, leftDiv2], {
                    link: 'cancel',
                    duration: 1800
                }).addEvent('complete', function() {
                    if (--leftRun <= 0 && catleft.mousing)
                        catleft.fade(1);
                    if (leftRun <= 0 && catright.mousing && fxIndex >= listLeft.length)
                        catright.fade(1);
                    if (leftRun <= 0 && catmleft.mousing)
                        catmleft.fade(1);
                    if (leftRun <= 0) {
                        setShare(cathref + (fxIndex*2-1));
                        window.location.hash = cathref.replace(/.*=/, '!magazine|') + (fxIndex*2-1);
                        curHash = window.location.hash;
                        try { _gaq.push(['_trackPageview', cathref + (fxIndex*2-1)]); } catch (e) {}
                    }
                    left.setStyle('display', 'none');
                    change.setStyle('zIndex', 100-changeIdx);
                });
                listLeft[i/2] = function() {
                    leftRun++;
                    leftFx.set(resetLeft);
                    right.each(setSrc);
                    right.setStyle('display', 'block');
                    leftFx.start(fxLeft);
                };
                if (i < 2*fxIndex) {
                    leftFx.set(setLeft);
                    if (i + 2 == 2*fxIndex) right.setStyle('display', 'block');
                    left.setStyle('display', 'none');
                }
            })();
        }
        $$(catleft,catright,catmleft,catmright)
            .removeEvents('click')
            .removeEvents('mouseenter')
            .removeEvents('mouseleave');
        catright.addEvents({
            click: function(e) {
                e.stop();
                if (fxIndex < listLeft.length && rightRun <= 0) {
                    listLeft[fxIndex++]();
                    if (fxIndex >= listLeft.length) this.fade(0.7);
                }
                if (fxIndex >= listLeft.length) this.fade(0.7);
            },
            mouseenter: function() {
                this.mousing = true;
                if (rightRun <= 0)
                    this.fade(1)
            },
            mouseleave: function() {
                this.mousing = false;
                this.fade(0.7)
            }
        }).fade(0.7);
        catleft.addEvents({
            click: function(e) {
                e.stop();
                if (fxIndex > 0 && leftRun <= 0) {
                    listRight[fxIndex--]();
                }
                if (fxIndex <= 0) this.fade(0.7);
                catToShop = false
            },
            mouseenter: function() {
                this.mousing = true;
                if (fxIndex > 0 && leftRun <= 0)
                    this.fade(1);
            },
            mouseleave: function() {
                this.mousing = false;
                this.fade(0.7);
            }
        }).fade(0.7);
        var basedir = '';
        if (catalogue.getElement('.catbase')) basedir = catalogue.getElement('.catbase').get('text');
        catmleft.addEvents({
            mouseenter: function() {
                this.mousing = true;
                if (fxIndex > 0 && leftRun <= 0) {
                    this.fade(1);
                    this.set('href', pagehref + (fxIndex*2-1) + '-big');
                }
            },
            mouseleave: function() {
                this.mousing = false;
                this.fade(0.1);
//                this.erase('href');
            }
        }).fade(0.1);
        catmright.addEvents({
            mouseenter: function() {
                this.mousing = true;
                if (fxIndex <= listLeft.length && rightRun <= 0) {
                    this.fade(1);
                    this.set('href', pagehref + (fxIndex*2) + '-big');
                }
            },
            mouseleave: function() {
                this.mousing = false;
                this.fade(0.1);
//                this.erase('href');
            }
        }).fade(0.1)
    }
});

function setSrc(div) {
    if (!div) return;
    var img = div.getElement('img');
    if (!img) return;
    img.set('src', img.get('src').replace('/dummy.png#', '/'));
}

function getSrc(div) {
    if (!div) return false;
    var img = div.getElement('img');
    if (!img) return false;
    return img.get('src').replace('/dummy.png#', '/').replace('/images/', '/').replace('.jpg', '.html')
}

var floatManager;

var curHash = window.location.hash;
var magLinks = new Array();
function loadLink(href, center, fromHash) {
    if (!href) return;
    if (href.substr(0,3) == '/#!' && !fromHash) {
        window.location.hash = href.substr(1);
        curHash = window.location.hash;
    }
    curHash = window.location.hash;
    var type = href_type(href);
    if (type == 'external') return;

    floatManager.add(href, center);
}

function handleLink(e) {
    document.body.addClass('clicked');
    var href = this.get('href');
    if (!href) return;
    if (this.get('target')) return;
    href = href.replace(/^http:\/\/(?:www|test\d?)\.slowfashionhouse\.com\//, '/').replace('%21', '!').replace(/^#/, '/#');
    var type = href_type(href);
    if (window.console) console.log(type, href);
    if (type == 'external') {
        this.set('target', '_blank');
        return;
    }
    e.preventDefault();
    this.blur();
    var parent = this.getParent(),
        parentTag = parent.tagName.toLowerCase();
    if (type == 'swf') {
        var swf = this.retrieve('swf');
        if (!swf)
            this.store('swf', swf = new Swiff(this.get('href'), {}));
        if (this.activate = !this.activate) {
            swf.inject(this.getElement('div'));
            this.setStyles({
                color: '#C5CCC7',
                fontWeight: 'bold'
            });
            var nexta = this.getNext('a');
            if (nexta && nexta.get('rel') == 'text')
                floatManager.add(nexta.get('href'));
        }
        else {
            this.getElement('div').empty();
            this.setStyles({
                color: 'black',
                fontWeight: 'normal'
            })
        }
        resizeAll();
    }
    else if (parent.hasClass('winShowOtherVar')) {
        var content = this.getParent('.floatContent');
        if (content) {
            content.reloaded = true;
            content.empty();
            content.addClass('mySpinner');
            content.set('load', { url: ajax_href(href) }).load();
        }
    }
    else if (parent.hasClass('winShowAv')) {
        var button = this.getParent('.winShowData').getElement('.winShowBuy a'),
        span = this.getNext('span'),
        myLi = this.getParent();
        if (button) {
            button.set('href', href);
            if (span) button.set('text', span.get('text'));
            if (href == "#") { button.set('rel', 'fake'); button.swapClass('winShowBuy', 'winShowNoBuy') }
            else { button.set('rel', 'buy'); button.swapClass('winShowNoBuy', 'winShowBuy') }
        }
        this.getParent('ul').getElements('li').each(function(li) {
            if (li === myLi) li.addClass('winShowAvSelected');
            else li.removeClass('winShowAvSelected');
        })
    }
    else loadLink(href);
}

function setZoom(content) {
    try {
        var main = content.getElement('div.winShowPicMain'),
        zoom = main.getElement('div.winShowZoom'),
        zoompic = zoom.getElement('img.winShowZoom'),
        zoomframe = main.getElement('div.winShowFrame'),
        zoomglass = main.getElement('div.winShowGlass'),
        pic = main.getElement('img.winShowPicMain'),
        div = pic.getParent('div'),
        side = content.getElements('ul.winShowPicList img'),
        data = content.getElement('ul.winShowData'),
        s = pic.getSize();
        zoom.setStyles({
            width: s.x,
            height: s.y
        });
        zoompic.pic = pic;
        zoompic.frame = zoomframe;
        updateZoom.apply(zoompic);
        zoompic.addEvent('load', updateZoom);
        zoompic.set('src', pic.get('src').replace('/show/', '/zoom/'));
        if (zoomglass) zoomglass.fade(0.1);
        var moveit = function(e) { zoompic.moveit(e); };
        div.addEvents({
            mouseenter: function(e) {
                zoom.setStyle('display', 'block');
                zoomframe.setStyle('display', 'block');
                zoomglass.setStyle('display', 'none');
                moveit(e);
                div.addEvent('mousemove', moveit);
            },
            mouseleave: function() {
                zoom.setStyle('display', 'none');
                zoomframe.setStyle('display', 'none');
                zoomglass.setStyle('display', 'block');
                div.removeEvent('mousemove', moveit);
            }
        });
        side.addEvents({
            click: function() {
                var src = this.get('src').replace('/list/', '/show/');
                pic.set('src', src);
                zoompic.set('src', src.replace('/show/', '/zoom/'));
            }
        });
        var headers = data.getElements('li.fold > h3'), reloadTarget = 1;
        headers.each(function (h, i) { if (h.hasClass('reloadTarget')) reloadTarget = i });
        data.accordion = new Fx.Accordion(headers, headers.getNext(), {
            display: content.reloaded ? reloadTarget : 1,
            onActive: function(e) { e.addClass('winShowActive') },
            onBackground: function(e) { e.removeClass('winShowActive') }
        })
    }
    catch(e) {}
}

function updateZoom() {
    try {
        var s = this.pic.getSize(),
            z = this.measure( function() { return this.getSize(); });
        if (!z.x || z.x < 320) {
            this.moveit = function(e) {
                this.setStyle('display', 'none');
                this.frame.setStyle('display', 'none');
            };
            return;
        }
        if (!z.x) z = {x: 1599, y: 1804};
        var f = { x: Math.round(s.x * s.x / z.x / 2), y: Math.round(s.y * s.x / z.x / 2) },
            m = { x: s.x - 2 * f.x, y: s.y - 2*f.y };
        this.frame.setStyles({width: 2 * f.x - 8, height: 2 * f.y - 8});
        this.moveit = function(e) {
            var p = this.pic.getPosition();
            var left = Math.max(0, Math.min(e.page.x - p.x - f.x, m.x)),
            top = Math.max(0, Math.min(e.page.y - p.y - f.y, m.y));
            this.setStyles({
                left: Math.round(-left*(z.x - s.x)/m.x),
                top: Math.round(-top*(z.y - s.y)/m.y)
            });
            this.frame.setStyles({
                left: left,
                top: top
            })
        };
    }
    catch(e) {}
}

function setShare (link, iframe) {
    if (!iframe) iframe = $('catshare');
    if (iframe) {
        if (link.substr(0,1) != '/') link = '/' + link;
        link = link.replace(/^\/#(!|%21)/, '/?_escaped_fragment_=');
        iframe.set('src', 'http://www.facebook.com/plugins/like.php?href='
            + encodeURIComponent(window.location.protocol + '//' + window.location.host + link)
            + '&send=false&layout=button_count&width=50&show_faces=false&action=like&colorscheme=light&font=verdana&height=21')
    }
}

window.addEvent('domready', function () {
    var winsize = window.getSize(),
        cover = $('cover');
    if (cover)
        cover.set('tween', {duration: 15000, link: 'chain'}).tween('opacity', 0).tween('visibility', 'hidden')
            .addEvent('click', function () { cover.get('tween').cancel().set('visibility', 'hidden') });
    floatManager = new FloatManager({
//        stash: 'floats'
    });
    $(document.body).addEvent('click:relay(a,area)', handleLink);
    $$('#topmenu > li').each(function (li) {
        li.addEvents({
            mouseenter: function () {
                li.addClass('hover');
                hidden && hidden.slide('in')
            },
            mouseleave: function () {
                li.removeClass('hover');
                hidden && hidden.slide('out');
            }
        });
        var hidden = li.getElement('ul');
        if (!hidden) return;
        li.getElement('div').setStyle('display', 'block');
        var sections = hidden.getElements('ul'), maxHeight = 0, ll = 'heights:';
        sections.each(function(s) {
            maxHeight = Math.max(s.getDimensions().height, maxHeight);
            ll += ' ' + s.getSize().y;
        });
        var heads = sections.getParent('li').getElement('h4');
        if (sections.length > 0 && sections.length == heads.length)
            li.accordion = new Fx.Accordion(heads, sections, {
                fixedHeight: maxHeight,
                trigger: 'click',
                display: -1,
                alwaysHide: true,
                onActive: function(e) { e.addClass('menuH4Active') },
                onBackground: function(e) { e.removeClass('menuH4Active') }
            });
        hidden.set('slide', {
            resetHeight: true,
            link: 'cancel'
        }).slide('hide');
    });
    $$('#leftmenu li.slide').each(function (li) {
        li.addEvents({
            mouseenter: function () {
                li.addClass('hover');
                hidden && hidden.slide('in')
            },
            mouseleave: function () {
                li.removeClass('hover');
                hidden && hidden.slide('out');
            }
        });
        var hidden = li.getElement('ul');
        if (!hidden) return;
        li.getElement('div').setStyle('display', 'block');
        hidden.set('slide', {
            link: 'cancel'
        }).slide('hide');
    });
    $$('#bottommenu > li').each(function (li) {
        li.addEvents({
            mouseenter: function () {
                li.addClass('hover');
            },
            mouseleave: function () {
                li.removeClass('hover');
            }
        });
    });
    $('bottommenu').addEvents({
        mousedown: function() { this.addClass('mouseFront')},
        mouseleave: function() { this.removeClass('mouseFront')}
    });
    window.addEvent('resize', function () { resizeAll.delay(0) });
    resizeAll();
    $$('#topmenu a').each(function (a) {
        var href = a.get('href');
        if (href && href_type(href) == 'magazine') magLinks.push(href);
    });
//    var magLink = magLinks[0];
    var magLink = null;
    if (window.location.hash) {
        // The replace is a workaround for Firefox where the hash is wrongly urldecoded
        document.body.addClass('clicked');
        var firstLink = '/' + window.location.hash.replace('|', '%7C');
        if (firstLink == '/#shopping') document.body.addClass('shopping');
        else loadLink(firstLink, true, true);
    }
    (function () {
        if (curHash == window.location.hash) return;
        loadLink('/' + window.location.hash.replace('|', '%7C'), false, true);
    }).periodical(200);
});

function resizeAll() {
    var topMenu = $('topmenu'),
        bottomMenu = $('bottommenu'),
        overBottom = document.documentElement.clientHeight - bottomMenu.getSize().y,
        leftMenu = $('leftmenu'),
        toRight = document.documentElement.clientWidth,
        centering = 0;
    winSize = {x: document.documentElement.clientWidth, y: overBottom };
    if (overBottom - underTop > maxFloat)
        overBottom = underTop + maxFloat;
    if (toRight > topWidth) {
        centering = (toRight - topWidth) / 2;
        toRight = topWidth;
    }
    $('logo').setStyles({marginLeft: centering});
//    topMenu.setStyles({marginTop: underTop - topMenu.getSize().y, marginLeft: leftArea + centering});
    leftMenu.setStyles({marginLeft: centering});
//    bottomMenu.setStyles({top: overBottom, left: centering});
    bottomMenu.setStyles({marginLeft: centering});
    $('floats').setStyles({top: underTop, left: leftArea + centering, height: overBottom - underTop, width: toRight - leftArea });
    resizeMenu('topmenu', toRight - leftArea);
    resizeMenu('bottommenu', toRight);
    resizeLeft('leftmenu', overBottom - topArea);
    openPos = {x: leftArea + centering, y: underTop};
    floatManager.setLimits();
}

function resizeMenu(id, width) {
    var items = $$('#'+id+' h3'), naturalWidth = 1, nItems = items.length * 2 - 2, moveRight = false; // add 1 to width may fix rounding in ie9
    items.each(function(el) {
        naturalWidth += el.getSize().x;
        if (el.hasClass('extrawidth'))
            nItems += 18;
        if (el.hasClass('moveright'))
            moveRight = true;
    });
    if (naturalWidth >= width) {
        if ($(id).getStyle('width').toInt() < naturalWidth) $(id).setStyle('width', naturalWidth);
        items.each(function(el) { el.getParent('li').setStyles({ 'margin-left': 0, 'margin-right': 0 }); });
        $(id).setStyle('width', naturalWidth);
        return;
    }
    if ($(id).getStyle('width').toInt() < width) $(id).setStyle('width', width);
    var count = 0,
        rightLeft = width,
        excess = width - naturalWidth,
        moveSpace = excess - 10 * nItems;
    if (moveRight && moveSpace > 0)
        excess = 10 * nItems;
    var which = 0;
    items.each(function(el) {
        var left = 0, right = 0;
        var ex = el.hasClass('extrawidth')? excess * 10 : excess;
        if (which > 0) {
            while (count < ex) {
                count += nItems;
                left++;
            }
            count -= ex;
            }
        which++;
        if (which < items.length) {
            while (count < ex) {
                count += nItems;
                right++;
            }
            count -= ex;
        }
        el.getParent('li').setStyles({
            'margin-left': el.hasClass('moveright') && moveSpace > 0? left + moveSpace : left,
            'margin-right': right
        });
        rightLeft -= left;
        var slide = el.getNext('div');
        if (slide) slide.setStyle('margin-left', Math.min(0, rightLeft - slide.clientWidth));
        rightLeft -= el.clientWidth + right;
    });
    $(id).setStyle('width', width);
}

function resizeLeft(id, height) {
    var items = $$('#'+id+' li.section'), naturalHeight = 0, nItems = items.length - 1;
    items.each(function(el) { naturalHeight += el.getSize().y - el.getStyle('padding-bottom').toInt(); });
    var count = 0,
        excess = height - naturalHeight,
        nLeft = nItems;
    items.each(function(el) {
        var bottom = 0;
        while (count < excess) {
            count += nItems;
            bottom++;
        }
        count -= excess;
        if (nLeft-- <= 0) {
            el.setStyle('padding-bottom', 0);
            return;
        }
        el.setStyle('padding-bottom', bottom);
    });
}

