/**
 * @author Martin Okorodudu
 * @email <webmaster@fotocrib.com>
 */

/**
 * This class contains methods for animating div layers
 */

boxes = new Array()

/**
 * Handles all animation
 * @param {String} id The id of the MovingLayer object
 */
function move(id) {
	
	var layer = boxes[id]
	
	if (layer.direction == 1) {
		if (layer.xpos >= layer.xto) {
			layer.xpos-- 
			document.getElementById(layer.id).style.left = layer.xpos + "px"
			if (layer.slope != 0) {
				layer.ypos = Math.abs(Math.round(layer.slope * layer.xpos))
				document.getElementById(layer.id).style.top = layer.ypos + "px"
			}
		}
		else {
			clearInterval(layer.tid)
		}
	}
	else if (layer.direction == 0) {
		if (layer.xpos <= layer.xto) {
			layer.xpos++ 
			document.getElementById(layer.id).style.left = layer.xpos + "px"
			if (layer.slope != 0) {
				layer.ypos = Math.round(layer.slope * layer.xpos)
				document.getElementById(layer.id).style.top = layer.ypos + "px"
			}
		}
		else {
			clearInterval(layer.tid)
		}
	}
	else if (layer.direction == 2) {
		if (layer.ypos <= layer.yto) {
			layer.ypos++ 
			document.getElementById(layer.id).style.top = layer.ypos + "px"
		}
		else {
			clearInterval(layer.tid)
		}
	}
	else if (layer.direction == 3) {
		if (layer.ypos >= layer.yto) {
			layer.ypos-- 
			document.getElementById(layer.id).style.top = layer.ypos + "px"
		}
		else {
			clearInterval(layer.tid)
		}
	}
}

function startAll() {
	for (var layer in boxes) {
		layer.start()
	}
}

/**
 * 
 * @param {String} id The id of the parent div
 * @param {Integer} xfrom The x coordinate of the starting point
 * @param {Integer} yfrom The y coordinate of the starting point
 * @param {Integer} xto The x coordinate of the destination
 * @param {Integer} yto The y coordinate of the destination
 * @param {Integer} speed The speed in microseconds for the animation
 * @param {String} unit % indicates percent otherwise pixels is assumed
 */
function MovingLayer(id, xfrom, yfrom, xto, yto, speed, unit) {
	this.id = id
	this.xfrom = (unit == "%") ? Math.round((xfrom/100) * screen.width) : xfrom
	this.yfrom = (unit == "%") ? Math.round((yfrom/100) * screen.height) : yfrom
	this.xto = (unit == "%") ? Math.round((xto/100) * screen.width) : xto
	this.yto = (unit == "%") ? Math.round((yto/100) * screen.height) : yto
	this.tid = 0
	this.xpos = xfrom
	this.ypos = yfrom
	this.speed = speed
	if (this.xto != this.xfrom) {
		this.slope = (this.yto - this.yfrom) / (this.xto - this.xfrom)
		this.direction = (this.xfrom <= this.xto) ? 0 : 1
	}
	else {
		if (this.yto >= this.yfrom) {
			this.direction = 2
		}
		else {
			this.direction = 3
		}
	}
	boxes[this.id] = this
	
	document.getElementById(this.id).style.position = "absolute"
	document.getElementById(this.id).style.left = this.xfrom + "px"
	document.getElementById(this.id).style.top = this.yfrom + "px"
}

MovingLayer.prototype = {
	start : function() {
		this.tid = setInterval('move("' + this.id + '")', this.speed)
	}
}
