var newChatWindow;
var receiveReq = getXmlHttpRequestObject();
var imReq = getXmlHttpRequestObject();
var lastUpdate = 0;
var mTimer;

// The window where we show profile of a Bride or Groom
function popprofile(url,name) {
    newChatWindow=window.open(url,name,'height=650, width=950, left=40, top=80, toolbar=no, menubar=no, directories=no, location=no, scrollbars=yes, status=no, resizable=yes, fullscreen=no');
    if (window.focus) { newChatWindow.focus() }
}
function poptastic(url,name) {
    newChatWindow=window.open(url,name,'height=600, width=750, left=40, top=40, toolbar=no, menubar=no, directories=no, location=no, scrollbars=no, status=no, resizable=yes, fullscreen=no');
    if (window.focus) { newChatWindow.focus() }
}

var chatOn = "Y";

// Called onload to get the ball rolling
function startChat() {

	// If we have turned off chat for this site
	//if (document.getElementById('ChatList').style.display == 'none') {
	if (chatOn == "N") {
        //alert ('To resolve an issue with our server, the chat feature has been temporarily turned off.  We regret the inconvenience cause.  We will have it up as soon as the server issue is resolved');
		return;
	}

	 refresh ("","");

    //Start Receiving Messages.
    //getChatText();
}

//Gets the browser specific XmlHttpRequest Object
function getXmlHttpRequestObject() {
    if (window.XMLHttpRequest) {
        return new XMLHttpRequest();
    } else if(window.ActiveXObject) {
        return new ActiveXObject("Microsoft.XMLHTTP");
    } else {
        alert("Browser does not support AJAX");
    }
}

// How does it all work?
/*

There are 2 php functions that do treh jobs for the javascripts.  php121im.php  & php121im-refresh.php

php121im.php does the following:

- Announce the presence of this user by updating a timestamp in the control table and the user table
- Checks to see if there is chat request for this user, if so display it
- If there are no chat request, display the list of active users instead

php121im-refresh.php does the following:

- It sets the timestamp to 0 for all the users who have not updated the timestamp for a while.
  This effectively, makes the user offline
- It then checks to see if this use id still online and it has received a request since the lst time
  the user had refreshed the chatters list.  If so it returns an xml that says that a request it pending
- If there no new requests, it checks to see if the chatters list has changed.  If so it returns 
  appropriate xml.  Javascript uses this XML to call php121im.php to get the latest list of
  chatters. If the chatter list has not changed it return empty XML, in which case javascripts 
  simply sets up the next call to php121im-refresh.php
- Also, once php121im-refresh.php is done returning the xml, it updates a timestamp in the user 
  table for this user so that the user remains online.  Without this update the user would go offline 
  after some time


We start by calling startChat ().  This calls refresh (). We call refresh () the first time because 
the user has to announce his/her presence for the chat.  What that effectively means that there needs 
to be a change in the list of users available for chat, so that all users update their list.

Having called the refresh (), we need to setup a call to getChatText (). This sets up an asynchronous
call to php121im-refresh.php. As noted above, php121im-refresh.php checks to see if the chatter list
has changed or if there are incoming chat requests for this user.  If so it makes javascript set up
a call to php121im.php to do what is needed.
	
Handling incoming chat requests

The space we use to show the list (of chatters) is also used to show incoming chat requests
If there is an incoming chat request, javascript detect it through php121im-refresh.php (it send back an XML
string), that there is a chat request, and we need to call refresh (). we replace the chatter list, with 
the chat request message.  We also, set up a call to refresh the list, so that the chatters list is 
re-displayed once the request message is taken care of.

Network disconnection

If there is a temporary disconnection of network takes place, call to php121im-refresh.php is not
successful for sometime.  This means the timestamp (in user table) does not get refreshed for certain
length of time.  If the network connection gets restored and eventually when php121im-refresh.php is successful
the time elapsed since the last refresh would be too great and the code assumes that the user las logged off.
In this case, we need to make a call to php121im.php instead of php121im-refresh.php so that the user's
chat session is restored, musch in the similar way when the user login the first time.

*/

// This is a varaible we use to note if we are in the process of refreshing
// the chat window
var gettingChatWindowContents = 0;

// If set to 1 set up the monitor for chat list
var setupChatListMonitor = 1;

var dt1 = new Date();

// When did we last call refresh to chat list
var lastCallToRefresh = dt1.getTime();


