<?php
require_once "check.class.php";
require_once "miscellaneous.class.php";

class misc extends miscellaneous {

	function __construct($db)
	{
		$this->dblink	= $db;
		$this->now		= date("Y-m-d H:i:s");
		$this->arrFile	= array();
		$this->arrExtns	= array("jpg", "jpeg", "gif", "png", "JPG", "JPEG", "GIF", "PNG");
		$this->arrSearch= array();
	}

	function get_my_story_count($id=0)
	{
		$count	= 0;
		$sql	= "SELECT COUNT(S.nStory_Id) as count
		            FROM ".TABLEPREFIX."success_story as S JOIN ".TABLEPREFIX."user as U 
		            ON S.nUser_Id = U.nUser_Id AND U.nUser_Id = '{$id}' 
					ORDER BY S.nStory_Id DESC";

		$res	= @mysql_query($sql, $this->dblink);
		if (@mysql_num_rows($res) > 0) {
			$row	= mysql_fetch_array($res);
			$count	= $row['count'];
			@mysql_free_result($res);
		}
		return $count;
	}

	function get_my_story_page($id=0, $start=0, $size=10)
	{
		$array	= array();
		$sql	= "SELECT *,DATE_FORMAT(S.dDate, '%D %M %Y') as dDay
		            FROM ".TABLEPREFIX."success_story as S JOIN ".TABLEPREFIX."user as U 
		            ON S.nUser_Id = U.nUser_Id AND U.nUser_Id = '{$id}' 
					ORDER BY S.nStory_Id DESC
					LIMIT ".($start).",".$size;
		$res	= @mysql_query($sql, $this->dblink);
		if (@mysql_num_rows($res) > 0) {
			while ($row = @mysql_fetch_array($res)) {
				$array[]	= $row;
			}
		}
		@mysql_free_result($res);
		return $array;
	}

	function get_story_count()
	{
		$count	= 0;
		$sql	= "SELECT COUNT(S.nStory_Id) as count
		            FROM ".TABLEPREFIX."success_story as S JOIN ".TABLEPREFIX."user as U 
		            ON S.nUser_Id = U.nUser_Id
					ORDER BY S.nStory_Id DESC";
		$res	= @mysql_query($sql, $this->dblink);
		if (@mysql_num_rows($res) > 0) {
			$row	= mysql_fetch_array($res);
			$count	= $row['count'];
			@mysql_free_result($res);
		}
		return $count;
	}

	function get_story_page($start=0, $size=10)
	{
		$array	= array();
		$sql	= "SELECT *,DATE_FORMAT(S.dDate, '%D %M %Y') as dDay
		            FROM ".TABLEPREFIX."success_story as S JOIN ".TABLEPREFIX."user as U 
		            ON S.nUser_Id = U.nUser_Id
					ORDER BY S.nStory_Id DESC
					LIMIT ".($start).",".$size;
		$res	= @mysql_query($sql, $this->dblink);
		if (@mysql_num_rows($res) > 0) {
			while ($row = @mysql_fetch_array($res)) {
				$array[]	= $row;
			}
		}
		@mysql_free_result($res);
		return $array;
	}

	function get_testimonial_count()
	{
		$count	= 0;
		$sql	= "SELECT COUNT(nTestimonial_Id) as count
		            FROM ".TABLEPREFIX."testimonial
					ORDER BY nTestimonial_Id DESC"; 
		$res	= @mysql_query($sql, $this->dblink);
		if (@mysql_num_rows($res) > 0) {
			$row	= mysql_fetch_array($res);
			$count	= $row['count'];
			@mysql_free_result($res);
		}
		return $count;
	}
	
	function get_testimonial_count2()
	{
		$count	= 0;
		$sql	= "SELECT COUNT(nTestimonial_Id) as count
		            FROM ".TABLEPREFIX."testimonial where vActive='1'
					ORDER BY nTestimonial_Id DESC"; 
		$res	= @mysql_query($sql, $this->dblink);
		if (@mysql_num_rows($res) > 0) {
			$row	= mysql_fetch_array($res);
			$count	= $row['count'];
			@mysql_free_result($res);
		}
		return $count;
	}

	function get_testimonial_page($start=0, $size=10)
	{
		$array	= array();
		$sql	= "SELECT *,DATE_FORMAT(dDate, '%D %M %Y') as dDay
		            FROM ".TABLEPREFIX."testimonial 
					ORDER BY dDate DESC
					LIMIT ".($start).",".$size;
		$res	= @mysql_query($sql, $this->dblink);
		if (@mysql_num_rows($res) > 0) {
			while ($row = @mysql_fetch_array($res)) {
				$array[]	= $row;
			}
		}
		@mysql_free_result($res);
		return $array;
	}
	
	function get_testimonial_page2($start=0, $size=10)
	{
		$array	= array();
		$sql	= "SELECT *,DATE_FORMAT(dDate, '%D %M %Y') as dDay
		            FROM ".TABLEPREFIX."testimonial where vActive='1'
					ORDER BY dDate DESC
					LIMIT ".($start).",".$size;
		$res	= @mysql_query($sql, $this->dblink);
		if (@mysql_num_rows($res) > 0) {
			while ($row = @mysql_fetch_array($res)) {
				$array[]	= $row;
			}
		}
		@mysql_free_result($res);
		return $array;
	}

	function get_upcoming_events_count($type="SE")
	{
		$count	= 0;
		$date	= date("Y-m-d")." 00:00:00";
		$sql	= "SELECT COUNT(nSE_Id) as count
		            FROM ".TABLEPREFIX."single_events
					WHERE dDate_Event > '{$date}' AND vType LIKE '{$type}' 
					ORDER BY nSE_Id DESC";  
		$res	= @mysql_query($sql, $this->dblink);
		if (@mysql_num_rows($res) > 0) {
			$row	= mysql_fetch_array($res);
			$count	= $row['count'];
			@mysql_free_result($res);
		}
		return $count;
	}

	function get_upcoming_events_page($start=0, $size=10, $type="SE")
	{
		$array	= array();
		$date	= date("Y-m-d")." 00:00:00";
		$sql	= "SELECT *
		            FROM ".TABLEPREFIX."single_events
					WHERE dDate_Event > '{$date}' AND vType LIKE '{$type}' 
					ORDER BY dDate_Event DESC
					LIMIT ".($start).",".$size;
		$res	= @mysql_query($sql, $this->dblink);
		if (@mysql_num_rows($res) > 0) {
			while ($row = @mysql_fetch_array($res)) {
				$array[]	= $row;
			}
		}
		@mysql_free_result($res);
		return $array;
	}

	function tell_friend_mail($arr=array())
	{
		$msg		= "";
		$arrEmail	= isset($arr['mail'])	?	$arr['mail']	:	array();
		$arrName	= isset($arr['name'])	?	$arr['name']	:	array();
		$message	= isset($arr['message'])	?	stripslashes(trim($arr['message']))	:	"";
		$frName		= isset($arr['fname'])		?	stripslashes(trim($arr['fname']))	:	"";
		$frEmail	= isset($arr['fmail'])		?	stripslashes(trim($arr['fmail']))	:	"";

                

		if ($frName == "")
			$msg	.= "Please enter your name.<br>";
		if ($frEmail == "")
			$msg	.= "Please enter your mail address.<br>";
		if (!$this->check_email($frEmail)) {
			$text	= $frEmail==""?"Your Email":$frEmail;
			$msg	.= "<b>".$text."</b> is an invalid email address.<br>";
		}
		if (trim(implode("", $arrName)) == "")
			$msg	.= "Please enter atleast one name in Friends list.<br>";
		if (trim(implode("", $arrEmail)) == "")
			$msg	.= "Please enter atleast one email in Friends list.<br>";

		if ($message == "")
			$msg	.= "Please enter the message.<br>";

		$array	= array();
		foreach ($arrName as $key=>$value) {
			if (trim($value) <> "")
				$array[]	= $value;
		}
		$arrName	= array();
		$arrName	= $array;

		$array	= array();
		foreach ($arrEmail as $key=>$value) {
			if (trim($value) <> "")
				$array[]	= $value;
		}
		$arrEmail	= array();
		$arrEmail	= $array;
		$array		= array();

		foreach ($arrEmail as $key=>$value) {
			if (!$this->check_email($value))
				$msg	.= "<b>".$value."</b> is an invalid email address.<br>";

		}
		if (count($arrEmail) <> count($arrName))
			$msg	.= "Mismatch of Name and Email address(s) in Friends list.<br>";

		if ($msg == "") {
			$flag	= true;
			foreach ($arrEmail as $key => $value) {
				if ($flag) {
					$message	= str_replace("{TONAME}", $arrName[$key], $message);
					$message	= str_replace("{FROMNAME}", $frName, $message);
					$from		= $frEmail;
					$to			= $value;
					$toname		= $arrName[$key];
					$fromname	= $frName;
					$subject	= 'Tell A Friend';
					$htmlbody	= '';

					require_once "settings.class.php";

//					$site_name	= settings::getone('sitename');
//					$site_url	= settings::getone('site_normal_url');
//					$site_logo	= settings::getone('sitelogo');
//					$site_valid_day	=  settings::getone('ValidityDayMembership');
                                        $settingsObj = new settings();
					$site_name	= $settingsObj->getone('sitename');
					$site_url	= $settingsObj->getone('site_normal_url');
					$site_logo	= $settingsObj->getone('sitelogo');
					$site_valid_day	= $settingsObj->getone('ValidityDayMembership');
					//checking site logo start
					if(trim($site_logo)!='')
					{
						switch($site_logo)
						{
							case "logo_default.gif":
								$site_top='24';
							break;
	
							default:
								$site_top='3';
							break;
						}//end switch
					}//end if
					else
					{
						$site_top='24';
						$site_logo=$site_name;
					}//end else
					//checking site logo ends

					$basepath	= BASE_PATH;
                                       
                                        $mail_title	= $subject;
					$send_date	= date('F j, Y');
					$content	= str_replace("Hi ".$arrName[$key].",", "<h2 style='font-size: 18px;'>Hi ".$arrName[$key].",</h2>", nl2br($message));
					$arrSearch	= array("{SITE_NAME}", "{SITE_URL}", "{MAIL_TITLE}",
										"{SEND_DATE}", "{EMAIL_CONTENT}","{SITE_LOGO}","{SITE_TOP}","{SITE_VALID-DAY}");
					$arrReplace	= array($site_name, $site_url, $mail_title, $send_date, $content,$site_logo,$site_top,$site_valid_day);
                                       
					$htmlbody	= $this->html_mail($basepath, $arrSearch, $arrReplace,'Tell A Friend');
                                        
					$textbody	= $message;

                                        $htmlbody       = str_replace('Tell A Friend','', $htmlbody);
                                        
                                        $flag		= $this->send_mail_perfect($from, $to, $subject, $fromname, $toname, $textbody, $htmlbody);
/*
					$flag	= $this->send_mail($arrName[$key]."<".$value.">", $message, "Tell A Friend", $frEmail, $frName);
*/
					$message	= str_replace($arrName[$key], "{TONAME}", $message);
                                        
				}
			}
                        
			if (!$flag)
				$msg	.= "Unable to send mail.<br>";
			else
				$msg	.= "<font color='green'>Message has been sent successfully.</font><br>";
		}
		return $msg;
	}
        
        function tell_friend_mail_api($objU,$loggedUserId,$toEmail,$name,$message)
	{
		$msg		= "";
		
//		                    $message = 'Hi {TONAME}, 
//
// I found a new site and hope you would really enjoy this .
//
// Please have a look at the site Cyber Match. 
//
// By {FROMNAME}';
                $fromDetails = $objU->select($loggedUserId);
                $frName = $fromDetails['vFirstName'];
                if($fromDetails['vMiddleName']) $frName .= " ".$fromDetails['vMiddleName'];
                if($fromDetails['vLastName']) $frName .= " ".$fromDetails['vLastName'];
                $frEmail	= $fromDetails['vEmail'];
               // echo $frEmail;
		$message        = stripslashes(trim($message));		
		if (trim($name)=="")
			$msg	.= "Please enter Friend's name.<br>";
		if (trim($toEmail)=="" || !$this->check_email($toEmail))
			$msg	.= "Please enter Friend's EmailId.<br>";
		if ($message == "")
			$msg	.= "Please enter the message.<br>";		
		if ($msg == "") {                      
                    $message	= str_replace("{TONAME}", $name, $message);
                    $message	= str_replace("{FROMNAME}", $frName, $message);
                    $from	= $frEmail;
                    $to		= $toEmail;
                    $toname	= $name;
                    $fromname	= $frName;
                    $subject	= 'Tell A Friend';
                    $htmlbody	= '';
                    require_once "settings.class.php";
//                    $site_name	= settings::getone('sitename');
//                    $site_url	= settings::getone('site_normal_url');
//                    $site_logo	= settings::getone('sitelogo');
//                    $site_valid_day	=  settings::getone('ValidityDayMembership');
                    $settingsObj = new settings();
                    $site_name	= $settingsObj->getone('sitename');
                    $site_url	= $settingsObj->getone('site_normal_url');
                    $site_logo	= $settingsObj->getone('sitelogo');
                    $site_valid_day	=  $settingsObj->getone('ValidityDayMembership');
                    //checking site logo start
                    if(trim($site_logo)!='')
                    {
                            switch($site_logo)
                            {
                                    case "logo_default.gif":
                                            $site_top='24';
                                    break;
                                    default:
                                            $site_top='3';
                                    break;
                            }//end switch
                    }//end if
                    else
                    {
                            $site_top='24';
                            $site_logo=$site_name;
                    }//end else
                    //checking site logo ends

                    

                    
                    $basepath	= BASE_PATH;
                    $mail_title	= $subject;
                    $send_date	= date('F j, Y');
                    $content	= str_replace("Hi ".$name.",", "<h2 style='font-size: 18px;'>Hi ".$name.",</h2>", nl2br($message));
                    $arrSearch	= array("{SITE_NAME}", "{SITE_URL}", "{MAIL_TITLE}",
                                                            "{SEND_DATE}", "{EMAIL_CONTENT}","{SITE_LOGO}","{SITE_TOP}","{SITE_VALID-DAY}");
                    $arrReplace	= array($site_name, $site_url, $mail_title, $send_date, $content,$site_logo,$site_top,$site_valid_day);
                    $htmlbody	= $this->html_mail('../', $arrSearch, $arrReplace,'Tell A Friend');
                   
                    $textbody	= $message;
                    $htmlbody   = str_replace('Tell A Friend','', $htmlbody);
                  
                    $flag	= $this->send_mail_perfect($from, $to, $subject, $fromname, $toname, $textbody, $htmlbody);
                    $message	= str_replace($name, "{TONAME}", $message);
                   
                    if (!$flag)
                            $msg	.= "Unable to send mail.<br>";                   
		}
		return $msg;
	}
        
	function send_mail_perfect($from, $to, $subject="", $fromname="", $toname="",
							   $textbody="", $htmlbody="")
	{

                $message	= "";
		$this->set_mail_environment();
		$header		= $this->create_header($from, $fromname, $to, $toname);
		$message	= $this->create_body($htmlbody, $textbody);
		$flag		= mail($to, $subject, $message, $header);
		return $flag;
	}

// this is depreciated with send_mail_perfect
	function send_mail($to, $body, $subject, $fromaddress, $fromname, $html=false)
	{
	  $eol="\r\n";
	  $mime_boundary=md5(time());
	
	  $headers	= "";

	  # Common Headers
	  $headers .= "From: ".$fromname."<".$fromaddress.">".$eol;
	  $headers .= "Reply-To: ".$fromname."<".$fromaddress.">".$eol;
	  $headers .= "Return-Path: ".$fromname."<".$fromaddress.">".$eol;    // these two to set reply address
	  $headers .= "Message-ID: <".time()."-".$fromaddress.">".$eol;
	  $headers .= "X-Mailer: PHP v".phpversion().$eol;          // These two to help avoid spam-filters

	  # Boundry for marking the split & Multitype Headers
	  $headers .= 'MIME-Version: 1.0'.$eol;
	  if ($html)
		$headers	.= 'Content-Type: text/html; charset=ISO-8859-15'.$eol;
	  else
		$headers .= 'Content-type: text/plain; charset=ISO-8859-15'.$eol;

	  $msg	= "";
	  $msg .= $body;

	  # SEND THE EMAIL
	  ini_set(sendmail_from,$fromaddress);  // the INI lines are to force the From Address to be used !
	  $mail_sent = mail($to, $subject, $msg, $headers);
	 
	  ini_restore(sendmail_from);
	 
	  return $mail_sent;
	}

	function logout($id=0)
	{
		$date	= date("Y-m-d");
		$sql	= "UPDATE ".TABLEPREFIX."user 
				   SET vOnline = 'Offline' 
				   WHERE nUser_Id = '{$id}'";
		$res	= @mysql_query($sql, $this->dblink);
	}
        
