//		ALL AJAX CODE AND FUNCTION STARTS HERE
//Gets the browser specific XmlHttpRequest Object




function getXmlHttpRequestObject() {
	var temp;
	if(window.XMLHttpRequest){
		try {
			netscape.security.PrivilegeManager.enablePrivilege("UniversalBrowserRead");
		} catch (e) {}
		temp = new XMLHttpRequest();
	}else if(window.ActiveXObject){
		temp = new ActiveXObject("Msxml2.XMLHTTP");
		if(!temp){
			temp = new ActiveXObject("Mircosoft.XMLHTTP");
		}
	}
    
    if (!temp) {
      alert('Cannot create XMLHTTP instance');
      temp = false;
    }
	
	
	return temp;
}



  var sendReq = false;
  var receiveReq = false;
  var sendRes = "";
  var receiveRes = "";
  var sendTar = "";
  var recieveTar = "";
  
function sendHandler(){
	if (sendReq.readyState == 4) {
	  if (sendReq.status == 200) {
		sendRes = sendReq.responseText;
		if(sendTar)
			window.setTimeout(sendTar,1);
			//alert('Hi');
	  } else {
		alert('There was a problem with the request.');
	  }
	}

}
function recieveHandler(){
	if (receiveReq.readyState == 4) {
	  if (receiveReq.status == 200) {
		receiveRes = receiveReq.responseText;
		if(recieveTar)
			window.setTimeout(recieveTar,1);
	  } else {
		alert('There was a problem with the request.');
	  }
	}
}
  
function sendRequest(parameters,message,tar) {
	sendReq = getXmlHttpRequestObject();
	sendTar = tar;
	sendReq.onreadystatechange = sendHandler;
	if (sendReq.overrideMimeType) {
      //sendReq.overrideMimeType('plain/text');
    }
	try{

	sendReq.open("POST","http://"+location.host+"/ajax.php?token="+token+"&"+parameters, true);
	sendReq.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
	}catch(e){
		alert("Your browser doesn't support AJAX.");
		return;
	}
    sendReq.send(message);
}
function recieveRequest(parameters,tar) {
	receiveReq = getXmlHttpRequestObject();
	recieveTar = tar;
	receiveReq.onreadystatechange = recieveHandler;
	if (receiveReq.overrideMimeType) {
      receiveReq.overrideMimeType('plain/text');
    }
	try{

	receiveReq.open("GET","http://"+location.host+"/ajax.php?token="+token+"&"+parameters, true);
	}catch(e){
		alert("Your browser doesn't support AJAX.");
		return;
	}
    receiveReq.send(null);
}

//NEWNEWNEWNNEW NEW NEW NEW NEW *******************
  var request = false;
  var reponse = "";
  var target = "";
  var token = 0;
  var block_list = [ "empty1" ];
  //this function takes the request fro url with parameters and the target function to be called when response recieved.
  //this method uses function alertContents to called the target method.
  function makeRequest(parameters,tar) {
	//parameters = encodeURIComponent(parameters);
	target = tar;
    if(window.XMLHttpRequest){
		try {
			netscape.security.PrivilegeManager.enablePrivilege("UniversalBrowserRead");
		} catch (e) {
			//alert("Permission UniversalBrowserRead denied.");
		}
		request = new XMLHttpRequest();
	}else if(window.ActiveXObject){
		request = new ActiveXObject("Msxml2.XMLHTTP");
		if(!request){
			request = new ActiveXObject("Mircosoft.XMLHTTP");
		}
	}
    
    if (!request) {
      alert('Cannot create XMLHTTP instance');
      return false;
    }
	
	if (request.overrideMimeType) {
      request.overrideMimeType('plain/text');
    }
	
    request.onreadystatechange = alertContents;
	try{

	request.open("GET","http://"+location.host+"/ajax.php?token="+token+"&"+parameters, true);
	}catch(e){
		alert("Your browser doesn't support AJAX.");
		return;
	}
    request.send(null);
  }

  function alertContents() {
    if (request.readyState == 4) {
      if (request.status == 200) {
        response = request.responseText;
		if(target)
			window.setTimeout(target,1);
      } else {
        alert('There was a problem with the request.');
      }
    }
  }

//		AJAX CODE AND FUNCTION ENDS HERE


