// JavaScript Document

//var request;
var urlBase = "http://friendsndates.khattam.com";
var urlFragment= urlBase + "/ajax/";
var urlCircular=urlFragment+'im_online_users.php';
var xmlOnlines = null;
var reqSkip = 0;
var reqState = 0;
preLoad()

function overrideXMLDoc(Doc){	
	xmlOnlines = Doc;
}

function preLoad(){
	var unblockImg = new Image(150, 30);
	unblockImg.src = urlBase + '/images/im_unblock.gif';
	var closeMole = new Image(15, 15);
	closeMole.src = urlBase + '/images/close_mole_orange.gif';
	var maxMole = new Image(15, 15);
	maxMole.src = urlBase + '/images/maximize_mole_orange.gif';
	var minMole = new Image(15, 15);
	minMole.src = urlBase + '/images/minimize_mole_orange.gif';
}

function runAjax(url, objId){
	this.responseObjId = objId;	
	var request;
	//function for XMLHttpRequest onreadystatechange event handler
	this.handleResponse = function () {
		//function handleResponse( ){	
		try{
			if(request.readyState == 4){
				if(request.status == 200){
					/* All headers received as a single string */
					//var headers = request.getAllResponseHeaders(  );
					//alert(request.getResponseHeader('Server'));
					reqState = 0;
					docType = request.getResponseHeader("Content-Type").search(/xml/i);
					if(docType == -1){
						docType = 'TEXT';
					}else{
						docType = 'XML';
					}					
					
					if(objId == 'im_online_users'){	
						var div = document.getElementById(objId);
						if(div == null){
							return;
						}
						if(docType == 'TEXT'){	// text/html							
							div.style.display = "block";
							this.Doc = request.responseText;
							div.innerHTML=this.Doc;
							return;
						}else{ //  xml								
							var xmlDoc = request.responseXML;	
							overrideXMLDoc(xmlDoc); // global xmlOnlines
							var onlineMembers = xmlDoc.getElementsByTagName('user');
							onlineMembers = onlineMembers.length;
							var onlineGuests = xmlDoc.getElementsByTagName('guests');
							onlineGuests = onlineGuests[0].firstChild.nodeValue;
							var caption = '';
							if(onlineMembers > 0){
								caption = caption + '<a href="online_users.php" onmouseover="showImMenu(event);"><b>';
								caption = caption + onlineMembers + ' member';
								createImMenu(xmlDoc);
							}							
							if(onlineMembers > 1) {
								caption = caption + 's';
							}
							if(onlineMembers > 0){
								caption = caption + '</b></a> ';
							}
							if(onlineMembers > 0 && onlineGuests > 0){
								caption = caption + ' and ';
							}
							if(onlineGuests > 0){
								caption = caption + onlineGuests + ' guest';
								if(onlineGuests > 1){
									caption = caption + 's';
								}
							}
							caption = caption + ' online';
							div.innerHTML = caption;
							var messages = xmlDoc.getElementsByTagName('message');	
							var msgLen = messages.length;
							for(var i=0;i<msgLen;i++){								
								var message = messages[i].firstChild.nodeValue;
								var msgId = messages[i].getAttribute("id");
								var fromId = messages[i].getAttribute("from");									
								var detail = getMemberDetail(fromId);								
								if(detail.name == null){
									return;
								}
								var tmp = detail.name.split(" ");
								message = "<B>" + tmp[0] + " : </B>" + message;									
								
								if(messages[i+1] != undefined){
									msgId = null;
								}	
								chatWindow(fromId, detail.name, message, msgId);								
							}
							var onlineListDiv = document.getElementById("im_online_users_list");
							if(onlineListDiv != null){
								im_online_users_list(onlineListDiv, xmlDoc);
							}
							return;
						}
					}else if(objId == 'im_online_users_list'){
						var div = document.getElementById(objId);
						if(div == null){
							return;
						}
						this.xmlDoc = request.responseXML;				
						im_online_users_list(div, this.xmlDoc);
					}else if(objId == 'im_user_status'){
						this.xmlDoc = request.responseText;
						var statusDiv = document.getElementById("im_user_status");
						if(statusDiv == null){
							return;
						}										
						statusDiv.innerHTML = this.xmlDoc;
						if(this.xmlDoc == 'Offline'){
							statusDiv.style.color = "#990000";													
						}
					}else if(objId == 'flushmsg'){				
						return;
					}else if(objId == 'im_msg_send'){
						this.Doc = request.responseText;
						if(this.Doc != "OK"){
							var tmp = this.Doc.split("|");
							var membId = tmp[0];
							var sysMsg = '<span style="color: #666666;"><i>System : ' + tmp[1] + '</i></span>';
							chatWindow(membId, null, sysMsg, null);
						}
					}else if(objId == 'blockUnblock'){
						this.Doc = request.responseText;
						var tmp = this.Doc.split("|");
						var membId = tmp[0];
						var bStatus = tmp[1];
						var chatTitleTxtDiv = document.getElementById("chatTitleTxt_" + membId);
						if(chatTitleTxtDiv != null){
							
						}
						return;
					}else{ // no available mode
						if(document.getElementById(objId) != null){									
							document.getElementById(objId).innerHTML = request.responseText;
						}
					}
				} else {
					//request.status is 503 if the application isn't available; 
					//500 if the application has a bug
					//alert(request.status);
					//alert("A problem occurred with communication "+  "with the server. Posibilities : Slow internet connection.");
				}
			}//end outer if
		} catch (err)   {
			// have to comment this 
			/*
			alert("It does not appear that the server is "+
				  "available for this application. Please"+
				  " try again very soon. \\nError: "+err.message); */
	
		}
	}
	
	
		/* Initialize a request object that is already constructed */
	this.initReq = function (reqType,url,bool){
		//function initReq(reqType,url,bool){		
		try{
			/* Specify the function that will handle the HTTP response */
			request.onreadystatechange=this.handleResponse;
			//this.request.onreadystatechange=this.handleResponse;
			request.open(reqType,url,bool);
			//this.request.setRequestHeader("label","value");
			request.send(null);
		} catch (errv) { /*
			alert(
					"The application cannot contact the server at the moment. "+
					"Please try again in a few seconds." ); */
		}
	}


		/* Wrapper function for constructing a request object.
	 Parameters:
	  reqType: The HTTP request type, such as GET or POST.
	  url: The URL of the server program.
	  asynch: Whether to send the request asynchronously or not. */
	this.httpRequest=function(reqType,url,asynch){
		//function httpRequest(reqType,url,asynch,responseObjId){
		//Mozilla-based browsers
		if(window.XMLHttpRequest){
			request = new XMLHttpRequest();
		} else if (window.ActiveXObject){
			this.request=new ActiveXObject("Msxml2.XMLHTTP");			
			if (! request){
				request=new ActiveXObject("Microsoft.XMLHTTP");
			}
			
		}
		//the request could still be null if neither ActiveXObject
		//initialization succeeded
		if(request){
			this.initReq(reqType,url,asynch);
		} else { /*
			alert("Your browser does not permit the use of all "+
				  "of this application's features!");	*/
		}
	}
	
	
    this.httpRequest("GET",url,true);
	
}



