// Call the ajaxResponser
//////////////////////// 
// ajaxQueue plugin needed
// port: 'identifier' // The identifier of the ajax request
// mode: 'abort', 'sync', 'queue' // Set the queue handling mode
$.inleadAjax = function(action, data, callback, port, mode) {

	if(EasyOpac.debug) {
		console.log('Calling'+action+' with '+data);
	}
	$.ajax({
		  url: '/ajaxResponder.php?action='+action
		, data: data
		, success: callback
		, dataType: 'json'
		, port: port
		, mode: mode
		, error : function(XMLHttpRequest, textStatus, errorThrown) {
			console.log(this);
			EasyOpac.alert("Error! call against '"+action+"' failed!<br />Error:<br />"+textStatus+"<br /><br />Please notify barfoed!");

		}
	});
}

$.inleadAjaxSync = function(action, data, callback, port, mode) {

	if(EasyOpac.debug) {
		console.log('Calling'+action+' with '+data);
	}
	$.ajax({
		  url: '/ajaxResponder.php?action='+action
		, data: data
		, success: callback
		, dataType: 'json'
		, port: port
		, mode: mode
		, async: false
		, error : function(XMLHttpRequest, textStatus, errorThrown) {
			console.log(this);
			EasyOpac.alert("Error! call against '"+action+"' failed!<br />Error:<br />"+textStatus+"<br /><br />Please notify barfoed!");

		}
	});
}

/**
*
* Adding string before the first '-' character in the document title
*
*/

$.addToDocumentTitle = function(addString) {
	originalTitle = document.title;
	splitIndex = originalTitle.indexOf('-');
	
	preTitle = originalTitle.substring(0, splitIndex);
	postTitle = originalTitle.substring(splitIndex, originalTitle.length);
	
	document.title = preTitle+'- '+addString+' '+postTitle;
}

/**
* 
* Styling of the fileupload
* 
*/

var FileUploadUI =  function(dUploadButtonEl){
	this.init.apply(this,arguments);
}

FileUploadUI.prototype = {
     
 init:function(dUploadButtonEl){

         var dEl = this.getEl(dUploadButtonEl);
         if( !dEl.type || dEl.type!='file' || !dEl.form ) return null;

         this._uploadButtonEl = dEl;
         this._uploadPathEl =   dEl.form.elements.namedItem(this.pathElementName);
         
         if( this._uploadPathEl ){
             this._eventListeners = [];
             this.addEvent(dEl,'change',this.syncFilePath);
             this.addEvent(dBtn.form,'submit',this.destruct);
             this.makeAccessible();
         }
 },
 
 pathElementName:'frontendInputFilePath',
 
 
 getEl:function(el){
       if( typeof(el) === 'string') el = document.getElementById(el);
       return el;
 },
 
 //simple addEvent, buggy and better replace it with your own Event Library
 addEvent:function(el,type,fn){
        
        el = this.getEl(el);
        
        var sOn = el.attachEvent ? 'on' : '';
        var oThis = this ;

        //let scope always be this (FileUploadUI)
        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);
        };
  },

  //you need to sync the value when user select a new file path;
  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;
              dPath.style.backgroundColor = '#ffffcc';
         
  },

  _onBtnKeyDown:function(e){
      
      if(e.keyCode != 13) return ;
      var dBtn =  this._uploadButtonEl;
      if( dBtn.click ) dBtn.click();
  },

  _onBtnBlur:function(e){
      var dPath = this._uploadPathEl;
      dPath.style.backgroundColor = '#fff';
  },

  destruct : function (){
        var dPath = this._uploadPathEl;
        var dBtn =  this._uploadButtonEl;
            dPath.disabled = true ;
            dBtn.style.display = 'none';//focus-not-allowed

        for( var i,arg;arg=this._eventListeners[i];i++){
             this.removeEvent.call(this,arg);  
        }
        this._eventListeners = null;
        
  }      
}
