/*
 * 09/03/2006 - 19:04:30
 * 
 * Ajax progress bar
 * require Prototype Javascript library!
 *
 * Copyright (C) 2006 Michele Ferretti
 * michele.ferretti@gmail.com
 * http://www.blackbirdblog.it
 * 
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License
 * as published by the Free Software Foundation; either version 2
 * of the License, or any later version.
 * 
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
 *
 */
var instanceNo = 0;
var AjaxProgressBar = Class.create();
AjaxProgressBar.prototype = {
	initialize: function(progressBarElementId, barElementId, initProperties){
		this.progressBarElement = document.getElementById(progressBarElementId);
		this.barElement = document.getElementById(barElementId);		
		if( initProperties != null ){
			this.frequency = initProperties["frequency"];
			this.url = initProperties["url"];
			this.total = initProperties["total"];
		}else{ this.frequency = 2; }
		this.value = 0;
		this.isFinish = false;
		this.repaint();
		this.id = "AjaxProgressBar"+ instanceNo++;
		window[this.id] = this; 
	},
	setValue: function(value){ this.value = value; this.repaint(); },
	repaint: function(){
		if( this.value >= 0 && this.value <= 100 ){
			this.barElement.style.width = this.value +"%";
		}
	},
	start: function(){ this.update(); },
	update: function(){
		var upThis = this;
		var ajax = new Ajax.Request(this.url, {
			method: "get",
			onSuccess: function(res){ upThis.updateSuccess(res); },
			onFailure: function(res){ alert("Error: "+ res.status +" "+ res.statusText);}
		});
		if( !this.isFinish ){
			setTimeout("window."+ this.id +".update()", this.frequency*1000);
		}
	},
	updateSuccess: function(res){
		var value = parseInt(res.responseXML.getElementsByTagName("value")[0].firstChild.nodeValue);
		var percent = Math.floor((100*value)/this.total);
		this.setValue(percent);
		this.isFinish = percent == 100;		
	}
}

