<?php 
/*
##################################################################
#                       PHP 4&5 MySQL 4&5                        #
##################################################################
#           Copyright (c) 2004-2008 Armia Systems Inc            #
##################################################################
#               This file is part of Cybermatch site             #
##################################################################
#    Developed By: simi (simi@armia.com)                         #

##################################################################
#               Developed On:   03-23-2009                       #
##################################################################
#  				Modified By:        	                         #
##################################################################
#               Modified On:                                     #
##################################################################
# This script may not be distributed, sold, given away for free  #
# to third party, or used as a part of any internet ervices such #
# as webdesign etc.                                              #
##################################################################
*/

require_once ("config.inc.php");
require_once ("includes/mysql.inc.php");
require_once ("includes/arrays.inc.php");

if (!isset($_SESSION['userlogged']) OR $_SESSION['userlogged'] <> "YES") {
	header("Location: chatboxlogin.php");
	exit;
}
/*if (!in_array(basename($_SERVER['PHP_SELF']), $arrUserAllowedPages)) {
	if (strpos($_SERVER['HTTP_REFERER'], $_SERVER['HTTP_HOST']) === false) {
		header("Location: chatboxlogout.php");
		exit;
	}
}*/
require_once ("classes/userside.class.php");
require_once ("classes/misc.class.php");

$message	= "";
$array		= array();
$status		= isset($_POST['vStatus'])	?	stripslashes(trim($_POST['vStatus']))	:	"Online";
if (!$objDB) {
	$message	= "Unable to Locate Database Server.";
} else {
	$objU		= new userside($objDB);
	$objM		= new misc($objDB);
	$objM->checkPremiumPermission();
	if ($objU->is_expired($_SESSION['user_id'])) {
		header("Location: chatboxlogin.php");
		exit;
	}
	
	if (isset($_POST['CA'])) { 
		$objM->change_user_online_status($_SESSION['user_id'], addslashes($status));
		header("Location: chatbox.php");
		exit();
	}
	$array		= $objU->getuser($_SESSION['user_id']);
	if (!empty($array))
		$status	= $array['vOnline'];
    $array		= $objM->get_my_friend_list($_SESSION['user_id']);
	$arrRequests	= $objM->get_chat_requests($_SESSION['user_id']);
        
        
        
        if (isset($_POST['CA'])) {
		$objM->change_user_online_status($_SESSION['user_id'], addslashes($status));
	}
        
}
include_once ("title_chat.inc.php");
?>
<!-- styles needed by jScrollPane -->


<!-- latest jQuery direct from google's CDN -->


<!-- the mousewheel plugin - optional to provide mousewheel support -->
<script type="text/javascript" src="js/jquery.nicescroll.js"></script>


<script src="js/boxover.js"></script>
<script language="javascript" type="text/javascript">
var req = null;
var reqOne = null;

var timerHandler = null;

function ChildCallBack()
{ 
  try
  {
    window.opener.chatwindow = 'open';
  }
  catch(e)
  {
  }
}

timerHandler = window.setInterval(ChildCallBack, 100);


function processReqChange() {
  if (req.readyState == 4 && req.status == 200 ) {
    var dobj = document.getElementById( "moreSpan" );
   // dobj.innerHTML = req.responseText;
  }
}

function loadUrl( url ) {
  if(window.XMLHttpRequest) {
    try { req = new XMLHttpRequest();
    } catch(e) { req = false; }
  } else if(window.ActiveXObject) {
    try { req = new ActiveXObject('Msxml2.XMLHTTP');
    } catch(e) {
    try { req = new ActiveXObject('Microsoft.XMLHTTP');
    } catch(e) { req = false; }
  } }
  if(req) {
    req.onreadystatechange = processReqChange;
    req.open('GET', url, true);
    req.send('');
  }
}

function getMore()
{
  var url = "getchatrequests.php";
  loadUrl( url );
}

function timers() {
setInterval ( "getMore()", 10000 );
}

var imagewindow ;
var children = Array();
function closechatboxsession(imagewindow) {
  if (imagewindow && imagewindow.open && !imagewindow.closed)
	imagewindow.close(); 
}
function closeAllchildren()
{   
    window.opener.chatwindow = 'closed'; 
	for(var n=0;n<children.length;n++)
	{
	 closechatboxsession(children[n]);
	}
} 

 var MyActiveWindows= new Array;    
