

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>',
        base_url: webroot
    }, settings);

    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]['filename'])+'" alt="" >').prependTo(self.container);
    self.image = $img[0];

    var $next = $('.image-next', $(self.container).parent());
    var $prev = $('.image-prev', $(self.container).parent());
    if( $prev.length < 1 ) {
        $prev = $(self.settings.prevButtonHTML).addClass('image-prev').appendTo($(self.container).parent() );
    }
    if( $next.length < 1 ) {
        $next = $(self.settings.nextButtonHTML).addClass('image-next').appendTo( $(self.container).parent() );
    }
    if(self.images.length < 2 ) {
        $next.hide();
        $prev.hide();
    }

    $(self.settings.captionID).after('<div class="image-numbers"></div>');
    
    
    // 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( self.settings.fullscreen == 'thickbox' ) {
        // Hookup to thickbox
        var $anchor = $('> a:eq(0)', self.container);
        $anchor.click( function() {
            var dim = self.getFullscreenSize();
            if( self.images[self.currentimg]['href'] ) {
                this.href = self.images[self.currentimg]['href'];
            } else {
                this.href = 'media/'+self.images[self.currentimg]['filename'];
            }
            $(this).attr('caption', encodeURIComponent(self.images[self.currentimg]['caption']));
            return false;
        });
        tb_init($anchor[0]);
    }    
    
    $(window).load(function(){self.switchImage(0)});
    self.switchImage(0);
},

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) {
    index = parseInt(index);
    this.currentimg = index;
    this.loadImage();
},

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

    //var $loading = $('<img id="thumbloading" src="'+self.settings.base_url+'img/modal/loading.gif" >');
    //$loading.hide().appendTo($container).css({position:'absolute',left:'45%',top:'40%'});

    var framedim = {
        width : parseInt($container.css('width')),
        height : parseInt($container.css('height'))
    };
    
    var pad = self.pad * 2;
    var width = (self.settings.width)? self.settings.width : framedim['width'] - pad; 
    var height = (self.settings.height)? self.settings.height :  framedim['height'] - pad;
    var src = self.createImgSrc($img.attr('src'), {
        img: self.images[self.currentimg]['filename'],
        crop:0,w: width, h: height
      });

    var preload = new Image();
    $img.hide();
    //$loading.fadeIn(4.0); 
    preload.onload = function () {
        $img.attr('src', preload.src);
        //$loading.remove();
        var t = parseInt((framedim['height']-preload.height)/2);
        var l = parseInt((framedim['width']-preload.width)/2);
        $img.parent().css({
            'position' : 'absolute',
            'top' : t,
            'left': l
        });
        
        if( self.settings.height )$container.height( this.height ); 
        if( self.settings.width ) $container.width( this.width );
        
        // Set caption
        var caption = unescape(self.images[self.currentimg]['caption']);
        $(self.settings.captionID).empty().append(caption).show();
        // Set copyright message
        var copyright = unescape(self.images[self.currentimg]['copyright']);
        var $copyright = $('#footer #copyright');
        if (copyright.length > 0) {
            self.copyright = $copyright.html();
            $copyright.empty().append(copyright);
        }
        else if( self.copyright ){
            $copyright.empty().append(self.copyright);
        }
        // Set image numbers
        $('.image-numbers').text( (self.currentimg+1) + ' / ' + self.images.length );
        $img.show();

        var anchor = $img.parent()[0];
        if( anchor.tagName.toLowerCase() == 'a' && self.images[self.currentimg]['href'] ) {
            anchor.href = self.images[self.currentimg]['href'];
        }
    }    
    preload.src = 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+'img/modal/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">&lt; prev</a> <a id="fullscreenNext">next &gt;</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) - 20;
        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.settings.base_url+'media/'+self.images[index]['filename']; 
    $loading.show();
},

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

// Create a new image url from given image and changed attributes
createImgSrc: function(src, attributes) {
    var qstr = $.parseQstr(src);
    $.extend(qstr,attributes);
    return src.split('?')[0] +'?'+ $.objToQstr(qstr);
},


// Adjust the size of the images based on window dimensions
getFullscreenSize: function() {
    var dim = [
        $(window).width(), $(window).height(),
        $(document.body).width(), $(document.body).height()
    ];
    var w = dim[0], h = dim[1];
            
    if( w <= 800 || h <= 600 ) {
        imgMaxWidth = 800; imgMaxHeight = 600;
    }
    else if( w <= 1024 || h <= 768 ) {
        imgMaxWidth = 1024; imgMaxHeight = 768;
    }
    else if( w <= 1280 || h <= 1024 ) {
        imgMaxWidth = 1280; imgMaxHeight = 1024;
    }
    else if( w <= 1600 || h <= 1200 ) {
        imgMaxWidth = 1600; imgMaxHeight = 1200;
    }
    else {
        imgMaxWidth = 2048; imgMaxHeight = 1280;
    }
    
    imgMaxWidth = parseInt(imgMaxWidth*0.9);
    imgMaxHeight = parseInt(imgMaxHeight*0.58);
    return [imgMaxWidth, imgMaxHeight];
}

};


jQuery.ImageFrame = {
    list : []
};
jQuery.fn.ImageFrame = function(images, settings) {
    return this.each( function () {
        jQuery.ImageFrame.list.push (
            new ImageFrame(images, this, settings )
        );
    });
}

