
function system(){
    this.status = 'ok';
    this.time_mgr = new time_manager();
    
    
}

function time_manager(){
    this.get_microtime = function microtime (get_as_float, reset) {
        var dt = new Date();
        // Check for reset: normaly from tx_cmd rtc
        if((reset !== undefined) && (reset === true)){
            var tmp = dt.getTime();
           dt.setTime(0);
           var tmp2 = dt.getTime();  
        }
        var now = dt.getTime();
        var s = parseInt(now, 10);
        return (get_as_float) ? now : (Math.round((now - s) * 1000) / 1000) + ' ' + s;
    }
}

function module_manager(){
    self = this;

    this.modules = [];
    
    this. install = function install(aj_cmd){
        if(aj_cmd.params.js === undefined){
            alert("No module code passed");
            return false;
        }
        $('#script_blocks').append(aj_cmd.params.js);
        delete aj_cmd.params.js;
        //alert("params js deleted");
        return true;   
    } 

}

function ajax_manager(url){
    
    self=this;
    
    this.cmd_blk = new DAB_CMD_Block();
    this.url = url; 
    this.tx_time = 0;
    this.rx_time = 0;
    this.tx_rx_time = 0;
    this.proc_time = 0;
    this.end_time = 0;
    this.total_time = 0;
    this.status = 'Idle';
    // Init front end controls
    function update_status(status, colour){
        if(colour === undefined) colour = 'green';
        self.status = status;
     $('#panel-ajax .displays td.status').html(self.status).css('color',colour);
     switch(status){
         case 'Processing':
          $('#panel-ajax .displays td.tx_rx_time').html(self.tx_rx_time+"ms");
          break;
          case 'Idle':
          $('#panel-ajax .displays td.proc_time').html(self.proc_time+"ms");  
          $('#panel-ajax .displays td.total_time').html(self.total_time+"ms");
          break; 
     }
    }
     
    this.send = function send(){
       self.tx_time = app.Sys.time_mgr.get_microtime(false, true);
       $.ajax({data:{'aj_cmd':JSON.stringify(this.cmd_blk)}}); 
       //self.cmd_blk = null;
   }
    
    this.process = function process(aj_cmd){
        self.rx_time = app.Sys.time_mgr.get_microtime(true);
        self.tx_rx_time = self.rx_time - self.tx_time;
        update_status('Processing', 'yellow');
        // ALL cmd's are handled by modules.
        // Check if we need to load any module cs code.
        if(app.mod_mgr.modules[aj_cmd.to] !== undefined){
          app.mod_mgr.modules[aj_cmd.to].process(aj_cmd);  
        }else{
            // Load the module cs code.
            if(app.mod_mgr.install(aj_cmd) === true){
              // Now process the CMD block.
              app.mod_mgr.modules[aj_cmd.to].process(aj_cmd);  
            }else{
                alert("Could not install module");
                return false;
            }           
        }
        self.end_time = app.Sys.time_mgr.get_microtime(true);
        self.proc_time = self.end_time - self.rx_time;
        self.total_time = self.end_time - self.tx_time;
        update_status('Idle', 'blue');
    }
    
    this.init = function init(){
      $.ajaxSetup({
          beforeSend: function(xhrObj){
                xhrObj.setRequestHeader("Content-Type","application/json");
                xhrObj.setRequestHeader("Accept","application/json");
        },
         cache: false,
         type:'post',
         timeout: 30000,
         url: this.url,
         dataType: 'json',
         error: this.error,
         beforeSend: this.pre_ajax,
         success: this.process
      });
     update_status('Idle', 'blue');
    }
    
    this.error = function error (event, request, settings){
      //$('#loading').dialog('close');
      alert("AJAX ERROR: "+event.status);
       switch(event.status){
         case 200:
         return;
         break; 
          
         default:
        alert("AJAX error : "+event.status+" : "+event.statusText ); 
         break;
       }
       update_status('ERROR', 'red');
   }
   
   this.pre_ajax = function pre_ajax(){
    //$('#loading').dialog('open');
    self.tx_time = app.Sys.time_mgr.get_microtime(true); 
    update_status('Sending', 'red');
  }
  
  this.init();
}

// Data Structures
function DAB_CMD_Block(){
        this.target = '4';
        this.from = '';
        this.to = '';
        this.cmd = '';
        this.params = [];
        this.result = [];
        this.error_no = 0;
        this.err_msg = '';       
}

// Prototypes
// Check if item in array
Array.prototype.hasObject = (
  !Array.indexOf ? function (o)
  {
    var l = this.length + 1;
    while (l -= 1)
    {
        if (this[l - 1] === o)
        {
            return true;
        }
    }
    return false;
  } : function (o)
  {
    return (this.indexOf(o) !== -1);
  }
);