//code and function Start here for menu bar
/*
navHover = function() {
	var lis = document.getElementById("navmenu").getElementsByTagName("li");
	for (var i=0; i<lis.length; i++) {
		lis[i].onmouseover=function() {
			this.className+=" iehover";
		}
		lis[i].onmouseout=function() {
			this.className=this.className.replace(new RegExp(" iehover\\b"), "");
		}
	}
}
if (window.attachEvent) window.attachEvent("onload", navHover);
*/
//code and fucntion  Finishs here for menu bar

function selectButton(index,back){

	if(back==0)
		sClass="left-button";
	else if(back==1)
		sClass="left-button-selected";

	var mainButton = document.getElementById(index);
	mainButton.className=sClass;
}
 
//All the link in the main chat area use this function to
//start new chat, load people online, load people online at specific page.
function loadItem(value){
	var mainRight = document.getElementById("mainRight");
	if(current==value){
		return;
	}else if( current == null){
		//we can assume that col[value] will not return null because it has be added using addItem() function.
		mainRight.innerHTML = col[value];
		current=value;
		selectButton(value,1);
		if(current != "mainButton")
			getOM();
	}else{
		selectButton(current,0);
		col[current] = mainRight.innerHTML;
		mainRight.innerHTML = col[value];
		current = value;
		selectButton(value,1);
		if(current != "mainButton")
			getOM();
	}
	
	//check and set a bit delay as it wont load it quickly in ie.
	if(	document.getElementById("newMessage")!=null)
		window.setTimeout("document.getElementById('newMessage').focus()",10);
}
//**********************************************************



//On Registration Page check if the name is available or not.
//requester and receiver pair of id availability check. including the function following after this function
function checkId() {
	var username = document.getElementById("username");
	if(username.value.length<=0){
		username.value = "Enter Username";
		username.select();
		return;
	}
	//need this cause once uploaded the host will change use using this, so no change needed once uploaded.
	//alert(location.host);
	var temp = username.value;
	username.value = "Checking...";
	makeRequest("cmd=checkId&username="+temp,"checkIdRcv()");
	username.value = temp;
}

function checkIdRcv(){
	//alert(response);
	var username = document.getElementById("username");
	if(response=="yes")
		document.getElementById("idCheckPic").src = "/chat_images/yes.png";
	else{
		document.getElementById("idCheckPic").src = "/chat_images/no.png";
		username.value="Try again...";
		username.select();
	}
}
//**************************************************

function populateMain(){
	if(response.length > 0){
		col.add("mainButton",response);
		loadItem("mainButton");
		var caution  =  document.getElementById("caution");
		if(caution != null)
			caution.style.display = "none";
	}
	
}

function populateMain1(){
	if(response.length > 0){
		//alert(response);
		var mainRight = document.getElementById("mainRight");
		if(current=="mainButton")
			mainRight.innerHTML = response;
		else{
			col["mainButton"] = response;
		}
		
		var caution  =  document.getElementById("caution");
		if(caution != null)
			caution.style.display = "none";
	}
	
}


function sendCMessage(){
	var messages = document.getElementById("messages");
	var item = document.getElementById("newMessage");
	
	//mainRight.innerHTML = "\n<div class='message'>"+item.value+"</div>\n"+mainRight.innerHTML;
	if(item.value.length <= 0)
		return false; 
	//replace here all the < or > with #
	var item1 = item.value.replace(/&/g,"&amp;");
	item1 = item1.replace(/</g,"&lt;");
	item1 = item1.replace(/>/g,"&gt;");
	
	
	var item2 = "";
	var lineLen = 60;
	if(item1.indexOf(" ")>=60 || item1.indexOf(" ")<=0){
		for(i=0;i<item.value.length/lineLen;i++){
		item2 += item1.substring(i*lineLen,(i+1)*lineLen)+"<br/>";
		}
	}else{
		item2 = item1;
	}
	
	//check the url
	var url = "cmd=sendcmessage&to="+current;
	if(inBlockList(current)==true){
	item2 = "Message not sent you have blocked the person.";
	messages.innerHTML = "<div class='mymessage' ><span style='color:black;'>["+username+"] :</span>"+item2+"</div>\n"+messages.innerHTML; 
	}else{
	sendRequest(url,"message="+item1,"dummy()");
	messages.innerHTML = "<div class='mymessage' ><span style='color:black;'>["+username+"] :</span>"+item2+"</div>\n"+messages.innerHTML; 
	//beep();
	}
	item.value = "";
	item.focus();
	return false;
}