function im_online_users_list(div, Doc){	
	var xmlDoc = Doc;	
	var x = xmlDoc.getElementsByTagName('user');
	if(!x.length){
		div.setAttribute("class", "fatalMsg");
		div.setAttribute("className", "fatalMsg");
		div.innerHTML = "None of the members are online!";
		return;
	}	
	var firstLevelNodeName='user';
	nodeTab=xmlDoc.getElementsByTagName(firstLevelNodeName);
	
	var newTbl = document.createElement('TABLE');
	newTbl.setAttribute('width',570);
	var tmp = document.createElement('TBODY');
	newTbl.appendChild(tmp);
	
	var row = document.createElement('TR');
	var td = document.createElement('TD');
	var text = document.createTextNode("Online Members");
	var span = document.createElement('SPAN');
	span.setAttribute('className', "style1");
	span.setAttribute('class', "style1");
	td.setAttribute("className", "ms_sans_12");
	td.setAttribute("class", "ms_sans_12");
	td.setAttribute("height", "22");
	td.style.backgroundColor = "#cc0000";
	td.setAttribute("colSpan", "3");	
	span.appendChild(text);
	td.appendChild(span);
	row.appendChild(td);	
	tmp.appendChild(row);

	
	var i = 0;
	flipFlop = false;
	while(nodeTab.length > i){		
		for(x=1;x<=3;x++){			
			if(x == 1 && i != 0){
				var row = document.createElement('TR');
				var td = document.createElement('TD');
				td.setAttribute("className", "simple_text");
				td.setAttribute("class", "simple_text");
				td.style.backgroundColor = "#ced2fb";
				td.setAttribute("colSpan", "3");
				td.setAttribute("height", "15");
				row.appendChild(td);
				tmp.appendChild(row);					
				var row = document.createElement('TR');
				if(flipFlop){
					flipFlop = false;
				}else{
					flipFlop = true;
				}
			}else if(x == 1){
				var row = document.createElement('TR');
				if(flipFlop){
					flipFlop = false;
				}else{
					flipFlop = true;	
				}
			}
			
			
			if(i < nodeTab.length){
				online_since = nodeTab[i].getAttribute("online_since");
				profile_id = nodeTab[i].getAttribute("profile_id");
				name = nodeTab[i].firstChild.nodeValue;
	
				var td = document.createElement('TD');
				td.setAttribute("className", "simple_text");
				td.setAttribute("class", "simple_text");
				td.setAttribute("width", "33%");
				if(flipFlop){					
					td.style.backgroundColor = "#ebebeb";
				}
				var ahref = document.createElement('A');
				ahref.setAttribute("href", "javascript: chatWindow('" + profile_id + "', '" + name + "');");
				var img = document.createElement('IMG');
				img.setAttribute("border", "0");
				img.setAttribute("hspace", "5");
				img.setAttribute("align", "left");
				img.setAttribute("alt", "Talk with " + name);
				img.setAttribute("title", "Talk with " + name);
				img.setAttribute("width", "50");
				img.setAttribute("height", "60");
				img.setAttribute("src", urlBase + "/images/tn_" + profile_id + "_1.jpg");
				ahref.appendChild(img);
				td.appendChild(ahref);				
				var br = document.createElement('BR');
				var text = document.createTextNode("Profile Id : " + profile_id);				
				td.appendChild(text);
				td.appendChild(br);
				var text = document.createTextNode(name);
				var br = document.createElement('BR');
				td.appendChild(text);
				td.appendChild(br);
				var text = document.createTextNode("Online Since : " + online_since);
				var br = document.createElement('BR');
				td.appendChild(text);
				td.appendChild(br);
				var ahref = document.createElement('A');
				ahref.setAttribute("href", "show_detail.php?profile_id=" + profile_id);
				var italic = document.createElement('I');
				var text = document.createTextNode("View Profile");
				italic.appendChild(text);
				ahref.appendChild(italic);
				td.appendChild(ahref);

			}else{
				var td = document.createElement('TD');
				td.setAttribute("className", "simple_text");
				td.setAttribute("class", "simple_text");
				if(flipFlop){					
					td.style.backgroundColor = "#ebebeb";
				}				
			}
			row.appendChild(td);
			tmp.appendChild(row);
			i++;
		}
	}
	tmp.appendChild(row);
	newTbl.appendChild(tmp);
	div.innerHTML = "";	
	div.appendChild(newTbl);		
}

