/*!
 * jQuery imagesLoaded plugin v1.0.4
 * http://github.com/desandro/imagesloaded
 *
 * MIT License. by Paul Irish et al.
 */

(function($, undefined) {

    // $('#my-container').imagesLoaded(myFunction)
    // or
    // $('img').imagesLoaded(myFunction)

    // execute a callback when all images have loaded.
    // needed because .load() doesn't work on cached images

    // callback function gets image collection as argument
    //  `this` is the container

    $.fn.imagesLoaded = function( callback ) {
        var $this = this,
        $images = $this.find('img').add( $this.filter('img') ),
        len = $images.length,
        blank = 'data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///ywAAAAAAQABAAACAUwAOw==';

        function triggerCallback() {
            callback.call( $this, $images );
        }

        function imgLoaded( event ) {
            if ( --len <= 0 && event.target.src !== blank ){
                setTimeout( triggerCallback );
                $images.unbind( 'load error', imgLoaded );
            }
        }

        if ( !len ) {
            triggerCallback();
        }

        $images.bind( 'load error',  imgLoaded ).each( function() {
            // cached images don't fire load sometimes, so we reset src.
            if (this.complete || typeof this.complete === "undefined"){
                var src = this.src;
                // webkit hack from http://groups.google.com/group/jquery-dev/browse_thread/thread/eee6ab7b2da50e1f
                // data uri bypasses webkit log warning (thx doug jones)
                this.src = blank;
                this.src = src;
            }
        });

        return $this;
    };
})(jQuery);


jQuery.fn.offScreen = function() {
    return this.each(function(){
        $(this).css({
            'position':'absolute',
            'left':'-5000px'
        });
    })
}

jQuery.fn.onScreen = function() {
    return this.each(function(){
        $(this).css({
            'position':'inherit',
            'left':'0'
        });
    })
}

jQuery.fn.toggleScreen = function() {
    return this.each(function(){
        if ($(this).css('left') == '0px')
            $(this).css({
                'position':'absolute',
                'left':'-5000px'
            });
        else
            $(this).css({
                'position':'inherit',
                'left':'0'
            });
    })
}

jQuery.fn.loadImage = function(actualimg) {
    return this.each(function(){
        if (typeof actualimg === 'undefined'){
            actualimg = $(this).attr('imgsrc');
        }
        
        
        var loadingimg = "/core/images/flickr/loading.jpg";
			
        if ($(this).attr('imgsize')) {
            loadingimg = loadingimg.replace(".jpg", "_" + $(this).attr('imgsize') + ".jpg");
            actualimg = actualimg.replace(".jpg", "_" + $(this).attr('imgsize') + ".jpg");
        }
                       
			
        //load the loading img		
        $(this).attr('src',loadingimg);
        $(this).data('actualimage',actualimg);
			
        //preload
        var preload = $("<img />");
        var targetimg = $(this);
        preload.load(function(){
            targetimg.attr('src',actualimg);				
        });
        preload.attr('src', actualimg);
    })
}