// Gets the current messages from the server
function getChatText() {

	// If we are in the process of getting chat window contents
	// do nothing and return;
	if (gettingChatWindowContents) {
        mTimer = setTimeout('getChatText();',8000); //Get new data in 5 seconds
		return;
	}

	var dt2 = new Date();
    var timenow = dt2.getTime();

	// We have not refreshed the chatters list in the last 90 seconds
	// We assume a netwrok disconnection here as the javascript is still running
	// But becuase we have net communicated with the server, server thinks we are
	// offline.  We call refresh and set up the calls to getChatText
	var diffTime = timenow - lastCallToRefresh;
	if (diffTime > 180000) {
		setupChatListMonitor = 1;
		var chatType = getCookie ("ChatType");
		if (chatType == "") {
			chatType = "Groom";
		}
		refresh ("", chatType);
		return;
	}

    if (receiveReq.readyState == 4 || receiveReq.readyState == 0) {

		// timenow has no meaning to php121im-refresh.php - oit is simplay added to query string
		// to make the browser call the programs rather than use the cache
		var checkRefreshUrl = 'http://www.oriyamatrimonials.com/im/php121/php121im-refresh.php?' + timenow;
        receiveReq.open("GET", checkRefreshUrl, true);
        receiveReq.onreadystatechange = handleReceiveChat;
        receiveReq.send(null);
    }
}
        
//Function for handling the return of chat text
function handleReceiveChat() {

    if (receiveReq.readyState == 4) {
		if (receiveReq.status == 200) {
			var xmldoc = receiveReq.responseXML;
			var message_nodes;
			if (xmldoc != null) {
				message_nodes = xmldoc.getElementsByTagName("message");
			}
			if (message_nodes && message_nodes[0]) {
				var update = message_nodes[0].getElementsByTagName("update");
				var request = message_nodes[0].getElementsByTagName("request");

				// Do we have a prending request, if so we need to show it to the recepient
				if (request[0].firstChild.nodeValue == 1) {
					// There is a request pending.  We need to give the o0ther party time to 
					// responsd.  So we do not call the refresh immediately.  We set a timeout
					setTimeout('refresh("","");',5000); // Made this 60 seconds 10.05.10
				}
            	if (update[0].firstChild.nodeValue == 1 && request[0].firstChild.nodeValue == 0) {
					refresh ("","");
            	} 
        	}
			else { // This is where we do not call refresh, but the time from 
                   // last call to refresh ticks on forcing a call to refresh.  But that is OK
				//alert ('No Message');
			}
		}
		else {
			//alert ('Refresh errored out');
		}
        mTimer = setTimeout('getChatText();',5000); //Get new data in 5 seconds
    }
}

function refresh(choice, onlineproftype) {

	// Do not do a refresh, when a refresh is already in progress
	if (gettingChatWindowContents) {
		return;
	}

	gettingChatWindowContents = 1;

	// Update the the time when we last called refresh. This helps to know as to
    // when we calst refreshed the list of chatters.  If the gap is too long
	// It is possible that we had a network disconnection.
	var dt3 = new Date();
    lastCallToRefresh = dt3.getTime();

	var refreshUrl = 'http://www.oriyamatrimonials.com/im/php121/php121im.php?';
	if (choice != '' ) {
		refreshUrl = refreshUrl + 'choice=' + choice + '&';
	}
	if (onlineproftype != '' ) {
		refreshUrl = refreshUrl + 'onlineproftype=' + onlineproftype + '&';
	}

	// lastCallToRefresh has no significance in refreshUrl, except to trick the
	// brwoser into thinking that the url is a newone and not to use anythin from the cache
	refreshUrl = refreshUrl + lastCallToRefresh;

    imReq.open("GET", refreshUrl, true);
    imReq.onreadystatechange = populateChatList;
    imReq.send(null);
}

function populateChatList () {
    if (imReq.readyState == 4) {
		gettingChatWindowContents = 0;
		if (imReq.status == 200) {
			var chatList = document.getElementById('ChatList');
			chatList.innerHTML  = imReq.responseText;
			if (setupChatListMonitor) {
        		mTimer = setTimeout('getChatText();',5000); //Get new data in 5 seconds
				setupChatListMonitor = 0;
			}
		}
		else { // Some error ocurred, perhaps a network disconnection, the timer for getChatText() 
               // keeps the process going ene if there is a network failure
       		mTimer = setTimeout('getChatText();',5000); //Get new data in 5 seconds
		}
	}
}