function getMemberDetail(fromId,  /* optional */ xmlDoc){
	var users = xmlOnlines.getElementsByTagName("user");	
	for(i=0;i<users.length;i++){		
		if(fromId == users[i].getAttribute("profile_id")){
			namex = users[i].firstChild.nodeValue;
			online_sincex = users[i].getAttribute("online_since");
			return {name:namex, online_since:online_sincex};
		}
	}
	return {name:null, online_since:null};
}

function createImMenu(xmlDoc){
	var menuDiv = document.getElementById("im_menu");
	if(menuDiv == null){
		var menuDiv = document.createElement('DIV');
		menuDiv.setAttribute("id", "im_menu");
		menuDiv.setAttribute("class", "im_menu");
		menuDiv.setAttribute("className", "im_menu");
		menuDiv.style.display = "none";		
	}
	menuDiv.innerHTML = "";
	var menuTitleDiv = document.createElement('DIV');
	menuTitleDiv.setAttribute("class", "title");
	menuTitleDiv.setAttribute("className", "title");
	var text = document.createTextNode("Online Members");
	menuTitleDiv.appendChild(text);
	menuDiv.appendChild(menuTitleDiv);	
	
	var menuUl = document.createElement('UL');
	var users = xmlDoc.getElementsByTagName("user");
	for(i=0;i<users.length;i++){
		var profile_id = users[i].getAttribute("profile_id")
		var namex = users[i].firstChild.nodeValue;
		var online_sincex = users[i].getAttribute("online_since");
		var menuLi = document.createElement("LI");		
		var menuLiA = document.createElement("A");
		menuLiA.setAttribute("href", "javascript: chatWindow('" + profile_id + "', '" + namex + "');");
		menuLiA.setAttribute("title", "Online Since " + online_sincex);
		menuLiA.setAttribute("alt", "Online Since " + online_sincex);		
		var nameText = document.createTextNode(namex);		
		menuLiA.appendChild(nameText);
		menuLi.appendChild(menuLiA);
		menuUl.appendChild(menuLi);
	}
	
	menuDiv.appendChild(menuUl);
	document.body.appendChild(menuDiv);	
}

