/**
 * ---------------------------------------------------------------------------------
 * jQuery-Plugin "autoHoverImage"
 * Version: 1.0, 2010.06.19
 * by Rangel Reale, http://www.rangelreale.com
 *
 * Copyright (c) 2010 Rangel Reale
 * Licensed under BSD (http://www.opensource.org/licenses/bsd-license.php)
 *
 * This function automatically adds mouseover effects to any image.
 * ---------------------------------------------------------------------------------
 */

(function($) {

    $.fn.autoHoverImage = function(settings) {
        settings = $.extend({
            mode: "image",      // image, opacity
            suffix: "-hover",    // default hover suffix (eg. menu-hover.png)
            selectedSuffix: null,    // default selected suffix (eg. menu-selected.png)
            opacityStart: 0.6,
            opacityEnd: 1.0,
            preload: true
        }, settings || {});

        if (settings.mode == "opacity") {
            // set start opacity
            $(this).fadeTo("slow", settings.opacityStart);

            // Set the hover handler
            $(this).hover(function() {
                $(this).fadeTo("slow", settings.opacityEnd);
            }, function() {
                $(this).fadeTo("slow", settings.opacityStart);
            });
        } else {
			// Preload the images
			if (settings.preload) {
				var preloadImageArray = new Array();
				$(this).filter("img").each(function() {
					var overImg = $(this).attr("src").split(".").join(settings.suffix+".");
					var img = new Image();
					img.src = overImg;
					preloadImageArray.push(img);
				});
			}

            // Set the hover handler
            $(this).filter("img").hover(function() {
				ahiData = {changed: true, selected: false};
				ahiData.selected = settings.selectedSuffix!=null && $(this).attr("src").split(".")[0].slice(-1*settings.selectedSuffix.length) == settings.selectedSuffix;

				if ($(this).attr("src").split(".")[0].slice(-1*settings.suffix.length) != settings.suffix)
				{
					if (ahiData.selected) splitValue=settings.selectedSuffix+"."; else splitValue=".";
					$(this).attr("src", $(this).attr("src").split(splitValue).join(settings.suffix+".")); // adds -hover to the name of the image
				}
				else
					ahiData.changed = false;

				$(this).data('autoHoverImage', ahiData);
            }, function() {
				ahiData = $(this).data('autoHoverImage');
				$(this).removeData('autoHoverImage');

                $(this).stop(true,false); // prevents the creation of stacked actions
				if (ahiData!=undefined && ahiData.changed)
				{
					if (ahiData.selected) joinValue=settings.selectedSuffix+"."; else joinValue=".";
					$(this).attr("src", $(this).attr("src").split(settings.suffix+".").join(joinValue));  // removes -hover from the name of the image
				}
            });
        }

	    return $;
    };

})(jQuery);