function recieveMessage(){
	var url = "cmd=recievemessage";
	//if(current != "mainButton")
	recieveRequest(url,"parserRecievedMessages()");
}

function inBlockList(name){
	//alert(block_list.length)
	for(var i=0;i<block_list.length;i++){
		if(block_list[i]==name)
			return true;
	}
	return false;
}
function movieobject(moviename)
{
	if (navigator.appName.indexOf ("Microsoft") !=-1) 
	{
		return window.beepoo;
	}

	else
	{
		return window.document.beepoo;
	}
}

function beep(){
	var test = movieobject();
	test.Play();
}

function parserRecievedMessages(){
	//alert(" "+response);
	if(receiveRes.length > 0){
		var messages = document.getElementById("messages");
		//messages.innerHTML = response+messages.innerHTML;
		var lines = receiveRes.split("<line>");
		var beepItem = document.getElementById("beep");
		var beepItem1 = document.getElementById("fbeepo");
		var beepItem2 = document.getElementById("fbeepf");
		var moviename = "beepoo";
		for(i=0;i<lines.length-1;i++){
			
			beep();
			var fields = lines[i].split("<field>");
			//skip if the sender is in block list.
			if( inBlockList(fields[0]) == true) continue;
			
			if(fields[0]=="admin")
				alert("[Admin] :"+fields[1]);
			else {
				if(fields[0]==current){
					messages.innerHTML = "<div class='hermessage' ><span style='color:black;'>["+fields[0]+"] :</span>"+fields[1]+"</div>\n"+messages.innerHTML; 
				} else if( col.exist(fields[0]) ) {
					markUser(fields[0]);
					offlineMessages[ fields[0] ] = "<next><div class='hermessage' ><span style='color:black;'>["+fields[0]+"] :</span>"+fields[1]+"</div>"+offlineMessages[fields[0]];
				} else {
					if(offlineMessages[fields[0]] == null)
						offlineMessages[fields[0]] = "<div class='hermessage' ><span style='color:black;'>["+fields[0]+"] :</span>"+fields[1]+"</div>";
					else
						offlineMessages[fields[0]] += "<next><div class='hermessage' ><span style='color:black;'>["+fields[0]+"] :</span>"+fields[1]+"</div>";
					addItem(fields[0],fields[0],false);
					markUser(fields[0]);
				}
			}
			
		}
	}
}

function addItem(name,image,load){
	//alert(name);
	var list = document.getElementById("mainLeft");
	var item = document.getElementById(name);
	if(item != null)
		if(load == true){
			loadItem(name);
			return;
		}else return;
	else{
	//this creates the left button for the item added in this method.
	var string = "\n<div class='left-button' id='"+name+"' onclick=\"loadItem('"+name+"');\">"
					+name+"</div>\n";
					
	//string1 goes to right hand panel when this item is clicked.
	var string1 = "\n<div style='margin-left:10px;height:100px;width:600px;color:white;'>";
	string1 += "<a href='/profile.php?user="+name+"' target='_blank' >View Profile</a> | ";
	if(inBlockList(name)){
		string1 += "<a id='unblocknow' style='cursor:pointer;' onclick='unblockNow(\""+name+"\");'>Unblock</a>";
		string1 += "<a id='blocknow'   style='display:none;cursor:pointer;' onclick='blockNow(\""+name+"\");'>Block</a> | ";
	}else{
		string1 += "<a id='unblocknow' style='display:none;cursor:pointer;' onclick='unblockNow(\""+name+"\");'>Unblock</a>";
		string1 += "<a id='blocknow'   style='cursor:pointer;' onclick='blockNow(\""+name+"\");'>Block</a> | ";
	}
	string1 += "<a href='/report.php?user="+name+"' target='_blank'>Report User</a> | ";
	string1 += "<a style='cursor:pointer;' onclick='closeThisWindow(\""+name+"\");' >Close This Window</a>";
	string1 += "<img src='"+
	(image.indexOf('/')>=0?image:"/profilepic.php?user="+name)
	+"' style='margin-left:480px;border:0px;height:120px;width:100px;max-width:100px;max-height:120px;margin-top:-20px;'></div>\n";
	string1 += "<form id='form' onsubmit=\"return sendCMessage();\">\n";
	string1 += "<div style='margin-top:-25px;'>&nbsp;&nbsp;Enter Your Message: &nbsp;<input type='text' id='newMessage' size='40' />\n";
	string1 += "<input type='button' id='sendMessage' value='Send' onclick='sendCMessage();' />\n";
	string1 += "</div>\n";
	string1 += "<div id='messages' class='mainMessages'></div>\n";
	string1 += "</form>\n";
	

	list.innerHTML += string;
	col.add(name,string1);
	if(load == true)
		loadItem(name);
	}
}

