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


/**
 * This class contains methods for creating and manupulating
 * a ProgressBar object
 */

 /** 
  * Helper function that generates random ids
  * @param {Integer} len The length of the id string
  */
function generateId(len) {
	var id = ""
	for (var i = 0; i < len; i++) {
		id+= Math.round(Math.random() * 10)
	}
	return id
}

/**
 * Extracts style string from an associative array
 * @param {Array} style
 */
function getStyle(style) {
	var styleString = ""
	for (var k in style) {
		styleString += k + ":" + style[k] + ";" 
	} 
	return styleString
}

//keeps track of our progress bars
bars = new Array()

/**
 * Handles animation
 * @param {String} id The id of the ProgressBar
 */
function start(id) {
	bar = bars[id]
	if (bar.pos <= bar.width) {	
		bar.pos++		
		var uWidth = bar.pos + "px"
		document.getElementById(id).style.width = uWidth	
	}
	else {
		clearInterval(bar.tid)
	}
}


/**
 * Constructor
 * @param {Array} style The associative array containing style info
 * @param {Integer} speed Indicates how quickly the animation will run
 * @param {String} container_id The id of the parent div
 */
 function ProgressBar(style, speed, containerId) {
 	this.width = (style["width"]) ? style["width"].substring(0, style["width"].length - 2) : 200
	style["height"] = (style["height"]) ? style["height"] : "30px"
	this.color = style["background"]
	this.style = style
	this.style["width"] = "0px"
	this.id = generateId(10)
	this.containerId = containerId
	this.tid = 0
	this.pos = 0
	this.speed = speed
	bars[this.id] = this
 }
 
 ProgressBar.prototype = {
 	
	template : '<div id="%id%" style="%style%"></div>' 
	,
	/**
	 * Setup div layer for progress bar
	 */
 	setup : function() {
		var html = this.template.replace(/%id%/, this.id)
		html = html.replace(/%style%/, getStyle(this.style))
		document.getElementById(this.containerId).innerHTML = html
	},
	
	/**
	 * Perform the animation
	 */
	start : function() {
		this.tid = setInterval('start("' + this.id + '")', this.speed)  
	}
	
 }
 
