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

class misc extends miscellaneous {

	function misc($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');
					//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}");
					$arrReplace	= array($site_name, $site_url, $mail_title, $send_date, $content,$site_logo,$site_top);
					$htmlbody	= $this->html_mail($basepath, $arrSearch, $arrReplace);

					$textbody	= $message;
					$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	.= "Success, mail has been sent.<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($toname."<".$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 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 (!$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)."'";
			$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 {
					$_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 {
				$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 = "errorinput";';
			}
			$script	.= '</script>';
		}
		$msg	.= $script;

		return $msg;
	}

	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 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 (!$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 == "") {
			$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');
					//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	= $subject;
					$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}");
					$arrReplace	= array($site_name, $site_url, $mail_title, $send_date, $content,$site_logo,$site_top);
					$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 = "errorinput";';
				}
				$script	.= '</script>';
			}
		}
		$message	.= $script;
		return $message;
	}

	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 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%'
				   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%'
				   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_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%'
				   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	.= "Selected favourite(s) deleted successfully.<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	.= "Selected hot(s) deleted successfully.<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%'
					   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%'
					   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, '%Y-%m-%d') 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, '%Y-%m-%d') 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%'
					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, '%Y-%m-%d') 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, '%Y-%m-%d') 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%'
					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_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	= "Selected message(s) have been successfully marked as read.<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%'
					   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%'
					   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, '%Y-%m-%d') 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%'
					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, '%Y-%m-%d') 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%'
					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 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	= "Decline";
		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	= "Selected interests have been successfully $msg.<br>";
		}
		return $message;
	}

	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	= "You have successfully reported abuse about this profile.<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	= "Your interest has been successfully expressed.<br>";
				$this->sms_interest_alert($iid, $id);
			}
		} else {
			$message	= "You have already expressed interest to this profile.<br>";
		}
		return $message;
	}

	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	= "This profile has been successfully added to your favourites list.<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 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	= "This profile has been successfully added to your hot list.<br>";
				$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	= "This profile has been successfully added to your friends list.<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_Friend = U.nUser_Id AND U.vStatus LIKE 'A%'
				   AND I.nUser_Id = '{$id}' AND I.vStatus LIKE 'AN'
				   ORDER BY U.vLogin ASC"; 
		$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}')";
			$res		= @mysql_query($sql, $this->dblink);
			if (!$res) {
				$message	.= "Could not accept the request now, please try later.<br>";
		    } else {
				$message	.= "Selected request(s) are accepted successfully.<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	.= "Selected request(s) settled down successfully.<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 sms_message_alert($id=0, $fid=0)
	{
		$name		= "";
		require_once "users.class.php";
		$arrUser	= users::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);
		$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();
		$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();
		$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); 
			if (!empty($arrAlerts) AND $arrAlerts['nAddFavourites'] == "Y") {
				require_once "settings.class.php";
				$arrSettings	= settings::select();
				if (!empty($arrSettings)) {
					$site_logo	= $arrSettings['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=$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}");
					$arrReplace	= array($site_name, $site_url, $mail_title, $send_date, $content,$site_logo,$site_top);
					$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);
			if (!empty($arrAlerts) AND $arrAlerts['nAddHot'] == "Y") {
				require_once "settings.class.php";
				$arrSettings	= settings::select();
				if (!empty($arrSettings)) {
					$site_logo	= $arrSettings['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=$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}");
					$arrReplace	= array($site_name, $site_url, $mail_title, $send_date, $content,$site_logo,$site_top);
					$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);
					if (!empty($arrAlerts) AND $arrAlerts['nProfileViewed'] == "Y") {
						require_once "settings.class.php";
						$arrSettings	= settings::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'];
							//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}");
							$arrReplace	= array($site_name, $site_url, $mail_title, $send_date, $content,$site_logo,$site_top);
							$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("YmdHis");
		$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_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}')
					AND (C.tTimeOf >= '{$timeof}' OR (C.nUser_Id_To = '{$uid}' AND C.vStatus LIKE 'N')) 
				    ORDER BY C.tTimeOf, C.nChat_Id";
		$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
				
					$text		.= "<b>".$row['vLogin_From']."&nbsp;(".$timeDisplay."):</b>&nbsp;".$row['tMessage']."<br>";
			}
			@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_array($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%'";
		$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}'
					JOIN ".TABLEPREFIX."orders as O ON P.nPayment_Id = O.nPayment_Id
					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 = "errortextarea";';
				else
					$script	.= 'document.frmUser.'.$value.'.className = "errorinput";';
			}
			$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>";
		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>";
		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>";

		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');
					//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_mail($basepath, $arrSearch, $arrReplace);

					$textbody	= $message;
					$flag		= $this->send_mail_perfect($from, $to, $subject, $fromname, $toname, $textbody, $htmlbody);
			}
			if (!$flag)
				$msg	.= "Unable to send mail.<br>";
			else
				$msg	.= "Success, mail has been sent.<br>";
		}
		return $msg;
	}


}
?>