var FileUploadUI =  function(dBtn,pathElementName){
	this.init.apply(this,arguments);
}
FileUploadUI.prototype = {
	init:function(dBtn,pathElementName){
		var dEl = this.getEl(dBtn);
		if( !dEl.type || dEl.type!='file' || !dEl.form ) return null;
		this._uploadButtonEl = dEl;
		this._uploadPathEl = dEl.form.elements.namedItem(pathElementName);
		if( this._uploadPathEl ) {
			this._eventListeners = [];
			this.addEvent(dEl,'change',this.syncFilePath);
			this.addEvent(dBtn.form,'submit',this.destruct);
			this.makeAccessible();
		}
	},
	getEl:function(el){
		if( typeof(el) === 'string') el = document.getElementById(el);
		return el;
	},
	addEvent:function(el,type,fn){
		el = this.getEl(el);
		var sOn = el.attachEvent ? 'on' : '';
		var oThis = this ;
		var wfn =  function(e){
			fn.call(oThis  ,e || window.event , el );
		};
		this._eventListeners.push( [el,type,wfn ]   );
		if(sOn) {
			el.attachEvent( sOn + type , wfn  );
		} else if(el.addEventListener) {
			el.addEventListener(type , wfn , false);
		};
		return wfn;
	},
	removeEvent:function(el,type,wfn){
		el = this.getEl(el);
		var sOn = el.attachEvent ? 'on' : '';           
		if(sOn){
			el.dettachEvent( sOn + type , wfn  );
		}else if(el.addEventListener){
			el.removeEventListener(type , wfn , false);
		};
	},
	syncFilePath:function() {
		var dPath = this._uploadPathEl;
		var dBtn =  this._uploadButtonEl;   
		dPath.value = dBtn.value.split('/').pop().split('\\').pop();
		if(  typeof(this.onChange) === 'function' ){
			this.onChange.call( this, dPath.value );
		}
	},
	onChange:function(){
		
	},
	makeAccessible:function(){
		var dPath = this._uploadPathEl;
		var dBtn =  this._uploadButtonEl;     
		dPath.tabIndex = -1;
		this.addEvent( dPath ,'focus' , this._onPathFocus );
		this.addEvent( dBtn  ,'focus' , this._onBtnFocus );
		this.addEvent( dBtn  ,'blur' , this._onBtnBlur );
		this.addEvent( dBtn ,'keydown' , this._onBtnKeyDown );
		this.makeAccessible = function(){};
	},
	_onPathFocus:function(){
		var dBtn =  this._uploadButtonEl;
		dBtn.focus();
		return false;
	},
	_onBtnFocus:function(){
		var dPath = this._uploadPathEl;
	},
	_onBtnKeyDown:function(e){
		if(e.keyCode != 13) return ;
		var dBtn =  this._uploadButtonEl;
		if( dBtn.click ) dBtn.click();
	},
	_onBtnBlur:function(e){
		var dPath = this._uploadPathEl;
	},
	destruct : function (){
		var dPath = this._uploadPathEl;
		var dBtn =  this._uploadButtonEl;
			dPath.disabled = true ;
			dBtn.style.display = 'none';
		for( var i,arg;arg=this._eventListeners[i];i++){
			this.removeEvent.call(this,arg);  
		}
		this._eventListeners = null;
	}      
}