// JavaScript Document
var visible = 0;
var logged=false;

function enterKeyPressed(field,e)
{	
	var keycode;
	if (window.event) 
		keycode = window.event.keyCode;
	else if (e) 
		keycode = e.which;

	if (keycode == 13)
		return true;
	else
		return false;
}

function setSelectionRange(input, selectionStart, selectionEnd) {
  if (input.setSelectionRange) {
    input.focus();
    input.setSelectionRange(selectionStart, selectionEnd);
  }
  else if (input.createTextRange) {
    var range = input.createTextRange();
    range.collapse(true);
    range.moveEnd('character', selectionEnd);
    range.moveStart('character', selectionStart);
    range.select();
  }
}

function setCaretToPos (input, pos) 
{
  setSelectionRange(input, pos, pos);
}

function chatInput(field,e,user)
{
	if(enterKeyPressed(field,e))
	{
		element = document.getElementById('chatinput');
        var str = element.value;
		sendData(str,user);
		element.value="";
		//setCaretToPos(element,0);
		element.focus();
	}
	if(e=="respondingAdmin"){
		var str="respondingAdmin_001";
		sendData(str,user);
				//setCaretToPos(element,0);
		//element.focus();
	}
}

function sendData(str,user)
{
	/*xmlhttp=GetXmlHttpObject();
	if (xmlhttp==null)
	{
	  	alert ("Your browser does not support AJAX!");
	  	return;
	}
	var url="scripts/chat/addMess.php";
	url=url+"?u="+user;
	url=url+"&q="+str;
	url=url+"&sid="+Math.random();
	xmlhttp.onreadystatechange=stateChanged;
	xmlhttp.open("GET",url,true);
	xmlhttp.send(null);*/
	
	$.ajax({
	  type: "GET",
	  url: "scripts/chat/addMess.php",
	  data: "u="+user+"&q="+str+"&sid="+Math.random(),
   	  success: function(msg){
      	//alert( "Data Saved: " + msg );
		update(msg);
	  }
	});
}

function getData(user)
{
	/*xmlhttp=GetXmlHttpObject();
	if (xmlhttp==null)
	{
	  alert ("Your browser does not support AJAX!");
	  return;
	}
	var url="scripts/chat/getMess.php";
	url=url+"?u="+user;
	url=url+"&sid="+Math.random();
	xmlhttp.onreadystatechange=stateChanged;
	xmlhttp.open("GET",url,true);
	xmlhttp.send(null);*/
	
	$.ajax({
	  type: "GET",
	  url: "scripts/chat/getMess.php",
	  data: "u="+user+"&sid="+Math.random(),
   	  success: function(msg){
      	//alert( "Data Saved: " + msg );
		update(msg);
	  }
	});

}

function update(msg)
{
	//var s=JSON.parse(msg);
	//eval("var s="+msg);
	chatContent=$("#contentBox").html();
	
	//alert(chatContent);
	
	chatContent+=msg;
	$("#contentBox").html(chatContent);
	$("#contentBox").scrollTop($("#contentBox").attr("scrollHeight"));  
}
function autoScroll(){
	$("#contentBox").scrollTop($("#contentBox").attr("scrollHeight"));	
}

function stateChanged()
{
	if (xmlhttp.readyState==4)
	  {
		var str = JSON.parse(xmlhttp.responseText);
		element = document.getElementById('contentBox');
		var content = element.innerHTML;
		content = content+str.mess;
		
		if(str.bing)
			makeSomeNoise();
		
		element.innerHTML = content;
		//element.scrollTop = element.scrollHeight;
	  }
}

function loginRequest(str,adminOn)
{
	xmlhttp=GetXmlHttpObject();
	if (xmlhttp==null)
	{
	  	alert ("Your browser does not support AJAX!");
	  	return;
	}
	var url="scripts/chat/login.php";
	url=url+"?u="+str;
	url=url+"&sid="+Math.random();
	
	if(adminOn)
		url=url+"&ad=1";
	
	xmlhttp.onreadystatechange=loginResponse;
	xmlhttp.open("GET",url,true);
	xmlhttp.send(null);
}