function launchchatboxsession(id)
{  //alert(MyActiveWindows[id]);
	var winVarName = "chatwindow_"+id;
        
        if (MyActiveWindows[id] === undefined) {
            
            MyActiveWindows[id] = '';
        }
        
        //  alert(MyActiveWindows[id]);
              //  alert(MyActiveWindows[id]);
	if (MyActiveWindows[id]== '') {
		imagewindow = window.open ('chatboxsession.php?fid='+id+'&window=new',
		"chatwindow_"+id,"menubar=0,statusbar=0,resizable=0,scrollbars=1,width=360,height=510");
		imagewindow.moveTo(180,150);
		children[children.length]=imagewindow;
		window[winVarName] = imagewindow;
	} else {
	 window[winVarName].focus();
	}
        
        
               if(MyActiveWindows[id]=='' || MyActiveWindows[id]=== undefined){
                MyActiveWindows[id]  = winVarName;
                //alert(MyActiveWindows[id])
                }
        
        
}

function timersOne()
{
setInterval ( "getMoreOne()", 10000 );
setInterval ( "setTimersChat()", 20000 );
}
function getMoreOne()
{
  var url = "getchatrequests_one.php";
  loadUrlOne( url );
}
function loadUrlOne( url ) {
  if(window.XMLHttpRequest) {
    try { reqOne = new XMLHttpRequest();
    } catch(e) { reqOne = false; }
  } else if(window.ActiveXObject) {
    try { reqOne = new ActiveXObject('Msxml2.XMLHTTP');
    } catch(e) {
    try { reqOne = new ActiveXObject('Microsoft.XMLHTTP');
    } catch(e) { reqOne = false; }
  } }
  if(reqOne) {
    reqOne.onreadystatechange = processReqChangeOne;
    reqOne.open('GET', url, true);
    reqOne.send('');
  }
}
function processReqChangeOne() {
  if (reqOne.readyState == 4 && reqOne.status == 200 ) {
  	eval(reqOne.responseText);
  }
}

function setTimersChat()
{
 //alert("safsd");   
 
 var myStringArray = MyActiveWindows;
var arrayLength = myStringArray.length;
for (var i = 0; i < arrayLength; i++) {
    myStringArray[i] = '';
    //Do something
}
}
</script>

<script language="javascript" src="js/jquery.form.js"></script>
<script language="javascript">
// prepare the form when the DOM is ready 
$(document).ready(function() { 
    
    
    $('.listpeople').niceScroll({cursorcolor:"#9fa2aa"});
    
    
    var options = { 
        target:        '#output2',   // target element(s) to be updated with server response 
        beforeSubmit:  showRequest,  // pre-submit callback 
        success:       showResponse, // post-submit callback 
		resetForm: true 			  
 
        // other available options: 
        //url:       url         // override for form's 'action' attribute 
        //type:      type        // 'get' or 'post', override for form's 'method' attribute 
        //dataType:  null        // 'xml', 'script', or 'json' (expected server response type) 
        //clearForm: true        // clear all form fields after successful submit 
        //resetForm: true        // reset the form after successful submit 
 
        // $.ajax options can be used here too, for example: 
        //timeout:   3000 
    }; 
 
    // bind to the form's submit event 
    $('#myForm2').submit(function() { 
        // inside event callbacks 'this' is the DOM element so we first 
        // wrap it in a jQuery object and then invoke ajaxSubmit 
        $(this).ajaxSubmit(options); 
 
        // !!! Important !!! 
        // always return false to prevent standard browser submit and page navigation 
        return false; 
    }); 
    
    
    $( "#searchusers" ).keyup(function() {
//alert($(this).val());
var str  = $(this).val();
var n = str.length;
 if(n>1)
  {
      $("#listpeople").html('');
       $.ajax(
       {
           url:"chatsearch.php?search="+str,
           dataType:'html',
           success:function(result){
           
   $("#listpeople").html(result);
   
      setTimeout(function() {
     $( "#searchusers" ).val('');
     $("#listpeople").html('');
}, 50000);
   
  }});



  }


});
    
    
   
    
}); 
 function addtochat(profile_id)
   {
       
        $.ajax(
       {
           url:"addtochatajax.php?profile_id="+profile_id,
           dataType:'html',
           success:function(result){
           
   $("#"+profile_id).html("<p style='color:green;'>Chat Invitation Send</p>");
  }});
   }
// pre-submit callback 
function showRequest(formData, jqForm, options) { 
    // formData is an array; here we use $.param to convert it to a string to display it 
    // but the form plugin does this for you automatically when it submits the data 
    var queryString = $.param(formData); 
 
    // jqForm is a jQuery object encapsulating the form element.  To access the 
    // DOM element for the form do this: 
    // var formElement = jqForm[0]; 
 
   // alert('About to submit: \n\n' + queryString); 
 
    // here we could return false to prevent the form from being submitted; 
    // returning anything other than false will allow the form submit to continue 
    return true; 
} 
 
