/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//     I M A G E   -   P R E L O A D E R

var IMAGE_PRELOADER = function(){
 
  var NEXT_PRELOAD_ID = 0;
  var loader = null;
  
  /**
   * Setup image preloader to preload images in the given container.
   */
  function init( container ){
    loader = $j(container);
  }
 
  function preload( elements, callback ){
    var thisPID = NEXT_PRELOAD_ID;
    NEXT_PRELOAD_ID ++;
    
    /* If we don't have anything to preload, then do nothing... */
    if(elements.length <= 0){
      if(callback){
        callback();
      };
      return;
    }
    
    /* Append images to the loader */
    var images = new Array();
    elements.each( function( i ){
      
      var src = $j(this).attr("src");
      var img = $j('<img />');
      img.addClass("preID" + thisPID);
      
      /* If this element is an image, extract its src */
      if( src != null){
        img.attr("src",src);
      }else{
        src = $j(this).css("background-image");
        /* If this element has a background image... */
        if(src != null){
          /* remove the junk we don't want */
          src = src.replace(/"|'|url|\(|\)/g, '');
          /* use bg image as src */
          img.attr("src",src);
        } 
      }

      /* If a valid image source was found, add it to the loader */
      if(src && src != "none" && src != "/none"){      
        /* Put the image in the preloader */
        loader.append(img);
        images.push(img);
      }
    });
    
    /* Wait for images to load */
    var wait = setInterval(function() {
      
      /* Check if each image has loaded */
      var hasFinished = true;
      for(var i = 0; i < images.length; i++){
        if(images[i].attr("complete") == false){
          hasFinished = false;
        }
      }

      /* If all images have loaded, break */
      if(hasFinished){
        clearInterval(wait);
        $j(".preID"+thisPID).remove();
        if(callback){
          callback();
        };
        return;
      }
    }, 200);
    
  };
  
  return {init:init, preload:preload};

}();
