var CControllerRequester = Class.create({
  initialize: function(frequency, browserId) {
    this.frequency = frequency;
    this.currentlyExecuting = false;
    this.timer = null;

    this.lastExecution = new Date();
    this.browserId = browserId;

    this.registerCallback();
  },

  registerCallback: function() {
    if(this.timer != null){
      clearInterval(this.timer);
      this.timer = null;
    }
    this.timer = setInterval(this.onTimerEvent.bind(this), this.frequency * 1000);
  },

  requestController: function(commande, parametres, callback, options){
  	var url = 'Controller/'+'?cmd='+commande;
  	var pars = 'browser='+this.browserId+'&cmd='+commande+'&'+parametres;

    pars += '&dummy='+Math.random();

  	consoleLog("Request:\n"+url+"?"+pars);

  	ajax_options = {
  			'method': 'post',
  			'parameters': pars,
  			'command': commande,
  			'onFailure': ajaxFailureEvent,
  			'onException': ajaxExceptionEvent,
  			'publingOnComplete': callback,
  			'onComplete': AJAX_commutator
  	};

  	Object.extend(ajax_options, options || {});
  	var myAjax = new Ajax.Request(url, ajax_options);
  	delete myAjax;
  },

  stop: function() {
    if (!this.timer) return;
    clearInterval(this.timer);
    this.timer = null;
  },

  onTimerEvent: function() {
    if (!this.currentlyExecuting) {
      try {
        this.currentlyExecuting = true;
        this.requestController('','',null,{});
      } finally {
        this.currentlyExecuting = false;
      }
    }
//    new Effect.vShake('menuFeedBack', {duration:0.3,distance:2,afterFinish:function(){$('menuFeedBack').style.right = '0px';}});
    if(switchTitle != '' || document.title != savedTitle){
      switchActions();
      setTimeout(switchActions, this.frequency * 1000 *1/4);
      setTimeout(switchActions, this.frequency * 1000 *2/4);
      setTimeout(switchActions, this.frequency * 1000 *3/4);
    }
  }
});

var savedTitle;
function switchActions(){
  if(savedTitle == '') savedTitle = document.title;
  if(switchTitle != ''){
    if(document.title != switchTitle){
      document.title = switchTitle;
      $$('td.smallWindowOngletRight')[0].setStyle({backgroundImage:'url(/Img/smallWindow/smallWindowBorder_onglet_r_red.png)'});
      $('chatBar.privateChatButton').style.display = 'none';
      return;
    }
  }
  document.title = savedTitle;
  $$('td.smallWindowOngletRight')[0].setStyle({backgroundImage:'url(/Img/smallWindow/smallWindowBorder_onglet_r.png)'});
  $('chatBar.privateChatButton').style.display = '';
}


var listValue = new Array();
var listDate = new Array();
function AJAX_commutator(originalRequest){

  if(isInDebugMode() && $('rateContainer')){
    listValue.push(originalRequest.responseText.length);
    listDate.push(new Date());

    while((listDate[listDate.length-1].getTime()-listDate[0].getTime())>15*1000){
      listDate.shift();
      listValue.shift();
    }

    $('rateContainer').innerHTML = '<span class="greyTransparency50" style="color:#0F0; font-size:0.8em; padding-right:10px; margin-right:5px; padding-left:10px;">'
                                  +Math.floor(1000*eval(listValue.join('+'))/Math.max(listDate[listDate.length-1].getTime()-listDate[0].getTime(), 1000))+'o/s'
                                  +'&nbsp;&nbsp;&nbsp;:&nbsp;&nbsp;&nbsp;'
                                  +Math.floor(eval(listValue.join('+'))/listValue.length)+'o/r'
                                  +'&nbsp;&nbsp;&nbsp;:&nbsp;&nbsp;&nbsp;'
                                  +Math.floor(100000*listValue.length/Math.max(listDate[listDate.length-1].getTime()-listDate[0].getTime(), 1000))/100+'r/s'
                                  +'</span>';
  }

  // Traitement Erreur de transport
  // Juste dans le cas d'une commande Utilisateur
  if(originalRequest.responseText=='' && originalRequest.request.options.command != ''){
    openErrorForm('Transport Error', 'Unable to contact the Server.<br /><br />If this Error persists, please check your Internet connexion and press F5 to reload Publing.');
  }

  if(originalRequest.responseText==''){
    return -1;
  }

  var response = eval('('+originalRequest.responseText+')');
	consoleLog("Response:\n"+originalRequest.responseText);

  if(response.error_code){
    closeWaitingForm();
    openErrorForm('Error '+response.error_code, response.error_msg);
    // Error -> CallBack
    if(Object.isFunction(originalRequest.request.options.publingOnComplete)){
      (originalRequest.request.options.publingOnComplete)(response);
    }
  }


  // DEBUT AJOUT DES CODES SECONDAIRES, CHAT, STATUS ECT...
  processBeforeCallBack(response);
  // FIN AJOUT DES CODES SECONDAIRES, CHAT, STATUS ECT...


  // CallBack
  if(Object.isFunction(originalRequest.request.options.publingOnComplete) && response.commandResponse){
    (originalRequest.request.options.publingOnComplete)(response.commandResponse);
  }


  // DEBUT AJOUT DES CODES SECONDAIRES, CHAT, STATUS ECT...
  processAfterCallBack(response);
  // FIN AJOUT DES CODES SECONDAIRES, CHAT, STATUS ECT...


}

var processPrivateMessages=null;
function processBeforeCallBack(response){
  if(response.userList && map!=null) refreshUsers(response.userList);
  if(response.followingsOnline) refreshFollowingsStatus(response.followingsOnline);
  if(response.isLogged) refreshMyLoginStatus(response.isLogged);
  if(response.newMessagesList) processNotifMessages(response.newMessagesList);
  if(response.newMessages && Object.isFunction(processPrivateMessages)) processPrivateMessages(response.newMessages);
  if(response.stopAJAX) {
    controller.stop();
    openErrorForm('Disconnection', 'You have open an other window in the same session.', {onClose:function(){
      controller.registerCallback();
    }});
  } else {
    if(controller.timer == null){
      controller.registerCallback();
    }
  }
}

function processAfterCallBack(response){
  if(response.publicFeed) processPublicFeed(response.publicFeed);
  if(response.action) eval(response.action);
  if(response.openMyPubling) openMyPubling = response.openMyPubling;
}

function ajaxFailureEvent(transport){
  closeWaitingForm();
  if(isInDebugMode()){
    openErrorForm('Failure', 'Unable to contact the Server.<br /><br />If this Error persists, please check your Internet connexion and press F5 to reload Publing.');
  }
}

function ajaxExceptionEvent(transport, err){
  closeWaitingForm();
  if(isInDebugMode()){
    openErrorForm('Exception', err.message+'<br />'+err.fileName+' on line '+err.lineNumber+'<br /><br />'+err.stack+'<br /><br />If this Error persists, please check your Internet connexion and press F5 to reload Publing.');
  }
}
