/*
 * Copyright (c) 2008, Aleajecta
 * All rights reserved.
 * 
 * The Service and any necessary software used in connection with the 
 * Service ("Software") contain proprietary and confidential information 
 * that is protected by applicable intellectual property and other laws.
 * You agree not to modify, rent, lease, loan, sell, distribute or create
 * derivative works based on the Service or the Software, in whole or in part.
 */
/**
 * @author Greenseed
 */
var MESSAGE_TYPE_ACTION = 0;
var MESSAGE_TYPE_INFO = 1;
var MESSAGE_TYPE_ERROR = 2;
var MESSAGE_TYPE_ATTACK = 3;

function Chat(){ this._construct() }(function()
{
    var TYPE = 0;
    var NICK = 1;
    var LEVEL= 2;
    var TEXT = 3;
    var TIMESTAMP = 4;
    var USERID = 5;
    
    var DISPLAY_START_INDEX = 0;
    var DISPLAY_COUNT = 12;
    var DISPLAY_COUNT_WIDTH = 74; //Number of Width Char Possible to Complete 1 Line.
    var DISPLAY_TIMERID = null;
    Chat.updateTimerId = null;
    Chat.lastIndex = 0;

    var MESSAGE = new Array();
    var MESSAGE_MAX = 5;
    Chat.eleChatBox = null;
    Chat.eleChatInput = null;
    Chat.isMouseOver = false;
    Chat.button = null;

    
    var DISPLAY = function()
    {
        return;
    };
    Chat.refreshDisplay = function()
    {
        return;
        DISPLAY();
    };
    Chat.buttonUp = function()
    {
    
    };/*
    Chat.nameOver = function(owner)
    {
        owner.style.fontSize = "14pt";
    };
    Chat.nameOut = function(owner)       
    {
        owner.style.fontSize = "12pt";
    };*/
    Chat.nameDown = function(owner,userId)
    {
        if(User.level != 3 || !userId)
            return;

        var _text = "Please Confirm BAN User: "+owner.innerHTML+" / "+userId;
        var _userId = userId;
        ConfirmBox.show
        (
            _text,
            function(_userId)
            {
                Chat.ban(_userId);
                ConfirmBox.hide();
            },
            function(_userId)
            {
                Chat.unban(_userId);
                ConfirmBox.hide();
            },
            function(_userId)
            {
                ConfirmBox.hide();
            }
        );
    };/*
    Chat.textOver = function(owner)
    {
        owner.style.color = "#CCCCCC";     
    };
    Chat.textOut = function(owner)
    {
        owner.style.color = "#BBBBBB";  
    };*/
    Chat.keyPress = function(event) 
    {
        if(!Chat.eleChatInput.value)
            return;
        var event = window.event ? window.event : event;
        if((event.keyCode | event.charCode) == 10 || (event.keyCode | event.charCode) == 13)
        {
            switch(Chat.eleChatInput.value.indexOf("/"))
            {
                case 0:
                {
                    var params = Chat.eleChatInput.value.split(" ");
                    Chat.eleChatInput.value = "";

                    if(!params || !params.length)
                        break;

                    switch(params[0]) 
                    {
                        case "/help":
                        {
                            if(params.length > 1)
                            {
                                switch(params[1])
                                {
                                    case "ban":
                                        alert(CHAT.COMMAND_HELP_BAN);break;
                                    case "unban":
                                        alert(CHAT.COMMAND_HELP_UNBAN);break;
                                    case "msg":
                                        alert(CHAT.COMMAND_HELP_MSG);break;
                                    case "update":
                                        alert(CHAT.COMMAND_HELP_UPDATE);break;
                                    default:
                                        alert("Bad Command Syntax: "+params[1]+", For "+"params[0]");
                                }
                            }
                            else
                                alert(CHAT.COMMAND_HELP);

                        }break;
                        case "/ban":
                        {
                            
                        }break;
                        case "/unban":
                        {
                            
                        }break;
                        case "/msg":
                        {
                            alert(CHAT.COMMAND_HELP_MSG);   
                        }break;
                        case "/update":
                        {
                            var param = Number(params[1]);
                            if(param < 1 || param > 900)
                                alert(CHAT.COMMAND_HELP_UPDATE);
                            else
                            {
                                clearInterval(Chat.updateTimerId);
                                Chat.updateTimerId = setInterval('Chat.get();',param*1000);
                                alert("Your update interval is now: "+ param +" seconds");  
                            }
                        }break;
                        case "/logout":
                        {
                    		JsRequest.open('GET', 'index.php', false);
                    		JsRequest.send('logout');
                    		eval(JsRequest.getXMLRequest().responseText);
                            User.load();
                        }break;
                        default:
                            alert("Unknown Command Name");
                    }
                }break;
                default:
                    Chat.send();
                    Chat.eleChatInput.value = "";
                    Chat.get();
            }
        }
    };
    Chat.send = function()
    {
		JsRequest.onreadystatechange = function()
		{
			//alert(reqClass.readyState);
			if (JsRequest.readyState == 4) 
			{
				if (!JsRequest.responseJS) 
					alert(JsRequest.responseText);
                
                Chat.eleChatInput.value = "";
				delete this.onreadystatechange;
			}
		};
		JsRequest.open('GET', 'index.php', false);
		JsRequest.send('Chat&sendChat&message='+escape(Chat.eleChatInput.value));
        eval(JsRequest.getXMLRequest().responseText);
    };
    Chat.add = function(type,nick,level,text,time,userid)
    {
       //MESSAGE.unshift( new Array(type,nick,level,text,time,userid) ); //Add new Message, in First
            
        
        var HTMLData = '<div class="chatMessages" title="'+Number(time).MStoTime()+'">\n';
        
        HTMLData += '<font class="chatNameBrac">[</font>\n';
        HTMLData += '<span onmousedown="Chat.nameDown(this,'+userid+')"';       
        switch(level)
        {
            case "1":
                 HTMLData += ' class="chatName userMember">';
                break;
            case "2":
                 HTMLData += ' class="chatName userModerator">';
                break;
            case "3":
                 HTMLData += ' class="chatName userAdmin">';
                break;
            default:
                 HTMLData += ' class="chatName userAnonymous">';
                break;
        }
        HTMLData += '\n'+nick+ '\n</span>\n'
        HTMLData += '<font class="chatNameBrac">]</font>\n';          
        
        HTMLData += '<span class="chatMessage">'+text+'</span>\n</div>\n';
        Chat.eleChatBox.innerHTML += HTMLData;
       //if(MESSAGE.length > MESSAGE_MAX)
           //MESSAGE.pop();
        Chat.eleChatBox.scrollTop = Chat.eleChatBox.scrollHeight;
    };
   	Chat.get = function()
    {
		//DISPLAY();
        JsRequest.onreadystatechange = function()
		{
			//alert(reqClass.readyState);
			if (JsRequest.readyState == 4) 
			{
				if (!JsRequest.responseJS) 
					alert(JsRequest.responseText);
                
               // var textToDisplay = "";
               //if(JsRequest.responseJS.length > 1)
                   //alert( JsRequest.responseJS);

                //JsRequest.responseJS = JsRequest.responseJS.reverse();
                for(var itr in JsRequest.responseJS)
                {
                    if(itr == "updateVSD")
                        continue;
                    var tempText = JsRequest.responseJS[itr];
                    
                    if(Number(tempText['id']))
                        Chat.lastIndex = Math.max(Chat.lastIndex,Number(tempText['id']));
                    else
                        continue;
                    Chat.add(MESSAGE_TYPE_INFO,tempText['username'],tempText['level'],tempText['message'],tempText['time'],tempText['accountId']);
                }
                Video.updateVSD(JsRequest.responseJS["updateVSD"]);

                //owner.scrollTop = owner.scrollHeight;
				delete this.onreadystatechange;
			}
		};
		JsRequest.open('GET', 'index.php', true);
		JsRequest.send('Chat&getChat&index='+String(Chat.lastIndex));
        //eval(JsRequest.getXMLRequest().responseText);
		
		/*while (Chat.eleChatBox.childNodes.length > MESSAGE_MAX * 2) //apparently 1 extra text node per message is generated
		{
			Chat.eleChatBox.removeChild(Chat.eleChatBox.firstChild);
		}*/
		
    };
   	Chat.ban = function(userid)
    {
        JsRequest.onreadystatechange = function()
		{
			//alert(reqClass.readyState);
			if (JsRequest.readyState == 4) 
			{
				if (!JsRequest.responseJS) 
					alert(JsRequest.responseText);

				delete this.onreadystatechange;
                
			}
		};
		JsRequest.open('GET', 'index.php', true);
		JsRequest.send('Chat&ban='+userid);
        //eval(JsRequest.getXMLRequest().responseText);
    };
   	Chat.unban = function(userid)
    {
        JsRequest.onreadystatechange = function()
		{
			//alert(reqClass.readyState);
			if (JsRequest.readyState == 4) 
			{
				if (!JsRequest.responseJS) 
					alert(JsRequest.responseText);

				delete this.onreadystatechange;
                
			}
		};
		JsRequest.open('GET', 'index.php', true);
		JsRequest.send('Chat&ban='+userid+'&unban');
        //eval(JsRequest.getXMLRequest().responseText);
    };
    Chat.init = function()
    {

    };
})();

commonInit.push
(
    function()
    {
        Chat.eleChatBox = GetElementById('chatBox');
        //Chat.eleChatBox.onmouseover = Scroll.setScrollMe;
        //Chat.eleChatBox.onmouseout = Scroll.unSetScrollMe;
        Chat.eleChatInput = GetElementById('chatInput');
        setTimeout('Chat.get();',10);
        Chat.updateTimerId = setInterval('Chat.get();',2500);
    }
);