function loginResponse()
{
	if (xmlhttp.readyState==4)
	  {
		var response = xmlhttp.responseText;
		if(response==1)
		{
			window.location.href="chat_test.php";
		}
		else if(response==2)
		{
			document.getElementById("pw").style.visibility = 'visible';
			document.getElementById("pass").style.visibility = 'visible';
			document.getElementById("admin_mess").style.visibility = 'visible';
		}
	  }
}

function GetXmlHttpObject()
{
	if (window.XMLHttpRequest)
  	{
  		// code for IE7+, Firefox, Chrome, Opera, Safari
  		return new XMLHttpRequest();
  	}
	if (window.ActiveXObject)
  	{
  		// code for IE6, IE5
  		return new ActiveXObject("Microsoft.XMLHTTP");
  	}
	return null;
}

function showChatBox(option)
{
	if(option!=0){
		document.getElementById('chatDiv').style.visibility = 'visible';
		chatBoxContent(option);
		visible = ! visible;
	}
	
}

function hideChatBox()
{
	parent.document.getElementById('chat_box').style.display='none';
/*	
	document.getElementById('active').style.visibility = 'hidden';
	document.getElementById('inactive').style.visibility = 'visible';
	document.getElementById('chatDiv').style.visibility = 'visible';
	if(document.getElementById('nn')){
		document.getElementById('nn').style.visibility = 'hidden';
		document.getElementById('pass').style.visibility = 'hidden';
		document.getElementById('admin_mess').style.visibility = 'hidden';
		document.getElementById('pw').style.visibility = 'hidden';
	}*/
	parent.visible = false; 
}

function top_chat_clicked(){
	visible = !visible;
	if (visible) {
		document.getElementById('chat_box').style.display='inline-block';
	} else {
		document.getElementById('chat_box').style.display='none';
	}

//	chatButtonClicked();
	
}

function chatButtonClicked()
{

  var wrapper = parent.document.getElementById ('wrapper');

	if(visible) {
		hideChatBox();
    wrapper.style.zIndex = "10";
  }
	else {
		showChatBox();
    wrapper.style.zIndex = "15";
  }
}

function chatBoxContent(option)
{
	if(option || logged)
	{
		logged = true;
		document.getElementById('inactive').style.visibility = 'hidden';
		document.getElementById('active').style.visibility = 'visible';
	}
	else
	{
		document.getElementById('active').style.visibility = 'hidden';
		document.getElementById('inactive').style.visibility = 'visible';
		if(document.getElementById('nn')){
			document.getElementById('nn').style.visibility = 'visible';
		}
	}
}