        function logoutApi($data)
	{
		$date	= date("Y-m-d");
		$sql	= "UPDATE ".TABLEPREFIX."user 
				   SET vOnline = 'Offline' 
				   WHERE nUser_Id = '{$data['userId']}'";
		$res	= @mysql_query($sql, $this->dblink);
                $this->deleteDeviceDetails($data['userId'], $data['device'], $data['deviceId']);
                return $res;
	}

	function login($arr=array())
	{
		$msg			= "";
		$script			= "";
		$arrElements	= array();
		$user	= isset($arr['user'])	?	stripslashes(trim($arr['user']))	:	"";
		$pass	= isset($arr['pass'])	?	stripslashes(trim($arr['pass']))	:	"";

		if ($user == "") {
			$msg			.= "Please enter your username.<br>";
			$arrElements[]	= "user";
		}
                if($user !=""){
		if (!$this->check_username($user)) {
//			$msg	.= "Only following characters allowed in username ([a-z][A-Z][0-9].-_).<br>";
                         $msg	.= "Please enter a valid username.<br>";
			if (!in_array("user", $arrElements))
				$arrElements[]	= "user";
		}
                }
		if ($pass == "") {
			$msg			.= "Please enter your password.<br>";
			$arrElements[]	= "pass";
		}

		if ($msg == "") {
			$sql	= "SELECT *,TRUNCATE((TO_DAYS(NOW()) - TO_DAYS(dDob))/365, 0) as Age
					   FROM ".TABLEPREFIX."user 
					   WHERE vLogin LIKE '".addslashes($user)."' 
					   AND vPass LIKE '".md5($pass)."' AND (vStatus='ANNN' OR vStatus='ENNN')";
			$res	= @mysql_query($sql, $this->dblink);
			if (@mysql_num_rows($res) > 0) {
				$row	= @mysql_fetch_array($res);				
                                $_SESSION['userlogged']		= "YES";
                                $_SESSION['user_login']		= $row['vLogin'];
                                $_SESSION['user_id']		= $row['nUser_Id'];
                                $_SESSION['user_gender']	= $row['vGender'];
                                $_SESSION['age_from']		= $row['Age'];
                                $_SESSION['user_name']		= $row['vFirstName']." ".$row['vMiddleName']." ".$row['vLastName'];
                                $_SESSION['user_ip']		= $_SERVER['REMOTE_ADDR'];
                                $_SESSION['vSG']=$arr['sex'];
                                $_SESSION['vSAF']=$arr['agefrom'];
                                $_SESSION['vSAT']=$arr['ageto'];
                                $this->loggedin($row['nUser_Id']);
                                $this->set_user_ip($row['nUser_Id'], $_SERVER['REMOTE_ADDR']);
				
			} else {                                
                                $sql	= "SELECT *,TRUNCATE((TO_DAYS(NOW()) - TO_DAYS(dDob))/365, 0) as Age
                                               FROM ".TABLEPREFIX."user 
                                               WHERE vLogin LIKE '".addslashes($user)."' 
                                               AND vPass LIKE '".md5($pass)."'";
                                $res	= @mysql_query($sql, $this->dblink);                               
                                if (@mysql_num_rows($res) > 0) {
                                        $row	= @mysql_fetch_array($res);
                                        if (substr($row['vStatus'], 0, 1) == "N") {
                                                $msg	.= "You are not allowed to login to the site, please contact the administrator.<br>"; 
                                        } else if (substr($row['vStatus'], 0, 1) == "D") {
                                                $msg	.= "You are not allowed to login to the site.<br>"; 
                                        } else if (substr($row['vStatus'], 0, 1) == "S") {
                                                $msg	.= "You are suspended from the site, please contact the administrator.<br>"; 
                                        }
                                }
                                else {
                                    $msg	.= "Invalid username/password.<br>";
                                    if (!in_array("user", $arrElements))
                                            $arrElements[]	= "user";
                                    if (!in_array("pass", $arrElements))
                                            $arrElements[]	= "pass";
                                }
			}
		}
		if (!empty($arrElements)) {
			$script	= '<script language="javascript">';
			foreach ($arrElements as $key=>$value) {
				$script	.= 'document.frmTells.'.$value.'.className = "textbox txt-bx01";';
			}
			$script	.= '</script>';
		}
		$msg	.= $script;

		return $msg;
	}
        
        function loginfacebook($email)
	{
		$msg			= "";
		$script			= "";
		$arrElements	= array();
		$user	= isset($arr['user'])	?	stripslashes(trim($arr['user']))	:	"";
		$pass	= isset($arr['pass'])	?	stripslashes(trim($arr['pass']))	:	"";
                $return = array();
		if ($email == "") {
			$msg			.= "Failed to retrive email from Facebook";
			$return['status'] = 0;
                        $return['message'] = $msg;
		}
               
		

		if ($msg == "") {
			 $sql	= "SELECT *,TRUNCATE((TO_DAYS(NOW()) - TO_DAYS(dDob))/365, 0) as Age
					   FROM ".TABLEPREFIX."user 
					   WHERE vEmail LIKE '".addslashes($email)."' ";
			$res	= @mysql_query($sql, $this->dblink);
                      
			if (@mysql_num_rows($res) > 0) {
				$row	= @mysql_fetch_array($res);
				if (substr($row['vStatus'], 0, 1) == "N") {
					$msg	.= "You are not allowed to login to the site, please contact the administrator.<br>"; 
				        $return['status'] = 0;
                                        $return['message'] = $msg;
                                        
                                } else if (substr($row['vStatus'], 0, 1) == "D") {
					$msg	.= "You are not allowed to login to the site.<br>"; 
                                         $return['status'] = 0;
                                        $return['message'] = $msg;
				
                                        
                                } else if (substr($row['vStatus'], 0, 1) == "S") {
					$msg	.= "You are suspended from the site, please contact the administrator.<br>"; 
				         $return['status'] = 0;
                                        $return['message'] = $msg;
                                        
                                } else {
					$_SESSION['userlogged']		= "YES";
					$_SESSION['user_login']		= $row['vLogin'];
					$_SESSION['user_id']		= $row['nUser_Id'];
					$_SESSION['user_gender']	= $row['vGender'];
					$_SESSION['age_from']		= $row['Age'];
					$_SESSION['user_name']		= $row['vFirstName']." ".$row['vMiddleName']." ".$row['vLastName'];
					$_SESSION['user_ip']		= $_SERVER['REMOTE_ADDR'];
					$_SESSION['vSG']                = "";
					$_SESSION['vSAF']               = "";
					$_SESSION['vSAT']               = "";
					$this->loggedin($row['nUser_Id']);
					$this->set_user_ip($row['nUser_Id'], $_SERVER['REMOTE_ADDR']);
                                        $return['status'] = 1;
                                        
				}
			} else {
				$msg	.= "Invalid username/password.<br>";
				if (!in_array("user", $arrElements))
					$arrElements[]	= "user";
				if (!in_array("pass", $arrElements))
					$arrElements[]	= "pass";
                                
                                 $return['status'] = 2;
                                        $return['message'] = $msg;
			}
		}
		

		return $return;
	}
        
        function login_facebook_api($arr)
	{		
                $return = array();		
                $sql	= "SELECT *,TRUNCATE((TO_DAYS(NOW()) - TO_DAYS(dDob))/365, 0) as Age
                                  FROM ".TABLEPREFIX."user 
                                  WHERE vEmail LIKE '".addslashes($arr['vEmail'])."'";
                //echo $sql;
               $res	= @mysql_query($sql, $this->dblink);

               if (@mysql_num_rows($res) > 0) {
                    $row	= @mysql_fetch_array($res);
                    $return['data']['userlogged']	=   "YES";
                    $return['data']['user_login']	=   $row['vLogin'];
                    $return['data']['user_id']		=   $row['nUser_Id'];
                    $return['data']['user_gender']	=   $row['vGender'];
                    $return['data']['age_from']		=   $row['Age'];
                    $return['data']['user_name']	=   $row['vFirstName']." ".$row['vMiddleName']." ".$row['vLastName'];
                    $return['data']['user_ip']		=   $_SERVER['REMOTE_ADDR'];
                    $return['data']['vSG']              =   $arr['sex'];
                    $return['data']['vSAF']             =   $arr['agefrom'];
                    $return['data']['vSAT']             =   $arr['ageto'];
                    $return['data']['fbId']             =   $row['fbId'];
                   
                    if($row['vStatus']=='ANNN' || $row['vStatus'] == 'ENNN'){
                    $return['status'] = 1;
                    $return['type'] = 'login';
                    if(!empty($arr['device']) && !empty($arr['deviceId'])){
                        $this->deviceLoggedin($row['nUser_Id'],$arr['device'],$arr['deviceId']);
                    }
                   
                    $this->loggedin($row['nUser_Id']);                   
                    $this->set_user_ip($row['nUser_Id'], $_SERVER['REMOTE_ADDR']);
                    }elseif (substr($row['vStatus'], 0, 1) == "N") {
                                                $return['status'] = 0;
                                                $return['error'] = "Your Account is inactive , Please contact Administrator"; 
                                        } else if (substr($row['vStatus'], 0, 1) == "D") {
                                                $return['status'] = 0;
                                                $return['error'] = "Your Account is inactive , Please contact Administrator"; 
                                        } else if (substr($row['vStatus'], 0, 1) == "S") {
                                                 $return['status'] = 0;
                                                 $return['error'] = "Your account is  suspended, please contact the administrator"; 
                                        }
                    
               } else { 
        $usernames = explode('@', $arr['vEmail']); 
        $objU		= new userside($objDB);
        $username = $objU->createusername($usernames[0]); 

        $data = array();
        $data['vLogin'] = $username;
        $data['vPass'] = $username;
        $data['vTitle'] = $arr['vTitle'];
        $data['vEmail'] = $arr['vEmail'];
        $data['vFirstName'] = $arr['vFirstName'];
        $data['vLastName'] = $arr['vLastName'];
        $data['vGender'] = $arr['vGender'];
        $data['vCountry'] = 'USA';
        $data['vState'] = 'ALABAMA';
        $data['dDob'] = $arr['dDob'];
        $data['fbId'] = $arr['fbId'];
        $data['vHearing_Source'] = 'Search Engine';
        
        
        
        $objU->set_values($data);

        $message=$objU->register_step_facebook();
       // print_r($message);
        if(!$message['message'])
        {
            $return = array();
  
            if($arr['deviceId']){
            $this->deviceLoggedin($message['user_id'],$arr['device'],$arr['deviceId']);
            }
            
            $sql	= "SELECT *,TRUNCATE((TO_DAYS(NOW()) - TO_DAYS(dDob))/365, 0) as Age
                                  FROM ".TABLEPREFIX."user 
                                  WHERE nUser_Id = '".addslashes($message['user_id'])."'";
                //echo $sql;
            $res = @mysql_query($sql, $this->dblink);
            
            if (@mysql_num_rows($res) > 0) {
                    $row	= @mysql_fetch_array($res);
                    $return['data']['userlogged']	=   "YES";
                    $return['data']['user_login']	=   $row['vLogin'];
                    $return['data']['user_id']		=   $row['nUser_Id'];
                    $return['data']['user_gender']	=   $row['vGender'];
                    $return['data']['age_from']		=   $row['Age'];
                    $return['data']['user_name']	=   $row['vFirstName']." ".$row['vMiddleName']." ".$row['vLastName'];
                    $return['data']['user_ip']		=   $_SERVER['REMOTE_ADDR'];
                    $return['data']['vSG']              =   '';
                    $return['data']['vSAF']             =   '';
                    $return['data']['vSAT']             =   '';
                    $return['data']['fbId']             =   $row['fbId'];
                    $return['status'] = 1;
                    $return['type'] = 'register';
                    
            }
            
            
            $return['message'] = "Successfully registered";            
            
        }else{
            $return = array();
            $return['status'] = 0;
            $return['message'] = $message;
            
        }
       
               }		
               return $return;
	}
        
      function loginApi($arr=array())
	{
		$msg			= "";
		$script			= "";
                
                $return = array();
                
		$arrElements	= array();
		$user	= isset($arr['user'])	?	stripslashes(trim($arr['user']))	:	"";
		$pass	= isset($arr['pass'])	?	stripslashes(trim($arr['pass']))	:	"";

                
                
		if ($user == "") {
			$msg			.= "Please enter your username";
                        $return['status'] = 0;
                        $return['error'] = $msg;
                        
			$arrElements[]	= "user";
		}
                if($user !=""){
		if (!$this->check_username($user)) {
//			$msg	.= "Only following characters allowed in username ([a-z][A-Z][0-9].-_).<br>";
                         $msg	.= "Please enter a valid username";
			if (!in_array("user", $arrElements))
				$arrElements[]	= "user";
		}
                }
		if ($pass == "") {
			$msg			.= "Please enter your password";
			$arrElements[]	= "pass";
		}
          
                if ($msg == "") {
			$sql	= "SELECT *,TRUNCATE((TO_DAYS(NOW()) - TO_DAYS(dDob))/365, 0) as Age
					   FROM ".TABLEPREFIX."user 
					   WHERE vLogin LIKE '".addslashes($user)."' 
					   AND vPass LIKE '".$pass."'";
                        
                    
			$res	= @mysql_query($sql, $this->dblink);
			if (@mysql_num_rows($res) > 0) {
				$row	= @mysql_fetch_array($res);
                                $return['data']['userlogged']		= "YES";
                                $return['data']['user_login']		= $row['vLogin'];
                                $return['data']['user_id']		= $row['nUser_Id'];
                                $return['data']['user_gender']          = $row['vGender'];
                                $return['data']['age_from']		= $row['Age'];
                                $return['data']['user_name']		= $row['vFirstName']." ".$row['vMiddleName']." ".$row['vLastName'];
                                $return['data']['user_ip']		= $_SERVER['REMOTE_ADDR'];
                                $return['data']['vSG']                  = $arr['sex'];
                                $return['data']['vSAF']                 = $arr['agefrom'];
                                $return['data']['vSAT']                 = $arr['ageto'];
                                if($row['vStatus']=='ANNN' || $row['vStatus'] == 'ENNN'){
                                if(!empty($arr['device']) && !empty($arr['deviceId'])){
                                    $this->deviceLoggedin($row['nUser_Id'],$arr['device'],$arr['deviceId']);
                                }
                                $this->loggedin($row['nUser_Id']);
                                $this->set_user_ip($row['nUser_Id'], $_SERVER['REMOTE_ADDR']);                                        
                                $return['status'] = 1;
                                }elseif (substr($row['vStatus'], 0, 1) == "N") {
                                                $return['status'] = 0;
                                                $return['error'] = "Your Account is inactive , Please contact Administrator"; 
                                        } else if (substr($row['vStatus'], 0, 1) == "D") {
                                                $return['status'] = 0;
                                                $return['error'] = "Your Account is inactive , Please contact Administrator"; 
                                        } else if (substr($row['vStatus'], 0, 1) == "S") {
                                                 $return['status'] = 0;
                                                 $return['error'] = "Your account is  suspended , please contact the administrator"; 
                                        }
                            } else {
                                $sql	= "SELECT *,TRUNCATE((TO_DAYS(NOW()) - TO_DAYS(dDob))/365, 0) as Age
                                               FROM ".TABLEPREFIX."user 
                                               WHERE vLogin LIKE '".addslashes($user)."' 
                                               AND vPass LIKE '".md5($pass)."'";
                                $res	= @mysql_query($sql, $this->dblink);
                                if (@mysql_num_rows($res) > 0) {
                                        $row	= @mysql_fetch_array($res);
                                       if (substr($row['vStatus'], 0, 1) == "N") {
                                            $msg	.= "You are not allowed to login to the site, please contact the administrator"; 
                                            $return['status'] = 0;
                                            $return['error'] = $msg;                                        
                                        } else if (substr($row['vStatus'], 0, 1) == "D") {
                                                $msg	.= "You are not allowed to login to the site"; 
                                                $return['status'] = 0;
                                                $return['error'] = $msg;
                                        } else if (substr($row['vStatus'], 0, 1) == "S") {
                                                $msg	.= "You are suspended from the site, please contact the administrator";
                                                $return['status'] = 0;
                                                $return['error'] = $msg;
                                        }                                       
                                }
                                else {
                                    $msg	.= "Invalid username/password.";
                                    if (!in_array("user", $arrElements))
                                            $arrElements[]	= "user";
                                    if (!in_array("pass", $arrElements))
                                            $arrElements[]	= "pass";                                    
                                    $return['status'] = 0;
                                    $return['error'] = $msg;

                                }
                        }				
                }
//		if (!empty($arrElements)) {
//			$script	= '<script language="javascript">';
//			foreach ($arrElements as $key=>$value) {
//				$script	.= 'document.frmTells.'.$value.'.className = "textbox txt-bx01";';
//			}
//			$script	.= '</script>';
//		}
//		$msg	.= $script;

		return $return;
	}
	function set_user_ip($id=0, $ip="")
	{
		$sql	= "UPDATE ".TABLEPREFIX."user
		           SET vIP = '{$ip}'
				   WHERE nUser_Id = '{$id}'";
		$res	= @mysql_query($sql, $this->dblink);
	}