jQuery.fn.niceImg = function(){
    return this.each(function(){
        if ($(this).data('niced')==true) return;
        $(this).data('niced', true);
        var targetimg = $(this);
        var currentzoom = $(this).attr('zoom');
        if (!currentzoom) currentzoom = niceimage_zoom;
        
        var replacementimg = $('<img />');
        
        //fixes bug with ie 7
        targetimg.css('text-align','left');
        
        replacementimg.css('width','auto');
        replacementimg.css('height','auto');
        replacementimg.bind('load', function(e){
            var that = $(this);
            setTimeout(function(){
                if (that.data('niced')==true) return;
                that.data('niced', true);
                        
                //these are the target width and height
                var width = targetimg.width();
                var height = targetimg.height();
                        
                //prepare the outerdiv (to carry the style of the original img) (optional)
                        
                var curthing = $('<div class="outerimagediv" />');
                curthing.attr('style', targetimg.attr('style'));
                curthing.css('z-index','0');
                curthing.width(width);
                curthing.height(height);
                //curthing.css('width', width);
                //curthing.css('height', height);
                curthing.attr('id', targetimg.attr('id'));
                curthing.addClass(targetimg.attr('class'));
            
                //support for ie 7
                if ($.browser.msie && $.browser.version == 7.0){
                    curthing.css('display','inline');
                } else {
                    curthing.css('display','inline-block');
                }
                        
                        
                //prepare the innerdiv (to clip the image)
                var innerthing = $('<div class="innerimagediv" />');
                //innerthing.css('width', width);
                //innerthing.css('height', height);
                innerthing.width(width);
                innerthing.height(height);
                        
                //swap
                targetimg.after(that);
                targetimg.hide();

                that.addClass('mainimg');
                        
                //this is the native height of the image file
                var orgheight = that.height();
                var orgwidth = that.width();
                        
                //this is the resized height on the html page
                var resizedheight;
                var resizedwidth;                    

                //perform wrapping
                that.wrap(curthing);
                that.wrap(innerthing);
                        
                //fit the width
                //            that.css('width', '100%');
                //            resizedwidth = that.width();
                //            resizedheight = orgheight * resizedwidth / orgwidth;
                //            that.css('height', '100%');
                        
            
                        
                        
                                 
                //check how to compress image
                var heightratio = orgheight/height;
                var widthratio = orgwidth/width;

                        
                if (heightratio>widthratio) {
                    //fit the width
                    that.css('height', 'auto');
                    that.css('width', '100%');                
                    resizedwidth = that.width();
                    resizedheight = orgheight * resizedwidth / orgwidth;
                } else {
                    //fit the height
                    that.css('height', '100%');
                    that.css('width', 'auto');
                    resizedheight = that.height();
                    resizedwidth = orgwidth * resizedheight / orgheight;                            
                }
            
                //            console.log(that.attr('src'));
                //            console.log("width: " + width);
                //            console.log("height: " + height);
                //            console.log("orgwidth: " + orgwidth);
                //            console.log("orgheight: " + orgheight);
                //            console.log("resizedwidth: " + resizedwidth);
                //            console.log("resizedheight: " + resizedheight);
                        
                        
                //set the z-index and position of the external element
                that.closest('.nicecontainer').css('position','relative');
                that.closest('.nicecontainer').css('z-index','0');
                that.closest('.nicecontainer').css('overflow','visible');                        
                        
                //give the expanded img a border (wrapping divs works for more browsers than applying to image)
                that.wrap('<div class="imgcontainer" />');
                var imgcontainer = that.closest('.imgcontainer');
                if (targetimg.attr('license')) that.closest('.imgcontainer').after('<a href="' + targetimg.attr('license') + '" target="_blank"><img class="ccimg" src="/core/images/cc-logo.png" /></a>');
                if (targetimg.attr('title')) that.after('<div class="imgcap">'+targetimg.attr('title')+'</div>');
                                                
                //setup the image (required by ie)
                imgcontainer.css("position","absolute");
            
                //set the var for the anon functions
                var timeout;
                var zoomwidth = resizedwidth * currentzoom;
                var zoomheight = resizedheight * currentzoom;
            
                if (currentzoom > 1) {
                    if (zoomwidth > orgwidth) {
                        zoomwidth = orgwidth;
                        zoomheight = orgheight;
                    }
                
                    that.mouseenter(function(){
                        var curimg = imgcontainer;
                        timeout = setTimeout(function() {
                            curimg.closest('.nicecontainer').css('z-index','1');
                            curimg.closest('.outerimagediv').css('z-index','1');
                            curimg.closest('.innerimagediv').css('overflow','visible');
                            curimg.closest('.outerimagediv').css('overflow','visible');
                            curimg.find('.imgcap').width(zoomwidth*0.8);
                            curimg.find('.imgcap').show();
                            curimg.addClass('expendedimagestyle');

                            curimg.animate({
                                width: zoomwidth,
                                height: zoomheight,
                                'margin-top': (height - zoomheight)/2,
                                'margin-left': (width - zoomwidth)/2
                            });
                        },500)
                    })
                }
            
                imgcontainer.mouseleave(function(){
                    $(this).stop();
                    clearTimeout(timeout);
                    $(this).closest('.nicecontainer').css('z-index','0');
                    $(this).closest('.outerimagediv').css('z-index','0');
                    $(this).closest('.innerimagediv').css('overflow','hidden');
                    $(this).closest('.outerimagediv').css('overflow','hidden');
                    $(this).find('.imgcap').hide();
                    $(this).removeClass('expendedimagestyle');
                    $(this).width(resizedwidth);
                    $(this).height(resizedheight);                       
                    $(this).css('margin-top', (height - resizedheight)/2);
                    $(this).css('margin-left', (width - resizedwidth)/2);
                })            
                        
                that.mouseout();
                targetimg.remove();
            }, 1);

        })
                    
        /*
                    if ( this.nodeType === 1 && this.tagName.toLowerCase() === 'img' && this.src !== '' ) {
                        console.log($(this).attr('src') + " is cached!");
                        $(this).load();
                    }
                    */
        replacementimg.attr('src', targetimg.attr('src'));
                   
                    
    })
};
