
/**
 * Display alternative images when one fails to load.
 */

var unavailable_images = {};
unavailable_images['spacer']   = '/i/spacer.gif';

// List of failed images.
var failed_images = Array();

function image_error(img, backup_url, unavailable_image_size)
{  
   // Count the number of times this image has had a failure.
   var failures = 0;
   for(var index in failed_images)
      if(img == failed_images[index])
         failures++;
      
   // Record this failure.
   failed_images.push(img);
   
   switch(failures)
   {
      case 0:
         // Attempt to load the backup image.
         img.src = backup_url;
      break;

      case 1:
         // If the backup image failed, display the unavailable image.
         if('none' != unavailable_image_size)
            img.src = unavailable_images[unavailable_image_size];
      break;

      default:
         // The unavailable image failed to load, we can't recover from this.
      break;
   }
}

/*
   Using the fancy image error recovery:
   
   <img class="image_error" src="first_image.jpg">
   <span class="image_error" title="second_image.jpg"></span>
   <span class="image_error" title="third_image.jpg"></span>

*/

function addImageErrorHandlers()
{
   if(typeof(jQuery) != 'undefined')
   {
      // Add error handlers to all images with the image_error class, and remove the class.
      jQuery('img.image_error').removeClass("image_error").error(function(){
   
            // The next span will contain the URL of another image.
            var failoverImage = jQuery(this).next('span.image_error');
   
            if(1 == failoverImage.length)
            {
               // Assign a new URL to this image.
               jQuery(this).attr('src', failoverImage.attr('title'));

               // Remove this failover image, so we'll move on to the next one in the chain.
               failoverImage.remove();
            }
         });
   }
}
