

var ImageFrame = function() {
    return this.initialize.apply(this, arguments);
}

ImageFrame.prototype = {

initialize : function(images, obj, settings) {
    var self = this;
    self.pad = 10;
    self.currentimg = 0;   
    self.container = obj;
    self.preloads = 0;
    
    self.settings = $.extend( {
        fullscreen : true,
        captionID : '.image-caption',
        nextButtonHTML: '<a>NEXT</a>',
        prevButtonHTML: '<a>BACK</a>',
        imageControlsContainer: null,
        base_url: media_url || '/',
        max_height: null,
        max_width: null,
        show_image_count: false,
        startImage: 0,
        getThumbs: false,
        thumbnail_url: '/thumbnails/'
    }, settings);
    
    // If we got a selector string
    var $images;
    if (typeof(images) == 'string') {
        $images = $(images);
        images = [];
        $images.each(function() {
            image = {
                img: $(this).attr('href').replace(/http:\/\/[^\/]+\//, '/'),
                caption: $(this).attr('caption')
            };                
            images[images.length] = image;
        });
    }
    if (images.length < 1 ) return;
    self.images = images;

    var $img = $('> img:eq(0)', self.container);
    if( $img.length < 1) $img = $('> a:eq(0) > img', self.container);
    if( $img.length < 1) $img = $('<img src="'+self.settings.base_url+'img/thumbnail.php?img='+encodeURIComponent(images[0]['img'])+'" alt="" >').prependTo(self.container);
    $img.hide()
    self.image = $img[0];

    // Next/Prev buttons
    var $next = $('.image-next', $(self.container).parent());
    var $prev = $('.image-prev', $(self.container).parent());
    self.controls = self.settings.imageControlsContainer ? $(self.settings.imageControlsContainer) :
            $(self.container).parent();
    if( $prev.length < 1 && self.settings.prevButtonHTML ) {
        $prev = $(self.settings.prevButtonHTML).addClass('image-prev').appendTo(self.controls);
    }
    if( $next.length < 1 && self.settings.nextButtonHTML ) {
        self.controls.append(' ');
        $next = $(self.settings.nextButtonHTML).addClass('image-next').appendTo(self.controls);
    }
    if(self.images.length < 2 ) {
        $next.hide();
        $prev.hide();
    }

    if (self.settings.show_image_count) {
        self.controls.prepend('<span class="image-count"></span> ');
    }

    
    // Events //////////////////////////////////////////////
    if( self.settings.fullscreen ) $('> a', self.container).click( function(){ self.fullScreen(self.currentimg); return false; });
    $next.click( function(){ self.rotateImage(1) });    
    $prev.click( function(){ self.rotateImage(-1) });
    if ($images) {
        $images.each(function(i, el) {
            $(el).click(function(){ self.switchImage(i); return false; });
        });
    }

    if( self.settings.fullscreen == 'thickbox' ) {
        // Hookup to thickbox
        var $anchor = $('> a:eq(0)', self.container);
        $anchor.click( function() {
            if( self.images[self.currentimg]['href'] ) {
                this.href = self.images[self.currentimg]['href'];
            } else {
                this.href = 'media/'+self.images[self.currentimg]['img'];
            }
            $(this).attr('caption', encodeURIComponent(self.images[self.currentimg]['caption']));
            return false;
        });
        tb_init($anchor[0]);
    }

    if (self.settings.max_width == 'container' || self.settings.max_height == 'container' ){
        $(window).resize(function() {
            self.switchImage(self.currentimg, false);
        });
    }
    
    $(window).load(function(){self.switchImage(self.settings.startImage)});
    //self.switchImage(self.settings.startImage);
},

rotateImage: function(direction) {
    var self = this;
    direction = parseInt(direction);
    var i = ((direction + self.currentimg) + self.images.length)%self.images.length;
    self.switchImage(i);
},

switchImage: function(index, animate) {
    index = parseInt(index);
    this.currentimg = index;
    this.loadImage(animate);
},

// Load single full size image into frame
loadImage: function(animate) {
    var self = this;
    var $container = $(self.container);
    var $img = $(self.image);
    var $caption = $(self.settings.captionID).hide();

    var x = self.settings.max_width;
    var y = self.settings.max_height;    
    var src = self.images[self.currentimg]['img'];
        
    $(self.container).trigger('imageframe-startload', [self])

    animate = (animate == null) ? true : animate;

    if (x == 'container')
        x = $container.width()
    if (y == 'container' )
        y = $container.height()

    if (self.settings.getThumbs && x && y) {
        src = self.get_thumb_from_src(src, x, y);
    }
    
    // Set image dimensions and info when preload loads
    preload = new Image();    
    preload.onload = function () {
        var imageWidth = this.width;
        var imageHeight = this.height;
        
        if (x && imageWidth > x) {
            imageHeight = imageHeight * (x / imageWidth); 
            imageWidth = x; 
            if (imageHeight > y) { 
                imageWidth = imageWidth * (y / imageHeight); 
                imageHeight = y; 
            }
        } else if (y && imageHeight > y) { 
            imageWidth = imageWidth * (y / imageHeight); 
            imageHeight = y; 
            if (imageWidth > x) { 
                imageHeight = imageHeight * (x / imageWidth); 
                imageWidth = x;
            }
        }

        $img.attr({
            width: imageWidth,
            height: imageHeight
        });
       
        // Set caption
        var caption = unescape(self.images[self.currentimg]['caption']);
        $caption.empty().append(caption);

        // Image count
        var count = self.currentimg + 1;
        self.controls.find('.image-count').text( count + ' of ' + self.images.length);

        var anchor = $img.parent()[0];
        if( anchor.tagName.toLowerCase() == 'a' && self.images[self.currentimg]['href'] ) {
            anchor.href = self.images[self.currentimg]['href'];
        }

        $img.attr('src', preload.src);
        
        $(self.container).trigger('imageframe-load', [self])
    };
    preload.src = src;

    // Show the image
    $img.hide().one('load', function() {
        if (animate) {
            $img.fadeIn(200);
            $caption.fadeIn(200);
        } else {
            $img.show();
            $caption.show();
        }
    });

},

get_thumb_from_src: function(src, w, h) {
    var self = this;
    src = self.settings.thumbnail_url + src.replace(/^\//,'') + '?size=' + 
        w + 'x' + h + '&options=detail';
    return src;
},

fullScreen: function(index){
    var self = this;
    $overlay = $('#overlay');
    var $overlay = $('<div id="overlay"></div>').
        css({display : 'none', 'position' : 'fixed'}).
        appendTo(document.body).
        click(self.closeFullScreen);
    $overlay.css({width:'100%',height:'100%','top':'0px','left':'0px',zIndex:100});
    $overlay.show().css('opacity', 0.9);

    var $loading = $('<img id="fullscreenLoad" src="'+self.settings.base_url+'lib/img/loadingAnimation.gif" alt="loading" >');
    $loading.hide().appendTo(document.body);


    // Build DOM nodes 
    var $fsContainer = $('<div id="fullscreenContainer"><img id="fullscreenImage" ><div id="fullscreenImageData">'+
        '<div id="fullscreenCaption"></div>'+
        '<a id="fullscreenCloseButton" href="#">X</a>'+
        '</div></div>').appendTo(document.body);
    
    $('#fullscreenCloseButton').click( function(){ self.closeFullScreen(); return false; } );
   
    if( self.images.length > 1 ) {
        var count = self.images.length;
        var cur = self.currentimg+1;
        $('<div id="fullscreenControls"><span>Image '+cur+' of '+count+'</span> &nbsp;<a id="fullscreenPrev">prev</a> <a id="fullscreenNext">next</a></div>').
            insertAfter('#fullscreenCaption');
        $('#fullscreenNext, #fullscreenImage').click(function(){
            self.closeFullScreen();
            self.rotateImage(1);
            self.fullScreen(self.currentimg);            
        });
        $('#fullscreenPrev').click(function(){
            self.closeFullScreen();
            self.rotateImage(-1);
            self.fullScreen(self.currentimg);
        });
    }
   
    // Set up Data
    $fsContainer.hide();
    var caption = unescape(self.images[index]['caption']) ;
    $('#fullscreenCaption').append(caption);
    
    var preload = new Image();
    if( $.browser.safari ) { // safari 1.x fix
        var webKitFields = RegExp("( AppleWebKit/)([^ ]+)").exec(navigator.userAgent);
        var version = parseFloat(webKitFields[2]);          
        if( parseFloat(version) < 200 ) { // 1.x needs the image in the document to get width and height
            preload = $('<img id="fullscreenPreload" >')[0]; 
            $(preload).css({'position': 'absolute', 'top':'-5000px'});
            $(document.body).append(preload);
        }
    }    
    preload.onload = function() {
        var pad = 15;
        var pagesize = [$(window).width(), $(window).height()];
        var x = pagesize[0] - (caption.length > 0 ? 200 : 150);
        var y = pagesize[1] - (caption.length > 0 ? 200 : 150);
        var imageWidth = preload.width;
        var imageHeight = preload.height;
        $('#fullscreenPreload').hide().remove(); // safari 1.x fix
        if (imageWidth > x) {
            imageHeight = imageHeight * (x / imageWidth); 
            imageWidth = x; 
            if (imageHeight > y) { 
                imageWidth = imageWidth * (y / imageHeight); 
                imageHeight = y; 
            }
        } else if (imageHeight > y) { 
            imageWidth = imageWidth * (y / imageHeight); 
            imageHeight = y; 
            if (imageWidth > x) { 
                imageHeight = imageHeight * (x / imageWidth); 
                imageWidth = x;
            }
        }
        $('#fullscreenImage').attr({
            'src': preload.src,
            'width': imageWidth,
            'height': imageHeight
        });

        $fsContainer.css({width:(imageWidth+(pad*2))});
        var t = parseInt(( pagesize[1] - $fsContainer.height() )/2) + $(document).scrollTop() - ($('body').offset().top *2);
        if( t < 0) t = 0;
        var l = parseInt(( pagesize[0] - $fsContainer.width() )/2);
        $fsContainer.css({'position':'absolute','top':t+'px','left':l+'px'});

        $loading.remove();
        $fsContainer.show();
    };
    preload.src = self.images[index]['img']; 
    $loading.show();
},

closeFullScreen: function(){
    $('#overlay').hide().remove();
    $('#fullscreenContainer').remove();
    $('#fullscreenLoad').remove();
}


};

jQuery.fn.ImageFrame = function(images, settings) {
    return this.each( function () {
        var imageFrame = new ImageFrame(images, this, settings);
        $.data(this, 'ImageFrame', imageFrame);
    });
}


