Ext.ns('Ext.pv.util');
Ext.pv.util.ProgressDlg = function(o) {
	
	// Configuration options
	this.progressTitle = (o.progressTitle!=null)? o.progressTitle : '';
	this.progressMsg = (o.progressMsg!=null)? o.progressMsg : '';
	this.updateUrl = (o.updateUrl!=null)? o.updateUrl : '';
	this.updateInterval = (o.updateInterval!=null)? o.updateInterval : 1;
	this.callback = o.callback;
	this.completeTitle = (o.completeTitle!=null)? o.completeTitle : '';
	this.completeMsg = (o.completeMsg!=null)? o.completeMsg : '';
	
	// Internal variables
	this.dialog = null;
	this.updater = null;
	this.log = '';
	this.cnt = 0;
	
	// Methods
	this.show = function() {  

		// Show the initial view of the progress dialog
		this.dialog = Ext.MessageBox.progress(this.progressTitle, this.progressMsg);
		
		// Since the MessageBox is a Singleton, it seems to 
		// show its last known value.  Bumping it again with
		// the starting value that we want seems to do the trick.
		this.dialog.updateProgress(0.01, this.progressMsg, this.progressMsg);
		this.log += 'START: ' + this.progressMsg + '\n';
		
		// Create an updater to dynamically alter the progress dialog
		this.updater = new Ext.Updater(document.getElementById('progressDiv'));
		this.updater.showLoadIndicator = false;

		// Register an update event handler with the updater
		this.updater.on(
			'update', 
			function(el,response) {
				// Update the progress bar with the response
				var responseObj = Ext.decode(response.responseText);
				this.dialog.updateProgress(
						responseObj.percentComplete,
						responseObj.progressMessage);
				
				this.cnt += 1;
				this.log += 'UPDATE[' + this.cnt + ']: ' + responseObj.progressMessage + '\n';

				// If progress has reached 100%, stop the updater,
				// hide the progress dialog and call the callback function.
				if (responseObj.percentComplete>=1.0) {
					this.log += 'HIDE\n';
					this.hide(false, this.completeTitle, this.completeMsg);
				}
			},
			this
		);

		// Start the updater
		this.updater.startAutoRefresh(this.updateInterval, this.updateUrl);
	};
	
	this.hide = function(blnError, title, message) {

		// Stop the updater.
		if (this.updater!=null) {
			this.updater.stopAutoRefresh();
		}

		if (title!=null && title.length>0 && message!=null && message.length>0) {
			// Re-purpose the dialog to show an alert.
			this.dialog.show({
				title : title,
				msg : message,
				buttons : Ext.MessageBox.OK
			});
		} else {
			// Hide the dialog.
			this.dialog.hide();
		}

		// If a callback method was specified then invoke it.
		if (this.callback != null && !blnError) {
			this.callback();
		}
		
		// Uncomment to see the full update history
		//alert(this.log);
		
	};
	
	return this;
};
