/*global jQuery */
/* ****************************************************************************

	CJ Object Scaler jQuery Plug-In v2.0

	This library is released under the BSD license:

	Copyright (c) 2008, Doug Jones. All rights reserved.
	
	Redistribution and use in source and binary forms, with or without
	modification, are permitted provided that the following conditions are met:
	
	Redistributions of source code must retain the above copyright notice, this
	list of conditions and the following disclaimer. Redistributions in binary
	form must reproduce the above copyright notice, this list of conditions and
	the following disclaimer in the documentation and/or other materials
	provided with the distribution. Neither the name BernieCode nor
	the names of its contributors may be used to endorse or promote products
	derived from this software without specific prior written permission. 
	
	THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
	AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
	IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
	ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE FOR
	ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
	DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
	SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
	CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
	LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
	OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH
	DAMAGE.
	
	For more information please visit www.cjboco.com.
	
	Example:
	
	$("#myImage").cjObjectScaler({
		destObj: $("#myDiv"),	// Needs to be a jQuery object
		method: "fit",			// fit | fill (default)
		fade: 500				// 0 no fade, positive integer fade duration
	});
	
	CHANGELOG
	
		v1.0	09/10/08 -	Initial Release
		v2.0	09/22/09 -	Coverted it to a jQuery plug-in
		v2.0.1	10/14/09 -	Fixed a bug where the scaling function
								wasn't being triggered, do to the
								image already being loaded.
								(Discovered by Ben Visser)
	

**************************************************************************** */
(function($) {
    $.fn.cjObjectScaler = function(options) {

        /* 
        user variables (settings)
        ***************************************/
        var settings = {
            // user editable settings
            destObj: null,
            // must be a jQuery object
            method: "fill",
            // fit|fill
            fade: 0 // if positive value, do hide/fadeIn
        };

        /* 
        system variables
        ***************************************/
        var sys = {
            // function parameters
            version: '2.0.0',
            elem: null
        };

        /* 
        scale the image
        ***************************************/
        function scale(self) {

            // declare some local variables
            var dest = settings.destObj,
			destW = $(dest).width(),
			destH = $(dest).height(),
			ratioX,
			ratioY,
			scale,
			newWidth,
			newHeight;

            // calculate scale ratios
            ratioX = destW / $(self).width();
            ratioY = destH / $(self).height();

            // Determine which algorithm to use
            if (!$(self).hasClass("cf_image_scaler_fill") && ($(self).hasClass("cf_image_scaler_fit") || settings.method === "fit")) {
                scale = ratioX < ratioY ? ratioX : ratioY;
            } else if (!$(self).hasClass("cf_image_scaler_fit") && ($(self).hasClass("cf_image_scaler_fill") || settings.method === "fill")) {
                scale = ratioX > ratioY ? ratioX : ratioY;
            }

            // calculate our new image dimensions
            newWidth = parseInt($(self).width() * scale, 10);
            newHeight = parseInt($(self).height() * scale, 10);

            //stop from expanding images past their own size
            if (newWidth > $(self).width()) {
                newWidth = $(self).width();
                newHeight = $(self).height();
            }

            // Set new dimensions & offset
            $(self).css({
                "width": newWidth + "px",
                "height": newHeight + "px",
                "position": "absolute",
                "top": parseInt((destH - newHeight) / 2, 10) + "px",
                "left": parseInt((destW - newWidth) / 2, 10) + "px"
            }).attr({
                "width": newWidth,
                "height": newHeight
            });

            // do our fancy fade in, if user supplied a fade amount
            if (settings.fade > 0) {
                $(self).fadeIn(settings.fade);
            }

        }

        /* 
        initialize the flipBox
        ***************************************/
        function init() {

            var self = $(sys.elem)[0];

            // check to make sure we have a valid destination object
            if (settings.destObj === null || typeof settings.method !== "string" || typeof $(settings.destObj)[0] !== "object") {
                return;
            } else {

                // need to make sure the user set the parent's position
                // things go bonkers, if not set.
                if ($(settings.destObj).css("position") === "static") {
                    $(settings.destObj).css({
                        "position": "relative"
                    });
                }

                // if the user supplied a fade amount, hide our image
                if (settings.fade > 0) {
                    $(self).hide();
                }

                // run our scale function. Special case for images, we need
                // to make sure the image has loaded in order to get the width & height
                if ($(self)[0].nodeName === "IMG") {
                    // check to see if the image is already loaded
                    if ($(self).attr("complete")) {
                        scale($(self)[0]);
                    } else {
                        $(self).load(function() {
                            scale($(self)[0]);
                        });
                    }
                } else {
                    scale($(self)[0]);
                }

            }
        }

        /* 
        set up any user passed variables
        ***************************************/
        if (options) {
            $.extend(settings, options);
        }

        /* 
        main
        ***************************************/
        return this.each(function() {
            sys.elem = this;
            init();
        });

    };
})(jQuery);