	function check_user_ip($id=0, $ip="")
	{
		$now	= date("Y-m-d H:i:s");
		$flag	= false;
		$sql	= "SELECT vIP 
		           FROM ".TABLEPREFIX."user
		           WHERE nUser_Id = '{$id}'";
		$res	= @mysql_query($sql, $this->dblink);
		if (@mysql_num_rows($res) > 0) {
			$row	= @mysql_fetch_array($res);
			if ($row['vIP'] == $ip OR $row['vIP'] == "") {
				$flag	= true;
		    }
		}
		return $flag;
	}

	function loggedin($id=0)
	{
		$date	= date("Y-m-d");
		$now	= date("Y-m-d H:i:s");
                
		$sql	= "UPDATE ".TABLEPREFIX."user 
				   SET dLast_Login = '{$date}',
				       dLast_Login_Time = '{$now}',
				       vOnline = 'Online'
				   WHERE nUser_Id = '{$id}'";
		$res	= @mysql_query($sql, $this->dblink);
	}
        
        function deviceLoggedin($id=0,$device,$deviceId)
	{
		$date	= date("Y-m-d");
		$now	= date("Y-m-d H:i:s");                
		$sql	= "UPDATE ".TABLEPREFIX."user 
				   SET dLast_Login = '{$date}',
				       dLast_Login_Time = '{$now}'
				       vOnline = 'Online'
				   WHERE nUser_Id = '{$id}'";                                   
		$res	= @mysql_query($sql, $this->dblink);
                
                $delsql = "DELETE FROM ".TABLEPREFIX."user_devices WHERE device = '$device' AND device_id = '$deviceId'";
                 mysql_query($delsql, $this->dblink);
                 
                if(!$this->checkDeviceExist($id,$device,$deviceId))
                {
                    $delsql = "DELETE FROM ".TABLEPREFIX."user_devices WHERE device = '$device' AND device_id = '$deviceId'";
                    mysql_query($delsql, $this->dblink);
                    
                    $sql	= "INSERT INTO ".TABLEPREFIX."user_devices(user_id,device,device_id) VALUES ('{$id}', '{$device}', '{$deviceId}')";
                    $res	= @mysql_query($sql, $this->dblink);
                }
                
	}

	function loggedin_track($id=0)
	{
		$date	= date("Y-m-d");
		$now	= date("Y-m-d H:i:s");

		$sql	= "UPDATE ".TABLEPREFIX."user 
				   SET dLast_Login = '{$date}',
				       dLast_Login_Time = '{$now}'
				   WHERE nUser_Id = '{$id}'";
		$res	= @mysql_query($sql, $this->dblink);
	}

	function forgot_password($arr=array())
	{
		$message	= "";
		$script		= "";
		$mail		= "";
		$flag		= true;
		$arrElements= array();
		$vLogin		= isset($arr['vLogin'])	?	stripslashes(trim($arr['vLogin']))	:	"";
		$dDob		= isset($arr['dDob'])	?	stripslashes(trim($arr['dDob']))	:	"";

		if ($vLogin == "")
			$message	.= "Please enter your username.<br>";
                if ($vLogin != "")
                        {
                
		if (!$this->check_username($vLogin))
                        {
//			$message	.= "Only following characters allowed in username ([a-z][A-Z][0-9].-_).<br>";
                         $message	.= "Please enter a valid username.<br>";
                        }

                        }
		if ($message <> "")
			$arrElements[]	= "vLogin";
		if (!$this->check_date($dDob)) {
			$message	.= "Please enter a valid date of birth.<br>";
			$arrElements[]	= "dDob";
		}

		if ($message == "") 
		{
			$arrDob=explode("/",$dDob);
			list($month,$date,$year)=$arrDob;
			$dDob=$year."-".$month."-".$date;

			$sql	= "SELECT * FROM ".TABLEPREFIX."user
					   WHERE vLogin = '".addslashes($vLogin)."'
					   AND dDob = '".addslashes($dDob)."'";
			$res	= @mysql_query($sql, $this->dblink);
			if (@mysql_num_rows($res) > 0) {
				$row	= @mysql_fetch_array($res);
				$newpassword	= $this->generate_password();
				$message		= $this->change_password($row['nUser_Id'], $newpassword);

				if ($message == "") {
					require_once "settings.class.php";
//					$site_name	= settings::getone('sitename');
//					$site_url	= settings::getone('site_normal_url');
//					$admin_mail	= settings::getone('adminmail');
//					$site_logo	= settings::getone('sitelogo');
//					$site_valid_day	=  settings::getone('ValidityDayMembership');
                                        $settingsObj = new settings();
					$site_name	= $settingsObj->getone('sitename');
					$site_url	= $settingsObj->getone('site_normal_url');
					$admin_mail	= $settingsObj->getone('adminmail');
					$site_logo	= $settingsObj->getone('sitelogo');
					$site_valid_day	=  $settingsObj->getone('ValidityDayMembership');
					//checking site logo start
					if(trim($site_logo)!='')
					{
						switch($site_logo)
						{
							case "logo_default.gif":
								$site_top='24';
							break;
	
							default:
								$site_top='3';
							break;
						}//end switch
					}//end if
					else
					{
						$site_top='24';
						$site_logo=$site_name;
					}//end else
					//checking site logo ends

					$mail	= "Hi ".$row['vLogin'].","."\n\n";
					$mail	.= "Your password has been changed as per your request and your new password is ".$newpassword."\n\n";
					$mail	.= "By"."\n".$site_name." Team";
/*
					$flag	= $this->send_mail($row['vLogin']."<".$row['vEmail'].">", $mail, "Forgot Password", $objSettings->adminmail, $objSettings->sitename." Team");
*/
					$from		= $admin_mail;
					$to			= $row['vEmail'];
					$toname		= $row['vLogin'];
					$fromname	= $site_name." Team";
					$subject	= 'Forgot Password';
					$htmlbody	= '';

					$basepath	= BASE_PATH;
					$mail_title	= '';
					$send_date	= date('F j, Y');
					$content	= "<h2 style='font-size: 18px;'>Dear member ".$row['vLogin']." </h2>
									<p>Your password has been changed as per your request 
									and your new password is ".$newpassword.".</p>
									<p>By Yours <br />".$site_name." Team</p>";
					$arrSearch	= array("{SITE_NAME}", "{SITE_URL}", "{MAIL_TITLE}",
										"{SEND_DATE}", "{EMAIL_CONTENT}","{SITE_LOGO}","{SITE_TOP}","{SITE_VALID-DAY}");
					$arrReplace	= array($site_name, $site_url, $mail_title, $send_date, $content,$site_logo,$site_top,$site_valid_day);
					$htmlbody	= $this->html_mail($basepath, $arrSearch, $arrReplace);

					$textbody	= $mail;
					$flag		= $this->send_mail_perfect($from, $to, $subject, $fromname, $toname, $textbody, $htmlbody);
					unset($objSettings);

					if (!$flag)
						$message	.= "Your password has changed to <b>".$newpassword."</b><br>";
					else
						$message	.= "Your password has changed, please check your mail for more details.<br>";
				}
			} else {
				$message	.= "Either username or date of birth is incorrect.<br>";
			}
		} else {
			if (!empty($arrElements)) {
				$script	= '<script language="javascript">';
				foreach ($arrElements as $key=>$value) {
					$script	.= 'document.frmTellf.'.$value.'.className = "textbox txt-bx01";';
				}
				$script	.= '</script>';
			}
		}
		$message	.= $script;
		return $message;
	}

        function forgot_password_api($arr=array())
	{
		$message	= "";
		$script		= "";
		$mail		= "";
		$flag		= true;
                $return = array();
		$arrElements= array();
		$vLogin		= isset($arr['vLogin'])	?	stripslashes(trim($arr['vLogin']))	:	"";
		$dDob		= isset($arr['dDob'])	?	stripslashes(trim($arr['dDob']))	:	"";

		if ($vLogin == ""){
			$message	.= "Please enter your username";
                        $return['status'] = 0;
                        $return['error'] = $message;
                        }
                if ($vLogin != "")
                        {
                
		if (!$this->check_username($vLogin))
                        {
//			$message	.= "Only following characters allowed in username ([a-z][A-Z][0-9].-_).<br>";
                         $message	.= "Please enter a valid username";
                         $return['status'] = 0;
                        $return['error'] = $message;
                        }

                        }
		if ($message <> "")
			$arrElements[]	= "vLogin";
		if (!$this->check_date($dDob)) {
			$message	.= "Please enter a valid date of birth";
			$arrElements[]	= "dDob";
                        
                        $return['status'] = 0;
                        $return['error'] = $message;
		}

		if ($message == "") 
		{
			$arrDob=explode("/",$dDob);
			list($month,$date,$year)=$arrDob;
			$dDob=$year."-".$month."-".$date;

			$sql	= "SELECT * FROM ".TABLEPREFIX."user
					   WHERE vLogin = '".addslashes($vLogin)."'
					   AND dDob = '".addslashes($dDob)."'";
			$res	= @mysql_query($sql, $this->dblink);
			if (@mysql_num_rows($res) > 0) {
				$row	= @mysql_fetch_array($res);
				$newpassword	= $this->generate_password();
				$message		= $this->change_password($row['nUser_Id'], $newpassword);

				if ($message == "") {
					require_once "settings.class.php";
//					$site_name	= settings::getone('sitename');
//					$site_url	= settings::getone('site_normal_url');
//					$admin_mail	= settings::getone('adminmail');
//					$site_logo	= settings::getone('sitelogo');
//					$site_valid_day	=  settings::getone('ValidityDayMembership');
                                        $settingsObj = new settings();
					$site_name	= $settingsObj->getone('sitename');
					$site_url	= $settingsObj->getone('site_normal_url');
					$admin_mail	= $settingsObj->getone('adminmail');
					$site_logo	= $settingsObj->getone('sitelogo');
					$site_valid_day	= $settingsObj->getone('ValidityDayMembership');
					//checking site logo start
					if(trim($site_logo)!='')
					{
						switch($site_logo)
						{
							case "logo_default.gif":
								$site_top='24';
							break;
	
							default:
								$site_top='3';
							break;
						}//end switch
					}//end if
					else
					{
						$site_top='24';
						$site_logo=$site_name;
					}//end else
					//checking site logo ends

					$mail	= "Hi ".$row['vLogin'].","."\n\n";
					$mail	.= "Your password has been changed as per your request and your new password is ".$newpassword."\n\n";
					$mail	.= "By"."\n".$site_name." Team";
/*
					$flag	= $this->send_mail($row['vLogin']."<".$row['vEmail'].">", $mail, "Forgot Password", $objSettings->adminmail, $objSettings->sitename." Team");
*/
					$from		= $admin_mail;
					$to			= $row['vEmail'];
					$toname		= $row['vLogin'];
					$fromname	= $site_name." Team";
					$subject	= 'Forgot Password';
					$htmlbody	= '';

					$basepath	= BASE_PATH;
					$mail_title	= '';
					$send_date	= date('F j, Y');
					$content	= "<h2 style='font-size: 18px;'>Dear member ".$row['vLogin']." </h2>
									<p>Your password has been changed as per your request 
									and your new password is ".$newpassword.".</p>
									<p>By Yours <br />".$site_name." Team</p>";
					$arrSearch	= array("{SITE_NAME}", "{SITE_URL}", "{MAIL_TITLE}",
										"{SEND_DATE}", "{EMAIL_CONTENT}","{SITE_LOGO}","{SITE_TOP}","{SITE_VALID-DAY}");
					$arrReplace	= array($site_name, $site_url, $mail_title, $send_date, $content,$site_logo,$site_top,$site_valid_day);
					$htmlbody	= $this->html_mail($basepath, $arrSearch, $arrReplace);

					$textbody	= $mail;
					$flag		= $this->send_mail_perfect($from, $to, $subject, $fromname, $toname, $textbody, $htmlbody);
					unset($objSettings);

					if (!$flag){
						$message	.= "Your password has changed to ".$newpassword."";
                                                $return['status'] = 1;
                                                $return['message'] = $message;
                                        }else{
						$message	.= "Your password has changed, please check your mail for more details";
                                                $return['status'] = 1;
                                                $return['message'] = $message;
                                        }
                                        
                                        }
			} else {
				$message	.= "Either username or date of birth is incorrect";
                                $return['status'] = 0;
                                $return['error'] = $message;
			}
		} else {
			if (!empty($arrElements)) {
//				$script	= '<script language="javascript">';
//				foreach ($arrElements as $key=>$value) {
//					$script	.= 'document.frmTellf.'.$value.'.className = "textbox txt-bx01";';
//				}
//				$script	.= '</script>';
			}
		}
		
		return $return;
	}
        
        
        
	function change_password($id=0, $pass="")
	{
		$message	= "";
		$sql		= "UPDATE ".TABLEPREFIX."user 
				       SET vPass = '".md5(addslashes($pass))."'
					   WHERE nUser_Id = '{$id}'";
		$res		= @mysql_query($sql, $this->dblink);
		if (!$res)
			$message	= "Sorry, unbale to change your password, try after some time.<br>";
		return $message;
	}
        
        function change_password_api($userId, $oldPassword,$newPassword)
	{
            $sql	= "SELECT * FROM ".TABLEPREFIX."user
					   WHERE nUser_Id = '".$userId."'
					   AND vPass = '".md5($oldPassword)."'";
            $res	= @mysql_query($sql, $this->dblink);
            if (@mysql_num_rows($res) > 0) {
                $sql	= "UPDATE ".TABLEPREFIX."user 
                                   SET vPass = '".md5($newPassword)."'
                                       WHERE nUser_Id = '{$userId}'";
                return @mysql_query($sql, $this->dblink);
            }
            else return "invalid";
	}

	function members_who_me_hot($id=0, $count=0)
	{
		$array	= array();
		$sql	= "SELECT H.*,U.nUser_Id, U.vLogin, U.vGender, U.vFirstName, P.nPhoto_Id, 
						  U.vTitle, U.vCountry, U.vState, U.vCity, U.vCounty, U.tAbout_Me, U.vProfession, 
						  TRUNCATE((TO_DAYS(NOW()) - TO_DAYS(U.dDob))/365, 0) as vAge,
						  DATE_FORMAT(U.dLast_Login, '%Y-%m-%d') as dLLogin, U.nHeight
				   FROM ".TABLEPREFIX."hot as H JOIN ".TABLEPREFIX."user as U
		           ON U.nUser_Id = H.nUser_Id AND H.nUser_Id_Hot = '{$id}' AND (U.vStatus LIKE 'A%' OR U.vStatus LIKE 'E%')
				   LEFT JOIN ".TABLEPREFIX."photos as P ON U.nUser_Id = P.nUser_Id
				   GROUP BY U.nUser_Id, H.nHot_Id
				   ORDER BY H.dDate";
		if ($count > 0)
			$sql	.= " LIMIT 0, ".$count;
		$res	= @mysql_query($sql, $this->dblink);
		if (@mysql_num_rows($res) > 0) {
			while($row=@mysql_fetch_array($res)) {
				$array[]	= $row;
			}
		}
		@mysql_free_result($res);
		return $array;
	}

	function members_who_me_favourite($id=0, $count=0)
	{
		$array	= array();
		$sql	= "SELECT F.*, U.nUser_Id, U.vLogin, U.vGender, U.vFirstName, P.nPhoto_Id, 
						  U.vTitle, U.vCountry, U.vState, U.vCity, U.vCounty, U.tAbout_Me, U.vProfession, 
						  TRUNCATE((TO_DAYS(NOW()) - TO_DAYS(U.dDob))/365, 0) as vAge,
						  DATE_FORMAT(U.dLast_Login, '%Y-%m-%d') as dLLogin, U.nHeight
				   FROM ".TABLEPREFIX."favorite as F JOIN ".TABLEPREFIX."user as U
		           ON U.nUser_Id = F.nUser_Id AND F.nUser_Id_Favorite = '{$id}' AND U.vStatus LIKE 'A%' 
				   LEFT JOIN ".TABLEPREFIX."photos as P ON U.nUser_Id = P.nUser_Id
				   GROUP BY U.nUser_Id, F.nFavorite_Id
				   ORDER BY F.dDate";
		if ($count > 0)
			$sql	.= " LIMIT 0, ".$count;
		$res	= @mysql_query($sql, $this->dblink);
		if (@mysql_num_rows($res) > 0) {
			while($row=@mysql_fetch_array($res)) {
				$array[]	= $row;
			}
		}
		@mysql_free_result($res);
		return $array;
	}

