﻿
var Camera = function (imageId, width, height, left, top) {
	this.width = width;
	this.height = height;
	
	
	var s = document.getElementById(imageId).style;
	s.position = "absolute";
	this.style = s;
	
	this.setPosition(left, top);
	
	this.currentIndex = 0;
	
};

Camera.prototype.setPosition = function (left, top) {
	this.left = left;
	this.top = top;
	var s = this.style;
	s.left = -left + "px";
	s.top = -top + "px";
	s.clip = "rect(" + top + "px " + (left + this.width) + "px " + (top + this.height) + "px " + left + "px)";
};

Camera.prototype.move = function (xDisplacement, yDisplacement, callback) {
	var that = this;
	var targetX = this.left + xDisplacement;
	var targetY = this.top + yDisplacement;
	var animate = function () {
		
		if (targetX == that.left && targetY == that.top) {
			// Reached the target position.
			// Call the callback and stop executing
			callback();
		} else {
			if (targetX > that.left) {
				that.left += 1;
			} else if (targetX < that.left) {
				that.left -= 1;			
			}
			
			if (targetY > that.top) {
				that.top += 1;
			} else if (targetY < that.top) {
				that.top -= 1;
			}
			
			that.setPosition(that.left, that.top);
			
			setTimeout(animate, 10);
		}
	};
	animate();
};

Camera.prototype.start = function (commands) {
	var that = this;
	var callback = function () {	
		that.currentIndex++;
		if (that.currentIndex < commands.length) {
			that.start(commands);
		}
	};
	
	var cur = commands[this.currentIndex];
	this.move(cur.x, cur.y, callback);
	
};
