/*



**



** ChatManager keeps track of all open chats and chat requests allowing



** the client to start new chats, deny/accept requests and close chats.



** Also, through events the client is notified of new requests or changes in the



** status of current chats



**



*/







/*



**



** Object describing an open chat



**



*/



function ChatDescriptor(alias, status, windowAlive)



{



    this.alias = alias;



    this.status = status;               //Enum: request, open, attention



    this.windowAlive = windowAlive;     //Notification from the db that the window is still alive



    this.stillAlive = false;            //Field used to track dead windows in updates



}







/*



**



** Constructor



**



**   errorHandler(message) - function to report errors



*/



function ChatManager(thisUserID, errorHandler)



{



    this.thisUserID = thisUserID;



    this.ajax = new AJAX(thisUserID);



    this.eventTimer = null;



    this.activeChats = new Object();     //Associative container with chatID as index containing ChatDescriptor:s



    this.errorHandler = errorHandler;



}







/*



**



** Helper Functions



**



*/







/*



**



** Returns name of window corresponding to chat chatID



**



*/



ChatManager.prototype.windowName = function(chatID)



{



    return "chat" + this.thisUserID + "x" + chatID;



}







/*



**



** Get(create) a chat window corresponding to the chat



**



*/



ChatManager.prototype.getChatWindow = function(chatID)



{



    //Make sure this is an active chat we are getting the window for



    if(this.activeChats['c' + chatID]==undefined)



        return null;



    



    var wnd = window.open('', this.windowName(chatID), "width=376,height=588,scrollbars=no,status=yes,toolbar=no,resizable=no,location=no,menubar=no,directories=no");



    if(wnd.document.getElementById("chat")==null) {



        //We just created the window



        wnd = this.createChatWindow(chatID);      //Create it with all the right properties



    }



    return wnd;



}







/*



**



** Create a new chat window



**



*/



ChatManager.prototype.createChatWindow = function(chatID)



{



    // If this chat already exists, try to open it



    if(!(this.activeChats['c' + chatID]==undefined)) {



        var wnd = window.open('', this.windowName(chatID), "width=376,height=588,scrollbars=no,status=yes,toolbar=no,resizable=no,location=no,menubar=no,directories=no");



        if(wnd.document.getElementById("chat")!=null) {



            wnd.focus();



            return;



        }



    }







    // Create window if new chat, otherwise just focus window



    var wnd = window.open("http://"+document.domain+"/include/page/chat/page/chat/chat.php?chatID=" + chatID, this.windowName(chatID), "width=376,height=588,scrollbars=no,status=yes,toolbar=no,resizable=no,location=no,menubar=no,directories=no");



    wnd.focus();



    return wnd;



}







/*



**



** Interface functions



**



*/







/*



**



** initChat - do a sync callback to get the ID for the new chat



**



*/



ChatManager.prototype.initChat = function(uID)



{



    //Need to use Sync post to avoid popup warnings (this way the popup is a direct response of a user activity)



    this.ajax.postSync({action: "init_new", userID: uID}, bind(this, 'initChat_ok'), bind(this, 'initChat_failed'));



}



ChatManager.prototype.initChat_ok = function(request)



{



    var error = getXmlNodeText(request.responseXML, "error");



    if(error!="") {



        //alert(error);



        if(this.errorHandler!=null)



            this.errorHandler(error);



        return;



    }



    



    var chatID = getXmlNodeText(request.responseXML, "chatID");



    this.createChatWindow(chatID);



    this.forceStatusUpdate();



}



ChatManager.prototype.initChat_failed = function(request)



{



    alert("Unable to start chat: " + request.status + " - " + request.statusText);



}







/*



**



** activateChat - Activate the chat window assuming it exists according to the internal database



**



*/



ChatManager.prototype.activateChat = function(chatID)



{



    var wnd = this.getChatWindow(chatID);



    if(wnd!=null)



        wnd.focus();



    



    this.forceStatusUpdate();



}







/*



**



** acceptChat - do an async post to accept the chat, and open a new chat window



**



*/



ChatManager.prototype.acceptChat = function(chatID)



