var Listing = new Class({

    Implements: [Events, Options],
    
    options: {
        'scroller': false,
        'listings': false
    },
        
    initialize: function(options) {
        this.setOptions(options);
        
        this.bound = {
            start: this.start.bind(this),
            stop: this.stop.bind(this),
            drag: this.drag.bind(this)
        };
        
        this.options.scroller.addEvent('mousedown', this.bound.start);
        this.options.scroller.addEvent('touchstart', this.bound.start);
    },
    
    start: function(e) {
        this.ox = e.page.x;
        this.oy = e.page.y;
       
        this.px = this.options.scroller.getPosition().x;
        
        this.options.scroller.addEvent('touchmove', this.bound.drag);
        this.options.scroller.addEvent('touchend', this.bound.stop);
    },
    
    stop: function(e) {
        this.options.scroller.removeEvent('touchmove', this.bound.drag);
        this.options.scroller.removeEvent('touchend', this.bound.stop);
        
        var el = this.options.scroller.getChildren('.listing:first-child')[0];
        var c = this.options.scroller.getChildren('.listing').length;
        var w = el.getSize().x + 20;
        var p = this.pos - 110;
        var i = Math.abs(Math.floor(p / w));
        
        if ( p > 0 ) {
            // left overflow
            new Fx.Tween(this.options.scroller, { duration: 200 }).start('left', 110);
        } else if ( i > c - 4 ) {
            // right overflow
            new Fx.Tween(this.options.scroller, { duration: 200 }).start('left', -((c - 5) * w + 90));
        } else {
            // snap
            var ni = i; 
            if ( Math.abs(p % w) < w / 2.0 ) ni -= 1;
            new Fx.Tween(this.options.scroller, { duration: 200 }).start('left', -(ni * w) + 110);
        }
        
        if ( e !== undefined ) {
            e.preventDefault();
        }
    },
    
    drag: function(e) {
        var dx = e.page.x - this.ox;
        var dy = Math.abs(e.page.y - this.oy);
        
        this.pos = this.px + dx;
        this.options.scroller.setStyle('left', this.pos);
        
        if ( dy > 20 ) {
            this.stop();
        } else {
            e.preventDefault();
        }  
    },
    
    change_page: function(url) {        
        var items = this.options.scroller.getChildren('.listing');
        var el = this.options.scroller.getChildren('.listing[rel=' + url + ']')[0];
        var w = el.getSize().x + 20;
        var i = items.indexOf(el);
        
        if ( i > items.length - 4 ) {
            i = items.length - 4;
        }
        
        new Fx.Tween(this.options.scroller, { duration: 200 }).start('left', -(i * w) + 110);
    }
});