	function my_hots($id=0, $count=0)
	{
		$array	= array();
		$sql	= "SELECT H.*,U.nUser_Id, U.vLogin, U.vGender, U.vFirstName, P.nPhoto_Id, 
						  U.vTitle, U.vCountry, U.vState, U.vCity, U.vCounty, U.tAbout_Me, U.vProfession, 
						  TRUNCATE((TO_DAYS(NOW()) - TO_DAYS(U.dDob))/365, 0) as vAge,
						  DATE_FORMAT(U.dLast_Login, '%Y-%m-%d') as dLLogin, U.nHeight
				   FROM ".TABLEPREFIX."hot as H JOIN ".TABLEPREFIX."user as U
		           ON U.nUser_Id = H.nUser_Id_Hot AND H.nUser_Id = '{$id}' AND (U.vStatus LIKE 'A%' OR U.vStatus LIKE 'E%')
				   LEFT JOIN ".TABLEPREFIX."photos as P ON U.nUser_Id = P.nUser_Id
				   GROUP BY U.nUser_Id, H.nHot_Id
				   ORDER BY H.dDate";
		if ($count > 0)
			$sql	.= " LIMIT 0, ".$count;
		$res	= @mysql_query($sql, $this->dblink);
		if (@mysql_num_rows($res) > 0) {
			while($row=@mysql_fetch_array($res)) {
				$array[]	= $row;
			}
		}
		@mysql_free_result($res);
		return $array;
	}
        
        
        function my_hots_api($id=0, $count=0)
	{
		$array	= array();
		$sql	= "SELECT H.*,U.nUser_Id, U.vLogin, U.vGender, U.vFirstName, P.nPhoto_Id, 
						  U.vTitle, U.vCountry, U.vState, U.vCity, U.vCounty, U.tAbout_Me, U.vProfession, 
						  TRUNCATE((TO_DAYS(NOW()) - TO_DAYS(U.dDob))/365, 0) as vAge,
						  DATE_FORMAT(U.dLast_Login, '%Y-%m-%d') as dLLogin, U.nHeight
				   FROM ".TABLEPREFIX."hot as H JOIN ".TABLEPREFIX."user as U
		           ON U.nUser_Id = H.nUser_Id_Hot AND H.nUser_Id = '{$id}' AND U.vStatus LIKE 'A%'
				   LEFT JOIN ".TABLEPREFIX."photos as P ON U.nUser_Id = P.nUser_Id
				   GROUP BY U.nUser_Id, H.nHot_Id
				   ORDER BY H.dDate";
		if ($count > 0)
			$sql	.= " LIMIT 0, ".$count;
		$res	= @mysql_query($sql);
		if (@mysql_num_rows($res) > 0) {
			while($row=@mysql_fetch_assoc($res)) {
                            /* Start- Section to get the photos of the hot users*/
                           $photo_sql	= "SELECT vUrl FROM ".TABLEPREFIX."photos WHERE nUser_Id = '{$row['nUser_Id_Hot']}'";     
                           $photo_res	= @mysql_query($photo_sql, $this->dblink);  
                           $photo_array = array();
                           if (@mysql_num_rows($photo_res) > 0) {
                               while($photo_row=@mysql_fetch_assoc($photo_res)) {
                                $photo_array[] = $photo_row['vUrl'];
                               }
                           }
                           @mysql_free_result($photo_res);
                           $row['photos'] = $photo_array;
                            /* end */
                           $array[]	= $row;
			}
		}
		@mysql_free_result($res);
		return $array;
	}
        
        function my_shortlists($id=0, $count=0)
	{
		$array	= array();
		$sql	= "SELECT H.*,U.nUser_Id, U.vLogin, U.vGender, U.vFirstName, P.nPhoto_Id, 
						  U.vTitle, U.vCountry, U.vState, U.vCity, U.vCounty, U.tAbout_Me, U.vProfession, 
						  TRUNCATE((TO_DAYS(NOW()) - TO_DAYS(U.dDob))/365, 0) as vAge,
						  DATE_FORMAT(U.dLast_Login, '%m-%d-%Y') as dLLogin, U.nHeight
				   FROM ".TABLEPREFIX."shortlists as H JOIN ".TABLEPREFIX."user as U
		           ON U.nUser_Id = H.nUser_Id_Shortlisted 	 AND H.nUser_Id = '{$id}' AND U.vStatus LIKE 'A%'
				   LEFT JOIN ".TABLEPREFIX."photos as P ON U.nUser_Id = P.nUser_Id
				   GROUP BY U.nUser_Id, H.nShortlist_Id
				   ORDER BY H.dDate";
		if ($count > 0)
			$sql	.= " LIMIT 0, ".$count;
		$res	= @mysql_query($sql, $this->dblink);
		if (@mysql_num_rows($res) > 0) {
			while($row=@mysql_fetch_array($res)) {
				$array[]	= $row;
			}
		}
		@mysql_free_result($res);
		return $array;
	}

	function my_favourites ($id=0, $count=0)
	{
		$array	= array();
		$sql	= "SELECT F.*, U.nUser_Id, U.vLogin, U.vGender, U.vFirstName, P.nPhoto_Id, 
						  U.vTitle, U.vCountry, U.vState, U.vCity, U.vCounty, U.tAbout_Me, U.vProfession, 
						  TRUNCATE((TO_DAYS(NOW()) - TO_DAYS(U.dDob))/365, 0) as vAge,
						  DATE_FORMAT(U.dLast_Login, '%Y-%m-%d') as dLLogin, U.nHeight
				   FROM ".TABLEPREFIX."favorite as F JOIN ".TABLEPREFIX."user as U
		           ON U.nUser_Id = F.nUser_Id_Favorite AND F.nUser_Id = '{$id}'  AND (U.vStatus LIKE 'A%' OR U.vStatus LIKE 'E%')
				   LEFT JOIN ".TABLEPREFIX."photos as P ON U.nUser_Id = P.nUser_Id
				   GROUP BY U.nUser_Id, F.nFavorite_Id
				   ORDER BY F.dDate";
		if ($count > 0)
			$sql	.= " LIMIT 0, ".$count;
		$res	= @mysql_query($sql, $this->dblink);
		if (@mysql_num_rows($res) > 0) {
			while($row=@mysql_fetch_array($res)) {
				$array[]	= $row;
			}
		}
		@mysql_free_result($res);
		return $array;
	}

	function delete_favourites($arr=array())
	{
		$message	= "";
		$ids		= isset($arr['ids'])	?	$arr['ids']	:	array();
		if (empty($ids))
			$message	.= "Please select user(s) which you need to delete.<br>";
		if ($message == "") {
			$idstring	= implode("','", $ids);
			$sql		= "DELETE FROM ".TABLEPREFIX."favorite
						   WHERE nFavorite_Id IN ('{$idstring}')";
			$res		= @mysql_query($sql, $this->dblink);
			if (!$res)
				$message	.= "Unable to delete favourite(s), please try later.<br>";
			else
				$message	.= "<font color='green'>Selected favorite(s) deleted successfully.</font><br>";
		}
		return $message;
	}

	function delete_hots($arr=array())
	{
		$message	= "";
		$ids		= isset($arr['ids'])	?	$arr['ids']	:	array();
		if (empty($ids))
			$message	.= "Please select user(s) which you need to delete.<br>";
		if ($message == "") {
			$idstring	= implode("','", $ids);
			$sql		= "DELETE FROM ".TABLEPREFIX."hot
						   WHERE nHot_Id IN ('{$idstring}')";
                                                   
                                                 
			$res		= @mysql_query($sql, $this->dblink);
			if (!$res)
				$message	.= "Unable to delete hot(s), please try later.<br>";
			else
				$message	.= "<font color='green'>Selected hot(s) deleted successfully.</font><br>";
		}
		return $message;
	}
        function delete_shortlist($arr=array())
	{
		$message	= "";
		$ids		= isset($arr['ids'])	?	$arr['ids']	:	array();
		if (empty($ids))
			$message	.= "Please select user(s) which you need to delete.<br>";
		if ($message == "") {
			$idstring	= implode("','", $ids);
			$sql		= "DELETE FROM ".TABLEPREFIX."shortlists 
						   WHERE nShortlist_Id IN ('{$idstring}')";
			$res		= @mysql_query($sql, $this->dblink);
			if (!$res)
				$message	.= "Unable to delete user(s) from shortlist, please try later.<br>";
			else
				$message	.= "Selected users(s) deleted from shortlist.<br>";
		}
		return $message;
	}

	function get_message_count($type="%", $id=0, $flag=true)
	{
		$count	= 0;
		if ($flag)
			$sql	= "SELECT COUNT(*) as no
		               FROM ".TABLEPREFIX."message as H  JOIN ".TABLEPREFIX."user as U 
					   ON U.nUser_Id = H.nUser_Id_From AND (U.vStatus LIKE 'A%' OR U.vStatus LIKE 'E%')
					   AND H.nUser_Id_To = '{$id}' AND H.vStatus LIKE '{$type}'";
		else
			$sql	= "SELECT COUNT(*) as no
		               FROM ".TABLEPREFIX."message as H  JOIN ".TABLEPREFIX."user as U
					   ON U.nUser_Id = H.nUser_Id_To  AND (U.vStatus LIKE 'A%' OR U.vStatus LIKE 'E%')
					   AND H.nUser_Id_From = '{$id}' AND H.vStatus LIKE '{$type}'";
		$res		= @mysql_query($sql, $this->dblink);
		if (@mysql_num_rows($res) > 0) {
			$row	= @mysql_fetch_array($res);
			$count	= $row['no'];
		}
		return $count;
	}

	function get_messages($type="%", $id=0, $flag=true)
	{
		$array	= array();
		if ($flag)
			$sql	= "SELECT H.*, DATE_FORMAT(H.dDate, '%m/%d/%Y') as dDay,
							  U.nUser_Id, U.vLogin, U.vGender, U.vFirstName, P.nPhoto_Id, 
							  U.vTitle as vTitleU, U.vCountry, U.vState, U.vCity, U.vCounty, 
							  U.tAbout_Me, U.vProfession, U.nHeight, 
							  TRUNCATE((TO_DAYS(NOW()) - TO_DAYS(U.dDob))/365, 0) as vAge,
							  DATE_FORMAT(U.dLast_Login_Time, '%Y-%m-%d %H:%i:%s') as dLLogin
					FROM ".TABLEPREFIX."message as H JOIN ".TABLEPREFIX."user as U
					ON U.nUser_Id = H.nUser_Id_From AND (U.vStatus LIKE 'A%' OR U.vStatus LIKE 'E%')
					AND H.nUser_Id_To = '{$id}' AND H.vStatus LIKE '{$type}'
					LEFT JOIN ".TABLEPREFIX."photos as P ON U.nUser_Id = P.nUser_Id
					GROUP BY U.nUser_Id, H.nMessage_Id
					ORDER BY H.dDate DESC";
		else
			$sql	= "SELECT H.*, DATE_FORMAT(H.dDate, '%m/%d/%Y') as dDay,
							  U.nUser_Id, U.vLogin, U.vGender, U.vFirstName, P.nPhoto_Id, 
							  U.vTitle as vTitleU, U.vCountry, U.vState, U.vCity,  U.vCounty,
							  U.tAbout_Me, U.vProfession, U.nHeight, 
							  TRUNCATE((TO_DAYS(NOW()) - TO_DAYS(U.dDob))/365, 0) as vAge,
							  DATE_FORMAT(U.dLast_Login_Time, '%Y-%m-%d %H:%i:%s') as dLLogin
					FROM ".TABLEPREFIX."message as H JOIN ".TABLEPREFIX."user as U
					ON U.nUser_Id = H.nUser_Id_To  AND (U.vStatus LIKE 'A%' OR U.vStatus LIKE 'E%')
					AND H.nUser_Id_From = '{$id}' AND H.vStatus LIKE '{$type}'
					LEFT JOIN ".TABLEPREFIX."photos as P ON U.nUser_Id = P.nUser_Id
					GROUP BY U.nUser_Id, H.nMessage_Id
					ORDER BY H.dDate DESC";
/*
		if ($flag)
			$sql	= "SELECT M.*, DATE_FORMAT(M.dDate, '%Y-%m-%d') as dDate,
						      U.vLogin as vLogin_From
		               FROM ".TABLEPREFIX."message as M JOIN ".TABLEPREFIX."user as U
					   ON M.nUser_Id_From = U.nUser_Id
					   WHERE M.nUser_Id_To = '{$id}' AND M.vStatus LIKE '{$type}'";
		else
			$sql	= "SELECT M.*, DATE_FORMAT(M.dDate, '%Y-%m-%d') as dDate,
		                      U.vLogin as vLogin_To
		               FROM  ".TABLEPREFIX."message as M JOIN ".TABLEPREFIX."user as U
					   ON M.nUser_Id_To = U.nUser_Id
					   WHERE M.nUser_Id_From = '{$id}' AND M.vStatus LIKE '{$type}'";
*/
		
                $res		= @mysql_query($sql, $this->dblink);
		if (@mysql_num_rows($res) > 0) {
			while($row	= @mysql_fetch_array($res)) {
				$array[]	= $row;
			}
		}
		return $array;
	}
        function get_messages_api($type="%", $id=0, $flag=true,$page = 1)
	{
		$array	= array();
                
                $pagecount = 10;
                
                $startpage = ($page-1)*$pagecount;
		if ($flag)
			$sql	= "SELECT H.*, DATE_FORMAT(H.dDate, '%m/%d/%Y') as dDay,
							  U.nUser_Id, U.vLogin, U.vGender, U.vFirstName, P.nPhoto_Id, 
							  U.vTitle as vTitleU, U.vCountry, U.vState, U.vCity, U.vCounty, 
							  U.tAbout_Me, U.vProfession, U.nHeight, 
							  TRUNCATE((TO_DAYS(NOW()) - TO_DAYS(U.dDob))/365, 0) as vAge,
							  DATE_FORMAT(U.dLast_Login_Time, '%Y-%m-%d %H:%i:%s') as dLLogin
					FROM ".TABLEPREFIX."message as H JOIN ".TABLEPREFIX."user as U
					ON U.nUser_Id = H.nUser_Id_From AND (U.vStatus LIKE 'A%' OR U.vStatus LIKE 'E%')
					AND H.nUser_Id_To = '{$id}' AND H.vStatus LIKE '{$type}'
					LEFT JOIN ".TABLEPREFIX."photos as P ON U.nUser_Id = P.nUser_Id
					GROUP BY U.nUser_Id, H.nMessage_Id
					ORDER BY H.dDate DESC LIMIT $startpage,$pagecount";
		else
			$sql	= "SELECT H.*, DATE_FORMAT(H.dDate, '%m/%d/%Y') as dDay,
							  U.nUser_Id, U.vLogin, U.vGender, U.vFirstName, P.nPhoto_Id, 
							  U.vTitle as vTitleU, U.vCountry, U.vState, U.vCity,  U.vCounty,
							  U.tAbout_Me, U.vProfession, U.nHeight, 
							  TRUNCATE((TO_DAYS(NOW()) - TO_DAYS(U.dDob))/365, 0) as vAge,
							  DATE_FORMAT(U.dLast_Login_Time, '%Y-%m-%d %H:%i:%s') as dLLogin
					FROM ".TABLEPREFIX."message as H JOIN ".TABLEPREFIX."user as U
					ON U.nUser_Id = H.nUser_Id_To  AND (U.vStatus LIKE 'A%' OR U.vStatus LIKE 'E%')
					AND H.nUser_Id_From = '{$id}' AND H.vStatus LIKE '{$type}'
					LEFT JOIN ".TABLEPREFIX."photos as P ON U.nUser_Id = P.nUser_Id
					GROUP BY U.nUser_Id, H.nMessage_Id
					ORDER BY H.dDate DESC LIMIT $startpage,$pagecount";
/*
		if ($flag)
			$sql	= "SELECT M.*, DATE_FORMAT(M.dDate, '%Y-%m-%d') as dDate,
						      U.vLogin as vLogin_From
		               FROM ".TABLEPREFIX."message as M JOIN ".TABLEPREFIX."user as U
					   ON M.nUser_Id_From = U.nUser_Id
					   WHERE M.nUser_Id_To = '{$id}' AND M.vStatus LIKE '{$type}'";
		else
			$sql	= "SELECT M.*, DATE_FORMAT(M.dDate, '%Y-%m-%d') as dDate,
		                      U.vLogin as vLogin_To
		               FROM  ".TABLEPREFIX."message as M JOIN ".TABLEPREFIX."user as U
					   ON M.nUser_Id_To = U.nUser_Id
					   WHERE M.nUser_Id_From = '{$id}' AND M.vStatus LIKE '{$type}'";
*/
		$res		= @mysql_query($sql, $this->dblink);
		if (@mysql_num_rows($res) > 0) {
			while($row	= @mysql_fetch_assoc($res)) {
				$array[]	= $row;
			}
		}
		return $array;
	}
	function get_message($id=0, $uid=0, $flag=true)
	{
		$array	= array();
		if ($flag)
			$sql	= "SELECT M.*, DATE_FORMAT(M.dDate, '%Y-%m-%d') as dDate,
						      U.vLogin as vLogin_From
		               FROM ".TABLEPREFIX."message as M JOIN ".TABLEPREFIX."user as U
					   ON M.nUser_Id_From = U.nUser_Id
					   WHERE M.nUser_Id_To = '{$uid}' AND M.nMessage_Id = '{$id}'";
		else
			$sql	= "SELECT M.*, DATE_FORMAT(M.dDate, '%Y-%m-%d') as dDate,
		                      U.vLogin as vLogin_To
		               FROM  ".TABLEPREFIX."message as M JOIN ".TABLEPREFIX."user as U
					   ON M.nUser_Id_To = U.nUser_Id
					   WHERE M.nUser_Id_From = '{$uid}' AND M.nMessage_Id = '{$id}'";
		$res		= @mysql_query($sql, $this->dblink);
		if (@mysql_num_rows($res) > 0) {
			$array	= @mysql_fetch_array($res);
		}
		return $array;
	}