{



    this.ajax.postAsync({action: "accept", chatID: chatID}, bind(this, 'forceStatusUpdate'), null);



    this.createChatWindow(chatID);



}







/*



**



** denyChat - do a async post to deny the chat



**



*/



ChatManager.prototype.denyChat = function(chatID)



{



    this.ajax.postAsync({action: "deny", chatID: chatID}, bind(this, 'forceStatusUpdate'), null);



}







/*



**



** closeChat - do a async post to close the chat and, assuming the window exists in the database, close the window



**



*/



ChatManager.prototype.closeChat = function(chatID)



{



    this.ajax.postAsync({action: "close", chatID: chatID}, bind(this, 'forceStatusUpdate'), null);







    //Make sure this is an active chat we are getting the window for



    if(this.activeChats['c' + chatID]==undefined)



        return null;



    



    var wnd = window.open('', this.windowName(chatID), "width=1000,height=350, status=1,location=1");



    if(wnd!=null)



        wnd.close();



}







/*



**



** Event handlers



**



** The following event handlers may be specified



**   newChatEvent(chatID, alias, status)



**          Called for each new chat window that is started



**



**   closedChatEvent(chatID)



**          Called when a chat window is closed



**



**   updateChatEvent(chatID, alias, status)



**          Called when a chat window has updated



**          Possible values for status is



**              request - other user requests a chat



**              open - chat is currently active



**              newdata - new data is the chat that has not been vied yet



**



*/







/*



**



** Start the event pump - check for new events with [interval] ms interval



**



*/



ChatManager.prototype.requireEvents = function(interval)



{   



    this.eventsRequestInterval = interval;



    this.forceStatusUpdate();



}







/*



**



** Force an update of the state



**



*/



ChatManager.prototype.forceStatusUpdate = function()



{



    if(this.eventTimer!=null)



        clearTimeout(this.eventTimer);



    this.queryStatus();



}







/*



**



** Query for new information from the server and trigger events depending on this information



**



*/



ChatManager.prototype.queryStatus = function()



{



    this.ajax.getAsync({action: "manager_status"}, bind(this, 'queryStatus_ok'), bind(this, 'queryStatus_failed'));



}



ChatManager.prototype.queryStatus_ok = function(request)



{



    //Set all chats to dead



    for(chat in this.activeChats)



        this.activeChats[chat].stillAlive = false;







    //Process the message



    var state = request.responseXML.getElementsByTagName("state")[0];



    



    //Process chats



    var chats = state.getElementsByTagName("chats")[0].getElementsByTagName("chat");



    for(var i=0; i<chats.length; ++i) {



        var id = getXmlNodeText(chats[i], "id");



        var alias = getXmlNodeText(chats[i], "alias");



        var status = getXmlNodeText(chats[i], "state");







        if(this.activeChats['c' + id]==undefined)



        {



            //New chat



            var cd = new ChatDescriptor(alias, status);



            this.activeChats['c' + id] = cd;



            if(typeof(this.newChatEvent) == 'function')



                this.newChatEvent(id, alias, status);



        } else {



            //Existing chat, has it changed?



            var change = false;



            



            if(this.activeChats['c' + id].status!=status) {



                this.activeChats['c' + id].status=status;



                change=true;



            }



            if(this.activeChats['c' + id].alias!=alias) {



                this.activeChats['c' + id].alias=alias;



                change=true;



            }



            if(change && typeof(this.updateChatEvent)=='function')



                this.updateChatEvent(id, alias, status);



        }



        this.activeChats['c' + id].stillAlive = true;



    }



    



    //Remove all dead chats



    var deadChats = new Array();



    for(chat in this.activeChats)



        if(!this.activeChats[chat].stillAlive)



            deadChats[deadChats.length] = chat;



    



    for(i in deadChats) {



        //alert(typeof(deadChats[i]));



        if(typeof(deadChats[i])!='string')



            continue;



        delete this.activeChats[deadChats[i]];



        if(typeof(this.closedChatEvent)=='function') {



            this.closedChatEvent(Number(deadChats[i].substr(1)));



        }



    }



    



    //Proccess guestbook



    var guestbook = state.getElementsByTagName("guestbooks")[0].getElementsByTagName("guestbook");



    for(var i=0; i<guestbook.length; ++i) {



    }



    



    //Proccess mail



    var mail = state.getElementsByTagName("mails")[0].getElementsByTagName("mail");



    for(var i=0; i<mail.length; ++i) {



    }



    



    //Request a new status message



    this.eventTimer = setTimeout(bind(this, "queryStatus"), this.eventsRequestInterval);



}



