var Photo = Class.create( {

    id: null,
    dir: { previous: "prev", next: "next" },
    
    initialize: function ( id ){
        this.id = id;
    },
    
    previous: function (){
        this.move( this.dir.previous );
    },
    
    next: function (){
        this.move( this.dir.next );
    },
    
    move: function ( where ){
        var opts = {
            method: "post",
            parameters: {
                id: this.id,
                where: where
            },
            
            onSuccess: function ( t ){
                var r = t.responseText.evalJSON();
                
                $( "index" ).update( r.index );
                $( "photo" ).writeAttribute( { src: r.src } );
                $( "caption" ).update( r.description );
                
                $( "prev_link" ).writeAttribute( { href: r.prev_href } );
                $( "next_link" ).writeAttribute( { href: r.next_href } );
                
                location.href = location.href.replace( /#.*$|$/, Photo.anchor + r.id );
            }
        };
        
        new Ajax.Request( "/photos/move.php", opts );
    }
} );

Photo.anchor = "#p";
Photo.identify = function (){

    var href = location.href;
    
    // anchor trumps query string
    if ( href.include( Photo.anchor ) ){
        return href.split( Photo.anchor )[1];
    } else {
        return (href.toQueryParams()).p;
    }
}

if ( location.href.include( Photo.anchor ) ){
    location.href = "/photos/?p=" + Photo.identify();
}

Event.observe( window, "load", function (){
    Event.observe( "prev_link", "click", function ( ev ){
        var photo = new Photo( Photo.identify() );
        photo.previous();
        Event.stop( ev );
    } );

    Event.observe( "next_link", "click", function ( ev ){
        var photo = new Photo( Photo.identify() );
        photo.next();
        Event.stop( ev );
    } );
} );