	function mark_read_message($id=0)
	{
		$sql	= "UPDATE ".TABLEPREFIX."message
				   SET vStatus = 'RN'
				   WHERE nMessage_Id = '{$id}'"; 
		$res	= @mysql_query($sql, $this->dblink);
	}

	function mark_as_read_message($arr=array())
	{ 
		$message	= "";
		$ids		= isset($arr['ids'])	?	$arr['ids']	:	array();
		if (empty($ids))
			$message	=  "Please select the messages which you need to mark as read.<br>";
		if ($message == "") {
			$idstring	= implode("','", $ids);

			$sql		= "UPDATE ".TABLEPREFIX."message
			               SET vStatus = 'RN'
						   WHERE nMessage_Id IN ('$idstring')";
			$res		= @mysql_query($sql, $this->dblink);
			if (!$res)
				$message	= "Unable to mark the message(s) as read , please try later.<br>";
			else
				$message	= "<font color='green'>Selected message(s) have been successfully marked as read.</font><br>";
		}
		return $message;

	}

	function get_intrest_count($type="%", $id=0, $flag=true)
	{
		$array	= array();
		if ($flag)
			$sql	= "SELECT COUNT(*) as no
		               FROM ".TABLEPREFIX."interests as H JOIN ".TABLEPREFIX."user as U
					   ON U.nUser_Id = H.nUser_Id_From  AND (U.vStatus LIKE 'A%' OR U.vStatus LIKE 'E%')
					   AND H.nUser_Id_To = '{$id}' AND H.vStatus LIKE '{$type}'";
		else
			$sql	= "SELECT COUNT(*) as no
		               FROM ".TABLEPREFIX."interests as H JOIN ".TABLEPREFIX."user as U
					   ON U.nUser_Id = H.nUser_Id_To  AND (U.vStatus LIKE 'A%' OR U.vStatus LIKE 'E%')
					   AND H.nUser_Id_From = '{$id}' AND H.vStatus LIKE '{$type}'";
		$res		= @mysql_query($sql, $this->dblink);
		if (@mysql_num_rows($res) > 0) {
			$row	= @mysql_fetch_array($res);
			$count	= $row['no'];
		}
		return $count;
	}

	function get_intrests($type="%", $id=0, $flag=true)
	{
		$count	= 0;

		if ($flag)
			 $sql	= "SELECT H.*, DATE_FORMAT(H.dDate, '%m/%d/%Y') as dDay,
							  U.nUser_Id, U.vLogin, U.vGender, U.vFirstName, P.nPhoto_Id, 
							  U.vTitle, U.vCountry, U.vState, U.vCity, U.vCounty,
							  U.tAbout_Me, U.vProfession, U.nHeight, 
							  TRUNCATE((TO_DAYS(NOW()) - TO_DAYS(U.dDob))/365, 0) as vAge,
							  DATE_FORMAT(U.dLast_Login, '%Y-%m-%d') as dLLogin
					FROM ".TABLEPREFIX."interests as H JOIN ".TABLEPREFIX."user as U
					ON U.nUser_Id = H.nUser_Id_From  AND (U.vStatus LIKE 'A%' OR U.vStatus LIKE 'E%')
					AND H.nUser_Id_To = '{$id}' AND H.vStatus LIKE '{$type}'
					LEFT JOIN ".TABLEPREFIX."photos as P ON U.nUser_Id = P.nUser_Id
					GROUP BY U.nUser_Id, H.nInterest_Id
					ORDER BY H.dDate DESC";
		else
			 $sql	= "SELECT H.*, DATE_FORMAT(H.dDate, '%m/%d/%Y') as dDay,
							  U.nUser_Id, U.vLogin, U.vGender, U.vFirstName, P.nPhoto_Id, 
							  U.vTitle, U.vCountry, U.vState, U.vCity, U.vCounty,
							  U.tAbout_Me, U.vProfession, U.nHeight, 
							  TRUNCATE((TO_DAYS(NOW()) - TO_DAYS(U.dDob))/365, 0) as vAge,
							  DATE_FORMAT(U.dLast_Login, '%Y-%m-%d') as dLLogin
					FROM ".TABLEPREFIX."interests as H JOIN ".TABLEPREFIX."user as U
					ON U.nUser_Id = H.nUser_Id_To  AND (U.vStatus LIKE 'A%' OR U.vStatus LIKE 'E%')
					AND H.nUser_Id_From = '{$id}' AND H.vStatus LIKE '{$type}'
					LEFT JOIN ".TABLEPREFIX."photos as P ON U.nUser_Id = P.nUser_Id
					GROUP BY U.nUser_Id, H.nInterest_Id
					ORDER BY H.dDate DESC";
/*		if ($flag)
			$sql	= "SELECT M.*, DATE_FORMAT(M.dDate, '%Y-%m-%d') as dDate,
						      U.vLogin as vLogin_From
		               FROM ".TABLEPREFIX."interests as M JOIN ".TABLEPREFIX."user as U
					   ON M.nUser_Id_From = U.nUser_Id 
					   WHERE M.nUser_Id_To = '{$id}' AND M.vStatus LIKE '{$type}'";
		else
			$sql	= "SELECT M.*, DATE_FORMAT(M.dDate, '%Y-%m-%d') as dDate,
		                      U.vLogin as vLogin_To
		               FROM  ".TABLEPREFIX."interests as M JOIN ".TABLEPREFIX."user as U
					   ON M.nUser_Id_To = U.nUser_Id
					   WHERE M.nUser_Id_From = '{$id}' AND M.vStatus LIKE '{$type}'";*/
		$res		= @mysql_query($sql, $this->dblink);
		if (@mysql_num_rows($res) > 0) {
			while($row	= @mysql_fetch_array($res)) {
				$array[]	= $row;
			}
		}
		return $array;
	}
        
        function get_intrests_api($type="%", $id=0, $flag=true,$page = 1)
	{
		$count	= 0;
                $pagecount = 10;
                
                $startpage = ($page-1)*$pagecount;
		if ($flag)
			 $sql	= "SELECT H.*, DATE_FORMAT(H.dDate, '%m/%d/%Y') as dDay,
							  U.nUser_Id, U.vLogin, U.vGender, U.vFirstName, P.nPhoto_Id, 
							  U.vTitle, U.vCountry, U.vState, U.vCity, U.vCounty,
							  U.tAbout_Me, U.vProfession, U.nHeight, 
							  TRUNCATE((TO_DAYS(NOW()) - TO_DAYS(U.dDob))/365, 0) as vAge,
							  DATE_FORMAT(U.dLast_Login, '%Y-%m-%d') as dLLogin
					FROM ".TABLEPREFIX."interests as H JOIN ".TABLEPREFIX."user as U
					ON U.nUser_Id = H.nUser_Id_From  AND (U.vStatus LIKE 'A%' OR U.vStatus LIKE 'E%')
					AND H.nUser_Id_To = '{$id}' 
					LEFT JOIN ".TABLEPREFIX."photos as P ON U.nUser_Id = P.nUser_Id
					GROUP BY U.nUser_Id, H.nInterest_Id
					ORDER BY H.dDate DESC LIMIT $startpage,$pagecount";
		else
			 $sql	= "SELECT H.*, DATE_FORMAT(H.dDate, '%m/%d/%Y') as dDay,
							  U.nUser_Id, U.vLogin, U.vGender, U.vFirstName, P.nPhoto_Id, 
							  U.vTitle, U.vCountry, U.vState, U.vCity, U.vCounty,
							  U.tAbout_Me, U.vProfession, U.nHeight, 
							  TRUNCATE((TO_DAYS(NOW()) - TO_DAYS(U.dDob))/365, 0) as vAge,
							  DATE_FORMAT(U.dLast_Login, '%Y-%m-%d') as dLLogin
					FROM ".TABLEPREFIX."interests as H JOIN ".TABLEPREFIX."user as U
					ON U.nUser_Id = H.nUser_Id_To  AND (U.vStatus LIKE 'A%' OR U.vStatus LIKE 'E%')
					AND H.nUser_Id_From = '{$id}' AND H.vStatus LIKE '{$type}'
					LEFT JOIN ".TABLEPREFIX."photos as P ON U.nUser_Id = P.nUser_Id
					GROUP BY U.nUser_Id, H.nInterest_Id
					ORDER BY H.dDate DESC LIMIT $startpage,$pagecount";
/*		if ($flag)
			$sql	= "SELECT M.*, DATE_FORMAT(M.dDate, '%Y-%m-%d') as dDate,
						      U.vLogin as vLogin_From
		               FROM ".TABLEPREFIX."interests as M JOIN ".TABLEPREFIX."user as U
					   ON M.nUser_Id_From = U.nUser_Id 
					   WHERE M.nUser_Id_To = '{$id}' AND M.vStatus LIKE '{$type}'";
		else
			$sql	= "SELECT M.*, DATE_FORMAT(M.dDate, '%Y-%m-%d') as dDate,
		                      U.vLogin as vLogin_To
		               FROM  ".TABLEPREFIX."interests as M JOIN ".TABLEPREFIX."user as U
					   ON M.nUser_Id_To = U.nUser_Id
					   WHERE M.nUser_Id_From = '{$id}' AND M.vStatus LIKE '{$type}'";*/
		$res		= @mysql_query($sql, $this->dblink);
		if (@mysql_num_rows($res) > 0) {
			while($row	= @mysql_fetch_array($res)) {
				$array[]	= $row;
			}
		}
		return $array;
	}

	function change_interest_status($arr=array(), $sta="NN")
	{
		$message	= "";
		$ids		= isset($arr['ids'])	?	$arr['ids']	:	array();
		if ($sta == "AN")
			$msg	= "approved";
		else if ($sta == "DN")
			$msg	= "declined";
		if (empty($ids))
			$message	=  "Please select the interests which you need to $msg.<br>";
		if ($message == "") {
			$idstring	= implode("','", $ids);

			$sql		= "UPDATE ".TABLEPREFIX."interests 
			               SET vStatus = '{$sta}'
						   WHERE nInterest_Id IN ('$idstring')";
			$res		= @mysql_query($sql, $this->dblink);
			if (!$res)
				$message	= "Unable to $msg the interests, please try later.<br>";
			else
				$message	= "<font color='green'>Selected interests  $msg  successfully</font><br>";
		}
		return $message;
	}
        
        function change_interest_status_api($interestId, $sta="NN")
	{
            $sql		= "UPDATE ".TABLEPREFIX."interests 
                           SET vStatus = '{$sta}'
                                       WHERE nInterest_Id='$interestId'";
            $res		= @mysql_query($sql, $this->dblink);
            return $res;
		
	}

	function report_abuse($id=0, $aid=0)
	{
		$date	= date("Y-m-d");
		$now	= date("Y-m-d H:i:s");
		$message	= "";
		$sql	= "SELECT * FROM ".TABLEPREFIX."abuse 
				   WHERE nUser_Id_Abused = '{$aid}' AND nUser_Id_Abusee = '{$id}'
				   AND DATE_FORMAT(dDate, '%Y-%m-%d') = '{$date}'";
		$res	= @mysql_query($sql, $this->dblink);
		if (@mysql_num_rows($res) > 0) {
			$message	.= "You have already reported abuse about this profile.<br>";
		} else {
			$sql	= "INSERT INTO ".TABLEPREFIX."abuse(nUser_Id_Abused, nUser_Id_Abusee, dDate)
					   VALUES ('{$aid}', '{$id}', '{$now}')";
			$res	= @mysql_query($sql, $this->dblink);
			if (!$res)
				$message	= "Unable to report abuse.<br>";
			else
				$message	= "<font color='green'>You have successfully reported abuse about this profile.</font><br>";
		}
		return $message;
	}

	function in_interestlist($id=0, $iid=0)
	{
		$flag	= false;
		$sql	= "SELECT * FROM ".TABLEPREFIX."interests
				   WHERE nUser_Id_From = '{$id}' 
				        AND nUser_Id_To = '{$iid}' AND vStatus NOT LIKE 'R%'";
		$res	= @mysql_query($sql, $this->dblink);
		if (@mysql_num_rows($res) > 0) {
			$flag	= true;
		}
		return $flag;

	}

	function add_interest($id=0, $iid=0)
	{
		$message	= "";
		if (!$this->in_interestlist($id, $iid)) {
			$sql		= "INSERT INTO ".TABLEPREFIX."interests (nUser_Id_From,
									   nUser_Id_To, dDate, vStatus)
						   VALUES ('{$id}', '{$iid}', '{$this->now}', 'NN')";
			$res		= @mysql_query($sql, $this->dblink);
			if (!$res) {
				$message	= "Unable to express your interest , please try later.<br>";
			} else {
				$message	= "<font color='green'>You have successfully send the express interest.</font><br>";
				$this->sms_interest_alert($iid, $id);
			}
		} else {
			$message	= "You have already expressed interest to this profile.<br>";
		}
		return $message;
	}
        function add_interest_api($id=0, $iid=0)
	{
		$message	= "";
                
                $retun = array();
            
		if (!$this->in_interestlist($id, $iid)) { 
			$sql		= "INSERT INTO ".TABLEPREFIX."interests (nUser_Id_From,
									   nUser_Id_To, dDate, vStatus)
						   VALUES ('{$id}', '{$iid}', '{$this->now}', 'NN')";
			$res		= @mysql_query($sql, $this->dblink);
			if (!$res) {
				$message	= "Unable to express your interest , please try later";
                                $retun['status'] = 0;
                                $retun['error'] = $message;
			} else {
				$message	= "You have successfully send the express interest";
				$this->sms_interest_alert($iid, $id);
                                $retun['status'] = 1;
                                $retun['message'] = $message;
			}
		} else {
			$message	= "You have already expressed interest to this profile";
                         $retun['status'] = 0;
                         $retun['message'] = $message;
		}
		return $retun;
	}
	function get_username($id=0)
	{
		$login		= "";
		require_once "users.class.php";
		$objUsers	= new users($this->dblink);
		$array		= $objUsers->select($id); 
		if (!empty($array)) {
			$login	= $array['vLogin'];
		}
		unset($objUsers);
		return $login;
	}

	function get_name($id=0)
	{
		$login		= "";
		require_once "users.class.php";
		$objUsers	= new users($this->dblink);
		$array		= $objUsers->select($id);
		if (!empty($array)) {
			$login	= $array['vFirstName'];
		}
		unset($objUsers);
		return $login;
	}

	function get_user_details($id=0)
	{
		$array		= array();
		require_once "users.class.php";
		$objUsers	= new users($this->dblink);
		$array		= $objUsers->select($id);
		unset($objUsers);
		return $array;
	}

	function in_favouritelist($id=0, $fid=0)
	{
		$flag	= false;
		$sql	= "SELECT * FROM ".TABLEPREFIX."favorite
				   WHERE nUser_Id = '{$id}' AND nUser_Id_Favorite = '{$fid}'";
		$res	= @mysql_query($sql, $this->dblink);
		if (@mysql_num_rows($res) > 0) {
			$flag	= true;
		}
		return $flag;
	}

	function add_to_favourites($id=0, $fid=0)
	{
		$message	= "";
		if (!$this->in_favouritelist($id, $fid)) {
			$login		= $this->get_username($fid);
			
			$sql		= "INSERT INTO ".TABLEPREFIX."favorite (nUser_Id,
									   nUser_Id_Favorite, vLogin_Favorite, dDate)
						   VALUES ('{$id}', '{$fid}', '{$login}', '{$this->now}')";
			$res		= @mysql_query($sql, $this->dblink);
			if (!$res) {
				$message	= "Unable to add to favourite list, please try later.<br>";
			} else {
				$message	= "<font color='green'>This profile has been successfully added to your favourites list.</font><br>";
				$this->favourite_alert($id, $fid);
			}
		} else {
			$message	= "Already exists in your favourite list.<br>";
		}
		return $message;
	}

	function in_hotlist($id=0, $fid=0)
	{
		$flag	= false;
		$sql	= "SELECT * FROM ".TABLEPREFIX."hot
				   WHERE nUser_Id = '{$id}' AND nUser_Id_Hot = '{$fid}'";

		$res	= @mysql_query($sql, $this->dblink);
		if (@mysql_num_rows($res) > 0) {
			$flag	= true;
		}
		return $flag;
	}
        function in_shortlist($id=0, $fid=0)
	{
		$flag	= false;
		echo $sql	= "SELECT * FROM ".TABLEPREFIX."shortlists 
				   WHERE nUser_Id = '{$id}' AND nUser_Id_Shortlisted = '{$fid}'";

		$res	= mysql_query($sql, $this->dblink);
		if (@mysql_num_rows($res) > 0) {
			$flag	= true;
		}
//                /exit;
		return $flag;
	}

