﻿/*
* jQuery Image Swapper
* By Instrux Media
*
* Parameters
*    targetsAndImages:  an array of one or more objects, each containing a linkSelector and swapImage property
*                       where linkSelector is a selector for the link surrounding the image to swap 
                        and swapImage is the location of the swap image
*    option:            an optional object containing handlers for any of the following events:
*                       init - fired when the setup begins
*                       loaded - fired after each image is preloaded and the handler is attached
*                       complete - fired after all images are preloaded and handlers are attached
*/
(function($) {
    var imgList = [];
    $.extend({
        imageLinkSwapper: function(targetsAndImages, option) {
            var setting = $.extend({
                init: function(loaded, total) { },
                loaded: function(img, loaded, total) { },
                complete: function(loaded, total) { }
            }, option);
            if (targetsAndImages != null) {
                if (!$.isArray(targetsAndImages)) {
                    if (targetsAndImages.hasOwnProperty("linkSelector") && targetsAndImages.hasOwnProperty("swapImage")) {
                        targetsAndImages = [targetsAndImages];
                    } else {
                        targetsAndImages = [];
                    }
                }
                var total = targetsAndImages.length;
                var loaded = 0;

                setting.init(0, total);
                for (var i = 0; i < targetsAndImages.length; i++) {
                    var hoverUrl = targetsAndImages[i]["swapImage"];
                    var targetId = targetsAndImages[i]["linkSelector"];
                    if (hoverUrl && targetId) {
                        var $link = $(targetId);
                        $link
                            .data("images", { url: $link.find("img").attr("src"), hoverUrl: hoverUrl })
                            .hover(function() {
                                var $this = $(this);
                                $this.find("img").attr("src", $this.data("images").hoverUrl);
                            }, function() {
                                var $this = $(this);
                                $this.find("img").attr("src", $this.data("images").url);
                            });
                        imgList.push($("<img />")
				            .attr("src", hoverUrl)
				            .load(function() {
				                loaded++;
				                setting.loaded(this, loaded, total);
				                if (loaded == total) {
				                    setting.complete(loaded, total);
				                }
				            })
			            );
                    }
                }
            }
        }
    });
})(jQuery);