function mousePosition(e) {
	var posx = 0;
	var posy = 0;
	if (!e) var e = window.event;
	if (e.pageX || e.pageY) 	{
		posx = e.pageX;
		posy = e.pageY;
	}
	else if (e.clientX || e.clientY) 	{
		posx = e.clientX + document.body.scrollLeft
			+ document.documentElement.scrollLeft;
		posy = e.clientY + document.body.scrollTop
			+ document.documentElement.scrollTop;
	}
	
	return {x:posx, y:posy}
	//alert(posx + ' : ' + posy);
	// posx and posy contain the mouse position relative to the document
	// Do something with this information
}

function showImMenu(e){
	var objMousePosition = mousePosition(e);
	var posx = objMousePosition.x;
	var posy = objMousePosition.y;
	var menuDiv = document.getElementById("im_menu");
	menuDiv.style.display = "block";
	menuDiv.style.position="absolute";
	menuDiv.style.top = posy+"px";
	menuDiv.style.left= posx+"px";
}

function hideImMenu(){
	var menuDiv = document.getElementById("im_menu");
	if(menuDiv == null){
		return true;
	}
	menuDiv.style.display = "none";
	return true;
}
document.documentElement.onmouseup = hideImMenu;

function getDocInfo(doc){
    var root = doc.documentElement;
    var info = "<h3>Document root element name: <h3 />"+ root.nodeName;
    var nds;
    if(root.hasChildNodes(  )) {
        nds=root.childNodes;
        info+= "<h4>Root node's child node names/values:<h4/>";
        for (var i = 0; i < nds.length; i++){
            info+=  nds[i].nodeName;
            if(nds[i].hasChildNodes(  )){
                info+=  " : \\"+nds[i].firstChild.nodeValue+"\\";
            } else {
                info+=  " : Empty<br />";
            }
        }
    }
    return info;
}


function triggerImOnlineUsers(){	
	if(document.getElementById("im_online_users") == null){
		var timeoutId = setTimeout(triggerImOnlineUsers,2000);
		return;
	}
	if(reqState == 1 && reqSkip <= 1){
		reqSkip++;
	}else{
		var x = new runAjax(urlCircular + '?tmpId=' +Math.random(), 'im_online_users');
		reqState = 1;
		reqSkip = 0;
	}
	timeoutId = setTimeout(triggerImOnlineUsers,15000);
}

if (window.addEventListener)
    window.addEventListener("load", triggerImOnlineUsers, false);
else if (window.attachEvent) window.attachEvent("onload", triggerImOnlineUsers);
else window.onload = triggerImOnlineUsers;

//triggerImOnlineUsers();