ChatManager.prototype.queryStatus_failed = function(request)



{



    this.eventTimer = setTimeout(bind(this, "queryStatus"), this.eventsRequestInterval);



}











/*



**



** Code for handling the actual chat requests



**



*/







function playChatSound(soundFile)



{



    soundManager.play('mySound');



}







function newChat(chatID, alias, status)



{



	var chatContainer = document.getElementById("chatBar");



	



    var d = document.createElement("div");



    d.id = "chat"+chatID;



    d.className = status;



/*	d.style.background='url(/pix/chat/indikator_chat_none_active.gif)';



	d.style.float='right';

	

	d.style.filter:'alpha(opacity:100)';

	

	filter:alpha(opacity=75);*/



	



	//= "filter:alpha(opacity:100);float:right;opacity:1.0; background:url(/pix/chat/bin/chat.gif); width:102px; height:30px;"



    



	if(chatContainer.firstChild==null)



        chatContainer.appendChild(d);



    else



        chatContainer.insertBefore(d, chatContainer.firstChild);



    



    var ux_alias = document.createElement("div");



    ux_alias.id = "innerText"+chatID;



    ux_alias.className = "chatBarInnerText";



    ux_alias.appendChild( document.createTextNode(alias) );



    d.appendChild(ux_alias);







    //Set the values



    updateChat(chatID, alias, status);



    



	//document.getElementById('indikatorNamn').innerHTML='$Name';



	



/*	document.getElementById('indikator').innerHTML='<div id=\"bild_chat\"></div><div id=\"text_chat\" class=\"td_tooltip\"><b>Jockemalvax</b> (M30)<br />Vill starta en konversation med dig!</div></div><div id=\"ChatClose\"></div>';*/



	



/*    setTimeout("Effect.BlindDown('indikator')",1000);*/



	



	if(status=="request")



	{



       soundManager.play('mySound');



	/*	setTimeout("Effect.BlindDown('indikator')",1000);



		setTimeout("Effect.BlindDown('shadow')",1000);



		



		setTimeout("Effect.SwitchOff('indikator')",10000);



		setTimeout("Effect.SwitchOff('shadow')",10000);

		

		*/

		 //setTimeout("Effect.BlindUp('indikator')",9000);

		 //setTimeout("Effect.BlindDown('indikator')",1000);



	}



}







// Update the representation of the chat



//



// status = open | newdata | request



function updateChat(chatID, alias, status)



{



	var chatContainer = document.getElementById("chatBar");







    var d = document.getElementById("chat"+chatID);



    var ux_alias = document.getElementById("alias"+chatID);



    if(d==null) {



        alert("Unable to get chat item for update");



        return;



    }



    d.className = status;



    if(ux_alias!=null)



        ux_alias.firstChild.nodeValue = alias;







    //Set javascript handlers



    if(status=='request') {



        d.onclick = function() { chatManager.acceptChat(chatID); };



    } else {



        d.onclick = function() { chatManager.activateChat(chatID); };



    }



}







function closeChat(chatID)



{



	var chatContainer = document.getElementById("chatBar");







    var d = document.getElementById("chat"+chatID);



    if(d==null) {



        alert("Unable to get chat item for update");



        return;



    }



    chatContainer.removeChild(d);



}







//var log = new Log(document.getElementById('log'));



var chatManager = null;







function chatError(err)



{



    alert(err);



}



function initChatManager(userID, refreshRate)



{



	chatManager = new ChatManager(userID, chatError);



	chatManager.newChatEvent = newChat;



	chatManager.updateChatEvent = updateChat;



	chatManager.closedChatEvent = closeChat;



	chatManager.requireEvents(refreshRate);



}







