var log = function(msg) {
    //try { console.log(msg); } catch(err) {}
}

var Photophie = new Class({
    Implements: Options,
    options: {
        minTop: 50,
        offsetTop: -20,
        minHeight: 425,
        maxHeight: 700,
        space: 200
    },
    height: 700,

    container: null,
    photos: null,
    menu: null,

    ready: false,
    initialize: function(options) {
        this.container = $('container');

        this.calculateHeight();
        this.setContainerPosition();

        var photosContainer = $(document.body).getElement('.ppPhotos');
        if (photosContainer) {
            this.photos = new Photophie.Photos(photosContainer, {
                'height': this.height
            });
        }

        var menuContainer = $(document.body).getElement('.ppMenu');
        if (menuContainer) {
            this.menu = new Photophie.Menu(menuContainer, {
                'height': this.height
            });
        }

        window.addEvent('resize', function() {
            this.calculateHeight();
            this.setContainerPosition();

            if (this.photos) {
                this.photos.setHeight(this.height);
            }
            if (this.menu) {
                this.menu.setHeight(this.height);
            }
        }.bind(this));
        this.ready = true;


        var hashJump = parseInt(document.location.hash.substring(1));
        if (hashJump) {
            (function(){
                this.photos.photos[hashJump-1].activate(true)
                this.showContainer();
            }.bind(this)).delay(200);
        } else {
            this.showContainer();
        }
    },

    showContainer: function() {
        if (this.container) {
            this.container.set('tween', {'duration':100}).tween('opacity', 1);
        }
    },

    calculateHeight: function() {
        this.height = Math.max(this.options.minHeight, Math.min(window.getSize().y-this.options.space, this.options.maxHeight));
    },
    
    setContainerPosition: function() {
        if (this.container) {
            var tY = ((window.getSize().y - this.height) / 2) + this.options.offsetTop
            this.container.setStyle('top', Math.max(this.options.minTop, Math.round(tY)));
        }
    }
});

Photophie.Menu = new Class({
    Extends: Photophie,
    options: {
        height: 700
    },
    container: null,

    initialize: function(container, options) {
        this.setOptions(options);
        this.container = container;
        this.setHeight(this.options.height);
    },

    setHeight: function(height) {
        this.container.setStyle('height', height + 30);
    }
    
});

Photophie.Photos = new Class({
    Extends: Photophie,
    options: {
        height: 700
    },
    container: null,
    photos: [],

    initialize: function(container, options) {
        this.setOptions(options);
        this.container = container;
        this.photos = [];
        var n = 0;
        this.container.getElements('.ppPhoto').each(function(c) {
            n++;
            this.photos.push(new Photophie.Photos.Photo(c, {
                'height': this.options.height,
                'number': n,
            })); 
        }.bind(this));
        this.setHeight(this.options.height);

        $$('.ppNext').addEvent('click', this.next.bind(this));
        $$('.ppPrevious').addEvent('click', this.previous.bind(this));


        window.addEvent('click', this.onClick.bind(this));
        window.addEvent('keyup', this.onKeyup.bind(this));
        window.addEvent('mousewheel', this.onMousewheel.bind(this));
    },
    
    onClick: function(e) {
        window.clearTimeout(this.wheelTimeout);
    },

    onKeyup: function(e) {
        window.clearTimeout(this.wheelTimeout);
        switch (e.key) {
            case 'enter':
            case 'space':
            case 'right':
            case 'down':
                e.stop();
                this.next();
                break;
            case 'up':
            case 'left':
                e.stop();
                this.previous();
                break;
        }
    },

    wheelDirection: 0,
    wheelTimeout: null,
    onMousewheel: function(e) {
        this.wheelDirection = (e.wheel > 0) ? 'left' : 'right';
        window.clearTimeout(this.wheelTimeout);
        this.wheelTimeout = window.setTimeout(this.wheelAction.bind(this), 2000);
    },
    wheelAction: function() {
        window.clearTimeout(this.wheelTimeout);
        this.getCurrent().activate(false, 2000);
    },

    setHeight: function(height) {
        $$('.ppBelowPhotos').setStyle('top', height + this.container.getCoordinates().top);
        this.photos.each(function(p){
            p.setHeight(height);
        });
        this.setContainerWidth();
        this.container.setStyle('height', height + 20);
    },

    setContainerWidth: function() {
        var width = 0;
        this.photos.each(function(p) {
            width += p.getWidth();
        });
        var w1 = window.getSize().x;
        var w2 = this.photos[this.photos.length-1].getWidth();
        if (w1 > w2) {
            width += w1 - w2 - this.container.getPosition().x + this.photos.length;
        }
        this.container.setStyle('width', width);
    },

    getZeroPos: function() {
        return window.getScroll().x;
    },
    
    getCurrent: function() {
        var zero = this.getZeroPos();
        var previous = this.getPrevious(10);
        var next = this.getNext(10);
        
        var previousDistance = Math.abs(previous.getRelativeX() - zero);
        var nextDistance = Math.abs(next.getRelativeX() - zero);

        return (previousDistance < nextDistance) ? previous: next;
    },
    
    getPrevious: function(tolerance) {
        tolerance = tolerance ? tolerance : 0;
        var zero = this.getZeroPos();
        var leftSide = this.photos[this.photos.length-1];
        for (var i=this.photos.length-1; i>=0; i--) {
            if (this.photos[i].getRelativeX() < (zero+tolerance)) {
                leftSide = this.photos[i];
                break;
            }
        };
        return leftSide;
    },
    
    getNext: function(tolerance) {
        tolerance = tolerance ? tolerance : 0;
        var zero = this.getZeroPos();
        var rightSide = this.photos[0];
        for (var i=0; i<=this.photos.length-1; i++) {
            if (this.photos[i].getRelativeX() > (zero-tolerance)) {
                rightSide = this.photos[i];
                break;
            }
        };
        return rightSide;
    },
    
    previous: function() {
        this.getPrevious().activate();
    },
    
    next: function() {
        this.getNext().activate();
    }

});

