<?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()", 5000 );
}
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:"#0000FF"});
    
    
    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.'); 
} 
</script>
<script language='javascript'>
	<?php foreach ($arrRequests as $key => $value) { ?>
		launchchatboxsession(<?php echo $value['nUser_Id_From']?>);
	<?php } ?>
</script>
<table width="100%"  border="0" cellspacing="0" cellpadding="0">
  <tr>
    <td valign="top" class="white"><table width="100%"  border="0" cellspacing="0" cellpadding="0">
      <tr>
        <td width="72%" valign="top"><table width="100%"  border="0" cellspacing="0" cellpadding="5">
          <tr>
            <td>              <table width="100%"  border="0" cellspacing="0" cellpadding="5">
              <tr>
                <td class="chat-title">Chat</td>
              </tr>
            </table>
              <table width="100%"  border="0" cellspacing="0" cellpadding="0">
                <tr>
                  <td><table width="100%"  border="0" cellspacing="0" cellpadding="0" class="helptext">
                    <tr>
					  <td width="99%" class="maintext1"><table width="100%"  border="0" cellspacing="0" cellpadding="0">
                      <form name="frmChat" id="myForm2" method="post" action="chatbox.php">
                          
                          <tr><td>Search </td> <td><input type="text" id="searchusers" class="maintext" placeholder="Search"></td></tr>  
                          
                          
                          <tr> <td colspan="2"><div id="listpeople" style="max-height: 100px;overflow: auto;" class="listpeople">
                             
                                      
                              </div>
                              </td></tr>
                          
                          
					  <tr>
                        <td width="45%" height="30" align="left" valign="bottom" class="maintext">
                          <input type="hidden" name="CA" value="CA">
                          <b>Make me
                           <select name="vStatus" class="chat-select">
                             <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>
                          </b></td>
                        <td width="26%" align="left" valign="top"><input name="submitButton" type="submit" class="chat-btn" value=" GO "></td>
					  </tr>
					  </form>
                  </table></td>
                      </tr>
                    <tr>
					  <td class="maintext1"><table width="100%"  border="0" cellspacing="0" cellpadding="0">
                    <tr>
                      <td width="60%" align="left"><div id='output2'> <?php echo $_SESSION['user_login']?> - I am <b><?php echo $status?></b> </div></span><span class="maintext51"><b><?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
					  ?></b></td>
                      <td width="37%" align=""><!--<a href="chatboxlogout.php" class="chat-signout">Sign Out</a> --> </td>
                    </tr>
                  </table></td>
                    </tr>
                    <tr>
					  <td><div id="moreSpan">
								<table width="100%"  border="0" cellspacing="0" cellpadding="8" class="maintext">
								<?php if (!empty($array)) {
								foreach ($array as $key => $value) { ?>
                                  <tr>
                                    <td align="left" scope="col">
									<?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;&nbsp;<a href="#" onClick="javascript:launchchatboxsession(<?php echo $value['nUser_Id_Friend']?>);" class="maintextCopy">
									<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']?>]"><strong><?php echo $value['vLogin_Friend']?>
									</strong></span></a>
									</td>
                                  </tr>
								  <?php } ?>
								  <?php if(count($array) < 7) { 
								  for ($index=1; $index<=(7-count($array)); $index++) { ?>
                                  <tr>
                                    <td>&nbsp;</td>
                                  </tr>
								  <?php } }?>
                                  <tr>
                                    <td>&nbsp;</td>
                                  </tr>
								  
								 <?php } else {?>
  <tr>
	<td class="maintext"><b>No Friends in your chatbox!</b></td>
  </tr>
								  <?php } ?>
                                </table>		
						  </div></td>
                    </tr>
                  </table>
                  </td>
                </tr>
              </table></td>
          </tr>
        </table></td>
        </tr>
    </table>      
    </td>
  </tr>
</table>
<?php //include_once('chat_bottomhtml.inc.php');?>