function removeItem(name){
	var item = document.getElementById(name);
	if(item!=null)
	item.parentNode.removeChild(item);
}

/*            disables all the links and shows the "my account" and "exit" buttons.                                                                            */
function disableAllLinks(){
	var links = document.links;
	var first  = document.getElementById("update");
	var second  = document.getElementById("logout");
	for(var i=0;i<links.length;i++){
		if(links[i]==first || links[i]==second)continue;
		links[i].style.display = "none";
	}
	
	
	//var homelink = document.getElementById("home-link");
	//homelink.style.display = "block";
	//homelink.href=null;
	
	//first.style.display = "block";
	//second.style.display = "block";
}

function logout(){
	location.href="/logout.php";
}

function dummy(){ }

function displayCaution(){
	var caution = document.getElementById("caution");
	caution.style.display = "block";
}

function exit(){
	logout();
}
function myaccount(){
}

/* Marks the tab pink to show user have recieved message for this tab all the tab names are same as user name them selfs.so if i am chating to x the tab name to x would be x */
function markUser(user){
 var toMark = document.getElementById(user);
 toMark.className = "left-button-marked";
}


/*   loads all the message for current tab when switched to current tab, messages received while browsing other tabs    */
// OFFLINE MESSAGES
function getOM(){
	var messages = document.getElementById("messages");
	
	if(offlineMessages[current] != null){
		/*var list = offlineMessages[current].split("<next>");
		
		for(i=0;i<list.length;i++){
			if(list[i]!=null){
				messages.innerHTML = list[i]+messages.innerHTML;
				alert(list[i]);
			}
		}
		
		offlineMessages[current] = null;*/
		messages.innerHTML = offlineMessages[current]+messages.innerHTML;
		offlineMessages[current]="";
	}
}

function closeThisWindow(name){
	var mainRight = document.getElementById("mainRight");
	//col.remove(current);
	//alert(col[current]);
	col[name] = null;
	removeItem(name);
	current = null;
	loadItem("mainButton");
	
}

function saveAndRefresh(){
	var min_age = document.getElementById("min_age").value;
	var max_age = document.getElementById("max_age").value;
	var pref_gender = document.getElementById("pref_gender").value;
	var pref_country = document.getElementById("pref_country").value;
	document.getElementById("caution").style.display="block";
	makeRequest("cmd=saveandrefresh&page=1&min_age="+min_age+
	"&max_age="+max_age+
	"&pref_gender="+pref_gender+
	"&pref_country="+pref_country,"saveAndRefreshHandler()");
	//alert(min_age+" "+max_age+" "+pref_gender+" "+pref_country);
}

function saveAndRefreshHandler(){
	//alert(response);
	document.getElementById("caution").style.display="block";
	makeRequest("cmd=main&page=1","populateMain1()");
}

function unblockNow(user){
	var link = document.getElementById("blocknow");
	var link1 = document.getElementById("unblocknow");
	for(var i=0;i<block_list.length;i++){
		if(block_list[i]==user){
			block_list[i]=null;
			link.style.display = "block";
			link1.style.display = "none";
			
		}
	}
}
function blockNow(user){
	
	if(!inBlockList(user)){
		var link = document.getElementById("blocknow");
		var link1 = document.getElementById("unblocknow");
		block_list[block_list.length] = user;
		link1.style.display = "block";
		link.style.display = "none";
		
	}
}

function insertAddThis(){
	var addThisDiv = document.getElementById("addthisgadget");
	addThisDiv.innerHTML = "<script type=\"text/javascript\">addthis_pub  = 'zeronexxx';</script><a href=\"\" rel=\"nofollow\" onmouseover=\"return addthis_open(this, '', '[URL]', '[TITLE]')\" onmouseout=\"addthis_close()\" onclick=\"return addthis_sendto()\"><img src=\"http://s9.addthis.com/button1-bm.gif\" width=\"125\" height=\"16\" style=\"border:0px;\" alt=\"\" /></a><script type=\"text/javascript\" src=\"http://s7.addthis.com/js/152/addthis_widget.js\"></script>";
}


function accessCheck(){ return true; }
