// -----------------------------------------------------------------------------------
//
//	PNGuin v 0.8
//	by Robin Gavin - http://www.jaij.net
//	11/11/06
//
//	For more information on this script, visit:
//	http://www.jaij.net/
//
//	Licensed under the Creative Commons Attribution 2.5 License - http://creativecommons.org/licenses/by/2.5/
//	
//	Credit also due to those who have helped, inspired, and made their code available to the public.
//	Bob Osola (http://homepage.ntlworld.com/bobosola) - The man behind the png-fix-in-ie script
//  Mårten Lundin (http://www.marten.nu) - The one who came up with the idea and created the icon for the script 
// -----------------------------------------------------------------------------------

var defaultFrameRate = 10; // This is the framerate that is applied if not overwritten by the second rel-parameter of the LAST animated png
var defaultLoop = "loop"; // This is the default loop behavior to be applied to the image hasn't got one assigned by the third parameter

// Do not change after this line
var animatedPngs = new Array;
var frameRate = defaultFrameRate;

// Create the PngAnimator object
PngAnimator = function() {}

// Create the initilization script to be run when the page has been loaded
PngAnimator.prototype.initialize = function() {
	// Pick up all the images on the page and put them in an array
	var images = document.getElementsByTagName('img');

	// Loop through all image tags
	for (var i=0; i<images.length; i++){		
		// Current image in the loop
		var image = images[i];

		// Rel-value of the current image in the loop
		var relAttribute = String(image.getAttribute('rel'));

		// Use the string.match() method to catch 'pnganimation' references in the rel attribute
		if ((image.getAttribute('src').toLowerCase().match('.png')) && (relAttribute.toLowerCase().match('pnganimation'))) {
			// Retrieving the attritbute values from the rel-tag being the value between "[" and "]" and turning the "|" values into an array
			var animationAttributes = relAttribute.split("[")[1].split("]")[0].split("|");
				
			// Getting important file parameters
			var file = image.getAttribute('src');
			var path = file.substr(0, file.lastIndexOf("/") + 1);
			var fileName = file.substr(file.lastIndexOf("/") + 1);
			var fileNamePrefix = fileName.substr(0, fileName.lastIndexOf(".") - 1);

			// The first parameter is the number of images
			var totalImages = Number(animationAttributes[0]);

			// Creating a temporary array to hold all the parameters for the current image in the loop
			var animationImages = new Array;

			// Looping through all the images that will be used for the animation and creating image objects to preload them
			for(var j = 1; j <= totalImages; ++j) {
				// Creating the new filename with path
				var newFile = path + fileNamePrefix + j + ".png";

				// Create the image objects so that the images gets preloaded
				animationImages[j] = new Image();
				animationImages[j].src = newFile;				
			}
			
			// If the second parameter is set, set the loop parameter to that value or use the defaultLoop value
			var loop = animationAttributes[1] ? animationAttributes[1] : defaultLoop;

			// If the third parameter is set, set framerate to that value or use the defaultFrameRate value
			frameRate = animationAttributes[2] ? Number(animationAttributes[2]) : frameRate;
			
			// If the loop parameter isn't "loop" convert it to a number
			loop = (loop == "loop") ? "loop" : Number(loop);

			// Create the imageArray
			var imageArray = {img:image, loop:loop, animationImages: animationImages, currentImageNumber: 1, loopCount: 0};
			
			// Add the imageArray loop to the array holding all the animated pngs
			animatedPngs.push(imageArray);
		}
	}

	
	// Create the interval iteration repeating #frameRate number of times per second
	window.setInterval("pa.animate()", 1000 / frameRate);
}

var j = 0;

// Animation function that is run by a setInterval initated in the initilize function
PngAnimator.prototype.animate = function() {
	// Loop through all the animated pngs
	for(var i = 0; i < animatedPngs.length; ++i) {			
		// If the current image object in the loop is set to loop infinitely or the amount of loops hasn't been reach, animate
		if(animatedPngs[i]["loop"] == "loop" || animatedPngs[i]["loopCount"] < animatedPngs[i]["loop"]) {
			// If the total amount of images in the animation has been reached, restart the animation and increment the loopCount value
			if(animatedPngs[i]["currentImageNumber"] > animatedPngs[i]["animationImages"].length - 2) {
				++animatedPngs[i]["loopCount"]; 
				animatedPngs[i]["currentImageNumber"] = 1;
			} else
				++animatedPngs[i]["currentImageNumber"];
			// Display the next image in the animation
			animatedPngs[i]["img"].src = animatedPngs[i]["animationImages"][animatedPngs[i]["currentImageNumber"]].src;
		}
	}
}

// Create a new instance of the PngAnimator class
var pa = new PngAnimator();

// Initialize the PngAnimator when the page has loaded
if(window.addEventListener)
	window.addEventListener("load", pa.initialize, false);
else if(window.attachEvent)
	window.attachEvent("onload", pa.initialize)
else
	window.onload = pa.initialize;