// post-submit callback 
function showResponse(responseText, statusText)  { 
    // for normal html responses, the first argument to the success callback 
    // is the XMLHttpRequest object's responseText property 
 
    // if the ajaxSubmit method was passed an Options Object with the dataType 
    // property set to 'xml' then the first argument to the success callback 
    // is the XMLHttpRequest object's responseXML property 
 
    // if the ajaxSubmit method was passed an Options Object with the dataType 
    // property set to 'json' then the first argument to the success callback 
    // is the json data object returned by the server 

   // alert('status: ' + statusText + '\n\nresponseText: \n' + responseText + 
       // '\n\nThe output div should have already been updated with the responseText.'); 
} 

function submitForm()
{
  
      
        
        document.getElementById("myForm2").submit();
}
</script>
<script language='javascript'>
	<?php foreach ($arrRequests as $key => $value) { ?>
		launchchatboxsession(<?php echo $value['nUser_Id_From']?>);
	<?php } ?>
</script>

<div class="row">
	<div class="twelve columns">
		<div class="search-rslts">
			<div class="row"><div class="inenr-hd"><h2>Chat</h2></div></div>
			<div class="row">
				<form name="frmChat" id="myForm2" method="post" action="chatbox.php">
					<div class="newdesignforinput maintext1">
						<div class="full_row">
							<div class="twelve columns"><input type="text" id="searchusers" class="chat_user_find" placeholder="Search"></div>
						</div>
						<div class="full_row">
							<div id="listpeople" style="max-height: 100px;overflow: auto;" class="listpeople">  </div>
						</div>
						
						<div class="full_row">
							<div class="twelve columns">
							<input type="hidden" name="CA" value="CA">
							<h2 class="headings2">Make me</h2>
                                                        <select name="vStatus" class="chat-select" onchange="submitForm()">
									<option value="Online" <?php echo $status=="Online"?"selected":""?>>Online</option>
									<option value="Invisible" <?php echo $status=="Invisible"?"selected":""?>>Invisible</option>
									<option value="Busy" <?php echo $status=="Busy"?"selected":""?>>Busy</option>
								</select>
							</div>
						</div>
					</div>
				</form>
					
					<div class="newdesignforinput maintext1">
						<div class="full_row">
							<div class="twelve columns user_txt">
								<div id='output2'>
									<b><?php echo $_SESSION['user_login']?></b> - I am <span style="color:#7c7c7c; "><?php echo $status?></span></div>
									<div class="clear"></div>
									<span class="date_txt"><?php
										//display time in est format
										$timeDisplay=gmdate('Y-m-d h:i:s A');
										$gttime=mysql_query("select date_add('$timeDisplay',INTERVAL '-4' hour) as gmttime") or die(mysql_error());
										if(mysql_num_rows($gttime)>0)
										{
										$timeDisplay=mysql_result($gttime,0,'gmttime');
										echo date('m/d/Y',  strtotime($timeDisplay));
										}//end if
									?>
					  			</span>
							</div>
						</div>
						
						<div class="full_row">
							<div class="twelve columns">
								<div id="moreSpan">
								<div class="row user_list_outer">
								<?php if (!empty($array)) {
								foreach ($array as $key => $value) { ?>
								  <div class="row user_list">
									<?php if($value['vOnline'] == "Online") { ?>
									<img src="images/chatonline.gif" width="12" height="12">
									<?php } elseif ($value['vOnline'] == "Busy") { ?>
									<img src="images/chatbusy.gif" width="12" height="12">
									<?php } else { ?>
									<img src="images/chatoffline.gif" width="12" height="12">
									<?php } ?>&nbsp;<a href="#" onClick="javascript:launchchatboxsession(<?php echo $value['nUser_Id']?>);" >
									<span title="header=[<img  style='vertical-align:middle' src='images/info.gif' width='20px' height='20px' border='0'>&nbsp;&nbsp;<?php echo $value['vLogin_Friend']?> (<?php echo $value['vOnline']?>)] body=[<?php echo $value['vName_Friend']?>, <?php echo $value['vAge']?> year old <?php echo $value['vGender']?>]">
									<span><?php echo $value['vLogin_Friend']?></span></span></a>
								  </div>
								  <?php } ?>
								  <?php if(count($array) < 7) { 
								  for ($index=1; $index<=(7-count($array)); $index++) { ?>
								 <div class="clear"></div>
								  <?php } }?>
								  <div class="clear"></div>
								  
								 <?php } else {?>
								<div class="row"><b>No Friends in your chatbox!</b></div>
								  <?php } ?>
								</div>		
								</div>
						  
							</div>
						</div>
				
			</div>
		</div>
	</div>
</div>



<?php //include_once('chat_bottomhtml.inc.php');?>
