$().ready(function(){
    var lightbox = new Ctrl_Dialog_Image(null, {
        resizable: false,
        modal: true,
        position: { my: 'center center', at: 'center center', of: window }
    });
    
    $('.gallery').each(function(){
        var $this = $(this);
        var $thumbs = $this.children('.thumbnails');
        var $primary = $this.children('.primary');
        var $viewport = $thumbs.children('.viewport');

        //$primary.children().eq(0).position({ my: 'center center', at: 'center center', of: $primary });
        
        $thumbs.find('li').click(function(){
            var id = this.id.substr(this.id.lastIndexOf('-')+1);
            $.getJSON(Ctrl.Config.baseUrl + '/media/oembed/format/json/id/'+ id +'/width/' + $primary.width() + '/height/' + $primary.height() + '/crop/0', function(json) {
                var newImg = $(json.thumbnail_html).hide().appendTo($primary);
                newImg.wrap('<a title="'+ json.title +'" href="'+ Ctrl.Config.baseUrl +'/media/thumbnail/id/'+ id +'/width/800/height/600/crop/0"></a>');
                newImg.load(function(){
                	newImg.fadeIn(500);
                	$primary.children().eq(0).fadeOut(500, function(){ $(this).remove(); });
                });

            });
        });
        
         $viewport.css({height: $thumbs.height(), overflow: 'hidden'}).jScrollPane({
            scrollbarWidth: 8,
            showArrows: false,
            dragMinHeight: 38,
            dragMaxHeight: 38,
            trackPadding: 12
        });
         var $o = $this.find('.overlay');
         var on = false;
         $primary.bind('mouseenter', function(){$o.fadeIn()});
         $this.bind('mouseleave', function(){$o.fadeOut()});
    });
    
    $('.gallery .primary a').live('click', function(){
        lightbox.setImage(this.href, this.title).open();
        return false;
    });  
});

