var u = new uploader();

function uploader() {
  this.isUploading = false;
  this.files = 0;
  this.sid = '';
  this.log = '';
  this.statusBox = '';
  this.messageBox = '';
  this.theform = '';
  this.delay = 250;
  this.maxbarwidth = '';
  
}

uploader.prototype.init = function() {
  this.sid = getObj( 'tmp_sid' ).value;
  this.log = getObj( 'log' );
  this.theform = getObj( 'uplform' );
  this.statusBox = getObj( 'uploadstatus' );
  this.statusBox.style.display = 'block';
  this.messageBox = getObj( 'uploadmessage' );
  this.maxbarwidth = this.getStyle( 'uploadbar-outer', 'width' ).replace( /px/, '' );;
}

uploader.prototype.start = function() {
  this.init();
  this.theform.submit();
  this.isUploading = true;
  this.message( 'Starting upload...' );
  //wait a little before asking for status (our status request moght get there before our upload request)
  window.setTimeout( 'u.getProgress()', 1500 );  
}

uploader.prototype.getProgress = function() {
  var me = this;
  
  $.get( '/modules/site/uploadstatus.php?tmp_sid=' + this.sid, function(resp) { me.showProgress( resp ); } );
  //FL.responseHandler = 'u.showProgress';
  //FL.handle( 'retrieve', '/modules/site/uploadstatus.php?tmp_sid=' + this.sid );  
}

uploader.prototype.showProgress = function( resp ) {
  eval( 'var status = ' + URLDecode( resp ) );
  if( status[0] == '100' ) {
    this.fillProgressBar();
    this.message( 'Upload complete' );
    this.isUploading = false;
  } else {
    this.updateProgressBar( status[0] );
    this.message( '<div style="float:left;">' + status[0] + '</div><div style="text-align:right;">' + status[1] + ' /  ' + status[2] + '</div>' );
  }
  if( this.isUploading ) window.setTimeout( 'u.getProgress()', u.delay );   
}

uploader.prototype.message = function( m ) {
  this.messageBox.innerHTML = m;
}

uploader.prototype.updateProgressBar = function( p ) {
  var curwidth = parseInt( this.getStyle( 'uploadbar-inner', 'width' ).replace( /px/, '' ) );
  var percentage =  parseFloat( p.replace( /%/, '' ) );

  var pixels = parseFloat( (this.maxbarwidth / 100 ) * percentage );
  if( curwidth < this.maxbarwidth && curwidth < pixels ) {
    var b = getObj( 'uploadbar-inner' );
    b.style.width = ( curwidth + 1 ) + 'px';
    window.setTimeout( 'u.updateProgressBar( "' + p + '" )', 20 );
  }
}

uploader.prototype.fillProgressBar = function() {
  var b = getObj( 'uploadbar-inner' );
  b.style.width = this.maxbarwidth + 'px';  
}

uploader.prototype.getStyle = function(el,styleProp) {
	var x = document.getElementById(el);
	if (x.currentStyle)
		var y = x.currentStyle[styleProp];
	else if (window.getComputedStyle)
		var y = document.defaultView.getComputedStyle(x,null).getPropertyValue(styleProp);
	return y;
}


