if(!themis) { var themis = new Object(); }

themis.cdn_images = Class.create();
themis.cdn_images.prototype = {

	initialize : function(options) {
		$$('img').each(function(image) {
			new themis.cdn_image_check(image, options);
		});
	}
}

themis.cdn_image_check = Class.create();
themis.cdn_image_check.prototype = {

	default_options : {
		cdn_url : "http://cdn.themis-media.com",
		origin_url : "http://cdn-origin.themis-media.com",
		script_url : "/global/ajax/cdn_refresh.php"
	},
	options				: null,
	element				: null,

	initialize : function(image,options)
	{
		// Set the options. First reset to derfault, then overwrite with the values passed in.
		this.options = Object.clone(this.default_options);
		Object.extend(this.options, options || {});

		this.element = image;

		// First, check if this image is hosted on our CDN
		if(this.element.src.indexOf(this.options.cdn_url) >= 0)
		{
			// Now try to load the image via JavaScript.
			var img = new Image();

			// If there is an error loading the image, fire this event.
			img.onerror = function(event) {

				// Now try to load the image off our CDN origin.
				var img2 = new Image();
				img2.onload = function(event) {

					// If the image is found on our origin, force a CDN refresh of the image ...
					new Ajax.Request(this.options.script_url + "?url=" + encodeURIComponent(this.element.src),{method:'get'});

					// ... and set the source of the element on the page to that of our origin. The image is already cached, so we may as well use it.
					this.element.src = this.element.src.replace(this.options.cdn_url,this.options.origin_url);
				}.bind(this);

				img2.src = this.element.src.replace(this.options.cdn_url,this.options.origin_url);
			}.bind(this);
			img.src=this.element.src;
		}
	}
}

Event.observe(document,'dom:loaded', function() {new themis.cdn_images()}, false);
