﻿$(document).ready(function() {
	
	function Rotator(el) {

		this.el							= el;

		this.rotation_start_timeout 	= 500;
		this.rotation_reriod			= 700;
		this.thumbnails_offset			= 0;
		this.do_rotate					= true;
		this.dim_regexp					= new RegExp("[0-9]{1,}x[0-9]{1,}", "i");

		this.uid						= this.el.attr("uid");
		this.rel						= this.el.attr("rel").split("r:").join("");
		this.original_src				= this.el.attr("src");
		this.thumbnails					= this.rel.split(",");
		this.parts						= this.original_src.split("preview");
		this.src_prefix					= this.parts[0]+"preview/";
		this.dimensions					= this.dim_regexp.exec(this.original_src);

		this.objConstruct = function() {
			this.do_rotate 			= true;
			this.thumbnails_offset 	= 0;
			this.startRotate();
		}
		
		this.preloadImage = function(obj_img) {
			var self = this;
			if (!obj_img.complete) {
				window.setTimeout(
					function() {
						self.preloadImage(obj_img);
					},
					700
				);
			} else {
				this.changeThumbnail(obj_img.src);
			}		
		}
		
		this.startRotate = function() {
							
			tmb = this.thumbnails[this.thumbnails_offset];
			tmb = tmb.split("o").join("original");
			
			if (tmb.indexOf(".") != "-1") {
				filename = this.src_prefix + tmb.split(".").join("."+this.dimensions+".", tmb) + ".jpg";
			} else {
				filename = this.src_prefix + tmb + "." + this.dimensions + ".jpg";
			}
			
			obj_img 		= new Image();
			obj_img.src 	= filename;
			this.preloadImage(obj_img);
			
			if (this.thumbnails_offset == this.thumbnails.length -1) {
				this.thumbnails_offset = 0;
			} else {
				this.thumbnails_offset++;
			}
			
			if (!this.do_rotate) return this.stopRotate();
			
			var self = this;
			window.setTimeout(
				function() {
					self.startRotate();
				}
				, 
				this.rotation_reriod
			);
			
		}		

		this.stopRotate = function() {
		
			this.el.attr("src", this.original_src);
			this.do_rotate = false;
			return false;
		
		}
		
		this.changeThumbnail = function(filename) {
		
			if (!this.do_rotate) return this.stopRotate();
			this.el.attr("src", filename);
		
		}

	}
		
	window.rotations = new Array();

	$("img[rel^='r:']").mouseenter(function() {

		var uid = $(this).attr("uid");
		if (window.rotations[uid]) {
		
			window.rotations[uid].objConstruct();
		
		} else {
		
			window.rotations[uid] = new Rotator($(this));
			window.rotations[uid].objConstruct();
		
		}

	}).mouseleave(function() {

		var uid = $(this).attr("uid");
		if (window.rotations[uid]) window.rotations[uid].stopRotate();

	});

});