function logUser(field,e,adminOn)
{
	if(enterKeyPressed(field,e))
	{
		var nickname = document.getElementById('nn').value;
		loginRequest(nickname,adminOn);
	} else {
		if(field.name=="auto_login"){
			var nickname = document.getElementById('auto_login').value;
			loginRequest(nickname,adminOn);
		}
	}
}
function sendTo(user)
{
	var str = (String)(user);
	document.getElementById('chatinput').value = "[@"+str+":]";
}
function getPass(field,e)
{
	if(enterKeyPressed(field,e))
	{
		var nickname = document.getElementById('nn').value;
		var password = document.getElementById('pass').value;
		checkPassword(nickname,password);
	}
}
function checkPassword(user,pass)
{
	xmlhttp=GetXmlHttpObject();
	if (xmlhttp==null)
	{
	  	alert ("Your browser does not support AJAX!");
	  	return;
	}
	var url="scripts/chat/login.php";
	url=url+"?u="+user;
	url=url+"&p="+pass;
	url=url+"&sid="+Math.random();
	xmlhttp.onreadystatechange=adminloginResponse;
	xmlhttp.open("GET",url,true);
	xmlhttp.send(null);
}
function adminloginResponse()
{
	if (xmlhttp.readyState==4)
	{
	  var response = xmlhttp.responseText;
	  if(response=="admin")
	  {
		parent.document.getElementById('top_chat_sub').className='chatButton_online';
		  parent.document.getElementById('top_chat_button').style.display='inline-block';
		  
		  window.location.href="chat_test.php";
	  }
	  else
		  $("admin_mess").html("<span style='color:red'>Incorrect nickname password combo.</span>");
	}
}
function getAll(user,time)
{
	if(time)
	{
		/*xmlhttp=GetXmlHttpObject();
		if (xmlhttp==null)
		{
		  alert ("Your browser does not support AJAX!");
		  return;
		}
		var url="scripts/chat/getAll.php";
		url=url+"?u="+user;
		url=url+"&sid="+Math.random();
		xmlhttp.onreadystatechange=showAll;
		xmlhttp.open("GET",url,true);
		xmlhttp.send(null);*/
		
		$.ajax({
		  type: "GET",
		  url: "scripts/chat/getAll.php",
		  data: "u="+user+"&sid="+Math.random(),
		  success: function(msg){
			//alert( "Data Saved: " + msg );
			showAll(msg)
		  }
		});
	}
}
function showAll(msg)
{
	 /* var response = xmlhttp.responseText;
	  //str=str.split(":");
	  element = document.getElementById('contentBox');
	  element.innerHTML = response;
	  element.scrollTop = element.scrollHeight;*/
	  
	  $("#contentBox").html(msg);
	 // $("#contentBox").scrollTop($("#contentBox").scrollHeight);
}
function cleanUp()
{
	/*xmlhttp=GetXmlHttpObject();
	if (xmlhttp==null)
	{
	  alert ("Your browser does not support AJAX!");
	  return;
	}
	var url="scripts/chat/reaper.php";
	url=url+"?sid="+Math.random();
	xmlhttp.onreadystatechange=reloadPage;
	xmlhttp.open("GET",url,true);
	xmlhttp.send(null);*/
	
	$.ajax({
	  type: "GET",
	  url: "scripts/chat/reaper.php",
	  data: "&sid="+Math.random(),
   	  success: function(msg){
      	//alert( "Data Saved: " + msg );
		reloadPage();
	  }
	});
}
function reloadPage()
{
	parent.document.getElementById('chat_box').style.display='none';

	parent.visible=false;
	
	document.getElementById('below_header').style.visibility = 'hidden';
	document.getElementById('active').style.visibility = 'hidden';
	document.getElementById('inactive').style.visibility = 'visible';

//	alert(parent.document.location.href);
	parent.document.location.href = parent.document.location.href;


}
function makeSomeNoise()
{
	//hideChatBox();
	//playSound();
}

function rgetStyle(oElm, strCssRule){
  var strValue = "";
  if(document.defaultView && document.defaultView.getComputedStyle){
	strValue = document.defaultView.getComputedStyle(oElm, "").getPropertyValue(strCssRule);
  }
  else if(oElm.currentStyle){
	strCssRule = strCssRule.replace(/\-(\w)/g, function (strMatch, p1){
	  return p1.toUpperCase();
	});
	strValue = oElm.currentStyle[strCssRule];
  }
  return strValue;
}

        var notif=false;
        var new_mess=true;
        function new_users(num){
          if(typeof parent.window !== 'undefined' && typeof parent.window.new_users_index === 'function'){
            parent.window.new_users_index(num); //Call the function only if it exists
            notif=true;
          }
        }
        function clear_interval(){
          if(notif==true){
            if(typeof parent.window !== 'undefined' && typeof parent.window.clear_interval_index === 'function'){
              parent.window.clear_interval_index(); //Call the function only if it exists
            }
            notif=false;
          }
        }
        function chat_resp(field,e,user){
          if(enterKeyPressed(field,e)){
            document.getElementById('head_img').src="images/chat_text3.jpg";
            new_mess=true;
          } else {
            if(new_mess==true){
              if(user=="admin"){
                document.getElementById('head_img').src="images/chat_admin_resp2.jpg";
                chatInput('document.chatinput',"respondingAdmin",'<? echo $_SESSION[user]; ?>')
              }
              new_mess=false;
            }
          }
        }
        function respond_check(bool){
          if(bool==true){
            document.getElementById('head_img').src="images/chat_admin_resp.jpg";
          } else {
            document.getElementById('head_img').src="images/chat_text3.jpg";
          }
        }
        function admin_move(){
          if('<? echo $_SESSION[user]; ?>'=="admin"){
            alert("Warning: You should not deviate from this page without logging out of the chat by clicking the X");
          }
        }