Photophie.Photos.Photo = new Class({
    Extends: Photophie.Photos,
    options: {
        height: 700,
        number: 0
    },
    container: null,
    image: null,
    originalWidth: 0,
    originalHeight: 0,
    sizeFactor: 0,
    height: 700,

    videoContainer: null,
    videoContainerId: 0,
    videoFile: false,
    videoPlayer: null,

    initialize: function(container, options) {
        this.setOptions(options);
        this.container = container;
        this.image = this.container.getElement('img');
        this.originalWidth = this.image.get('width');
        this.originalHeight = this.image.get('height');
        this.sizeFactor = this.originalWidth / this.originalHeight;
        this.setHeight(this.options.height);
        this.image.addEvent('click', this.onClick.bind(this));

        this.videoContainer = this.container.getElement('.ppVideo');
        if (this.videoContainer) {
            this.enableVideo();
        }
    },
    
    onClick: function() {
        this.activate();
    },
    
    setHeight: function(height) {
        this.height = height;
        this.image.setStyles({
            'height': this.height,
            'width': 'auto'
        });
    },
    
    getWidth: function() {
        return Math.ceil(this.sizeFactor * this.height);
    },
    
    getX: function() {
        return this.image.getPosition().x;
    },

    getRelativeX: function() {
        return this.image.getPosition(this.container.getParent('div')).x;
    },
    
    clicks: 0,
    activate: function(instant, speed) {
        this.clicks ++;
        speed = speed ? speed : 500;
        document.location.hash = this.options.number;
        var x = this.getRelativeX();
        var y = window.getScroll().y;
        if (instant) {
            window.scrollTo(x,y);
        } else {
            var scroll = new Fx.Scroll(window, {
                wait: false,
                duration: speed,
                transition: Fx.Transitions.Quad.easeOut
            }).start(x, y);
        }
        if (this.videoFile && !this.videoPlayer) {
            if (x != 0 || this.clicks > 1) {
                this.playVideo();
            }
        }
    },
    
    enableVideo: function() {
        this.videoContainerId = this.videoContainer.get('id');
        this.videoFile = this.videoContainer.get('rel');
        this.videoContainer.addEvent('click', this.onClick.bind(this));
    },
    
    playVideo: function() {
        var size = this.image.getSize();
        this.videoPlayer = new SWFObject('/media/res/jwplayer/player.swf','mpl',size.x,size.y,'9');
        this.videoPlayer.addParam('allowfullscreen','true');
        this.videoPlayer.addParam('allowscriptaccess','always');
        this.videoPlayer.addParam('wmode','opaque');
        this.videoPlayer.addVariable('file','/media/'+this.videoFile);
        this.videoPlayer.addVariable('autostart','true');
        this.videoPlayer.addVariable('icons','false');
        this.videoPlayer.write(this.videoContainerId);
    }
    
});

var photophie = {ready: false}
window.addEvent('domready', function() {
    photophie = new Photophie();
});
