/**
 * chatCommunication - class controlls all AJAX calls
 *
 * @param {String} domainChat
 * @param {String} chatKey
 * @constructor
 * @class
 */

function multiChatCommunication(domainChat, chatKey) {
    var self = this;

    self.chat    = null;
    self.ka      = null;
    self.history = {};
    self.stack   = [];

    self.alreadyKeepAlive = false;
    self.isInit           = false;
    self.domainChat       = domainChat;
    self.chatKey          = chatKey;

    eChatUtils.call(this);

    this.init = function() {
        var div = document.body.appendChild(document.createElement('div'));
        var src = [self.domainChat, 'chat_transfer.php'].join('');

        div.className     = 'chatTransferFrame';
        div.style.display = 'none';
        div.iframeLoad    = function () {
            self.isInit = true;
            while (self.stack.length) {
                _postMessage(self.history[self.stack.shift()]);
            }
        };
        div.iframeLoadKa  = function () {
            self.keepAlive();
        };
        div.innerHTML     = [
            '< iframe id="iframe_multi_com_chat" src="', src, '" name="chat" onload="this.parentNode.iframeLoad();">',
            '< iframe id="iframe_multi_ka_com_chat" src="', src, '" name="ka_chat"   onload="this.parentNode.iframeLoadKa();">'
        ].join('');
        
        self.chat = $('iframe_multi_com_chat');
        self.ka   = $('iframe_multi_ka_com_chat');
        

        if (window.postMessage) {
            if (window.addEventListener) {
                window.addEventListener('message', _onMessage, false);
            } else if (window.attachEvent) {
                window.attachEvent('onmessage', _onMessage);
            }
        }
    }
    
  
    function _postMessage(obj) {
        self.chat.contentWindow.postMessage(self.toJSON(obj), self.domainChat);
    }

   /**
    * Make request to server
    *
    * @param {Object} obj Object of parameters to request
    * @param {Function} callBack Callback
    * @return {Boolean} listen Flag - listen multiplextor or make regular call
    */
    this.askServer = function(obj, callBack){
        if (window.postMessage) {
            var key = self.unicId();
            self.history[key] = {
                chat_tmp_key: self.chatKey,
                orgin: document.domain,
                hid:      key,
                data:     obj,
                callBack: callBack ? callBack : function() {}
            }
            if (!self.isInit) {
                self.stack[self.stack.length] = key;
            } else _postMessage(self.history[key]);
        } else {
            //if browser is old - use simple ajax call
            self.ajax({
                url: '/multi_chat?identifier=' + self.chatKey,
                success: function(responseText) {
                  var req = {responseText: responseText}
                  try {
                    if (listen) {
                      eval(req.responseText);
                      self.keepAlive();
                    }
                    else {
                      self.askServerSuccess(req, obj);
                      if (callBack) callBack(req);
                    }
                  }
                  catch(e){
                    //console.log(e);
                  }
                }
            });
        }
    }

    function _onMessage(e) {
        var data = self.fromJSON(e.data);
        if (data && self.history[data.hid]) {
            self.askServerSuccess(data.req);
            var callBack = self.history[data.hid].callBack;
            if (self.getType(callBack) == 'function') callBack(data.req);
            delete self.history[data.hid];
        }
    }
    
   /**
    * Method for load on success ajax call
    *
    * @param {Object} req Object of server response
    */
    this.askServerSuccess = function(req) {
        if (req && req.responseText) {
            var root = self.fromJSON(req.responseText);
            if (root) {
                switch(root.nodeName) {
                    case 'keepAlive':
                        _keepAlive()
                        break;
                    default:
                    	_keepAlive();
                    	addMessageToList(root.nodes);
                    	break;
                }

            }
        }  
    }

    function _keepAlive() {
        if (self.alreadyKeepAlive) {
            self.alreadyKeepAlive = false;
            self.keepAlive();
        }
    }
    
   /**
    * Listen messages from server
    *
    */
    this.keepAlive = function(){
        if (self.alreadyKeepAlive) return false;
        
        self.alreadyKeepAlive = true;
        var key = self.unicId();
        self.history[key] = {
            chat_tmp_key: self.chatKey,
            orgin:        document.domain,
            hid:          key,
            data:         '',
            keepAlive:    1
        };
        self.ka.contentWindow.postMessage(self.toJSON(self.history[key]), self.domainChat);
    }


    self.init();
}