/*
 * intercom.js	11/11/2009
 *
 * Copyright (c) 2009 ERPK WEB S.A.
 * All rights reserved.
 */

var Chat = {
    _domain: 'erepublik.com',
    _main: 'http://www.erepublik.com/',
    _openWindow: function(url, name, width, height, isResizeAble){
        name = name.replace(/[^\w\d]/g, "_"); 
        name = name.replace(/undefined/, '_');
        name = name.replace(/\./, '_');
        url = encodeURI(url);
        var left = Math.round((screen.width - width) / 2);
        var top = Math.round((screen.height - height) / 2);
        var styleStr = Chat._makeStyle(left, top, width, height, isResizeAble);
        var res = window.open(url, name, styleStr);
        try{ res.focus(); } catch(E) { }
        return res;    
    },
    _makeStyle: function(left, top, width, height, isResizeAble) {
        var styleStr = 'toolbar=no,location=no,directories=no,status=no,menubar=no,scrollbars=no';
        styleStr += ',resizable=' + (isResizeAble ? 'yes' : 'no');
        styleStr += ',width=' + width + ',height=' + height;
        styleStr += ',left=' + left + ',top=' + top;
        styleStr += ',screenX=' + left + ',screenY=' + top;
        return styleStr;
    },
    _getCookie: function(domain, name){
        document.domain = Chat._domain;
        var nameEQ = name + "=";
        var ca = document.cookie.split(';');
        for(var i=0;i < ca.length;i++) {
            var c = ca[i];
            while (c.charAt(0)==' ') c = c.substring(1,c.length);
            if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
        }
	//document.domain = domain;
        return null;
    },
    _setCookie: function(domain, name, value, days){
        document.domain = Chat._domain;
        if (days) {
            var date = new Date();
            date.setTime(date.getTime()+(days*24*60*60*1000));
            var expires = "; expires="+date.toGMTString();
        }
        else var expires = "";
        document.cookie = name+"="+value+expires+"; path=/; domain="+Chat._domain;
	//document.domain = domain;
    },
    _deleteCookie: function(domain, name){
        Chat._setCookie(domain, name,"",-1);
    },
    Parent: {
        _checker: null,
        _popup: null,
        _sendQueue: [],
        _poll: 150,
		_domain: 'www.erepublik.com',
        init: function(){
			Chat.Parent._domain = document.domain;
        },
        focusChat: function(win){
			try {
				if(Chat.Parent._popup != null) Chat.Parent._popup.focus();
				if(win.focus) win.focus();
			}
			catch(E){ }
        },
        openPopup: function(params){
		    var name = 'videochat_' + params['uid'];
			var url = 'http://' + location.hostname + '/' + params['langId'] + '/chat/open/' + params['room'];
			if (location.port) {
				url = 'http://' + location.host + '/' + params['langId'] + '/chat/open/' + params['room'];
			}
		    Chat.Parent._popup = Chat._openWindow(url, name, 765, 560, true);
        },
        sendCommand: function(command, params){
            if(!Chat.Parent.isOpened() && command == 'room') return Chat.Parent.openPopup(params);
            var cmd = ['command:'+command];
            for(key in params) cmd.push(key+':'+params[key]);
            var cmdStr = cmd.join(',');
            
            Chat.Parent._sendQueue.push(cmdStr);
            if(!Chat.Parent._checker) Chat.Parent.processQueue();
            
            return null;
        },
        isOpened: function(){
            var flag = Chat._getCookie(Chat.Parent._domain, 'chatstatus');
            if(flag == 'ready' || flag == 'loading') return true;
            return false;
        },
        processQueue: function(){
            if(Chat._getCookie(Chat.Parent._domain, 'chatcommand')) {
                Chat.Parent._checker = window.setTimeout(Chat.Parent.processQueue, Chat.Parent._poll);
                return;
            }
            if(Chat.Parent._sendQueue.length == 0) return;
            Chat._setCookie(Chat.Parent._domain, 'chatcommand', Chat.Parent._sendQueue.shift());
        }
    },
    Client: {
        _checker: null,
        _initChecker: null,
        _poll: 150,
        _movie: 'videochat',
		_domain: 'chat.erepublik.com',
        unload: function(){
            Chat._deleteCookie(Chat.Client._domain, 'chatstatus');
            Chat._deleteCookie(Chat.Client._domain, 'chatcommand');
            return true;
        },
        init: function(){
            history.navigationMode = 'compatible';
			Chat.Client._domain = document.domain;
            Chat._setCookie(Chat.Client._domain, 'chatstatus', 'loading');
            // IE
            if(!+"\v1"){
                window.attachEvent('onbeforeunload', function(){
                    if (document.readyState == 'interactive') {  
                        function stop() {  
                            document.detachEvent('onstop', stop);  
                            Chat.Client.unload();  
                        };  
                        document.attachEvent('onstop', stop);  
                        window.setTimeout(function() {  
                            document.detachEvent('onstop', stop);  
                        }, 0);  
                    }  
                });
                window.attachEvent('onunload', Chat.Client.unload);
            }
            // the rest
            else window.onunload = Chat.Client.unload;
            
            // detect when chat is loaded
            Chat.Client._initChecker = window.setTimeout(Chat.Client.checkClientLoaded, Chat.Client._poll);
            
        },
        checkClientLoaded: function(){
            var swf = Chat.Client.findChat();
            var ok = false;
            if(swf) {
                if(typeof swf['OpenRoom'] == 'function') ok = true;
                else ok = false;
            }
            if(!ok) {
                Chat.Client._initChecker =
                window.setTimeout(Chat.Client.checkClientLoaded, Chat.Client._poll);
            }
            else Chat.Client.initComplete();
        },
        initComplete:function(){
            Chat._setCookie(Chat.Client._domain, 'chatstatus', 'ready');
            // go
            Chat.Client.check();
        },
        check: function(){
            if(Chat.Client._checker) window.clearTimeout(Chat.Client._checker);
            
            var what = Chat._getCookie(Chat.Client._domain, 'chatcommand');
            if(what) {
                var parts = what.split(',');
                var command = '';
                var params = {};
                for(var i=0; i<parts.length; i++ ){
                    var p = parts[i].split(':');
                    if(p[0] == 'command' && p.length > 1) {
                        command = p[1];
                        continue;
                    }
                    if(p.length > 1) params[p[0]] = p[1];
                    else params[p[0]] = null;
                }

                if(command != '') {
                    try{
						self.focus();
                        window.opener.Chat.Parent.focusChat(self);
                    }
					catch(ex){ }
                    Chat.Client.execute(command, params);
                }
                Chat._deleteCookie(Chat.Client._domain, 'chatcommand');
            }
            Chat.Client._checker = window.setTimeout(Chat.Client.check, Chat.Client._poll);
        },
        findChat: function(){
			return ChatHandler.movieClip();
            // find swf and return it;
            //var where = document;
            //if(!+"\v1") where = window; // IE
            //if(where[Chat.Client._movie]) {
            //    return document[Chat.Client._movie];
            //}
            //return null;
        },
        execute: function(command, params){
            if(typeof Chat.Client[command+'Command'] == 'function'){
                Chat.Client[command+'Command'](params);
            }
        },
        // callbacks
        roomCommand: function(params){
            if(typeof params['room'] == 'undefined') return;
			
			var client = ChatHandler.movieClip();
			if(!client) return;
			
			if(typeof client['OpenRoom'] == 'function') {
				
				try {
					ChatHandler.NewRoom('room_' + params['room']);
				} catch (ex) {
					console.debug(ex);
				}
				
			}
			
            //var client = Chat.Client.findChat();
            //if(!client) return;
            //if(typeof client['OpenRoom'] == 'function') {
            //    try {
            //        client.OpenRoom('room_' + params['room']);
            //    } catch(ex) {  }
            //}
        }
    }
}