//	function add_to_shortlist($id=0, $hid=0)
//	{
//		$message	= "";
//		if (!$this->in_shortlist($id, $hid)) {
//			//$login		= $this->get_username($hid);
//			
//			$sql		= "INSERT INTO ".TABLEPREFIX."shortlists (nUser_Id,
//									   nUser_Id_Shortlisted, dDate)
//						   VALUES ('{$id}', '{$hid}',  '{$this->now}')";
//			$res		= @mysql_query($sql, $this->dblink);
//			if (!$res) {
//				$message	= "Unable to add to shortlist, please try later.<br>";
//			} else {
//				$message	= "This profile has been successfully added to your shortlists.<br>";
//				$this->hotlist_alert($id, $hid);
//			}
//		} else {
//			$message	= "Already exists in your shortlists.<br>";
//		}
//		return $message;
//	}
        function add_to_hotlist($id=0, $hid=0)
	{
		$message	= "";
		if (!$this->in_hotlist($id, $hid)) {
			$login		= $this->get_username($hid);
			
			$sql		= "INSERT INTO ".TABLEPREFIX."hot (nUser_Id,
									   nUser_Id_Hot, vLogin_Hot, dDate)
						   VALUES ('{$id}', '{$hid}', '{$login}', '{$this->now}')";
			$res		= @mysql_query($sql, $this->dblink);
			if (!$res) {
				$message	= "Unable to add to hot list, please try later.<br>";
			} else {
				$message	= "<font color='green'>This profile has been successfully added to your hot list.</font><br>";
				$this->hotlist_alert($id, $hid);
			}
		} else {
			$message	= "Already exists in your hot list.<br>";
		}
		return $message;
	}

        function add_to_hotlist_api($id=0, $hid=0)
	{
		$message	= "";                
		if (!$this->in_hotlist($id, $hid)) {
			$login		= $this->get_username($hid);
			
			$sql		= "INSERT INTO ".TABLEPREFIX."hot (nUser_Id,
									   nUser_Id_Hot, vLogin_Hot, dDate)
						   VALUES ('{$id}', '{$hid}', '{$login}', '{$this->now}')";
			$res		= @mysql_query($sql, $this->dblink);
			if (!$res) {
				$message	= "Unable to add to hot list, please try later.<br>";
			} else {				
				$this->hotlist_alert($id, $hid);
			}
		} else {
			$message	= "Already exists in your hot list.<br>";
		}
		return $message;
	}
	function in_friendslist($id=0, $fid=0)
	{
		$flag	= false;
		$sql	= "SELECT * FROM ".TABLEPREFIX."imfriends
				   WHERE nUser_Id = '{$id}' AND nUser_Id_Friend = '{$fid}'
						 AND vStatus NOT LIKE 'R%'";
		$res	= @mysql_query($sql, $this->dblink);
		if (@mysql_num_rows($res) > 0) {
			$flag	= true;
		}
		return $flag;
	}

	function add_to_friendslist($id=0, $fid=0, $flag="NN")
	{
		$message	= "";
		if (!$this->in_friendslist($id, $fid)) {
			$login		= $this->get_username($fid);
			$name		= $this->get_name($fid);
			
			$sql		= "INSERT INTO ".TABLEPREFIX."imfriends (nUser_Id, nUser_Id_Friend,
									   vLogin_Friend, vName_Friend, vStatus)
						   VALUES ('{$id}', '{$fid}', '{$login}', '{$name}', '{$flag}')";
			$res		= @mysql_query($sql, $this->dblink);
			if (!$res)
				$message	= "Unable to add to friends list, please try later.<br>";
			else
				$message	= "<font color='green'>This profile has been successfully added to your friends list.</font><br>";
		} else {
			$message	= "This profile already exists in your friends list.<br>";
		}
		return $message;
	}

	function get_pending_friend_requests($id=0)
	{
		$array	= array();
		$sql	= "SELECT * FROM ".TABLEPREFIX."imfriends
				   WHERE nUser_Id = '{$id}'
				   AND vStatus LIKE 'NN'"; 
		$res	= @mysql_query($sql, $this->dblink);
		if (@mysql_num_rows($res) > 0) {
			while($row = @mysql_fetch_array($res)) {
				$array[]	= $row;
			}
		}
		@mysql_free_result($res);
		return $array;
	}
	
	function get_im_friends($id=0)
	{
		$array	= array();
		$sql	= "SELECT H.*,U.nUser_Id, U.vLogin, U.vGender, U.vFirstName, P.nPhoto_Id, 
						  U.vTitle, U.vCountry, U.vState, U.vCity, U.vCounty, U.tAbout_Me,
						  TRUNCATE((TO_DAYS(NOW()) - TO_DAYS(U.dDob))/365, 0) as vAge,
						  DATE_FORMAT(U.dLast_Login, '%Y-%m-%d') as dLLogin, U.nHeight
				   FROM ".TABLEPREFIX."imfriends as H JOIN ".TABLEPREFIX."user as U
		           ON  H.nUser_Id_Friend = U.nUser_Id AND H.nUser_Id = '{$id}' 
				   AND H.vStatus NOT LIKE 'R%' AND U.vStatus LIKE 'A%'
				   LEFT JOIN ".TABLEPREFIX."photos as P ON U.nUser_Id = P.nUser_Id
				   GROUP BY U.nUser_Id";
		$res	= @mysql_query($sql, $this->dblink);
		if (@mysql_num_rows($res) > 0) {
			while($row = @mysql_fetch_array($res)) {
				$array[]	= $row;
			}
		}
		@mysql_free_result($res);
		return $array;
	}

	function get_my_friend_list($id=0)
	{
		$array	= array();
/*		$sql	= "SELECT I.nImf_Id, I.nUser_Id, I.nUser_Id_Friend,
						  I.vLogin_Friend, I.vName_Friend,
						  I.vStatus, U.vOnline
				   FROM ".TABLEPREFIX."imfriends as I JOIN ".TABLEPREFIX."user as U
		           ON I.nUser_Id_Friend = U.nUser_Id
				   WHERE I.nUser_Id = '{$id}' AND I.vStatus LIKE 'AN'
				   ORDER BY I.vLgoin_Friend ASC"; */
		 $sql	= "SELECT I.nImf_Id, I.nUser_Id, I.nUser_Id_Friend,
                          U.vLogin as vLogin_Friend,
                          CONCAT_WS(' ', U.vFirstName,U.vMiddleName,U.vLastName) as vName_Friend,
                          TRUNCATE((TO_DAYS(NOW()) - TO_DAYS(U.dDob))/365, 0) as vAge,
                          U.vGender, I.vStatus, U.vOnline, U.nHeight
                          FROM ".TABLEPREFIX."imfriends as I
                          JOIN ".TABLEPREFIX."user as U
                          ON I.nUser_Id = U.nUser_Id
                          WHERE U.vStatus LIKE 'A%'
                          AND I.nUser_Id_Friend = '{$id}'  AND I.vStatus LIKE 'AN' AND (U.vOnline <> 'Invisible' OR U.vOnline = '')
                          ORDER BY U.vLogin ASC";
                          
                        //  echo $sql;
		$res	= @mysql_query($sql, $this->dblink);
		if (@mysql_num_rows($res) > 0) {
			while($row = @mysql_fetch_array($res)) {
				$array[]	= $row;
			}
		}
		@mysql_free_result($res);
		return $array;
	}

	function change_user_online_status($id=0, $status="Online")
	{
		$sql	= "UPDATE ".TABLEPREFIX."user
				   SET vOnline = '{$status}'
				   WHERE nUser_Id = '{$id}'";
		$res	= @mysql_query($sql, $this->dblink);
	}

	function change_request_status($arrID=array(), $flag='NN')
	{
		$message	= "";
		$ids		= isset($arrID['ids'])	?	$arrID['ids']	:	array();
		if (empty($ids))
			$message	.= "Please use the check box on the right side to select a profile and accept invitation.<br>";
		if ($message == "") {
			$idstring	= implode("','", $ids);
			$sql		= "UPDATE ".TABLEPREFIX."imfriends
						   SET vStatus = '{$flag}'
						   WHERE nImf_Id IN ('{$idstring}')";
                                                   //exit;
			$res		= @mysql_query($sql, $this->dblink);
			if (!$res) {
				$message	.= "Could not accept the request now, please try later.<br>";
		    } else {
				$message	.= "<font color='green'>Selected request(s) are accepted successfully.</font><br>";
			}
		}
		return $message;

	}

	function delete_requests($id=0, $arrID=array(), $flag='NN')
	{
		$message	= "";
		$ids		= isset($arrID['ids'])	?	$arrID['ids']	:	array();
		if (empty($ids))
			$message	.= "Please select the request(s) which you need to settle down.<br>";
		if ($message == "") {
			$idstring	= implode("','", $ids);
			$sql		= "UPDATE ".TABLEPREFIX."imfriends
						   SET vStatus = '{$flag}'
						   WHERE nImf_Id IN ('{$idstring}')";
			$res		= @mysql_query($sql, $this->dblink);
			if (!$res) {
				$message	.= "Unable to settle down request(s), please try later.<br>";
		    } else {
				$sql		= "DELETE C.* FROM ".TABLEPREFIX."chats as C JOIN ".TABLEPREFIX."imfriends as F
							   ON C.nUser_Id_From = F.nUser_Id_Friend
							   AND C.nUser_Id_To = '{$id}'
							   AND F.nImf_Id IN ('{$idstring}')";
                $res		= @mysql_query($sql, $this->dblink);
				$message	.= "<font color='green'>Selected request(s) settled down successfully.</font><br>";
			}
		}
		return $message;

	}

	function send_message($id=0, $arr=array())
	{
		$message	= "";
		$toid		= isset($arr['id'])			?	stripslashes(trim($arr['id']))		:	"0";
		$vTitle		= isset($arr['vTitle'])		?	stripslashes(trim($arr['vTitle']))	:	"";
		$tContent	= isset($arr['tContent'])	?	stripslashes(trim($arr['tContent'])):	"";

		if ($vTitle  == "")
			$message	.= "Please enter title of the message.<br>";
		if ($tContent == "")
			$message	.= "Please enter content of the message.<br>";

		if ($message == "") {
			$sql		= "INSERT INTO ".TABLEPREFIX."message (nUser_Id_From, nUser_Id_To, vTitle,
													 tContent, dDate, vStatus)
						   VALUES ('{$id}', '{$toid}',
								   '".addslashes($vTitle)."', '".addslashes($tContent)."',
								   '".addslashes($this->now)."', 'NN')";
			$res		= @mysql_query($sql, $this->dblink);
			if (!$res)
				$message	.= "Unable to send message, please try later.<br>";
			else
				$this->sms_message_alert($toid, $id);
		}
		return $message;
	}
        function send_message_api($id=0, $arr=array())
                {
                       
                        $return = array();
            
                        $message	= "";
                        $toid		= isset($arr['id'])			?	stripslashes(trim($arr['id']))		:	"0";
                        $vTitle		= isset($arr['vTitle'])		?	stripslashes(trim($arr['vTitle']))	:	"";
                        $tContent	= isset($arr['tContent'])	?	stripslashes(trim($arr['tContent'])):	"";

                        if ($vTitle  == ""){
                                $message	.= "Please enter title of the message";
                                $return['status'] = 0;
                                $return['error'] = $message;
                        }
                        if ($tContent == ""){
                                $message	.= "Please enter content of the message";
                                 $return['status'] = 0;
                                 $return['error'] = $message;
                        }

                        if ($message == "") {
                                $sql		= "INSERT INTO ".TABLEPREFIX."message (nUser_Id_From, nUser_Id_To, vTitle,
                                                                                                                 tContent, dDate, vStatus)
                                                           VALUES ('{$id}', '{$toid}',
                                                                           '".addslashes($vTitle)."', '".addslashes($tContent)."',
                                                                           '".addslashes($this->now)."', 'NN')";
                                $res		= @mysql_query($sql, $this->dblink);
                                if (!$res){
                                        $message	.= "Unable to send message, please try later";
                                         $return['status'] = 0;
                                         $return['error'] = $message;
                                }
                                else{
                                         $this->sms_message_alert($toid, $id);
                                         $return['status'] = 1;
                                         $return['message'] = "Successfully send message";
                                }
                        }
                        return $return;
                }
	function sms_message_alert($id=0, $fid=0)
	{
		$name		= "";
		require_once "users.class.php";
		//$arrUser	= users::get_user_alerts($id);
                $userObj = new users();
                $arrUser = $userObj->get_user_alerts($id);
		$name		= $this->get_name($fid);

		if (!empty($arrUser) AND $arrUser['nNewMessageMobile'] == "Y" 
				AND strlen($arrUser['vMobile'])>=10 AND strlen($arrUser['vProvider'])>0) {
			$this->send_inhouse_sms($arrUser['vProvider'], $id, $arrUser['vMobile'], "$name has sent you a  personal message");
		}

	}

	function sms_interest_alert($id=0, $fid=0)
	{
		$name		= "";
		require_once "users.class.php";
		//$arrUser	= users::get_user_alerts($id);
                $userObj = new users();
                $arrUser = $userObj->get_user_alerts($id);
		$name		= $this->get_name($fid);

		if (!empty($arrUser) AND $arrUser['nNewInterestMobile'] == "Y" 
				AND strlen($arrUser['vMobile'])>=10 AND strlen($arrUser['vProvider'])>0) {
			$this->send_inhouse_sms($arrUser['vProvider'], $id, $arrUser['vMobile'], "$name has expressed interest on your profile");
		}
	}

	function send_inhouse_sms($provider="email.uscc.net",$id=1, $no="919446746549", $msg="test message")
	{
		$flag	= false;
		require_once "settings.class.php";
		//$array	= settings::select();
                $settingsObj = new settings();
                $array	= $settingsObj->select();
		$from	= isset($array['sitename'])	?	$array['sitename']	:	"";
		$flag	= mail($no."@".$provider, $from, $msg);
		return $flag;
	}

