/**
 * Ajax
 */
function Micos_Ajax() {}
Micos_Ajax.prototype = {
  // objekt komunikace
  xmlHttp: false,

  // funkce pro zpetne volani
  callback: null,

  // fronta
  queue: [],

  /**
   * Spoustec
   * @param  string   Url
   * @param  integer  Interval volani
   * @param  string   Funkce, ktera se bude volat
   */
  Trigger: function(url, timer, callback)
  {
    var self = this;
    intervalID = setInterval(function() {self.Call({method: 'GET', url: url, callback: callback})}, timer * 1000);
  },

  /**
   * Volani
   * @param  string  Url
   * @param  string  Funkce, ktera se bude volat
   */
  Call: function(option)
  {
    if (!option.method) {
      option.method = 'POST';
    }
    this.queue.push({method: option.method, url: option.url, callback: option.callback});
    this.makeRequest();
  },

  /**
   * Pozadavek
   */
  makeRequest: function()
  {
    if (!this.xmlHttp) {
      this.httpClient();
    }

    var self = this;
    if (this.xmlHttp.readyState == 4 || this.xmlHttp.readyState == 0) {
      if (this.queue.length > 0) {
        if (params = this.queue.shift()) {
          try {
            this.xmlHttp.open(params.method, params.url, true);
            this.xmlHttp.onreadystatechange = function() {self.readyStateChangeCallback(params.callback);};
            if (params.method == 'POST') {
              this.xmlHttp.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
              this.xmlHttp.send();
            } else {
              this.xmlHttp.send(null);
            }
          } catch(e) {}
        }
      }
    } else {
      setTimeout(function() {self.makeRequest()}, 1);
    }
  },

  /**
   * Zmena statusu
   * @param  string  Funkce, ktera se bude volat
   */
  readyStateChangeCallback: function(callback)
  {
    try {
      switch (this.xmlHttp.readyState) {
        case 4:
          if (this.xmlHttp.status == 200) {
            var response = this.Response();
            eval(callback + '(response);');
          }
        break;
      }
    } catch(e) {}
  },

  /**
   * Odpoved
   */
  Response: function()
  {
    var content = this.xmlHttp.getResponseHeader('Content-Type');
    if (content.indexOf(';') != -1) {
      content = content.substring(0, content.indexOf(';'));
    }

    // odpoved v xml
    if (content == 'application/xml') {
      return this.xmlHttp.responseXML;
    }

    // odpoved jako text
    return this.xmlHttp.responseText;
  },

  /**
   * Pripojeni
   */
  httpClient: function()
  {
    try {
      this.xmlHttp = new XMLHttpRequest();
    } catch(e) {
      var XmlHttpVersions = new Array('MSXML2.XMLHTTP.6.0', 'MSXML2.XMLHTTP.5.0', 'MSXML2.XMLHTTP.4.0', 'MSXML2.XMLHTTP.3.0', 'MSXML2.XMLHTTP', 'Microsoft.XMLHTTP');
      for (var i = 0; i < XmlHttpVersions.length && !this.xmlHttp; i++) {
        try {
          this.xmlHttp = new ActiveXObject(XmlHttpVersions[i]);
        } catch(e) {}
      }
    }
  }
}
