/* Copyright (c) 2007 CRM */

var DataFetcher = {
  tasks : new Array(),
  tickers: new Array(),
  lm : null,
  nsm: null,
  errmsg : null,
  encoding: 'utf-8',
  missedTasks : new Array(),
  checkForAuth : null,
  checkForAuth_flag : false,
  /* PRIVATE FUNCTIONS */ 
   
  Perform : function (DelayPeriod)
  {
    var DATA = new Array();
    for(var taskid in this.tasks)
    {
        if(this.tasks[taskid]['paused'] == false && this.tasks[taskid]['seconds'] == DelayPeriod)
        {
            DATA[taskid] = { module : this.tasks[taskid]['module'], params : this.tasks[taskid]['params'] };
        }
    }    
    this.Send(DATA);
    this.tickers[DelayPeriod] = setTimeout("DataFetcher.Perform("+DelayPeriod+");", DelayPeriod*1000);
  },

  Send : function (DATA)
  {
    if(this.lm) this.lm.style.display='';
    req = new JsHttpRequest();
    req.onreadystatechange = this.OnReadyStateChainge;
    req.caching = false;
    req.open('GET', '?', true);
    req.send( { JSLIB: DATA, encoding : this.encoding } );
  },
   
  OnReadyStateChainge : function()
  {
    if (req.readyState == 4) {
        if (req.responseJS && DataFetcher.FetcingFinished(req.responseJS, true)) {
            for(var key in req.responseJS)
            {
              if(DataFetcher.tasks[key])
              {
                DataFetcher.tasks[key]['func'](req.responseJS[key]);
              }
            }
        }        
    }    
  },
   
  Init : function ()
  {
    try{
        var meta = document.getElementsByTagName('head').item(0).getElementsByTagName('meta').item(0);
        var reg = /charset=([a-z0-9\-]+)/i;
        if(reg.test(meta.content))
        {
            encoding = RegExp.$1;
        }
    }catch(e) {}
    this.lm = document.getElementById('loading_message');
    this.nsm = document.getElementById('nosession_message');
    this.errmsg = document.getElementById('loginFormError');
  },   
   
  SetUpFunc : function (taskid)
  {
    if(!this.tickers[this.tasks[taskid].seconds])
    {
        this.tickers[this.tasks[taskid].seconds] = setTimeout("DataFetcher.Perform("+this.tasks[taskid].seconds+");", this.tasks[taskid].seconds*1000);
    }
  },
  
  FetcingFinished : function (isNoAuth, isPeriodical)
  {
    if(this.lm) this.lm.style.display='none';
    if(this.nsm)
        this.nsm.style.display= (isNoAuth && isNoAuth['NOAUTH'] == 'NOAUTH'? '' : 'none');
    
    if(this.errmsg && isNoAuth && isNoAuth['NOAUTHREASON']) this.errmsg.innerHTML = isNoAuth['NOAUTHREASON'];
    
    if(isNoAuth && isNoAuth['NOAUTH'] == 'NOAUTH' && !isPeriodical)
    {
    	if(!this.checkForAuth) this.CheckForAuth();
    	try{ loginForm(true); }catch(e){ }
    }else if( isNoAuth && isNoAuth['NOAUTH'] != 'NOAUTH')
    {
    	try{ loginForm(false); }catch(e){ }
    }
        
    return (isNoAuth && isNoAuth['NOAUTH'] != 'NOAUTH');
  },
   
  CheckForAuth : function ()
  {
  	if(this.lm.style.display=='none' && (this.checkForAuth_flag == false) && (getCookie('auth_id').length > 0) )
  	{
	  	req = new JsHttpRequest();
	    req.onreadystatechange = function() {
	        if (req.readyState == 4) {
	        	if(DataFetcher.FetcingFinished(req.responseJS))
	        	{        
		            if (req.responseJS && req.responseJS[0] && req.responseJS[0] == 'Ok' ) {
		              	DataFetcher.ProcessLostTasks();
		            }
	        	}
	        	DataFetcher.checkForAuth_flag = false;
	        }
	    }
	    req.caching = false;
	    req.open( 'GET', '?', true );
	    req.send( { JSLIB : { 0 : { module : 'get_auth' } }, encoding : this.encoding } );
	    this.checkForAuth_flag = true;
  	}
    this.checkForAuth = setTimeout('DataFetcher.CheckForAuth();', 1000 * 5);
  },
  
  AddTaskToProcessAfterLogin : function (func, module, params)
  {
  	var new_id = this.missedTasks.length + 1;
  	this.missedTasks[new_id] = { 
  		func : func,
        module : module,
        params : params
  		};
  },
  
  ProcessLostTasks : function()
  {
    clearTimeout(this.checkForAuth);
  	for(var i in this.missedTasks)  	
  	{
  		var task = this.missedTasks[i];
  		this.FetchData(
  			function (rez) { task['func'](rez); DataFetcher.ProcessLostTasks();  }, 
  			this.missedTasks[i]['module'], 
  			this.missedTasks[i]['params']
  			);
  		delete(this.missedTasks[i]);
  		break;
  	}
  },  
  
  
  /* PUBLIC FUNCTIONS */ 
  AddTask : function (func, module, seconds, params, paused)
  {
    var new_id = this.tasks.length + 1;
    this.tasks[new_id] = {
        func : func,
        module : module,
        seconds : seconds,
        params : params,
        paused : (paused == true)
        };
    if(paused != true) this.SetUpFunc(new_id);    
    return new_id;
  },
  
  Pause : function (taskid)
  {
    this.tasks[taskid]['paused'] = true;
  },
  
  Play  : function (taskid)
  {
    this.tasks[taskid]['paused'] = false;
    this.SetUpFunc(taskid);
  },
  
  SetParams : function (taskid, params)
  {
    this.tasks[taskid]['params'] = params;
  },
  
  RunNow : function (taskid)
  {
    var Data = new Array();
    Data[taskid] = { module : this.tasks[taskid]['module'], params : this.tasks[taskid]['params'] };
    this.Send(Data);
  },
  
  FetchData : function (func, module, params)
  {
    if(this.lm) this.lm.style.display='';
    req = new JsHttpRequest();
    req.onreadystatechange = function() {
        if (req.readyState == 4) {
        	if(DataFetcher.FetcingFinished(req.responseJS))
        	{        
	            if (req.responseJS && req.responseJS[0]) {
	                func(req.responseJS[0]);
	            }
        	}else
        	{
        		DataFetcher.AddTaskToProcessAfterLogin(func, module, params);
        	}
        }
    }
    req.caching = false;
    req.open( 'GET', '?', true );
    req.send( { JSLIB : { 0 : { module : module, params : params } }, encoding : this.encoding } );
  },
  
  FetchDataPost : function (func, module, params)
  {
  	if(this.lm) this.lm.style.display='';
    req = new JsHttpRequest();
    req.onreadystatechange = function() {
        if (req.readyState == 4 && DataFetcher.FetcingFinished(req.responseJS)) {            
            if (req.responseJS && req.responseJS[0]) {
                func(req.responseJS[0]);
            }
        }
    }
    req.caching = false;
    req.open( 'POST', '?JSLIB[0][module]=' + module , true );
    params['encoding'] = this.encoding;
    req.send( params );
  }
};

DataFetcher.Init();