// This is depricated by send_inhouse_sms()	
	function send_sms($id=1, $no="919446746549", $msg="test message")
	{
		$message	= "";
		$agent		= "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.0)";
		$ref		= $_SERVER['PHP_SELF']; 
		$authurl	= "http://api.clickatell.com/http/auth";
		$sendurl	= "http://api.clickatell.com/http/sendmsg";

		require_once "settings.class.php";
		//$array		= settings::select();
                $settingsObj = new settings();
                $array	= $settingsObj->select();
		$user		= $array['sms_user'];
		$password	= $array['sms_pass'];
		$api_id		= $array['sms_api'];

		$fields		= "user=$user&password=$password&api_id=$api_id";
		$ch			= curl_init();
		curl_setopt($ch, CURLOPT_URL, $authurl);
		curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
		curl_setopt($ch, CURLOPT_NOPROGRESS, 1);
		curl_setopt($ch, CURLOPT_VERBOSE, 1);
		curl_setopt($ch, CURLOPT_FOLLOWLOCATION,0);
		curl_setopt($ch, CURLOPT_POST, 1);
		curl_setopt($ch, CURLOPT_POSTFIELDS, $fields);
		curl_setopt($ch, CURLOPT_TIMEOUT, 120);
		curl_setopt($ch, CURLOPT_USERAGENT, $agent);
		curl_setopt($ch, CURLOPT_REFERER, $ref);
		curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
		$buffer		= curl_exec($ch);
		curl_close($ch);
		$return		= preg_split("/[:]+/", "$buffer");
		$details	= $return[0];

		if ($details == "OK") {
			$session	= trim($return[1]);
			$msg		= urlencode($msg);
			$fields		= "session_id=$session&to=$no&text=$msg";
			$ch			= curl_init();
			curl_setopt($ch, CURLOPT_URL, $sendurl);
			curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
			curl_setopt($ch, CURLOPT_NOPROGRESS, 1);
			curl_setopt($ch, CURLOPT_VERBOSE, 1);
			curl_setopt($ch, CURLOPT_FOLLOWLOCATION,0);
			curl_setopt($ch, CURLOPT_POST, 1);
			curl_setopt($ch, CURLOPT_POSTFIELDS, $fields);
			curl_setopt($ch, CURLOPT_TIMEOUT, 120);
			curl_setopt($ch, CURLOPT_USERAGENT, $agent);
			curl_setopt($ch, CURLOPT_REFERER, $ref);
			curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
			$buffer		= curl_exec($ch);
			curl_close($ch);
			$return		= preg_split("/[:]+/", "$buffer");
			$details	= $return[0];

			if ($details == "ID") {
				$message_id	= trim($return[1]);
				$date	= date("Y-m-d");
				$sql	= "INSERT INTO ".TABLEPREFIX."sms (nUserId, sms_code, sms_date, sms_message) 
				           VALUES ('{$id}', '{$message_id}', '{$date}',
								   '".addslashes(urldecode($msg))."')";
				$res	= @mysql_query($sql, $this->dblink);
			} else {
				$message	.= $return[1];
			}
		} else {
			$message	.= $return[1];
		}
		return $message;
	}

	function favourite_alert($id=0, $fid=0)
	{
		$arrUser	= $this->get_user_details($id);
		$arrFav		= $this->get_user_details($fid);

		if (!empty($arrUser) AND !empty($arrFav)) {
			require_once "users.class.php";
			//$arrAlerts	= users::get_user_alerts_only($fid); 
                        $userObj = new users();
                        $arrAlerts = $userObj->get_user_alerts_only($fid);
			if (!empty($arrAlerts) AND $arrAlerts['nAddFavourites'] == "Y") {
				require_once "settings.class.php";
				//$arrSettings	= settings::select();
                                $settingsObj = new settings();
                                $arrSettings	= $settingsObj->select();
				if (!empty($arrSettings)) {
					$site_logo	= $arrSettings['sitelogo'];
					$site_valid_day	=  $arrSettings['ValidityDayMembership'];
					//checking site logo start
					if(trim($site_logo)!='')
					{
						switch($site_logo)
						{
							case "logo_default.gif":
								$site_top='24';
							break;
	
							default:
								$site_top='3';
							break;
						}//end switch
					}//end if
					else
					{
						$site_top='24';
						$site_logo=$arrSettings['sitename'];
					}//end else
					//checking site logo ends

					$message	= "Hi ".$arrFav['vLogin'].","."\n\n";
					$message	.= "Your profile have been added to Favourite list of the user ".$arrUser['vLogin'].".\n\n";
					$message	.= "By"."\n";
					$message	.= $arrSettings['sitename'];

					$from		= $arrSettings['adminmail'];
					$to			= $arrFav['vEmail'];
					$toname		= $arrFav['vLogin'];
					$fromname	= $arrSettings['sitename']." Team";
					$subject	= 'You have been added to Favourite List';
					$htmlbody	= '';

					$site_name	= $arrSettings['sitename'];
					$site_url	= $arrSettings['site_normal_url'];
					$basepath	= BASE_PATH;
					$mail_title	= $subject;
					$send_date	= date('F j, Y');
					$content	= "<h2 style='font-size: 18px;'>Dear member ".$arrFav['vLogin']." </h2>
								<p>Your profile have been added to Favourite list of the user ".$arrUser['vLogin'].".
								Please click <a href='".$site_url."/profile.php?id=".$arrUser['nUser_Id']."'>here</a> to
								view the profile of ".$arrUser['vLogin']."</p><p>Personalised</p>
								<p>By Yours <br /> ".$site_name." Team.</p>";
					$arrSearch	= array("{SITE_NAME}", "{SITE_URL}", "{MAIL_TITLE}",
										"{SEND_DATE}", "{EMAIL_CONTENT}","{SITE_LOGO}","{SITE_TOP}","{SITE_VALID-DAY}");
					$arrReplace	= array($site_name, $site_url, $mail_title, $send_date, $content,$site_logo,$site_top,$site_valid_day);
					$htmlbody	= $this->html_mail($basepath, $arrSearch, $arrReplace);

					$textbody	= $message;
					$flag		= $this->send_mail_perfect($from, $to, $subject, $fromname, $toname, $textbody, $htmlbody);
/*
					$this->send_mail($arrFav['vLogin']."<".$arrFav['vEmail'].">", $message, "You have been added to Favourite List", $arrSettings['adminmail'], $arrSettings['sitename']);
*/
				}
			}
		}
	}

	function hotlist_alert($id=0, $hid=0)
	{
		$arrUser	= $this->get_user_details($id);
		$arrHot		= $this->get_user_details($hid);

		if (!empty($arrUser) AND !empty($arrHot)) {
			require_once "users.class.php";
			//$arrAlerts	= users::get_user_alerts_only($hid);
                        $userObj = new users();
                        $arrAlerts = $userObj->get_user_alerts_only($hid);
			if (!empty($arrAlerts) AND $arrAlerts['nAddHot'] == "Y") {
				require_once "settings.class.php";
				//$arrSettings	= settings::select();
                                $settingsObj = new settings();
                                $arrSettings	= $settingsObj->select();
				if (!empty($arrSettings)) {
					$site_logo	= $arrSettings['sitelogo'];
					$site_valid_day	=  $arrSettings['ValidityDayMembership'];
					//checking site logo start
					if(trim($site_logo)!='')
					{
						switch($site_logo)
						{
							case "logo_default.gif":
								$site_top='24';
							break;
	
							default:
								$site_top='3';
							break;
						}//end switch
					}//end if
					else
					{
						$site_top='24';
						$site_logo=$arrSettings['sitename'];
					}//end else
					//checking site logo ends

					$message	= "Hi ".$arrHot['vLogin'].","."\n\n";
					$message	.= "Your profile have been added to Hot list of the user ".$arrUser['vLogin'].".\n\n";
					$message	.= "By"."\n";
					$message	.= $arrSettings['sitename'];

					$from		= $arrSettings['adminmail'];
					$to			= $arrHot['vEmail'];
					$toname		= $arrHot['vLogin'];
					$fromname	= $arrSettings['sitename']." Team";
					$subject	= 'You have been added to Hot List';
					$htmlbody	= '';
					$site_name	= $arrSettings['sitename'];
					$site_url	= $arrSettings['site_normal_url'];
					$basepath	= BASE_PATH;
					$mail_title	= $subject;
					$send_date	= date('F j, Y');
					$content	= "<h2 style='font-size: 18px;'>Dear member ".$arrHot['vLogin']." </h2>
								<p>Your profile have been added to Hot list of the user ".$arrUser['vLogin'].".
								Please click <a href='".$site_url."/profile.php?id=".$arrUser['nUser_Id']."'>here</a> to
								view the profile of ".$arrUser['vLogin']."</p><p>Personalised</p>
								<p>By Yours <br /> ".$site_name." Team.</p>";
					$arrSearch	= array("{SITE_NAME}", "{SITE_URL}", "{MAIL_TITLE}",
										"{SEND_DATE}", "{EMAIL_CONTENT}","{SITE_LOGO}","{SITE_TOP}","{SITE_VALID-DAY}");
					$arrReplace	= array($site_name, $site_url, $mail_title, $send_date, $content,$site_logo,$site_top,$site_valid_day);
					$htmlbody	= $this->html_mail($basepath, $arrSearch, $arrReplace);

					$textbody	= $message;
					$flag		= $this->send_mail_perfect($from, $to, $subject, $fromname, $toname, $textbody, $htmlbody);
/*
					$this->send_mail($arrHot['vLogin']."<".$arrHot['vEmail'].">", $message, "You have been added to Hot List", $arrSettings['adminmail'], $arrSettings['sitename']);
*/
				}
			}
		}
	}

	function view_alert($id=0, $uid=0)
	{
		if ($id <> $uid) {
			$array		= $this->get_today_views($id, $uid);
			if (empty($array)) {
				$arrUser	= $this->get_user_details($id);
				$arrView	= $this->get_user_details($uid);

				if (!empty($arrUser) AND !empty($arrView)) {
					require_once "users.class.php";
					//$arrAlerts	= users::get_user_alerts_only($uid);
                                        $userObj = new users();
                                        $arrAlerts = $userObj->get_user_alerts_only($uid);
					if (!empty($arrAlerts) AND $arrAlerts['nProfileViewed'] == "Y") {
						require_once "settings.class.php";
						//$arrSettings	= settings::select();
                                                $settingsObj = new settings();
                                                $arrSettings	= $settingsObj->select();
						if (!empty($arrSettings)) {
							$message	= "Hi ".$arrView['vLogin'].","."\n\n";
							$message	.= "Your profile has been viewed by the user ".$arrUser['vLogin'].".\n\n";
							$message	.= "By"."\n";
							$message	.= $arrSettings['sitename'];

							$from		= $arrSettings['adminmail'];
							$to			= $arrView['vEmail'];
							$toname		= $arrView['vLogin'];
							$fromname	= $arrSettings['sitename']." Team";
							$subject	= 'Your Profile has been Viewed';
							$htmlbody	= '';

							$site_name	= $arrSettings['sitename'];
							$site_url	= $arrSettings['site_normal_url'];
							$site_logo	= $arrSettings['sitelogo'];
							$site_valid_day	=  $arrSettings['ValidityDayMembership'];
							//checking site logo start
							if(trim($site_logo)!='')
							{
								switch($site_logo)
								{
									case "logo_default.gif":
										$site_top='24';
									break;
			
									default:
										$site_top='3';
									break;
								}//end switch
							}//end if
							else
							{
								$site_top='24';
								$site_logo=$site_name;
							}//end else
							//checking site logo ends
							$basepath	= BASE_PATH;
							$mail_title	= $subject;
							$send_date	= date('F j, Y');
							$content	= "<h2 style='font-size: 18px;'>Dear member ".$arrView['vLogin']." </h2>
										<p>Your profile has been viewed by the user ".$arrUser['vLogin'].".
										Please click <a href='".$site_url."/profile.php?id=".$arrUser['nUser_Id']."'>here</a> to
										view the profile of ".$arrUser['vLogin']."</p><p>Personalised</p>
										<p>By Yours <br /> ".$site_name." Team.</p>";
							$arrSearch	= array("{SITE_NAME}", "{SITE_URL}", "{MAIL_TITLE}",
												"{SEND_DATE}", "{EMAIL_CONTENT}","{SITE_LOGO}","{SITE_TOP}","{SITE_VALID-DAY}");
							$arrReplace	= array($site_name, $site_url, $mail_title, $send_date, $content,$site_logo,$site_top,$site_valid_day);
							$htmlbody	= $this->html_mail($basepath, $arrSearch, $arrReplace);

							$textbody	= $message;
							$flag		= $this->send_mail_perfect($from, $to, $subject, $fromname, $toname, $textbody, $htmlbody);
	/*
							$this->send_mail($arrView['vLogin']."<".$arrView['vEmail'].">", $message, "Your Profile has been Viewed", $arrSettings['adminmail'], $arrSettings['sitename']);
	*/
							$this->insert_view($id, $uid);
						}
					}
	//				$this->insert_view($id, $uid);
				}
			}
		}
	}

	function insert_view($id=0, $uid=0)
	{
		$date	= date("Y-m-d");
		$sql	= "INSERT INTO ".TABLEPREFIX."views (nUserId, nUserViewId, dDate)
				   VALUES ('{$id}', '{$uid}', '{$date}')";
		$res	= @mysql_query($sql, $this->dblink);
	}

	function get_today_views($id=0, $uid=0)
	{
		$array	= array();
		$date	= date("Y-m-d");
		$sql	= "SELECT * FROM ".TABLEPREFIX."views
		           WHERE nUserId = '{$id}' AND nUserViewId = '{$uid}' AND dDate = '{$date}'";
		$res	= @mysql_query($sql, $this->dblink);
		if (@mysql_num_rows($res) > 0) {
			$array	= @mysql_fetch_array($res);
		}
		return $array;
	}


	function get_smilies()
	{
		$array	= array();
		$sql	= "SELECT * FROM ".TABLEPREFIX."smilies";
		$res	= @mysql_query($sql, $this->dblink);
		if (@mysql_num_rows($res) > 0) {
			while($row = @mysql_fetch_array($res)) {
				$array[]	= $row;
			}
			@mysql_free_result($res);
		}
		return $array;
	}

	function get_chat_data($uid=0, $fid=0, $timeof = "")
	{
		if ($timeof == "")
			$timeof	= date("mYdHis");
		$text	= $this->get_full_chat($uid, $fid, $timeof);
		$array	= array();
		$arrS	= $this->get_smilies();
		foreach ($arrS as $key => $value) {
			$arrCode[]	= $value['code'];
			$arrImag[]	= "<img src='smilies/".$value['smile_url']."' border='0' title='".$value['emoticon']."'>";
		}
		$text	= str_replace($arrCode, $arrImag, $text);
		return $text;
	}

        function get_chat_data_ajax($uid=0, $fid=0, $timeof = "")
	{
		if ($timeof == "")
			$timeof	= date("mYdHis");
		$text	= $this->get_full_chat_ajax($uid, $fid, $timeof);
		$array	= array();
		$arrS	= $this->get_smilies();
		foreach ($arrS as $key => $value) {
			$arrCode[]	= $value['code'];
			$arrImag[]	= "<img src='smilies/".$value['smile_url']."' border='0' title='".$value['emoticon']."'>";
		}
		$text	= str_replace($arrCode, $arrImag, $text);
		return $text;
	}
        
	function get_full_chat($uid, $fid, $timeof)
	{
		$text	= "";
		$sql	= "SELECT C.*, U.vLogin as vLogin_To, U1.vLogin as vLogin_From
					FROM ".TABLEPREFIX."chats as C JOIN ".TABLEPREFIX."user as U ON U.nUser_Id = C.nUser_Id_To
					JOIN ".TABLEPREFIX."user as U1 ON U1.nUser_Id = C.nUser_Id_From
					WHERE (C.nUser_Id_To = '{$uid}' OR C.nUser_Id_To = '{$fid}') 
					AND (C.nUser_Id_From = '{$uid}' OR C.nUser_Id_From = '{$fid}')";

					//$sql	.= "AND (C.tTimeOf >= '{$timeof}' OR (C.nUser_Id_To = '{$uid}' AND C.vStatus LIKE 'N'))";
                                        $sql	.= "AND (SUBSTRING( C.tTimeOf, 0, 10 ) >= SUBSTRING( '".$timeof."', 0, 10 ) OR (C.nUser_Id_To = '{$uid}' AND C.vStatus LIKE 'N'))";
				    $sql	.= "ORDER BY C.tTimeOf, C.nChat_Id";
                                                // SUBSTRING( C.tTimeOf, 0, 10 ) >= SUBSTRING( '20121011110731', 0, 10 )
		
                                  
                                    $res	= @mysql_query($sql, $this->dblink);
              
		if (@mysql_num_rows($res) > 0) {
			while($row = @mysql_fetch_array($res)) {
			
				//display time in est format
                            
				$timeDisplay=gmdate('Y-m-d h:i:s A',time($row['tTimeOf']));
				
				$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');
				}//end if
				//display time in est format

                                $mdisplay=date('m/d/Y',  strtotime($timeDisplay));
				//print_r($row);
				$class = ($row['nUser_Id_To']==$_SESSION['user_id'])?1:2;
                                $name = ($row['nUser_Id_From']==$_SESSION['user_id'])?'me':$row['vLogin_From'];
				
					$text		.= "<div class='msg_container$class'><div class='msg_name'>".$name."<div class='msg_body'>".$row['tMessage']."</div></div><div class='msg_time'>(".$mdisplay.")</div><div class='chat_arrow$class'></div></div>";
			}
			@mysql_free_result($res);
			$sql	= "UPDATE ".TABLEPREFIX."chats SET vStatus = 'R'
					   WHERE nUser_Id_To = '{$uid}' AND nUser_Id_From = '{$fid}'";
                                           
                       //echo $sql;              
			$res	= @mysql_query($sql, $this->dblink);
		}

		return stripslashes($text);
	}
