$(document).ready(function() {
	affLoad();
});

// Image pre-load and error checking function.
function affLoad() {

	// Drop all of the black and white images in the affiliate container into an array,  
	// and create a new array to hold their color versions.
	affiliates = $('#ctl00_Affiliates').find('img');
	
	var affImages = new Array(affiliates.size());
	
	// Grab the hostname 
	hostname = "http://" + window.top.location.host;
	
	// Iterate through the image array and pre-load each of the associated color images.
	// If a color image exists, add mouseover/out listeners.
	for (var i = 0; i < affiliates.size(); i++) {

		var affImage = new Image();
		affImage.onload = function () {
			affSwap(this.prototype);
		};
		
		affImage.prototype = affiliates[i].src.replace(hostname, "");	// Store the BW image source in the prototype variable, after stripping out the hostname.
		affImage.src = affSwapOn(affiliates[i], 1);	// Run the image through the affSwapOn function to remove the '-bw' suffix
		affImages[i] = affImage;
	}

}

// Changes a black and white affiliate image to a color image.
// Can also return the full converted image source if isReturned is set.
function affSwapOn(image, isReturned) {

	var imgPath = image.src.substring(0, image.src.lastIndexOf("/")+1);
	var imgName = image.src.substring(image.src.lastIndexOf("/")+1);
	var imgExtension = image.src.substring(image.src.lastIndexOf("."));
	imgName = imgName.split(".")[0].split("-")[0];
	
	if (isReturned) {
		return imgPath + imgName + imgExtension;
	} else {
		image.src = imgPath + imgName + imgExtension;
	}
	
}

// Changes a color affiliate image to a black and white image.
// Can also return the full converted image source if isReturned is set.
function affSwapOff(image, isReturned) {

	var imgPath = image.src.substring(0, image.src.lastIndexOf("/")+1);
	var imgName = image.src.substring(image.src.lastIndexOf("/")+1);
	var imgExtension = image.src.substring(image.src.lastIndexOf("."));
	imgName = imgName.split(".")[0] + "-bw";
	
	if (isReturned) {
		return imgPath + imgName + imgExtension;
	} else {
		image.src = imgPath + imgName + imgExtension;
	}
	
}

// Adds mouseover/out event listeners to images that are error-free.
function affSwap(imgSrc) {
		$('img[src="' + imgSrc + '"]').attr({
			onmouseover: 'affSwapOn(this)',
			onmouseout: 'affSwapOff(this)'
		});
}
