/* 
 * jQuery.imageInfo.js
 * © 2011 kumagaiyusuke
*/
(function ($) {
  
  $.imageInfo = function ($target, isBgInclude) {
    
    var $imageInfo;
    var imageLoaded = 0;
    var imageList = [];
    
    var events = $.imageInfo.events;
    
    $imageInfo = $({});
    
    $target.find("img").each(function (i) {
      imageList.push($(this).get(0));
    });
    
    if (isBgInclude) {
      
      $target.each(function (i) {
      
        var $this = $(this);
        var target = $this.get(0);
        var url = getBackgroundURL(target);

        if (url) {
          var image = new Image();
          image.src = url;
          imageList.push(image);
        }
        
        $this.contents().not("[nodeType=1]").each(function (i) {
          var url = getBackgroundURL(this);
          if (url) {
            var image = new Image();
            image.src = url;
            imageList.push(image);
          }
        });
        
      });
    }
    
    function getBackgroundURL(target) {
      
      var backgroundURL = null;
      var bgData;
      
      if (target.currentStyle) {
        bgData = target.currentStyle.backgroundImage;
      }
      else {
    		bgData = document.defaultView.getComputedStyle(target, "").backgroundImage;
      }
      
      bgData = bgData.match(/url\((.+)\)/);
      
      if ($.isArray(bgData)) {
        backgroundURL = bgData[1].replace(/\"/g, "");
      }
      
      return backgroundURL;
    }
    
    $imageInfo.load = function () {
      
      for (var i = 0; i < imageList.length; i++) {
      
        var orgSrc = imageList[i].src;
      
        if (!$.browser.msie) {
          imageList[i].src = "";
        }

        if (typeof imageList[i].addEventListener === "function") {
          imageList[i].addEventListener("load", onLoad, false);
        }
        else {
          imageList[i].attachEvent("onload", onLoad);
        }
      
        if (!$.browser.msie) {
          imageList[i].src = orgSrc;
        }
        else if (this.complete || this.complete === undefined) {
          imageList[i].src = orgSrc;
        }
      }
      
      function onLoad(e) {
        
        ++imageLoaded;
        
        $imageInfo.trigger(events.CHANGE);

        if (imageLoaded === imageList.length) {
          $imageInfo.trigger(events.COMPLETE);
        }

      }

    };
    
    $imageInfo.getImageTotal = function () {
      return imageList.length;
    };
    
    $imageInfo.getImageLoaded = function () {
      return imageLoaded;
    };
    
    return $imageInfo;
  };
  
  $.imageInfo.events = {
    COMPLETE: "complete",
    CHANGE: "change"
  };
  
})(jQuery);