function get_full_chat_ajax($uid, $fid, $timeof)
	{
		$text	= "";
		$sql	= "SELECT C.*, U.vLogin as vLogin_To, U1.vLogin as vLogin_From
					FROM ".TABLEPREFIX."chats as C JOIN ".TABLEPREFIX."user as U ON U.nUser_Id = C.nUser_Id_To
					JOIN ".TABLEPREFIX."user as U1 ON U1.nUser_Id = C.nUser_Id_From
					WHERE ((C.nUser_Id_To = '{$uid}' OR C.nUser_Id_To = '{$fid}') AND C.vStatus LIKE 'N') 
					AND (C.nUser_Id_From = '{$uid}' OR C.nUser_Id_From = '{$fid}')";

					//$sql	.= "AND (C.tTimeOf >= '{$timeof}' OR (C.nUser_Id_To = '{$uid}' AND C.vStatus LIKE 'N'))";
                                        $sql	.= "AND (SUBSTRING( C.tTimeOf, 0, 10 ) >= SUBSTRING( '".$timeof."', 0, 10 ) OR (C.nUser_Id_To = '{$uid}' AND C.vStatus LIKE 'N'))";
				    $sql	.= "ORDER BY C.tTimeOf, C.nChat_Id";
                                                // SUBSTRING( C.tTimeOf, 0, 10 ) >= SUBSTRING( '20121011110731', 0, 10 )
		
                                 // echo $sql;
                                    $res	= @mysql_query($sql, $this->dblink);
              
		if (@mysql_num_rows($res) > 0) {
			while($row = @mysql_fetch_array($res)) {
			
				//display time in est format
                            
				$timeDisplay=gmdate('Y-m-d h:i:s A',time($row['tTimeOf']));
				
				$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');
				}//end if
				//display time in est format

                                $mdisplay=date('m/d/Y',  strtotime($timeDisplay));
				
					$class = ($row['nUser_Id_To']==$_SESSION['user_id'])?1:2;
                                        $name = ($row['nUser_Id_From']==$_SESSION['user_id'])?'me':$row['vLogin_From'];
				
					$text		.= "<div class='msg_container$class'><div class='msg_name'>".$name."</div><div class='msg_body'>".$row['tMessage']."</div><div class='msg_time'>(".$mdisplay.")</div><div class='chat_arrow$class'></div></div>";
			}
			@mysql_free_result($res);
			$sql	= "UPDATE ".TABLEPREFIX."chats SET vStatus = 'R'
					   WHERE nUser_Id_To = '{$uid}' AND nUser_Id_From = '{$fid}'";
                                           
                                           
			$res	= @mysql_query($sql, $this->dblink);
		}

		return stripslashes($text);
	}
	function get_chat_timeof($uid=0)
	{
		$timeof	= gmdate("YmdHis");
		$id	= 0;
		 $sql	= "SELECT * FROM ".TABLEPREFIX."chats
		           WHERE nUser_Id_To = '{$uid}' AND vStatus LIKE 'N'";
		$res	= @mysql_query($sql, $this->dblink);
		if (@mysql_num_rows($res) > 0) {
			$row	= @mysql_fetch_array($res);
			$timeof	= $row['tTimeOf'];
		}
		return $timeof;
	}

	function exists_in_chat($uid=0, $fid=0)
	{
		$flag	= false;
		$sql	= "SELECT * FROM ".TABLEPREFIX."imfriends
				   WHERE nUser_Id = '{$uid}'
				   AND nUser_Id_Friend = '{$fid}'
				   AND vStatus NOT LIKE 'R%'";
		$res	= @mysql_query($sql, $this->dblink);
		if (@mysql_num_rows($res) > 0) {
			$flag	= true;
		}
		return $flag;
	}

	function get_chat_requests($uid=0)
	{
		$timeof	= gmdate("YmdHis");
		$array	= array();
		$sql	= "SELECT * FROM ".TABLEPREFIX."chats
		           WHERE nUser_Id_To = '{$uid}' 
				   AND vStatus LIKE 'N'
				   AND tTimeOf < '{$timeof}'
				   GROUP BY nUser_Id_From";
		$res	= @mysql_query($sql, $this->dblink);
		if (@mysql_num_rows($res) > 0) {
			while($row	= @mysql_fetch_assoc($res)) {
				$array[]	= $row;
				if (!$this->exists_in_chat($row['nUser_Id_To'], $row['nUser_Id_From']))
					$this->add_to_friendslist($row['nUser_Id_To'], $row['nUser_Id_From'], "AN");
				if (!$this->exists_in_chat($row['nUser_Id_From'], $row['nUser_Id_To']))
					$this->add_to_friendslist($row['nUser_Id_From'], $row['nUser_Id_To'], "AN");
			}
		}
		return $array;
	}

	function valid_friend($uid=0, $fid=0)
	{
		$flag	= false;
		$sql	= "SELECT * FROM ".TABLEPREFIX."imfriends
		           WHERE nUser_Id = '{$fid}' 
				   AND nUser_Id_Friend = '{$uid}' AND vStatus LIKE 'A%'";
                                   
                                  // echo $sql;
		$res	= @mysql_query($sql, $this->dblink);
		if (@mysql_num_rows($res) > 0) {
			$flag	= true;
		}
		return $flag;
	}

	function save_chat($uid=0, $fid=0, $comment="")
	{
		$message	= "";
		if (trim($comment) <> "") {
			$timeof	= gmdate("YmdHis");
			$date	= date("Y-m-d");
			if ($this->valid_friend($uid, $fid)) {
				$sql	= "INSERT INTO ".TABLEPREFIX."chats (nUser_Id_To, nUser_Id_From,
										tMessage, tTimeOf, dDate)
						   VALUES ('{$fid}', '{$uid}', '".addslashes(trim($comment))."',
								   '{$timeof}', '{$date}')";
                                                                   
                                                                   
				$res	= @mysql_query($sql, $this->dblink);
			} else {
				$message	= "Sorry, you cannot chat with this user, since your friendship request hasn't accepted by this user.";
			}
		}
	}

	function get_my_payments($id=0)
	{
		$array	= array();
		$sql	= "SELECT U.nUser_Id, U.vLogin, P.*, PR.vType, PR.nProdId,
		                  O.nOrdId, DATE_FORMAT(P.dDate, '%D %M %Y') as dDay 
				   FROM ".TABLEPREFIX."payments as P JOIN ".TABLEPREFIX."user as U 
						ON P.nUser_Id = U.nUser_Id AND U.nUser_Id = '{$id}'
					INNER JOIN ".TABLEPREFIX."orders as O ON P.nPayment_Id = O.nPayment_Id
					LEFT JOIN ".TABLEPREFIX."products as PR ON PR.nProdId = O.nProdId
				   ORDER BY P.nPayment_Id DESC";
		$res	= @mysql_query($sql, $this->dblink);
		if (@mysql_num_rows($res) > 0) {
			while ($row = @mysql_fetch_array($res)) {
				$array[]	= $row;
			}
		}
		@mysql_free_result($res);
		return $array;

	}

	function get_my_stories($id=0)
	{
		$array	= array();
		$sql	= "SELECT *,DATE_FORMAT(S.dDate, '%D %M %Y') as dDay
		            FROM ".TABLEPREFIX."success_story as S JOIN ".TABLEPREFIX."user as U 
		            ON S.nUser_Id = U.nUser_Id AND U.nUser_Id = '{$id}' 
					ORDER BY S.nStory_Id DESC";
		$res	= @mysql_query($sql, $this->dblink);
		if (@mysql_num_rows($res) > 0) {
			while ($row = @mysql_fetch_array($res)) {
				$array[]	= $row;
			}
		}
		@mysql_free_result($res);
		return $array;

	}

	function get_my_success_story($uid=0, $id=0)
	{
		$array	= array();
		$sql	= "SELECT *	FROM ".TABLEPREFIX."success_story as s JOIN ".TABLEPREFIX."user as u 
						ON s.nUser_Id = u.nUser_Id AND s.nUser_Id = '{$uid}'
				   WHERE s.nStory_Id = '{$id}'";
		$res	= @mysql_query($sql, $this->dblink);
		if (@mysql_num_rows($res) > 0) {
			$array = @mysql_fetch_array($res);
		}
		@mysql_free_result($res);
		return $array;
	}


	function save_my_success_story($uid=0, $id=0)
	{
		$message	= $this->check_my_success_story($uid, $id);
		if ($message == "") {
			if ($id >= 1) {
				$message	= $this->update_my_success_story($uid, $id);
			} else {
				$message	= $this->insert_my_success_story($uid);
			}
		}
		return $message;
	}

	function check_my_success_story($uid, $id)
	{
		$message	= "";
		$script			= "";
		$arrElements	= array();

		if ($this->vStory_Title == "") {
			$message	.= "Please enter title for the story.<br>";
			$arrElements[]	= "vStory_Title";
		}
		if ($this->tStory == "") {
			$message	.= "Please enter description for the story.<br>";
			$arrElements[]	= "tStory";
		}
		if ($this->arrFile['size'] > 0) {
			$extn	= substr(strrchr($this->arrFile['name'], "."), 1);
			if (!in_array($extn, $this->arrExtns)) {
				$message	.= "The extension <b>".$extn."</b>is not allowed.<br>";
			} else {
				$message	.= $this->save_image($id);
			}
		}
		if (!empty($arrElements)) {
			$script	= '<script language="javascript">';
			foreach ($arrElements as $key=>$value) {
				if ($value == "tStory")
					$script	.= 'document.frmUser.'.$value.'.className = "textbox_textarea txt-bx01";';
				else
					$script	.= 'document.frmUser.'.$value.'.className = "textbox txt-bx01";';
			}
			$script	.= '</script>';
		}
		$message	.= $script;
		return $message;
	}

	function insert_my_success_story($uid=0)
	{
		$messagae	= "";
		$sql		= "INSERT INTO ".TABLEPREFIX."success_story (nUser_Id, vStory_Title,
								   tStory, vPicURL, dDate)
					   VALUES ('{$uid}',
							   '".addslashes($this->vStory_Title)."',
							   '".addslashes($this->tStory)."', '".addslashes($this->vPicURL)."',
							   '".addslashes($this->now)."')";
		$res		= @mysql_query($sql, $this->dblink);
		if (!$res)
			$message	.= "Unable to add success story, please try later.<br>";
                else
                    $message ="<font color='green'>Success story inserted successfully</font>";

                
		return $message;
	}

	function update_my_success_story($uid=0, $id=0)
	{
		$messagae	= "";
		$sql		= "UPDATE ".TABLEPREFIX."success_story 
					   SET nUser_Id = '{$uid}',
					       vStory_Title = '".addslashes($this->vStory_Title)."',
						   tStory = '".addslashes($this->tStory)."'
					   WHERE nStory_Id = '{$id}'";
		$res		= @mysql_query($sql, $this->dblink);
		if (!$res)
			$message	.= "Unable to update success story image, please try later.<br>";
                else
                    $message ="<font color='green'>Success story updated successfully</font>";
		return $message;
	}

	function contact_us_mail($arr=array())
	{
		$msg		= "";
		$frEmail	= isset($arr['txtEmail'])	?	$arr['txtEmail']	:	"";
		$frName	= isset($arr['txtName'])	?	$arr['txtName']	:	"";
		$message	= isset($arr['txtMsg'])		?	stripslashes(trim($arr['txtMsg']))	:	"";

		if ($frEmail == "")
			$msg	.= "Please enter your mail address.<br>";
		if (!$this->check_email($frEmail)) {
			$text	= $frEmail==""?" Your Email ":$frEmail;
			$msg	.= "<b>".$text."</b> is an invalid email address.<br>";
		}
		if ($message == "")
			$msg	.= "Please enter the message.<br>";
                
                else{//New mail content format
                    $mailcontent = "A new contact has been added.The details are as follows:<br>
                                    Name : $frName<br>
                                    Email : $frEmail<br>
                                    Comment : $message";
                    $message    = $mailcontent;
                }

		if ($msg == "") {
			$flag	= true;
				if ($flag) {
					$message	= str_replace("{TONAME}", $arrName[$key], $message);
					$message	= str_replace("{FROMNAME}", $frName, $message);
					$from		= $frEmail;
					$toname		= 'Admin';
					$fromname	= $frName;
					$subject	= 'Contact Us';
					$htmlbody	= '';

					require_once "settings.class.php";
//					$to			= settings::getone('adminmail');
//					$site_name	= settings::getone('sitename');
//					$site_url	= settings::getone('site_normal_url');
//					$site_logo	= settings::getone('sitelogo');
                                        $settingsObj = new settings();
					$to		= $settingsObj->getone('adminmail');
					$site_name	= $settingsObj->getone('sitename');
					$site_url	= $settingsObj->getone('site_normal_url');
					$site_logo	= $settingsObj->getone('sitelogo');
					//checking site logo start
					if(trim($site_logo)!='')
					{
						switch($site_logo)
						{
							case "logo_default.gif":
								$site_top='24';
							break;
	
							default:
								$site_top='3';
							break;
						}//end switch
					}//end if
					else
					{
						$site_top='24';
						$site_logo=$site_name;
					}//end else
					//checking site logo ends

					$basepath	= BASE_PATH;
					$mail_title	= $subject;
					$send_date	= date('F j, Y');
					$content	=  nl2br($message);
					$arrSearch	= array("{SITE_NAME}", "{SITE_URL}", "{MAIL_TITLE}",
										"{SEND_DATE}", "{EMAIL_CONTENT}","{SITE_LOGO}","{SITE_TOP}");
					$arrReplace	= array($site_name, $site_url, $mail_title, $send_date, $content,$site_logo,$site_top);
					$htmlbody	= $this->html_mail2($basepath, $arrSearch, $arrReplace);
                                        //exit;

					$textbody	= $message;
                                        //exit;
                    $flag		= $this->send_mail_perfect($from, $to, $subject, $fromname, $toname, $textbody, $htmlbody);
 			}
			if (!$flag)
				$msg	.= "Unable to send mail.<br>";
			else
				$msg	.= "Thank you for contacting us. Will get back to you soon...<br>";
		}
		return $msg;
	}

        function getuserDevices($userId)
	{		
            $sql	= "SELECT * FROM ".TABLEPREFIX."user_devices WHERE user_id = '".$userId."'";
            $res	= @mysql_query($sql, $this->dblink);
            $array = array();
            if (@mysql_num_rows($res) > 0) {
                while ($row = @mysql_fetch_assoc($res)) {
                        $array[]	= $row;
                }
            }
            @mysql_free_result($res);
            return $array;
	}
        
        function getuserAllDevices($userId)
	{		
            $sql	= "SELECT * FROM ".TABLEPREFIX."user_devices WHERE device <> '' AND device_id <> '' ";
            $res	= @mysql_query($sql, $this->dblink);
            $array = array();
            if (@mysql_num_rows($res) > 0) {
                while ($row = @mysql_fetch_assoc($res)) {
                        $array[]	= $row;
                }
            }
            @mysql_free_result($res);
            return $array;
	}
        
        
        function checkDeviceExist($userId,$device,$deviceId)
	{		
            $sql	= "SELECT * FROM ".TABLEPREFIX."user_devices WHERE user_id = '".$userId."' AND device='".$device."' AND device_id='".$deviceId."'";
            $res	= @mysql_query($sql, $this->dblink);
            $array = array();
            if (@mysql_num_rows($res) > 0) {
                while ($row = @mysql_fetch_array($res)) {
                        $array[]	= $row;
                }
            }
            @mysql_free_result($res);
            return $array;
	}
        
        function deleteDeviceDetails($userId,$device,$deviceId)
	{		
            $sql	= "DELETE FROM ".TABLEPREFIX."user_devices WHERE user_id='$userId' AND device='$device' AND device_id='$deviceId'";
            return @mysql_query($sql, $this->dblink);
	}
      
        
        function checkPremiumPermission($return=false,$user_id='')
	{         
            
            $user_id = ($user_id)?$user_id:$_SESSION['user_id'];
            
            require_once "settings.class.php";
            $settingsObj = new settings();
            $arrS	= $settingsObj->select();
            
            $objU		= new userside($objDB);    
            
            if($arrS['regmode']==REGISTRATION_FREEMIUM_MODE && ($this->isPremiumUser($user_id) || $this->isInFreemiumPeriod($user_id))){
                return true;
            } else if($arrS['regmode']==REGISTRATION_PAID_MODE && !$objU->is_expired($user_id)){
                return true;
            }
            else if($arrS['regmode']==REGISTRATION_FREE_MODE){
                return true;
            }
            else {
                if($return) return false;
                if(!empty($user_id))
                    header("location:myprofile.php");
                else header("location:index.php");
                exit;
            }    
	}
        
        
        function isPremiumUser($userId)
	{        
            $sql_fld=mysql_query("select nUser_Id from ".TABLEPREFIX."user WHERE premiumUser='Y' AND nUser_Id='$userId'") or die(mysql_error());
            if(mysql_num_rows($sql_fld)>0) {  
                return true;
            }           
            return false;
	}        
        function isInFreemiumPeriod($userId)
	{        
            require_once "settings.class.php";
            //$arrS	= settings::select();
            $settingsObj = new settings();
            $arrS	= $settingsObj->select();
            $date	= date("Y-m-d H:i:s");	
            $freePeriod = $arrS['freemium_period'];            
            $sql = "select nUser_Id from ".TABLEPREFIX."user WHERE DATE_ADD(dStartDate, INTERVAL $freePeriod DAY) > '{$date}' AND nUser_Id='$userId'";
            $sql_fld=mysql_query($sql) or die(mysql_error());
            if(mysql_num_rows($sql_fld)>0) {  
                return true;
            }           
            return false;
	}
}
?>