<?php

require_once "users.class.php";



class userside extends users {



    var $vCode;

    var $dStart;

    var $dEnd;

    var $nFreeCode_Id;

    var $nProvider;


    var $publickey = "6LcXxdoSAAAAAHjK3YLDkdhg-BugotbQQIr3CbEA";

    var $privatekey = "6LcXxdoSAAAAAMeDjyNnnH9DT9_NJ5VVkUThvKrf";


    var $vAddress;

    var $vPostCode;

    var $vPhone;

    var $nNumber;
	var $vPaymentMethodType;

    var $nCvv2;

    var $vMM;

    var $vYYYY;



    var $vDD;

    var $vSSN;

    var $vDriverLicenseNumber;

    var $vDriverLicenseState;



    var $nCC_Id;



    var $ENCSEED;



    var $arrBCIDV;





    var $rBank;

    var $nAccountNumber;

    var $txtAccountType;

    var $txtBankName;

    var $txtBankHolderName;



    function __construct($db) {

        $this->dblink	= $db;

        $this->now		= date("Y-m-d");

        $this->arrFile	= array();

        $this->arrExtns	= array("jpg", "jpeg", "gif", "png", "JPG", "JPEG", "GIF", "PNG");

        $this->arrSearch= array();

        $this->ENCSEED	= "32876342347";

    }

function get_values_api($arr=array()) {

        parent::set_values($arr);
        /*$userObj = new users();
        $userObj->set_values($arr);*/
        
        $data = array();
        $arr['vAddress']		= isset($arr['vAddress'])	?	stripslashes(trim($arr['vAddress']))	:	"";

        $arr['vPostCode']	= isset($arr['vPostCode'])	?	stripslashes(trim($arr['vPostCode']))	:	"";

        $arr['vPhone']		= isset($arr['vPhone'])		?	stripslashes(trim($arr['vPhone']))		:	"";

        $arr['nNumber']		= isset($arr['nNumber'])	?	stripslashes(trim($arr['nNumber']))		:	"";

        $arr['nCvv2']		= isset($arr['nCvv2'])		?	stripslashes(trim($arr['nCvv2']))		:	"";

        $arr['vMM']			= isset($arr['vMM'])		?	stripslashes(trim($arr['vMM']))			:	"";

        $arr['vYYYY']		= isset($arr['vYYYY'])		?	stripslashes(trim($arr['vYYYY']))		:	"";

        $arr['nCC_Id']		= isset($arr['nCC_Id'])		?	stripslashes(trim($arr['nCC_Id']))		:	"";



        $arr['vDD']			= isset($arr['vDD'])		?	stripslashes(trim($arr['vDD']))			:	"";

        $arr['vSSN']			= isset($arr['vSSN'])		?	stripslashes(trim($arr['vSSN']))		:	"";

        $arr['vStreet']		= isset($arr['vStreet'])	?	stripslashes(trim($arr['vStreet']))		:	"";
        
        
        $arr['vEducation']		= isset($arr['vEducation'])	?	stripslashes(trim($arr['vEducation']))		:	"";

        $arr['vDriverLicenseNumber']		= isset($arr['vDriverLicenseNumber'])		?

                stripslashes(trim($arr['vDriverLicenseNumber']))		:	"";

        $arr['vDriverLicenseState']		= isset($arr['vDriverLicenseState'])		?

                stripslashes(trim($arr['vDriverLicenseState']))			:	"";



        $arr['rBank']		= isset($arr['rBank'])	? stripslashes(trim($arr['rBank']))			:	"";

        $arr['nAccountNumber']		= isset($arr['nAccountNumber'])	? stripslashes(trim($arr['nAccountNumber']))			:	"";

        $arr['txtAccountType']		= isset($arr['txtAccountType'])	? stripslashes(trim($arr['txtAccountType']))			:	"";

        $arr['txtBankName']		= isset($arr['txtBankName'])		? stripslashes(trim($arr['txtBankName']))			:	"";

        $arr['txtBankHolderName']		= isset($arr['txtBankHolderName']) ? stripslashes(trim($arr['txtBankHolderName']))			:	"";

        return $arr;

    }

    function set_values($arr=array()) {

        parent::set_values($arr);
        // $userObj = new users();
        // $userObj->set_values($arr);

        $this->vAddress		= isset($arr['vAddress'])	?	stripslashes(trim($arr['vAddress']))	:	"";

        $this->vPostCode	= isset($arr['vPostCode'])	?	stripslashes(trim($arr['vPostCode']))	:	"";

        $this->vPhone		= isset($arr['vPhone'])		?	stripslashes(trim($arr['vPhone']))		:	"";

        $this->nNumber		= isset($arr['nNumber'])	?	stripslashes(trim($arr['nNumber']))		:	"";

        $this->vPaymentMethodType		= isset($arr['vPaymentMethodType'])	?	stripslashes(trim($arr['vPaymentMethodType']))		:	"";
        
        $this->nCvv2		= isset($arr['nCvv2'])		?	stripslashes(trim($arr['nCvv2']))		:	"";

        $this->vMM			= isset($arr['vMM'])		?	stripslashes(trim($arr['vMM']))			:	"";

        $this->vYYYY		= isset($arr['vYYYY'])		?	stripslashes(trim($arr['vYYYY']))		:	"";

        $this->nCC_Id		= isset($arr['nCC_Id'])		?	stripslashes(trim($arr['nCC_Id']))		:	"";



        $this->vDD			= isset($arr['vDD'])		?	stripslashes(trim($arr['vDD']))			:	"";

        $this->vSSN			= isset($arr['vSSN'])		?	stripslashes(trim($arr['vSSN']))		:	"";

        $this->vStreet		= isset($arr['vStreet'])	?	stripslashes(trim($arr['vStreet']))		:	"";

        $this->vDriverLicenseNumber		= isset($arr['vDriverLicenseNumber'])		?

                stripslashes(trim($arr['vDriverLicenseNumber']))		:	"";

        $this->vDriverLicenseState		= isset($arr['vDriverLicenseState'])		?

                stripslashes(trim($arr['vDriverLicenseState']))			:	"";



        $this->rBank		= isset($arr['rBank'])	? stripslashes(trim($arr['rBank']))			:	"";

        $this->nAccountNumber		= isset($arr['nAccountNumber'])	? stripslashes(trim($arr['nAccountNumber']))			:	"";

        $this->txtAccountType		= isset($arr['txtAccountType'])	? stripslashes(trim($arr['txtAccountType']))			:	"";

        $this->txtBankName		= isset($arr['txtBankName'])		? stripslashes(trim($arr['txtBankName']))			:	"";

        $this->txtBankHolderName		= isset($arr['txtBankHolderName']) ? stripslashes(trim($arr['txtBankHolderName']))			:	"";



    }



    function idverification_form_check($arr=array()) {

        $this->set_values($arr);

        $message		= "";

        $script			= "";

        $arrElements	= array();

        $_SESSION['idverify']	= "";



        if ($this->vFirstName == "") {

            $message	.= "Please enter your first name.<br>";

            $arrElements[]	= "vFirstName";

        }

        if ($this->vLastName == "") {

            $message	.= "Please enter your last name.<br>";

            $arrElements[]	= "vLastName";

        }

        if ($this->vSSN == "") {

            $message	.= "Please enter your SSN number.<br>";

            $arrElements[]	= "vSSN";

        }

        if ($this->vDD == "") {

            $message	.= "Please enter 'day' in your date of birth.<br>";

            $arrElements[]	= "vDD";

        }

        if ($this->vMM == "") {

            $message	.= "Please enter 'month' in your date of birth.<br>";

            $arrElements[]	= "vMM";

        }

        if ($this->vYYYY == "") {

            $message	.= "Please enter 'year' in your date of birth.<br>";

            $arrElements[]	= "vYYYY";

        }

        if ($this->vDriverLicenseNumber == "") {

            $message	.= "Please enter your driver license number.<br>";

            $arrElements[]	= "vDriverLicenseNumber";

        }

        if ($this->vDriverLicenseState == "") {

            $message	.= "Please enter your driver license state.<br>";

            $arrElements[]	= "vDriverLicenseState";

        }

        if ($this->vStreet == "") {

            $message	.= "Please enter your street address.<br>";

            $arrElements[]	= "vStreet";

        }

        if ($this->vCity == "") {

            $message	.= "Please enter your city.<br>";

            $arrElements[]	= "vCity";

        }

        if ($this->vState == "") {

            $message	.= "Please enter your state.<br>";

            $arrElements[]	= "vState";

        }

        if ($this->vPostCode == "") {

            $message	.= "Please enter your zip code.<br>";

            $arrElements[]	= "vPostCode";

        }

        if ($this->vPhone == "") {

            $message	.= "Please enter your phone number.<br>";

            $arrElements[]	= "vPhone";

        }



        if (!empty($arrElements)) {

            $script	= '<script language="javascript">';

            foreach ($arrElements as $key=>$value) {

                $script	.= 'document.frmTell.'.$value.'.className = "errorinput";';

            }

            $script	.= '</script>';

        } else {

            $_SESSION['idverify']	= $arr;

        }



        $message	.= $script;

        return $message;



    }



    function backgroundcheck_form_check($arr=array()) {

        $this->set_values($arr);

        $message		= "";

        $script			= "";

        $arrElements	= array();

        $_SESSION['idverify']	= "";



        if ($this->vFirstName == "") {

            $message	.= "Please enter your first name.<br>";

            $arrElements[]	= "vFirstName";

        }

        if ($this->vLastName == "") {

            $message	.= "Please enter your last name.<br>";

            $arrElements[]	= "vLastName";

        }

        /*if ($this->vSSN == "") {

            $message	.= "Please enter your SSN number.<br>";

            $arrElements[]	= "vSSN";

        }*/

        if ($this->vDD == "") {

            $message	.= "Please enter 'day' in your date of birth.<br>";

            $arrElements[]	= "vDD";

        }

        if ($this->vMM == "") {

            $message	.= "Please enter 'month' in your date of birth.<br>";

            $arrElements[]	= "vMM";

        }

        if ($this->vYYYY == "") {

            $message	.= "Please enter 'year' in your date of birth.<br>";

            $arrElements[]	= "vYYYY";

        }
        
        if(!checkdate($this->vMM, $this->vDD, $this->vYYYY))
        {
            $message	.= "Please enter a valid date of birth.<br>";
        }

        if ($this->vStreet == "") {

            $message	.= "Please enter your street address.<br>";

            $arrElements[]	= "vStreet";

        }

        if ($this->vCity == "") {

            $message	.= "Please enter your city.<br>";

            $arrElements[]	= "vCity";

        }

        if ($this->vState == "") {

            $message	.= "Please enter your state.<br>";

            $arrElements[]	= "vState";

        }

        if ($this->vPostCode == "") {

            $message	.= "Please enter your zip code.<br>";

            $arrElements[]	= "vPostCode";

        }

        if ($this->vPhone == "") {

            $message	.= "Please enter your phone number.<br>";

            $arrElements[]	= "vPhone";

        }



        if (!empty($arrElements)) {

            $script	= '<script language="javascript">';

            foreach ($arrElements as $key=>$value) {

                $script	.= 'document.frmTell.'.$value.'.className = "errorinput";';

            }

            $script	.= '</script>';

        } else {

            $_SESSION['idverify']	= $arr;

        }



        $message	.= $script;

        return $message;



    }



    //function for disply site securl url from ".TABLEPREFIX."lookup

    function SecureUrl() {
        if(ISCRIPTSCLOUD) {
            if (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off' || $_SERVER['SERVER_PORT'] == 443) {
                return "https://".$_SERVER['HTTP_HOST'];
            }
            else {
                return "http://".$_SERVER['HTTP_HOST'];
            }

        }
        $sql=mysql_query("select vValue from ".TABLEPREFIX."lookup where vName='site_secure_url'") or die(mysql_error());

        if(mysql_num_rows($sql)>0) {

            return (mysql_result($sql,0,'vValue'));

        }//end if



    }//end funciton



    //function for disply site securl url from ".TABLEPREFIX."lookup

    function SiteUrl() {

        if(ISCRIPTSCLOUD) {
            if (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off' || $_SERVER['SERVER_PORT'] == 443) {
                return "https://".$_SERVER['HTTP_HOST'];
            }
            else {
                return "http://".$_SERVER['HTTP_HOST'];
            }

        }

        $sql=mysql_query("select vValue from ".TABLEPREFIX."lookup where vName='site_normal_url'") or die(mysql_error());

        if(mysql_num_rows($sql)>0) {

            return (mysql_result($sql,0,'vValue'));

        }//end if

    }//end funciton



    function set_BCIDV($arr=array()) {

        $this->arrBCIDV	= $arr;

    }



    function background_check() {

        $string		= "";

        $passed		= "NO";

        $msg		= "Invalid input parameters";

        $qtyFound	= 0;

        $qtyReturn	= 0;



        $arr		= $this->arrBCIDV;

        $bgc_url	 ='https://model.backgroundchecks.com/integration/bgcdirectpost.aspx';



        require_once "settings.class.php";

        //$arrSet		= settings::select();
        $settingsObj = new settings();
        $arrSet	= $settingsObj->select();

        $user		= $arrSet['bc_user'];

        $pass		= $arrSet['bc_password'];

        $account	= $arrSet['bc_account'];

        $firstName	= addslashes($arr['vFirstName']);

        $middleName	= addslashes($arr['vMiddleName']);

        $lastName	= addslashes($arr['vLastName']);

        $suffixCode	= "";

        $ssn		= addslashes($arr['vSSN']);

        $month		= addslashes($arr['vMM']);

        $day		= addslashes($arr['vDD']);

        $year		= addslashes($arr['vYYYY']);

        $street		= addslashes($arr['vStreet']);

        $city		= addslashes($arr['vCity']);

        $state		= addslashes($arr['vState']);

        $postalCode			= addslashes($arr['vPostCode']);

        $telephoneNumber	= addslashes($arr['vPhone']);

        /********************************************************************/
        // For Backgroud Search two products are used                       ||
        // #1 UsOneSearchWithValidation - for Backgroud Search with SSN     ||
        // #2 USOneSearch - for Backgroud Search without SSN                ||
        // Trurn on and off the conditions according to your needs          ||
        /********************************************************************/
        
        if (!empty($ssn)) { // If SSN is there
         
            $xmlrequest = '<BGC version="3.4">
                            <login>
                                <user>'.$user.'</user>
                                <password>'.$pass.'</password>
                                <account>'.$account.'</account>
                            </login>
                            <product>
                                <UsOneSearchWithValidation version="1">
                                    <initiate>
                                        <order>
                                            <firstName>'.$firstName.'</firstName>
                                            <middleName />
                                            <lastName>'.$lastName.'</lastName>
                                            <SSN>'.$ssn.'</SSN>
                                            <DOB>
                                                <month>'.$month.'</month>
                                                <day>'.$day.'</day>
                                                <year>'.$year.'</year>
                                            </DOB>
                                        </order>
                                        <custom>
                                            <options />
                                        </custom>
                                    </initiate>
                                </UsOneSearchWithValidation>
                            </product>
                        </BGC>';

            //separate the request URL and parameters into separate variables

            //initialize curl session $session = curl_init($request);

            $ch = curl_init();

            //set curl options to set to use https post point to url

            curl_setopt($ch, CURLOPT_URL, $bgc_url);

            curl_setopt($ch, CURLOPT_POST, TRUE);

            //specify which fields to post



            curl_setopt($ch, CURLOPT_POSTFIELDS, $xmlrequest);

            curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);



            /*//for goddady server

		curl_setopt ($ch, CURLOPT_HTTPPROXYTUNNEL, TRUE);

		curl_setopt ($ch, CURLOPT_PROXYTYPE, CURLPROXY_HTTP);

		curl_setopt ($ch, CURLOPT_PROXY,"http://proxy.shr.secureserver.net:3128");

		//for goddady server*/



            //set authentication and security

            curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);

            curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);

            curl_setopt($ch, CURLOPT_TIMEOUT, CURL_TIMEOUT);

            //run the curl_exec to execute the post $response = curl_exec($session);

            $xml_report = curl_exec ($ch);

            //close curl resource and free up resources

            curl_close ($ch);


            $xml_report = preg_replace("/<form[^~]*<\/form>/","", $xml_report,1);

            $xml_report = preg_replace("/<script>[^~]*<\/script>/","", $xml_report,1);



            $xml	= $this->get_sub_string("<response>", "</response>", $xml_report);

            $passed = $msg = NULL;

            if ($xml <> "") {

                $xml_report	= $xml;

                $passed		= strip_tags($this->get_sub_string("<successful>", "</successful>", $xml_report));

                
            } else {

                $msg		= strip_tags($this->get_sub_string("<warnings>", "</warnings>", $xml_report));

                $msg		.= strip_tags($this->get_sub_string("<errors>", "</errors>", $xml_report));

            }
  

        } else { // If SSN is not
           
            $xmlrequest ='<BGC version="3.4">
                            <login>
                                    <user>'.$user.'</user>
                                    <password>'.$pass.'</password>
                                    <account>'.$account.'</account>
                            </login>
                            <product>
                                    <USOneSearch version="1">
                                            <order>
                                                    <firstName>'.$firstName.'</firstName>
                                                    <middleName>'.$middleName.'</middleName>
                                                    <lastName>'.$lastName.'</lastName>
                                                    <DOB>
                                                            <month>'.$month.'</month>
                                                            <day>'.$day.'</day>
                                                            <year>'.$year.'</year>
                                                    </DOB>
                                            </order>
                                            <custom>
                                                    <options>
                                                            <includeDetails>YES</includeDetails>
                                                    </options>
                                                    <filters/>
                                            </custom>
                                    </USOneSearch>
                            </product>
                    </BGC>';

            //separate the request URL and parameters into separate variables

            //initialize curl session $session = curl_init($request);

            $ch = curl_init();

            //set curl options to set to use https post point to url

            curl_setopt($ch, CURLOPT_URL, $bgc_url);

            curl_setopt($ch, CURLOPT_POST, TRUE);

            //specify which fields to post



            curl_setopt($ch, CURLOPT_POSTFIELDS, $xmlrequest);

            curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);



            /*//for goddady server

		curl_setopt ($ch, CURLOPT_HTTPPROXYTUNNEL, TRUE);

		curl_setopt ($ch, CURLOPT_PROXYTYPE, CURLPROXY_HTTP);

		curl_setopt ($ch, CURLOPT_PROXY,"http://proxy.shr.secureserver.net:3128");

		//for goddady server*/



            //set authentication and security

            curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);

            curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);

            curl_setopt($ch, CURLOPT_TIMEOUT, CURL_TIMEOUT);

            //run the curl_exec to execute the post $response = curl_exec($session);

            $xml_report = curl_exec ($ch);

            //close curl resource and free up resources

            curl_close ($ch);

           
            $xml_report = preg_replace("/<form[^~]*<\/form>/","", $xml_report,1);

            $xml_report = preg_replace("/<script>[^~]*<\/script>/","", $xml_report,1);
            
            $xml	= $this->get_sub_string("<response>", "</response>", $xml_report);

            $passed = $msg = NULL;

            if ($xml <> "") {

                $xml_report	= $xml;
                

                /* $qtyFound	= $this->get_sub_string("qtyFound=\"", "\"", $xml_report);

                $qtyReturn	= $this->get_sub_string("qtyReturned=\"", "\"", $xml_report); */

                $qtyFound	= $this->getBCKSUserCrimianalCount('qtyFound="', '" qtyReturned', $xml_report);

		$qtyReturn	= $this->getBCKSUserCrimianalCount('qtyReturned="', '" /></detail', $xml_report);

                if ($qtyFound == 0 && trim($qtyFound) != "" ){
				$passed	= "YES";
                } else {
				$passed	= "NO";
                }


            } else {

                $msg		= strip_tags($this->get_sub_string("<warnings>", "</warnings>", $xml_report));

                $msg		.= strip_tags($this->get_sub_string("<errors>", "</errors>", $xml_report));

            }



        }
        
        
        return array("passed" => $passed, "msg" => $msg);

    }

    function getBCKSUserCrimianalCount($from="", $to="", $string=""){
                $pos	= strpos($string, $from);
                    if ($pos === false) {
                            $return	= " ";
                    } else {
                       $string = substr($string, $pos , strlen($string));
                       $string = str_replace($from, '', $string);
                        $pos1	= strpos($string, $to);
                            if ($pos1 === false) {
                                    $return	= " ";
                            } else {
                               return  substr($string, 0, $pos1);
                            }
                    }
                    return $return;
    }

    function id_find() {

        $string		= "";

        $arr		= $this->arrBCIDV;

        $bgc_url	 ='https://model.backgroundchecks.com/integration/bgcdirectpost.aspx';



        require_once "settings.class.php";

        //$arrSet		= settings::select();
        $settingsObj = new settings();
        $arrSet	= $settingsObj->select();

        $user		= $arrSet['bc_user'];

        $pass		= $arrSet['bc_password'];

        $account	= $arrSet['bc_account'];



        $firstName	= addslashes($arr['vFirstName']);

        $middleName	= addslashes($arr['vMiddleName']);

        $lastName	= addslashes($arr['vLastName']);

        $suffixCode	= "";

        $ssn		= addslashes($arr['vSSN']);

        $month		= addslashes($arr['vMM']);

        $day		= addslashes($arr['vDD']);

        $year		= addslashes($arr['vYYYY']);

        $driverLicenseNumber	= addslashes($arr['vDriverLicenseNumber']);

        $driverLicenseState		= addslashes($arr['vDriverLicenseState']);

        $street		= addslashes($arr['vStreet']);

        $city		= addslashes($arr['vCity']);

        $state		= addslashes($arr['vState']);

        $postalCode			= addslashes($arr['vPostCode']);

        $telephoneNumber	= addslashes($arr['vPhone']);



        $xmlrequest = '<?xml version="1.0" encoding="us-ascii" standalone="yes"?>

		<BGC version ="1.88">

		<login>

			<user>'.$user.'</user>

			<password>'.$pass.'</password>

			<account>'.$account.'</account>

		</login>

		<product>

			<ID-Find version="1">

				<order>

					<firstName>'.$firstName.'</firstName>

					<middleName>'.$middleName.'</middleName>

					<lastName>'.$lastName.'</lastName>

					<suffixCode>'.$suffixCode.'</suffixCode>

					<ssn>'.$ssn.'</ssn>

					<DOB>

						<month>'.$month.'</month>

						<day>'.$day.'</day>

						<year>'.$year.'</year>

					</DOB>

					<driverLicenseNumber>'.$driverLicenseNumber.'</driverLicenseNumber>

					<driverLicenseState>'.$driverLicenseState.'</driverLicenseState>

					<currentAddress>

						<street>'.$street.'</street>

						<city>'.$city.'</city>

						<state>'.$state.'</state>

						<postalCode>'.$postalCode.'</postalCode>

					</currentAddress>

					<telephoneNumber>'.$telephoneNumber.'</telephoneNumber>

				</order>

			</ID-Find>

		</product>

		</BGC>';

        //separate the request URL and parameters into separate variables

        //initialize curl session $session = curl_init($request);

        $ch = curl_init();

        //set curl options to set to use https post point to url

        curl_setopt($ch, CURLOPT_URL, $bgc_url);

        curl_setopt($ch, CURLOPT_POST, TRUE);

        //specify which fields to post

        curl_setopt($ch, CURLOPT_POSTFIELDS, $xmlrequest);

        curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);



        /*//for goddady server

		curl_setopt ($ch, CURLOPT_HTTPPROXYTUNNEL, TRUE);

		curl_setopt ($ch, CURLOPT_PROXYTYPE, CURLPROXY_HTTP);

		curl_setopt ($ch, CURLOPT_PROXY,"http://proxy.shr.secureserver.net:3128");

		//for goddady server*/



        //set authentication and security

        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);

        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);

        curl_setopt($ch, CURLOPT_TIMEOUT, CURL_TIMEOUT);

        //run the curl_exec to execute the post $response = curl_exec($session);

        $xml_report = curl_exec ($ch);

        //close curl resource and free up resources

        curl_close ($ch);



        $xml_report = preg_replace("/<form[^~]*<\/form>/","", $xml_report,1);

        $xml_report = preg_replace("/<script>[^~]*<\/script>/","", $xml_report,1);



        $score		= $this->get_sub_string("<score>", "</score>", $xml_report);

        $passed		= $this->get_sub_string("<passed>", "</passed>", $xml_report);

        $msg		= strip_tags($this->get_sub_string("<warnings>", "</warnings>", $xml_report));

        $msg		.= strip_tags($this->get_sub_string("<errors>", "</errors>", $xml_report));

        if ($score == "") $score = "0";

        if ($passed == "") $passed = "NO";

        return array("score" => $score, "passed" => $passed, "msg" => $msg);

    }



    function get_latest_id_find($id=0) {

        $array	= array();

        $sql	= "SELECT *,DATE_FORMAT(dDate, '%D %M %Y') as dDay

				   FROM ".TABLEPREFIX."background_check

				   WHERE nUser_Id = '{$id}' AND vType = 'ID'

				   ORDER BY nBC_Id DESC";

        $res	= @mysql_query($sql, $this->dblink);

        if (@mysql_num_rows($res) > 0) {

            $array	= @mysql_fetch_array($res);

        }

        @mysql_free_result($res);

        return $array;

    }



    function get_latest_backgroundcheck($id=0) {

        $array	= array();

        $sql	= "SELECT *,DATE_FORMAT(dDate, '%D %M %Y') as dDay

				   FROM ".TABLEPREFIX."background_check

				   WHERE nUser_Id = '{$id}' AND vType = 'BC'

				   ORDER BY nBC_Id DESC";

        $res	= @mysql_query($sql, $this->dblink);

        if (@mysql_num_rows($res) > 0) {

            $array	= @mysql_fetch_array($res);

        }

        @mysql_free_result($res);

        return $array;

    }



    function select($id=0) {

        $array	= array();

        $sql	= "SELECT * FROM ".TABLEPREFIX."user WHERE nUser_Id = '{$id}'";

        $res	= @mysql_query($sql, $this->dblink);

        if (@mysql_num_rows($res) > 0) {

            $array = @mysql_fetch_assoc($res);

        }

        @mysql_free_result($res);

        return $array;

    }



    function selectpartner($id=0) {

        $array	= array();

        $sql	= "SELECT * FROM ".TABLEPREFIX."partner_preferance WHERE nUser_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 getuser($id=0) {

        $array	= array();

        $sql	= "SELECT *,TRUNCATE((TO_DAYS(NOW()) - TO_DAYS(dDob))/365, 0) as Age

				   FROM ".TABLEPREFIX."user

		           WHERE nUser_Id = '{$id}' AND vStatus NOT LIKE 'D%'";

        $res	= @mysql_query($sql, $this->dblink);

        if (@mysql_num_rows($res) > 0) {

            $array	= @mysql_fetch_array($res);

        }

        return $array;

    }



    function check_username_available($login="") {

        $flag	= false;

        $sql	= "SELECT * FROM ".TABLEPREFIX."user

				   WHERE vLogin LIKE '".addslashes($login)."' ";

        $res	= @mysql_query($sql, $this->dblink);


        if (@mysql_num_rows($res) > 0) {

            $flag	= true;

        }

        return $flag;

    }



    function register_step_one() {

        $message		= "";

        $script			= "";

        $arrElements	= array();
        
        if ($this->vLogin == "") {

            $message	.= "Please enter your username.<br>";

            $arrElements[]	= "vLogin";

        }

        if (!$this->check_username($this->vLogin)) {

//			$message	.= "Only following characters allowed in username ([a-z][A-Z][0-9].-_).<br>";

            $message	.= "Please enter a valid username.<br>";

            if (!in_array("vLogin", $arrElements))

                $arrElements[]	= "vLogin";

        }
        
        if ($this->username_existance($id)) {

            $message	.= "Same username already exists.<br>";

            if (!in_array("vLogin", $arrElements))

                $arrElements[]	= "vLogin";

        }

        if ($this->vPass == "") {

            $message	.= "Please enter password for the user.<br>";

            $arrElements[]	= "vPass";

        }

        if (!$this->check_email($this->vEmail)) {

            $message	.= "Please enter a valid email address.<br>";

            $arrElements[]	= "vEmail";

        }


 if ($this->check_email_available($this->vEmail,$id)) {

//			$message	.= "Only following characters allowed in username ([a-z][A-Z][0-9].-_).<br>";

            $message	.= "This Email is already in use.<br>";

            if (!in_array("vEmail", $arrElements))

                $arrElements[]	= "vEmail";

        }


        /*if ($this->vCounty == "") {

			$message	.= "Please select your county.<br>";

			$arrElements[]	= "vCounty";

		}*/



        if ($message == "") {

            //$arrDob=explode("-",$this->dDob);
//                    $arrDob=explode("/",$this->dDob);
//
//			list($month,$date,$year)=$arrDob;
//
//			$dob=$year."-".$month."-".$date;
//
//			$_SESSION['sess_echeck_dob']=$this->dDob;

            $sql	= "INSERT INTO ".TABLEPREFIX."user (vLogin, vPass, vEmail, vGender, dDob,

								vCountry, vState, vCity, vStatus, vHearing_Source,

								vBilling, dActive_Date, dLast_Login, dLast_Login_Time, vCounty)

					   VALUES ('".addslashes($this->vLogin)."', '".md5(addslashes($this->vPass))."',

							'".addslashes($this->vEmail)."', '".addslashes($this->vGender)."',

							'".addslashes($dob)."', '".addslashes($this->vCountry)."', 

							'".addslashes($this->vState)."', '".addslashes($this->vCity)."', 

							'ANNN', '".addslashes($this->vHearing_Source)."',

							'".addslashes($this->vBilling)."',

							'".addslashes($this->dActive_Date)."',

							'".addslashes($this->dLast_Login)."',

							'".addslashes($this->dLast_Login_Time)."',

							'".addslashes($this->vCounty)."')";
       
            $res	= @mysql_query($sql, $this->dblink);

            if (!$res) {

                $message	.= "Sorry, unable to register your account, please try later.<br>";

            } else {

                $_SESSION['register_id']	= @mysql_insert_id($this->dblink);

                $this->set_user_alert();

                $this->insert_user_alerts($_SESSION['register_id']);

            }

        } else {

            if (!empty($arrElements)) {

                $script	= '<script language="javascript">';

                foreach ($arrElements as $key=>$value) {

                    $script	.= 'document.frmStep1.'.$value.'.className = "textbox";';

                }

                $script	.= '</script>';

            }

        }

        $message	.= $script;

        return $message;

    }

    function register_step_facebook() {
       $objM		= new misc($objDB);
        $return = array();
        
        $message		= "";

        $script			= "";

        $arrElements	= array();
        
        if ($this->vLogin == "") {

            $message	.= "Please enter your username";

            $arrElements[]	= "vLogin";

        }

        if (!$this->check_username($this->vLogin)) {

//			$message	.= "Only following characters allowed in username ([a-z][A-Z][0-9].-_).<br>";

            $message	.= "Please enter a valid username";

            if (!in_array("vLogin", $arrElements))

                $arrElements[]	= "vLogin";

        }
        
        if ($this->username_existance($id)) {

            $message	.= "Same username already exists";

            if (!in_array("vLogin", $arrElements))

                $arrElements[]	= "vLogin";

        }

        if ($this->vPass == "") {

            $message	.= "Please enter password for the user";

            $arrElements[]	= "vPass";

        }

        if (!$this->check_email($this->vEmail)) {

            $message	.= "Please enter a valid email address";

            $arrElements[]	= "vEmail";

        }


 if ($this->check_email_available($this->vEmail,$id)) {

//			$message	.= "Only following characters allowed in username ([a-z][A-Z][0-9].-_).<br>";

            $message	.= "This Email is already in use.<br>";

            if (!in_array("vEmail", $arrElements))

                $arrElements[]	= "vEmail";

        }


        /*if ($this->vCounty == "") {

			$message	.= "Please select your county.<br>";

			$arrElements[]	= "vCounty";

		}*/



        if ($message == "") {

            //$arrDob=explode("-",$this->dDob);
//                    $arrDob=explode("/",$this->dDob);
//
//			list($month,$date,$year)=$arrDob;
//
//			$dob=$year."-".$month."-".$date;
//
//			$_SESSION['sess_echeck_dob']=$this->dDob;

            $sql	= "INSERT INTO ".TABLEPREFIX."user (vLogin, vPass,vFirstName,vLastName, vEmail, vGender, dDob,vTitle,

								vCountry, vState, vCity, vStatus, vHearing_Source,

								vBilling, dActive_Date, dLast_Login, dLast_Login_Time, vCounty,fbId)

					   VALUES ('".addslashes($this->vLogin)."', '".md5(addslashes($this->vPass))."',

							'".addslashes($this->vFirstName)."','".addslashes($this->vLastName)."','".addslashes($this->vEmail)."', '".addslashes($this->vGender)."',

							'".addslashes($this->dDob)."', '".  addslashes($this->vTitle)."','".addslashes($this->vCountry)."', 

							'".addslashes($this->vState)."', '".addslashes($this->vCity)."', 

							'ANNN', '".addslashes($this->vHearing_Source)."',

							'".addslashes($this->vBilling)."',

							'".addslashes($this->dActive_Date)."',

							'".addslashes($this->dLast_Login)."',

							'".addslashes($this->dLast_Login_Time)."',

							'".addslashes($this->vCounty)."',
                                                            '".addslashes($this->fbId)."')";
            
          
         
       
            $res	= @mysql_query($sql);

            if (!$res) {

                $message	.= "Sorry, unable to register your account, please try later.<br>";

            } else {

                $return['user_id']	= @mysql_insert_id();

                $this->set_user_alert();
                $this->insert_user_alerts($return['user_id']);
                
                $objM->loggedin($return['user_id']);
					$objM->set_user_ip($return['user_id'], $_SERVER['REMOTE_ADDR']);

            }

        } else {

            if (!empty($arrElements)) {

                $script	= '<script language="javascript">';

                foreach ($arrElements as $key=>$value) {

                    $script	.= 'document.frmStep1.'.$value.'.className = "textbox";';

                }

                $script	.= '</script>';

            }

        }

        $message	.= $script;
        $return['message'] = $message;
        return $return;

    } 
    
    
function dbRowInsert($table,$form_data)
{
    // retrieve the keys of the array (column titles)
    $fields = array_keys($form_data);

    // build the query
    $sql = "INSERT INTO ".TABLEPREFIX.$table."
    (`".implode('`,`', $fields)."`)
    VALUES('".implode("','", $form_data)."')";

    // run and return the query result resource
    mysql_query($sql,$this->dblink);
    return @mysql_insert_id($this->dblink);
    
}

    function update_primaries($id=0) {

        $message		= "";

        $script			= "";

        $arrElements	= array();

        if (!$this->check_date($this->dDob)) {

            $message	.= "Please enter a valid date of birth.<br>";

            $arrElements[]	= "dDob";

        }

        /*if ($this->vCounty == "") {

			$message	.= "Please select your county.<br>";

			$arrElements[]	= "vCounty";

		}*/



        if ($message == "") {

            //$arrDob=explode("-",$this->dDob);
            $arrDob=explode("/",$this->dDob);

            list($month,$date,$year)=$arrDob;

            $dob=$year."-".$month."-".$date;

            $sql	= "UPDATE ".TABLEPREFIX."user

					   SET dDob = '".addslashes($dob)."',

							vCountry = '".addslashes($this->vCountry)."',

							vState = '".addslashes($this->vState)."',

							vCounty = '".addslashes($this->vCounty)."', 

							vCity = '".addslashes($this->vCity)."',

							vProfileType = '".addslashes($this->vProfileType)."' 

						WHERE nUser_Id = '{$id}'";

//echo $sql;

            $res	= @mysql_query($sql, $this->dblink);

            if (!$res) {

                $message	.= "Sorry, unable to register your account, please try later.<br>";

            }
            else {
                $message	.= "<font color='green'>Your profile has been successfully updated.</font><br>";
            }

        } else {

            if (!empty($arrElements)) {

                $script	= '<script language="javascript">';

                foreach ($arrElements as $key=>$value) {

                    $script	.= 'document.frmStep1.'.$value.'.className = "errorinput";';

                }

                $script	.= '</script>';

            }

        }

        $message	.= $script;

        return $message;



    }



    function register_step_two($id=0) {

        $message		= "";

        $script			= "";

        $arrElements	= array();



        if ($this->vTitle == "") {

            $message	.= "Please enter title for your profile.<br>";

            $arrElements[]	= "vTitle";

        }



        if ($this->vFirstName == "") {

            $message	.= "Please enter your first name.<br>";

            $arrElements[]	= "vFirstName";

        }

        if ($this->vLastName == "") {

            $message	.= "Please enter your last name.<br>";

            $arrElements[]	= "vLastName";

        }

        if($id > 0) {

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

            }
        }

        if ($this->vMobile <> "") {

            if (!$this->check_numerals($this->vMobile)) {

                $message	.= "Only numerals are allowed in mobile number (prefix your country code too).<br>";

                $arrElements[]	= "vMobile";

            }

            if ($this->vProvider == "") {

                $message	.= "Please select your mobile sevice provider too.<br>";

                $arrElements[]	= "vProvider";

            }



        }



        if ($message == "") { 
            $arrDob=explode("/",$this->dDob);

            list($month,$date,$year)=$arrDob; 

            $dob=$year."-".$month."-".$date; 

            $_SESSION['sess_echeck_dob']=$this->dDob;

            $sql	= "UPDATE ".TABLEPREFIX."user

					   SET vTitle = '".addslashes($this->vTitle)."',

					   	   vFirstName = '".addslashes($this->vFirstName)."',

					       vMiddleName = '".addslashes($this->vMiddleName)."',

						   vLastName = '".addslashes($this->vLastName)."',
                                                   dDob ='".addslashes($dob)."',    

						   vProvider = '".addslashes($this->vProvider)."',
 
                                                   vDate_Preference = '".addslashes($this->vDate_Preference)."',


   						   vRealtion_Status = '".addslashes($this->vRealtion_Status)."',

						   vAstro_Sign = '".addslashes($this->vAstro_Sign)."',

						   nHeight = '".addslashes($this->nHeight)."',

						   vBody_Type = '".addslashes($this->vBody_Type)."',

						   vMobile = '".addslashes($this->vMobile)."',

						   vSmoking = '".addslashes($this->vSmoking)."',

						   vDrinking = '".addslashes($this->vDrinking)."',

						   nChildren = '".addslashes($this->nChildren)."',

						   vEthinicity = '".addslashes($this->vEthinicity)."',

						   vReligion = '".addslashes($this->vReligion)."',

						   vEducation = '".addslashes($this->vEducation)."'

					   WHERE nUser_Id = '{$id}'";

            $res	= @mysql_query($sql, $this->dblink);

            if (!$res) {

                $message	.= "Sorry, unable to register your account, please try later.<br>";

            }
            $_SESSION['user_name']		= $this->vFirstName." ".$this->vMiddleName." ".$this->vLastName;
        } else {

            if (!empty($arrElements)) {

                $script	= '<script language="javascript">';

                foreach ($arrElements as $key=>$value) {

                    $script	.= 'document.frmStep2.'.$value.'.className = "textbox";';

                }

                $script	.= '</script>';

            }

        }

        $message	.= $script;

        return $message;

    }

    function edit_personal_info_api($id=0) {

        $message		= "";               
        if ($this->vFirstName == "") {
            $message	.= "Please enter your first name.<br>";
        }
        if ($this->vLastName == "") {
            $message	.= "Please enter your last name.<br>";
        }     
        if ($this->vMobile <> "") {
            if (!$this->check_numerals($this->vMobile)) {
                $message	.= "Only numerals are allowed in mobile number (prefix your country code too).<br>";
            }
            if ($this->vProvider == "") {
                $message	.= "Please select your mobile sevice provider too.<br>";
            }
        }
        if ($message == "") { 
            $sql	= "UPDATE ".TABLEPREFIX."user
					   SET vFirstName = '".addslashes($this->vFirstName)."',
					           vMiddleName = '".addslashes($this->vMiddleName)."',
						   vLastName = '".addslashes($this->vLastName)."',                                                       
						   vProvider = '".addslashes($this->vProvider)."',   						   
						   vMobile = '".addslashes($this->vMobile)."',
                                                   vEducation = '".addslashes($this->vEducation)."'    
                                            WHERE nUser_Id = '{$id}'";
            $res	= @mysql_query($sql, $this->dblink);
            if (!$res) {
                $message	.= "Sorry, unable to edit your personal details, please try later.<br>";
            }
            $_SESSION['user_name']		= $this->vFirstName." ".$this->vMiddleName." ".$this->vLastName;
        }                 
        return $message;
    }
    
    function edit_basic_info_api($id=0) {

        $message		= "";        
        if ($this->vTitle == "") {

            $message	.= "Please enter title for your profile.<br>";           
        }        
        if ($message == "") { 
            $sql	= "UPDATE ".TABLEPREFIX."user
					   SET vTitle = '".addslashes($this->vTitle)."',					   	  
   						   vRealtion_Status = '".addslashes($this->vRealtion_Status)."',
						   vAstro_Sign = '".addslashes($this->vAstro_Sign)."',
						   nHeight = '".addslashes($this->nHeight)."',
						   vBody_Type = '".addslashes($this->vBody_Type)."',						   
						   vSmoking = '".addslashes($this->vSmoking)."',
						   vDrinking = '".addslashes($this->vDrinking)."',
						   nChildren = '".addslashes($this->nChildren)."',
						   vEthinicity = '".addslashes($this->vEthinicity)."',
						   vReligion = '".addslashes($this->vReligion)."'
					   WHERE nUser_Id = '{$id}'";
            $res	= @mysql_query($sql, $this->dblink);
            if (!$res) {
                $message	.= "Sorry, unable to edit your basic details, please try later.<br>";
            }            
        }                 
        return $message;
    }
    
    function edit_appearence_info_api($id=0) {

        $message		= "";                   
        if ($message == "") { 
           $sql	= "UPDATE ".TABLEPREFIX."user
				   SET tmy_looks_today = '".addslashes($this->tmy_looks_today)."',
					   tmy_likes_onanyday = '".addslashes($this->tmy_likes_onanyday)."',
					   tmy_dislikes_onanyday = '".addslashes($this->tmy_dislikes_onanyday)."',
					   tmy_mood_today = '".addslashes($this->tmy_mood_today)."',
					   tmy_personality = '".addslashes($this->tmy_personality)."'
				   WHERE nUser_Id = '{$id}'";
            $res	= @mysql_query($sql, $this->dblink);
            if (!$res) {
                $message	.= "Sorry, unable to edit your appearence details, please try later.<br>";
            }            
        }                 
        return $message;
    }

    function register_step_three($id=0) {

        $message		= "";

        $sql	= "UPDATE ".TABLEPREFIX."user

				   SET tmy_looks_today = '".addslashes($this->tmy_looks_today)."',

					   tmy_likes_onanyday = '".addslashes($this->tmy_likes_onanyday)."',

					   tmy_dislikes_onanyday = '".addslashes($this->tmy_dislikes_onanyday)."',

					   tmy_mood_today = '".addslashes($this->tmy_mood_today)."',

					   tmy_personality = '".addslashes($this->tmy_personality)."'

				   WHERE nUser_Id = '{$id}'";



        $res	= @mysql_query($sql, $this->dblink);

        if (!$res) {

            $message	.= "Sorry, we were unable to register your account at this time, please try again later.<br>";

        }

        return $message;

    }



    function register_step_four($id=0) {

        $message		= "";

        $script			= "";

        $arrElements	= array();



        if ($this->tmy_doings_on_major_world_issue <> "" AND $this->tmy_major_world_issue == "") {

            $message	.= "Please enter your response to the profile question 'Of the major issues in the world, which ones are you the most passionate about?' before entering your response to the profile question 'What are you are doing about it?'.<br>";

            $arrElements[]	= "tmy_major_world_issue";

        }

        $sql	= "UPDATE ".TABLEPREFIX."user

				   SET  tmy_music = '".addslashes($this->tmy_music)."',

						tmy_movies = '".addslashes($this->tmy_movies)."',

						tmy_tv = '".addslashes($this->tmy_tv)."',

						tmy_sports_play = '".addslashes($this->tmy_sports_play)."',

						tmy_sports_watch = '".addslashes($this->tmy_sports_watch)."',

						tmy_travel_been = '".addslashes($this->tmy_travel_been)."',

						tmy_travel_going = '".addslashes($this->tmy_travel_going)."',

						tmy_arts_culture_events = '".addslashes($this->tmy_arts_culture_events)."',

						tmy_poison_place = '".addslashes($this->tmy_poison_place)."',

						tmy_politics = '".addslashes($this->tmy_politics)."',

						tmy_major_world_issue = '".addslashes($this->tmy_major_world_issue)."',

						tmy_doings_on_major_world_issue = '".addslashes($this->tmy_doings_on_major_world_issue)."',

						tmy_perfect_mate = '".addslashes($this->tmy_perfect_mate)."'

						

				   WHERE nUser_Id = '{$id}'";



        $res	= @mysql_query($sql, $this->dblink);

        if (!$res) {

            $message	.= "Sorry, we were unable to register your account at this time, please try again later.<br>";

        }

        else {

            if (!empty($arrElements)) {

                $script	= '<script language="javascript">';

                foreach ($arrElements as $key=>$value) {

                    $script	.= 'document.frmStep4.'.$value.'.className = "errortextarea";';

                }

                $script	.= '</script>';

            }

        }

        $message	.= $script;

        return $message;

    }



    function register_step_five($id=0) {

        $message		= "";

        $script			= "";

        $arrElements	= array();



        if ($this->tmy_last_restaurant_review <> "" AND $this->tmy_last_restaurant == "") {

            $message	.= "Please the enter name of the last restaurant you visited, before entering your review of it.<br>";

            $arrElements[]	= "tmy_last_restaurant";

        }

        if ($message == "") {

            $sql	= "UPDATE ".TABLEPREFIX."user

					   SET  taday_in_my_life = '".addslashes($this->taday_in_my_life)."',

							vmy_night_life_out = '".addslashes($this->vmy_night_life_out)."',

							vmy_night_life_in = '".addslashes($this->vmy_night_life_in)."',

							tmy_food = '".addslashes($this->tmy_food)."',

							tmy_money = '".addslashes($this->tmy_money)."',

							tmy_last_restaurant = '".addslashes($this->tmy_last_restaurant)."',

							tmy_last_restaurant_review = '".addslashes($this->tmy_last_restaurant_review)."',

							tmy_charity = '".addslashes($this->tmy_charity)."'

					   WHERE nUser_Id = '{$id}'";

            $res	= @mysql_query($sql, $this->dblink);

            if (!$res) {

                $message	.= "Sorry, we were unable to register your account at this time, please try again later.<br>";

            }

        } else {

            if (!empty($arrElements)) {

                $script	= '<script language="javascript">';

                foreach ($arrElements as $key=>$value) {

                    $script	.= 'document.frmStep5.'.$value.'.className = "errortextarea";';

                }

                $script	.= '</script>';

            }

        }

        $message	.= $script;

        return $message;

    }



    function register_step_eight($id=0) {

        $message	= "";

        $sql		= "INSERT INTO ".TABLEPREFIX."partner_preferance (nUser_Id, nAge_Low, nAge_High,

								   vBody_Type, nHeight_Low, nHeight_High, vDrinking,

								   vSmoking, vEye_Color, vHair_Color, vEthinicity,

								   vRelegion, vEducation, vLanguages, vProfession,

								   vIncome, vRelationship, vChildren)

				       VALUES ('{$id}', '".addslashes($this->nAge_Low)."',

							   '".addslashes($this->nAge_High)."',

							   '".addslashes($this->vBody_Type)."',

							   '".addslashes($this->nHeight_Low)."',

							   '".addslashes($this->nHeight_High)."',

							   '".addslashes($this->vDrinking)."',

							   '".addslashes($this->vSmoking)."',

							   '".addslashes($this->vEye_Color)."',

							   '".addslashes($this->vHair_Color)."',

							   '".addslashes($this->vEthinicity)."',

							   '".addslashes($this->vRelegion)."',

							   '".addslashes($this->vEducation)."',

							   '".addslashes($this->vLanguages)."',

							   '".addslashes($this->vProfession)."',

							   '".addslashes($this->vIncome)."',

							   '".addslashes($this->vRealationship)."',

							   '".addslashes($this->vChildren)."')";

        $res		= @mysql_query($sql, $this->dblink);

        if (!$res)

            $message	.= "We were unable to add your partner preference at this time, please try later.<br>";

        return $message;

    }



    function update_partner_preference($id=0) {

        $message	= "";

        $sql		= "UPDATE ".TABLEPREFIX."partner_preferance

					   SET nAge_Low = '".addslashes($this->nAge_Low)."',

						  nAge_High = '".addslashes($this->nAge_High)."',

						  vBody_Type = '".addslashes($this->vBody_Type)."',

						  nHeight_Low = '".addslashes($this->nHeight_Low)."',

						  nHeight_High = '".addslashes($this->nHeight_High)."',

						  vDrinking = '".addslashes($this->vDrinking)."',

						  vSmoking = '".addslashes($this->vSmoking)."',

						  vEye_Color = '".addslashes($this->vEye_Color)."',

						  vHair_Color = '".addslashes($this->vHair_Color)."',

						  vEthinicity = '".addslashes($this->vEthinicity)."',

						  vRelegion = '".addslashes($this->vRelegion)."',

						  vEducation = '".addslashes($this->vEducation)."',

						  vLanguages = '".addslashes($this->vLanguages)."',

						  vProfession = '".addslashes($this->vProfession)."',

						  vIncome = '".addslashes($this->vIncome)."',

						  vRelationship = '".addslashes($this->vRealationship)."',

						  vChildren = '".addslashes($this->vChildren)."'

					   WHERE nUser_Id = '{$id}'";

        $res		= @mysql_query($sql, $this->dblink);

        if (!$res)

            $message	.= "We were unable to add your partner preference at this time, please try later.<br>";

        return $message;

    }

// Send Message....................


    function send_usr_msg($id=0) {

        $message		= "";
        $script			= "";
        $arrElements	= array();

        $date=date('Y-m-d');
        if ($message == "") {
            $sql		= "INSERT INTO ".TABLEPREFIX."usermessage (message_id, message, user_id, date, status)
						   VALUES ('', '".addslashes($this->Mmessage)."', '{$id}', '$date',
									'".addslashes($this->Mstatus)."')";
            $res		= @mysql_query($sql, $this->dblink);

            $from=$email;
            $sql3 = "SELECT vValue FROM ".TABLEPREFIX."lookup where vName='adminmail'";
            $result = mysql_query($sql3);
            if (mysql_num_rows($result) != 0) {
                $row = mysql_fetch_array($result);
                $to= $row["vValue"];

            }

            $headers = "From:$from\r\nReply-to: $from\r\nContent-type: text/html; charset=us-ascii";
            mail($to,$subject,$message,$headers);

            if (!$res) {
                $message=$sql;
                $message	.= "Sorry, unable to send Message, please try later.<br>";

            }
        } else {
            if (!empty($arrElements)) {
                $script	= '<script language="javascript">';
                foreach ($arrElements as $key=>$value) {
                    $script	.= 'document.frmStep2.'.$value.'.className = "textbox";';
                }
                $script	.= '</script>';
            }
        }
        $message	.= $script;
        return $message;
    }

//....................................
// Update Status....................


    function update_status($id=0) {

        $message		= "";
        $script			= "";
        $arrElements	= array();

        $date=date('Y-m-d');
        if ($message == "") {

            $sql	= "UPDATE ".TABLEPREFIX."usermessage

				   SET status = '".addslashes($this->Mstatus)."'

				   WHERE message_id = '{$id}'";

            $res	= @mysql_query($sql, $this->dblink);


            if (!$res) {
                $message=$sql;
                $message	.= "Sorry, unable to send Message, please try later.<br>";

            }
        } else {
            if (!empty($arrElements)) {
                $script	= '<script language="javascript">';
                foreach ($arrElements as $key=>$value) {
                    $script	.= 'document.frmStep2.'.$value.'.className = "errorinput";';
                }
                $script	.= '</script>';
            }
        }
        $message	.= $script;
        return $message;
    }

//....................................


// Send Replies by user....................


    function user_comment($id=0,$uid=0) {

        $message		= "";
        $script			= "";
        $arrElements	= array();

        $date=date('Y-m-d');
        if ($message == "") {
            $user1=mysql_query("select * from ".TABLEPREFIX."usermessage where message_id='$id'") or die(mysql_error());
            $arr1=mysql_fetch_array($user1);
            $status = $arr1[4];

            $sql		= "INSERT INTO ".TABLEPREFIX."usermessage (message_id, message, user_id, date, status, parentid)
						   VALUES ('', '".addslashes($this->comment)."', '{$uid}', '$date',
									'$status', '$id')";
            $res		= @mysql_query($sql, $this->dblink);

            $sql		= "INSERT INTO ".TABLEPREFIX."adminreply (reply_id, message_id, reply, date, userid)
						   VALUES ('', '$id', '".addslashes($this->comment)."', '$date', '$uid')";
            $res		= @mysql_query($sql, $this->dblink);
            if (!$res) {
                $message=$sql;
                $message	.= "Sorry, unable to send Message, please try later.<br>";

            }
        } else {
            if (!empty($arrElements)) {
                $script	= '<script language="javascript">';
                foreach ($arrElements as $key=>$value) {
                    $script	.= 'document.frmStep2.'.$value.'.className = "errorinput";';
                }
                $script	.= '</script>';
            }
        }
        $message	.= $script;
        return $message;
    }

//....................................


    function check_freecode($code="") {

        $now	= date("Y-m-d");

        $flag	= true;

        $sql	= "SELECT nFreeCode_Id 	 FROM ".TABLEPREFIX."free_code

		           WHERE vCode = '{$code}' AND  dStart <= '{$now}' AND dEnd >= '{$now}'";

        $res	= @mysql_query($sql, $this->dblink);

        if (@mysql_num_rows($res) <= 0) {

            $flag	= false;
            $data_array=array("flag"=>$flag,
                    "freecode_id"=>'');
        }
        else {
            $row	= @mysql_fetch_row($res);
            $data_array=array("flag"=>$flag,
                    "freecode_id"=>$row[0]);
        }



        return $data_array;

    }



    function register_freecode($code="", $id=0) {

        $now		= date("Y-m-d H:i:s");

        $message	= "";
        $free_code_array=$this->check_freecode($code);

        if (!$free_code_array['flag']) {

            $message	.= "Invalid Free Code.<br>";

        } else {

            $message	= $this->registration_finished($id);

            $sql		= "INSERT INTO ".TABLEPREFIX."payments (vMethod, vTxn_Id, dDate, nUser_Id, vReason)

						   VALUES ('Free Code', 'FREE', '{$now}', '{$id}',

									'Profile Registration')";

            $res		= @mysql_query($sql, $this->dblink);

            if (!$res) {

                $message	.= "We were unable to log your payment details.<br>";

            } else {

                $payid	= @mysql_insert_id($this->dblink);

                //$prid	= $this->get_product_id('Profile Registration');
                $prid	= $free_code_array['freecode_id'];

                $message	.= $this->make_order($id, $prid, $payid);

            }

        }

        return $message;

    }



    //for free registration

    function free_registration($id=0) {

        $now		= date("Y-m-d H:i:s");

        $message	= "";



        $message	= $this->registration_finished($id);

        return $message;

    }//end function



    function registration_finished($id=0) {

        $message	= "";

        $date		= date("Y-m-d H:i:s");

        $flag		= "AU";

        $status		= "NNNN";



        require_once "settings.class.php";

        //$flag	= settings::getone('profile_approval');
        $settingsObj = new settings();
        $flag	= $settingsObj->getone('profile_approval');

        if ($flag	== "AU")

            $status	= "ANNN";

        elseif ($flag == "EM")

            $this->send_email_approval_message($id);



        $sql	= "UPDATE ".TABLEPREFIX."user

				   SET vStatus = '{$status}', vOnline = 'Offline',

				       vFeatured = 'NNNN', vId_Varified = 'NN',

					   vBC_Verified = 'NN', dStartDate = '{$date}'

				   WHERE nUser_Id = '{$id}'";

        $res	= @mysql_query($sql, $this->dblink);

        if (!$res)

            $message	.= "We were unable to register your account at this time, please try again later.<br>";

        return $message;

    }

     
    function renewal_finished($uid=0, $id=0, $array) {

        $message	= "";

        $date		= date("Y-m-d H:i:s");

        $sql	= "UPDATE ".TABLEPREFIX."user

				   SET vStatus = INSERT (vStatus, 1, 1, 'A'), dStartDate = '{$date}'

				   WHERE nUser_Id = '{$uid}'";



        $res	= @mysql_query($sql, $this->dblink);

        if (!$res)

            $message	.= "Unable to renew your account at this time, please try again later.<br>";

        $amount		= $this->get_amount($id);



        //checking credits avilable

        $sql_check=mysql_query("select nCredits from ".TABLEPREFIX."user where nUser_Id='{$uid}' and nCredits!='0'") or die(mysql_error());

        if(mysql_num_rows($sql_check)>0) {

            $message	.='';

        }//end if

        else {

            $message	.= $this->buy_last_step($uid, $id, $array, 'Profile Renewal', $amount);

        }//end else



        return $message;

    }
    
    function freemium_upgrade_finished($uid=0, $id=0, $array) {
        $message	= "";
        $date		= date("Y-m-d H:i:s");
        $sql            = "UPDATE ".TABLEPREFIX."user SET premiumUser = 'Y' WHERE nUser_Id = '{$uid}'";        
        $res            = @mysql_query($sql, $this->dblink);
        if (!$res) $message	= "Unable to upgrade your account at this time, please try again later.<br>";
        $amount		= $this->get_amount($id);        
        $message	.= $this->buy_last_step($uid, $id, $array, 'Freemium Profile Upgrade', $amount);       
        return $message;
    }


    function send_email_approval_message($id=0) {
        
        //require_once "misc.class.php";
        require_once "classes/misc.class.php";
        require_once "settings.class.php";



        //$arrS	= settings::select();
        $settingsObj = new settings();
        $arrS	= $settingsObj->select();

        $arrU	= $this->select($id);



        if (!empty($arrS) AND !empty($arrU)) {

            $body		= "";

            $body	= "Hi ".$arrU['vLogin'].","."\n\n";

            $body	.= "<p>Your Membership to ".$arrS['sitename']." requires email approval."."\n\n";
            $body	.= "Please click <a href='".$arrS['site_normal_url']."/approval.php?code=".strtotime($arrU['dActive_Date'])."'>here</a> to validate your email address.</p>";

            //$body	.= "Please click on the link below to validate your email address."."\n";

            //$body	.= $arrS['site_normal_url']."/approval.php?code=".strtotime($arrU['dActive_Date'])."\n\n";

            $body	.= "<p>If you were unable to click on the link above, please copy the link below to the address field of your browser"."\n</p>";

            $body	.= $arrS['site_normal_url']."/approval.php?code=".strtotime($arrU['dActive_Date']).""."\n\n";

            $body       .= "<p>Your Credentials are  </p>
                                                <p>Username: ".$_SESSION['USERNAME']." </p>
                                                <p>Password: ".$_SESSION['PASSWORD']." </p>";
            
            $body	.= "<p>By"."\n<br>".$arrS['sitename']." Team</p>";



            $subject	= "Membership to ".$arrS['sitename']." requires email approval.";



            $from		= $arrS['adminmail'];

            $to			= $arrU['vEmail'];

            $toname		= $arrU['vLogin'];

            $fromname	= $arrS['sitename']." Team";

            $htmlbody	= '';



            require_once "settings.class.php";

            $site_name	= $arrS['sitename'];

            $site_url	= $arrS['site_normal_url'];

            $site_logo	=  $arrS['sitelogo'];

            $site_valid_day	=  $arrS['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 ".$row['vLogin']." </h2>

						<p>Your membership to ".$site_name." requires email approval.

						Please click <a href='".$site_url."/approval.php?code=".strtotime($arrU['dActive_Date'])."'>here</a> to validate your email address.</p><p>Personalized</p>
                                                <p>Your Credentials are  </p>
                                                <p>Username: ".$_SESSION['USERNAME']." </p>
                                                <p>Password: ".$_SESSION['PASSWORD']." </p>
						<p>by  <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, $body,$site_logo,$site_top,$site_valid_day);

            $htmlbody	= $this->html_mail($basepath, $arrSearch, $arrReplace);



            $textbody	= $body;
            

            //$flag		= misc::send_mail_perfect($from, $to, $subject, $fromname, $toname, $textbody, $htmlbody);
            $miscObj = new misc();
            $flag = $miscObj->send_mail_perfect($from, $to, $subject, $fromname, $toname, $textbody, $htmlbody);

            /*

			misc::send_mail($arrU['vLogin']."<".$arrU['vEmail'].">", $body, $subject, $arrS['adminmail'], $arrS['sitename']);

            */

        }

    }



    function email_approval($arr=array()) {

        $msg	= "";

        $user	= isset($arr['user'])	?	stripslashes(trim($arr['user']))	:	"";

        $pass	= isset($arr['pass'])	?	stripslashes(trim($arr['pass']))	:	"";

        $code	= isset($arr['code'])	?	stripslashes(trim($arr['code']))	:	"";



        if ($user == "")

            $msg	.= "Please enter your username.<br>";

        if (!$this->check_username($user))

            $msg	.= "Only following characters are allowed in a username ([a-z][A-Z][0-9].-_).<br>";

        if ($pass == "")

            $msg	.= "Please enter your password.<br>";

        if ($code == "")

            $msg	.= "Invalid email address or code.<br>";



        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 ($code <> strtotime($row['dActive_Date'])) {

                    $msg	.= "Invalid email address or code.<br>";

                } else {

                    if (substr($row['vStatus'], 0, 1) == "E") {

                        $msg	.= "Sorry, your profile is expired. Please login and renew your profile. Please click <a href='login.php'>here</a> to login now.<br>";

                    } else if (substr($row['vStatus'], 0, 1) == "S") {

                        $msg	.= "Sorry, your profile is currently suspended from the site. Please contact the administrator of the site.<br>";

                    } else if (substr($row['vStatus'], 0, 1) == "A") {

                        $msg	.= "Sorry, your profile is already active. Please click <a href='login.php'>here</a> to login now.<br>";

                    } else {

                        $sql	= "UPDATE ".TABLEPREFIX."user SET vStatus = INSERT(vStatus, 1, 1, 'A')

								   WHERE nUser_Id = '".$row['nUser_Id']."'";

                        $res	= @mysql_query($sql, $this->dblink);

                    }

                }

            } else {

                $msg	.= "Invalid username/password.<br>";

            }

        }

        return $msg;

    }



    function check_payment_form() {

        $message		= "";

        $script			= "";

        $arrElements	= array();



        if ($this->vFirstName == "") {

            $message	.= "Please enter your first name.<br>";

            $arrElements[]	= "vFirstName";

        }

        if ($this->vLastName == "") {

            $message	.= "Please enter your last name.<br>";

            $arrElements[]	= "vLastName";

        }

        //for echeck

        if($_SESSION['sess_register_stype']=='ECHECK') {

            if ($this->rBank == "") {

                $message	.= "Please enter the Routing Number of your bank.<br>";

                $arrElements[]	= "rBank";

            }

            if ($this->nAccountNumber == "") {

                $message	.= "Please enter your Bank Account Number.<br>";

                $arrElements[]	= "nAccountNumber";

            }

            if ($this->txtAccountType == "") {

                $message	.= "Please enter the Account Type.<br>";

                $arrElements[]	= "txtAccountType";

            }

            if ($this->txtBankName == "") {

                $message	.= "Please enter the Bank Name.<br>";

                $arrElements[]	= "txtBankName";

            }

            if ($this->txtBankHolderName == "") {

                $message	.= "Please enter the Bank Holder's Name.<br>";

                $arrElements[]	= "txtBankHolderName";

            }

        }//end if

        //for echeck

		if($_SESSION['sess_register_stype']=='CC' || $_SESSION['sess_register_stype']=='UP' || $_SESSION['sess_register_stype']=='PRO')

		{
			
			if($_SESSION['sess_register_stype']=='PRO'){
				if ($this->vPaymentMethodType == "") {
	
					$message	.= "Please enter your credit card Type.<br>";
	
					$arrElements[]	= "vPaymentMethodType";
	
				}
			}
            if ($this->nNumber == "") {

                $message	.= "Please enter your credit card number.<br>";

                $arrElements[]	= "nNumber";

            }

            if ($this->nCvv2 == "") {

                $message	.= "Please enter the verification code for your credit card.<br>";

                $arrElements[]	= "nCvv2";

            }

            if ($this->vMM == "") {

                $message	.= "Please enter the month of expiration for your credit card.<br>";

                $arrElements[]	= "vMM";

            }

            if ($this->vYYYY == "") {

                $message	.= "Please enter the year of expiration for your credit card.<br>";

                $arrElements[]	= "vYYYY";

            }

        }//end if

        if ($this->vAddress == "") {

            $message	.= "Please enter your address.<br>";

            $arrElements[]	= "vAddress";

        }

        if ($this->vCity == "") {

            $message	.= "Please enter your city.<br>";

            $arrElements[]	= "vCity";

        }

        if ($this->vState == "") {

            $message	.= "Please enter your state.<br>";

            $arrElements[]	= "vState";

        }

        if ($this->vCountry == "") {

            $message	.= "Please enter your country.<br>";

            $arrElements[]	= "vCountry";

        }

        if ($this->vPostCode == "") {

            $message	.= "Please enter your zip code.<br>";

            $arrElements[]	= "vPostCode";

        }

        if ($this->vPhone == "") {

            $message	.= "Please enter your phone number.<br>";

            $arrElements[]	= "vPhone";

        }

        if ($this->vEmail == "") {

            $message	.= "Please enter your email address.<br>";

            $arrElements[]	= "vEmail";

        }



        if (!empty($arrElements)) {

            $script	= '<script language="javascript">';

            foreach ($arrElements as $key=>$value) {

                $script	.= 'document.frmPayment.'.$value.'.className = "errorinput";';

            }

            $script	.= '</script>';

        }

        $message	.= $script;

        return $message;



    }



    function get_client_ip() {

        $client_ip	= (!empty($_SERVER['REMOTE_ADDR'])) ? $_SERVER['REMOTE_ADDR'] :

                (!empty($_ENV['REMOTE_ADDR'])) ? $_ENV['REMOTE_ADDR'] : $REMOTE_ADDR;



        if ($_SERVER["HTTP_CLIENT_IP"])

            $proxy_ip	= $_SERVER["HTTP_CLIENT_IP"];

        elseif ($_SERVER["HTTP_X_FORWARDED_FOR"])

            $proxy_ip	= $_SERVER["HTTP_X_FORWARDED_FOR"];

        if ($proxy_ip) {

            if (preg_match("/^([0-9]+\.[0-9]+\.[0-9]+\.[0-9]+)/", $proxy_ip, $ip_list)) {

                $private_ip		= array('/^0\./', '/^127\.0\.0\.1/', '/^192\.168\..*/', '/^172\.16\..*/',

                        '/^10.\.*/', '/^224.\.*/', '/^240.\.*/');

                $client_ip		= preg_replace($private_ip, $client_ip, $ip_list[1]);

            }

        }

        return $client_ip;

    }



    function fill_number($var_inv_no="0") {

        $var_inv_no		= "" . $var_inv_no;

        switch(strlen($var_inv_no)) {

            case 1:

                $var_inv_no = "000000" . $var_inv_no;

                break;

            case 2:

                $var_inv_no = "00000" . $var_inv_no;

                break;

            case 3:

                $var_inv_no = "0000" . $var_inv_no;

                break;

            case 4:

                $var_inv_no = "000" . $var_inv_no;

                break;

            case 5:

                $var_inv_no = "00" . $var_inv_no;

                break;

            case 6:

                $var_inv_no = "0" . $var_inv_no;

                break;

            default:

                $var_inv_no = $var_inv_no;

                break;

        }

        return $var_inv_no;

    }



    function make_payment($id, $type="M") {

        $arrU		= $this->select($id);


        $array		= array();



        if($_SESSION['sess_register_stype']=='UP') {

            $array	= $this->yourpay_capture($id, $type);

        }//end if

        else {

                require_once "settings.class.php";
                //$arrSettings	= settings::select();
                $settingsObj = new settings();
                $arrSettings	= $settingsObj->select();
                $payment_method = $arrSettings['paymentmethod'];
                if($payment_method == 'PRO'){
                   /*****propay starts*****/
                        $array	= $this->propay_payment($id, $type);
                        /*****propay ends*****/
                }else{                    
                    if ($arrU['vBilling'] == "D") {
                        $array	= $this->authorize_capture($id, $type);
                    } else {
                        $array	= $this->authorize_only($id, $type);
                    }
            }
        }//end if

        return $array;



    }

	function propay_payment($id, $type){
		include ("class-propaySPS.php");
		require_once "settings.class.php";
		//$arrSettings	= settings::select();
                $settingsObj = new settings();
                $arrSettings	= $settingsObj->select();
		$authToken = $arrSettings['propay_token'];
 		$billerID = $arrSettings['propay_billerid'];
 		$testmode = $arrSettings['propay_demo'];
                //exit;
 		if($testmode == 'NO'){
 			$testmode = 'live';
 			//$testmode = 'test';
 		}else{
 			$testmode = 'test';
 		}
		$client = new propaySPS($authToken, $billerID, $testmode);
             //echo"<pre>";print_r($client);
                //exit;
		
		$result = $client->CreatePayer(urlencode(addslashes($this->vFirstName)),"N");
               //echo"<pre>";print_r($result);
//                exit;
		$PayerAccountId=$result['result']['ExternalAccountID'];
		$ExpDate				= addslashes($this->vMM) . addslashes(substr($this->vYYYY,'2','4'));
		$PayerAccountId = $result['result']['ExternalAccountID']; // this is returned from CreatePayer()
		$PaymentMethodType = $this->vPaymentMethodType;
		$AccountNumber = addslashes($this->nNumber);
		$Description = "Credit Card";
		$ExpirationDate = $ExpDate;
		$AccountName = urlencode(addslashes($this->vFirstName))."".urlencode(addslashes($this->vLastName));
		$Address1 = urlencode(addslashes($this->vAddress));;
		$Address2 = ""; $Address3 = "";
		$City = urlencode(addslashes($this->vCity));
		$State = urlencode(addslashes($this->vState));
		//$State = 'IL';
		$ZipCode = urlencode(addslashes($this->vPostCode));
		$Country = "USA";
		$Priority = "";
		
		$client = new propaySPS($authToken, $billerID);
		$result = $client->CreatePaymentMethod($PayerAccountId, $PaymentMethodType, $AccountNumber, $Description, $ExpirationDate, $AccountName, $Address1, $Address2, $Address3, $City, $State, $ZipCode, $Country, $Priority);
                //echo"<pre>";print_r($result);
              // exit;
		$PayerAccountId = $PayerAccountId; // this is returned from CreatePayer()
		if ($type == "FP") {
		
			$Amount			= $arrSettings['featured_amount'];
		
			$description	= "Dollar Date Featured Profile";
		
		}
		if ($type == "MB") {
		
			$Amount			= $arrSettings['membership_amount'];
		
			$description	= "Dollar Date Membership";
		
		} else if ($type == "MR") {
		
			$Amount			= $arrSettings['membership_amount'];
		
			$description	= "Dollar Date Membership Renewal";
		
		} else if ($type == "BC") {
		
			$Amount			= $arrSettings['background_check_amount'];
		
			$description	= "Dollar Date Background Check";
		
		} else if ($type == "IV") {
		
			$Amount			= $arrSettings['identity_verification_amount'];
		
			$description	= "Dollar Date Identity Verification";
		
		} else if ($type == "FP") {
		
			$Amount			= $arrSettings['featured_amount'];
		
			$description	= "Dollar Date Featured Profile";
		
		}
                else if ($type == "FM") {
		
			$Amount			= $arrSettings['membership_amount'];
		
			$description	= "Dollar Date Profile Upgrade";
		
		}
                else {
		
			$Amount			= $this->get_product_amount($type);
		
			$description	= $this->get_product($type);
		
		}
		//echo $Amount = urlencode($this->get_product_amount($type)); // ProPay uses no decimal points, so 100 is $1.00
		$CurrencyCode = "USD";
		$Invoice = ""; // optional, but recommended to avoid duplicate transaction errors and to have unique identifiers per transaction.
		$client = new propaySPS($authToken, $billerID, $testmode);
		//Amount given should be in penny 1penny = .01Dollars
		$Amount = $Amount*100;
		$result = $client->ProcessPayment($PayerAccountId, $Amount, $CurrencyCode, $Invoice);
		$cc_flag  = $result['result']['ResultValue'];
		$message  = $result['result']['ResultMessage'];
		$txn  = $result['result']['TransactionInformation']['TransactionId'];
		$status  = $result['result']['TransactionInformation']['TransactionResult'];
		$return_array = array("flag"=>$cc_flag, "msg"=>$message, "txn"=>$txn, "sta" => $status);
// 		echo '<pre>';
// 		print_r($return_array);die;
		return $return_array;
		//die;
	}


    function authorize_only($id, $type) {

        $cc_flag	= false;

        $message	= "";

        $txn		= 0;

        $status		= "A";



        $this->set_creditcard($id);

// Comment below line when CURL is activated properly

//return array("flag"=>true, "msg"=>$message, "txn"=>$txn, "sta" => $status);



        require_once "settings.class.php";

        //$arrSettings	= settings::select();
        $settingsObj = new settings();
        $arrSettings	= $settingsObj->select();

        if ($arrSettings['auth_demo'] == "YES")

            $flag	= false;

        else

            $flag	= true;

        //settings::set_authorize_url($flag);
        $settingsObj = new settings();
        $settingsObj->set_authorize_url($flag);

        //$authurl	= settings::get_authorize_url();
        $authurl = $settingsObj->get_authorize_url();



        if ($type == "MB") {

            $amount			= $arrSettings['membership_amount'];

            $description	= "Dollar Date Membership";

        } else if ($type == "MR") {

            $amount			= $arrSettings['membership_amount'];

            $description	= "Dollar Date Membership Renewal";

        } else if ($type == "BC") {

            $amount			= $arrSettings['background_check_amount'];

            $description	= "Dollar Date Background Check";

        } else if ($type == "IV") {

            $amount			= $arrSettings['identity_verification_amount'];

            $description	= "Dollar Date Identity Verification";

        } else if ($type == "FP") {

            $amount			= $arrSettings['featured_amount'];

            $description	= "Dollar Date Featured Profile";

        } else if ($type == "FM") {

            $amount			= $arrSettings['membership_amount'];

            $description	= "Dollar Date Profile Upgrade";

        }
        else {
            $amount		= $this->get_product_amount($type);
            $description	= $this->get_product($type);
            if($amount==0 && isset($_SESSION['sess_buy_credits']) && $_SESSION['sess_buy_credits']!=''){
                $amount= $arrSettings['credit_value']*$_SESSION['sess_buy_credits'];       
            }

        }

        $custip					= $this->get_client_ip();

        $x_customdata			= "Custom";

        $x_Login				= urlencode($arrSettings['auth_loginid']);

        $x_Password				= urlencode($arrSettings['auth_pass']);

        $x_tran_key				= urlencode($arrSettings['auth_txnkey']);

        $x_Merchant_Email		= urlencode($arrSettings['auth_email']);

        $x_Delim_Data			= urlencode("TRUE");

        $x_Delim_Char			= urlencode(",");

        $x_Encap_Char			= urlencode("");

        $x_Type					= urlencode("AUTH_ONLY");

        $x_ADC_Relay_Response	= urlencode("FALSE");

        if($arrSettings['auth_demo'] == "YES") {

            $x_Test_Request	= urlencode("TRUE");

        } else {

            $x_Test_Request	= urlencode("FALSE");

        }



        $x_Method				= urlencode("CC");

        $x_Amount				= urlencode($amount);

        $x_First_Name			= urlencode(addslashes($this->vFirstName));

        $x_Last_Name			= urlencode(addslashes($this->vLastName));

        $x_Card_Num				= urlencode(addslashes($this->nNumber));

        $ExpDate				= (addslashes($this->vMM) . addslashes($this->vYYYY));

        $x_Exp_Date				= urlencode($ExpDate);

        $x_card_code			= urlencode(addslashes($this->nCvv2));



        $x_Address				= urlencode(addslashes($this->vAddress));

        $x_City					= urlencode(addslashes($this->vCity));

        $x_State				= urlencode(addslashes($this->vState));

        $x_Zip					= urlencode(addslashes($this->vPostCode));

        $x_country				= urlencode(addslashes($this->vCountry));

        $x_Email				= urlencode(addslashes($this->vEmail));

        $x_phone				= urlencode(addslashes($this->vPhone));

        $x_Email_Customer		= urlencode("TRUE");

        $x_description			= urlencode($description);

        $x_cust_ip				= $custip;

        $x_dDate				= urlencode($now);

        $x_cust_id				= $id;

        $x_company				= "Dollar Date";

        $x_invid				= "";



        $fields					= "x_Version=3.1&x_Login=$x_Login&x_tran_key=$x_tran_key&

								   x_Delim_Data=$x_Delim_Data&x_Delim_Char=$x_Delim_Char&

								   x_Encap_Char=$x_Encap_Char&x_Type=$x_Type&x_Test_Request=$x_Test_Request&

								   x_Method=$x_Method&x_Amount=$x_Amount&x_First_Name=$x_First_Name

								   &x_Last_Name=$x_Last_Name&x_Card_Num=$x_Card_Num&x_Exp_Date=$x_Exp_Date

								   &x_card_code=$x_card_code&x_Address=$x_Address&x_City=$x_City

								   &x_State=$x_State&x_Zip=$x_Zip&x_country=$x_country&x_Email=$x_Email&

								   x_Email_Customer=$x_Email_Customer&x_cust_id=$x_cust_id&

								   x_ADC_Relay_Response=$x_ADC_Relay_Response&x_invid=$x_invid

								   &x_cust_ip=$x_cust_ip&x_company=$x_company&x_phone=$x_phone

								   &x_invoice_num=$x_invno&x_description=$x_description";

        if ($x_Password <> "") {

            $fields		.= "&x_Password=$x_Password";

        }

        if ($x_Merchant_Email <> "") {

            $fields		.= "&x_Merchant_Email=$x_Merchant_Email";

        }



        $agent		= "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.0)";

        $ref		= $_SERVER['PHP_SELF'];



        $ch			= curl_init();

        curl_setopt($ch, CURLOPT_URL, $authurl);

        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);



        /*//for goddady server

		curl_setopt ($ch, CURLOPT_HTTPPROXYTUNNEL, TRUE);

		curl_setopt ($ch, CURLOPT_PROXYTYPE, CURLPROXY_HTTP);

		curl_setopt ($ch, CURLOPT_PROXY,"http://proxy.shr.secureserver.net:3128");

		//for goddady server*/

        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];

        switch ($details) {

            case "1":

                $cc_flag	= true;

                $txn		= $return[6];

                break;

            case "2":

                $cc_flag	= false;

                $message	= "The card has been declined";

                $message	.= "<br>" . $return[3];

                break;

            case "4":

                $cc_flag	= false;

                $message    = "The card has been held for review";

                $message	.= "<br>" . $return[3];

                break;

            default:

                $cc_flag	= false;

                $message	= "Error From autorize_only ";

                $message	.= "<br>" . $return[3];

                break;

        }

        return array("flag"=>$cc_flag, "msg"=>$message, "txn"=>$txn, "sta" => $status);

    }



    function authorize_capture($id, $type) {


        $cc_flag	= false;

        $cc_tran		= 0;

        $status		= "C";

        require_once "settings.class.php";

        //$arrSettings	= settings::select();
        $settingsObj = new settings();
        $arrSettings	= $settingsObj->select();
        if ($arrSettings['auth_demo']=="YES") {
            $flag	= false;
            $authorize_url="https://test.authorize.net/gateway/transact.dll";
        }
        else {
            $flag	= true;
            $authorize_url="https://secure.authorize.net/gateway/transact.dll";
        }

        if ($type == "MB") {
            $amount			= $arrSettings['membership_amount'];
            $description	= "Dollar Date Membership";
        } else if ($type == "MR") {
            $amount			= $arrSettings['membership_amount'];
            $description	= "Dollar Date Membership Renewal";
        } else if ($type == "BC") {
            $amount			= $arrSettings['background_check_amount'];
            $description	= "Dollar Date Background Check";
        } else if ($type == "IV") {
            $amount			= $arrSettings['identity_verification_amount'];
            $description	= "Dollar Date Identity Verification";
        } else if ($type == "FP") {
            $amount			= $arrSettings['featured_amount'];
            $description	= "Dollar Date Featured Profile";
        } else if ($type == "FM") {
            $amount			= $arrSettings['membership_amount'];
            $description	= "Dollar Date Profile Upgrade";
        }
        else {
            $amount			= $this->get_product_amount($type);
            $description	= $this->get_product($type);            
        }

        $txtAuthorizeLoginId=urlencode($arrSettings['auth_loginid']);
        $txtAuthorizePassword='';
        $txtAuthorizeTransKey=urlencode($arrSettings['auth_txnkey']);
        $chkAuthorizeMode=$arrSettings['auth_demo'];
        $x_customdata="Custom";
        $x_Login= urlencode($txtAuthorizeLoginId); // Replace LOGIN with your login
        $x_Password= urlencode($txtAuthorizePassword); // Replace PASS with your password
        $x_tran_key = urlencode($txtAuthorizeTransKey); // Tran Key
        $x_Delim_Data= urlencode("TRUE");
        $x_Delim_Char= urlencode(",");
        $x_Encap_Char= urlencode("");
        $x_Type= urlencode("AUTH_CAPTURE");
        $x_ADC_Relay_Response = urlencode("FALSE");

        if($chkAuthorizeMode != "NO") {
            $x_Test_Request= urlencode("TRUE");
        }//end if

        # Customer Information

        //for echeck
        
        if($_SESSION['sess_register_stype']=='ECHECK') {

            $x_Method= urlencode("ECHECK");
            $x_bank_aba_bode=urlencode($this->rBank);
            $x_bank_acct_num=urlencode($this->nAccountNumber);
            //Describes the type of bank account; if no value is provided,default is set to CHECKING
            if($_POST['txtAccountType']!='') {
                $BankAcType=$this->txtAccountType;
            }//end if
            else {
                $BankAcType='CHECKING';
            }//end else
            
            $x_bank_acct_type=urlencode($BankAcType);

            $x_bank_name=urlencode($this->txtBankName);

            $x_bank_acct_name=urlencode($this->txtBankHolderName);

            $x_echeck_type=urlencode('WEB');

            $x_customer_ip='';



            //I=Individual,B=Business

            $x_customer_organization_type=urlencode('I');



            /*Tax ID or SSN of the customer initiating the transaction.

				 If the Tax ID or SSN is not available, the custoerm's driver's license number,

		 		driver's license state and date of birht must be used in it place*/



            $x_customer_tax_id='';

            $x_drivers_license_num='';

            $x_drivers_license_state=$x_State;

            $x_drivers_license_dob=urlencode($_SESSION['sess_echeck_dob']);

        }//end if

        else {

            $x_Method= urlencode("CC");

        }//end else



        //in credit buying

        if(isset($_SESSION['sess_buy_credits']) && $_SESSION['sess_buy_credits']!='') {
            $x_Amount= urlencode($arrSettings['credit_value']*$_SESSION['sess_buy_credits']);
        }//end if
        else {
            $x_Amount= urlencode($amount);
        }//end else

        $x_First_Name= urlencode($this->vFirstName);

        $x_Last_Name= urlencode($this->vLastName);

        $x_Card_Num= urlencode($this->nNumber);

        $ExpDate = ($this->vMM . $this->vYYYY);

        $x_Exp_Date= urlencode($ExpDate);

        $x_card_code =urlencode($this->nCvv2);



        $x_Address= urlencode($this->vAddress);

        $x_City= urlencode($this->vCity);

        $x_State= urlencode($this->vState);

        $x_Zip= urlencode($this->vPostCode);

        $x_country=urlencode($this->vCountry);



        $x_saleid = urlencode($saleid);

        $x_userid = urlencode($userid);

        $x_dDate = urlencode(date('Y-m-d'));



        $x_Email= urlencode($this->vEmail);

        $x_Email_Customer= urlencode("TRUE");

        $x_Merchant_Email= urlencode($arrSettings['auth_email']);

        $x_description = urlencode($description);

        $custip	= $this->get_client_ip();

        $x_cust_ip=$custip;

        $x_invid="15";

        $x_company="Dollar Date";

        $x_phone=urlencode($this->vPhone);

        $x_cust_id=$id;

        $x_invoice_num=$var_inv_no;

        $x_invno=$var_inv_no;



        # Build fields string to post



        $fields = "x_Version=3.1&x_Login=$x_Login&x_tran_key=$x_tran_key&x_Delim_Data=$x_Delim_Data&x_Delim_Char=$x_Delim_Char&x_Encap_Char=$x_Encap_Char";

        $fields .= "&x_Type=$x_Type&x_Test_Request=$x_Test_Request&x_Method=$x_Method&x_Amount=$x_Amount&x_First_Name=$x_First_Name";



        /*for echeck*/

        if($_SESSION['sess_register_stype']=='ECHECK') {

            $fields .="&x_bank_aba_bode=$x_bank_aba_bode&x_bank_acct_num=$x_bank_acct_num&x_bank_acct_type=$x_bank_acct_type";

            $fields .="&x_bank_name=$x_bank_name&x_bank_acct_name=$x_bank_acct_name&x_echeck_type=$x_echeck_type&x_customer_ip=$x_customer_ip";

            $fields .="&x_customer_organization_type=$x_customer_organization_type&x_customer_tax_id=$x_customer_tax_id&x_drivers_license_num=$x_drivers_license_num";

            $fields .="&x_drivers_license_state=$x_drivers_license_state&x_drivers_license_dob=$x_drivers_license_dob";

        }//end if

        /*for echeck*/



        $fields .= "&x_Last_Name=$x_Last_Name&x_Card_Num=$x_Card_Num&x_Exp_Date=$x_Exp_Date&x_card_code=$x_card_code&x_Address=$x_Address&x_City=$x_City&x_State=$x_State&x_Zip=$x_Zip&x_country=$x_country&x_Email=$x_Email&x_Email_Customer=$x_Email_Customer&x_Merchant_Email=$x_Merchant_Email&x_ADC_Relay_Response=$x_ADC_Relay_Response&x_invid=$x_invid&x_cust_ip=$x_cust_ip&x_company=$x_company&x_phone=$x_phone&x_cust_id=$x_cust_id&x_invoice_num=$x_invno&x_description=$x_description";

        if ($x_Password != '') {

            $fields .= "&x_Password=$x_Password";

        }//end if



        # Start CURL session



        $agent = "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.0)";

        $ch=curl_init($authorize_url);

        curl_setopt($ch, CURLOPT_HEADER, 0); // set to 0 to eliminate header info from response

        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); // Returns response data instead of TRUE(1)

        curl_setopt($ch, CURLOPT_POSTFIELDS, rtrim( $fields, "& " )); // use HTTP POST to send form data

        curl_setopt($ch, CURLOPT_VERBOSE, 1);

        curl_setopt ($ch, CURLOPT_HTTPPROXYTUNNEL, TRUE);

        curl_setopt ($ch, CURLOPT_PROXYTYPE, CURLPROXY_HTTP);

        //curl_setopt ($ch, CURLOPT_PROXY,"http://proxy.shr.secureserver.net:3128");

        $buffer = curl_exec($ch);

        curl_close($ch);

        $return = preg_split("/[,]+/", "$buffer");

//		echopre($return);exit;

        $details = $return[0];
        


        switch ($details) {

            case "1":

                $cc_flag=true;

                $cc_tran=$return[6];

                break;



            case "2":

                $cc_flag = false;

                $cc_err="The card has been declined";

                $cc_err .="<br>" . $return[3];

                break;

            case "4":

                $cc_flag = false;

                $cc_err="The card has been held in queque for review";

                $cc_err .="<br>" . $return[3];

                break;

            default:

                $cc_flag = false;

                // $cc_flag = true;

                $cc_err="Error ";

                $cc_err .="<br>" . $return[3];

                break;

        }//end switch       
        return array("flag"=>$cc_flag, "msg"=>$cc_err, "txn"=>$cc_tran, "sta" => $status);

    }



    function yourpay_capture($id, $type) {

        $cc_flag	= false;

        $cc_tran		= 0;

        $status		= "C";

        require_once "settings.class.php";

        //$arrSettings	= settings::select();
        $settingsObj = new settings();
        $arrSettings	= $settingsObj->select();



        $txtYourpayStoreId = $arrSettings['urpaystoreid'];

        $pemfolder = $arrSettings['pemfolder'];

        $txtUrPayDemo = $arrSettings['urpaydemo'];

        $reccuringpayment=false;





        if ($type == "MB") {

            $amount			= $arrSettings['membership_amount'];

            $description	= "Dollar Date Membership";

        } else if ($type == "MR") {

            $amount			= $arrSettings['membership_amount'];

            $description	= "Dollar Date Membership Renewal";

        } else if ($type == "BC") {

            $amount			= $arrSettings['background_check_amount'];

            $description	= "Dollar Date Background Check";

        } else if ($type == "IV") {

            $amount			= $arrSettings['identity_verification_amount'];

            $description	= "Dollar Date Identity Verification";

        } else if ($type == "FP") {

            $amount			= $arrSettings['featured_amount'];

            $description	= "Dollar Date Featured Profile";

        } 
        else if ($type == "FM") {

            $amount			= $arrSettings['membership_amount'];

            $description	= "Dollar Date Upgrade Profile";

        }
        else {

            $amount			= $this->get_product_amount($type);

            $description	= $this->get_product($type);

        }



        include_once "lphp.php";

        $mylphp=new lphp;

        //$myorder["host"]       = "secure.linkpt.net"; // [LIVE]
        //$myorder["host"]       = "staging.linkpt.net";  //[DEMO]

        $myorder["port"]       = "1129";

        $myorder["keyfile"]    = "pem/".$pemfolder; # Change this to the name and location of your certificate file

        $myorder["configfile"] = urlencode($txtYourpayStoreId);        # Change this to your store number





        //$x_currency_code = urlencode($txtACurrency); //currency code



        $myorder["ordertype"]    = "SALE";

        if($txtUrPayDemo=="YES") {

            $myorder["result"]       = "GOOD";# For a test, set result to GOOD, DECLINE, or DUPLICATE
            $myorder["host"]       = "staging.linkpt.net";  //[DEMO]

            $flag	= false;

        }//end if

        else {

            $myorder["result"]       = "LIVE";
            $myorder["host"]       = "secure.linkpt.net"; // [LIVE]

            $flag	= true;

        }//end else



        //in credit buying

        if(isset($_SESSION['sess_buy_credits']) && $_SESSION['sess_buy_credits']!='') {

            $cost= urlencode($this->get_amount(1)*$_SESSION['sess_buy_credits']);

        }//end if

        else {

            $cost= urlencode($amount);

        }//end else



        $myorder["cardnumber"]   = urlencode($this->nNumber);

        $myorder["cardexpmonth"] = $this->vMM;

        $myorder["cardexpyear"]  = substr($this->vYYYY,-2);

        $myorder["chargetotal"]  = urlencode($cost);



        if($reccuringpayment==true and $reccuringmode=="SUBMIT") {

            //echo " <br>Yourpay submited::$recurringinstallment::$recurringstartdate:$recurringperiodicity";

            $myorder["action"]="SUBMIT";

            $myorder["installments"] = $recurringinstallment;

            $myorder["threshold"] = "3";

            $myorder["startdate"] = $recurringstartdate;

            $myorder["periodicity"] = $recurringperiodicity;

        }//end if



        if($reccuringpayment==true and $reccuringmode=="CANCEL") {

            //echo " <br>Yourpay cancel ::$recurringinstallment::$recurringstartdate:$recurringperiodicity::$recurringorderid";

            $myorder["action"]="CANCEL";

            $myorder["installments"] = $recurringinstallment;

            $myorder["threshold"] = "3";

            $myorder["startdate"] = $recurringstartdate;

            $myorder["periodicity"] = $recurringperiodicity;

            $myorder["oid"] = $recurringorderid;

        }//end if



        # BILLING INFO 4111111111111111

        $myorder["name"]     =urlencode($this->vFirstName)." ".urlencode($this->vLastName);

        $myorder["company"]  = "-NA-";

        $myorder["address1"] = urlencode($this->vAddress);

        $myorder["city"]     = urlencode($this->vCity);

        $myorder["state"]    = urlencode($this->vState);

        $myorder["country"]  = urlencode($this->vCountry);

        $myorder["phone"]    = urlencode($this->vPhone);

        $myorder["email"]    = urlencode($this->vEmail);//CURRENCY

        //$myorder["debugging"] = "true";  # for development only - not intended for production use

        $result = $mylphp->curl_process($myorder);  # use curl methods

//		  echo "<br>result::$result<br>";
//
//		  echo "<br>approved==".$result["r_approved"];
//
//		  echo "<br>ordernum===".$result[r_ordernum];
//
//		  echo "<br>ordernum1===".$result["r_ordernum"];
//
//		  echo "<br>resultarray<br>";
//
//		  foreach($result as $key=>$value){
//
//		  echo "<br>$key::$value";

//		 }

//		  echo "<br>";exit;

        if(!is_array($result)) {

            $cc_flag = false;

            $cc_err = "Error";

            //$cc_err .= "<br>Transcation declined. Please contact the administrator." . $result;

            $cc_err =$result;

        }//end if

        else {

            if ($result["r_approved"]!= "APPROVED")	// transaction failed, print the reason
            {

                $cc_flag = false;

                $cc_err = "Error";

                $err=explode(":",$result[r_error]);

                if(is_array($err))

                    $len=strlen($err[0])+1;

                else

                    $len=0;

                $cc_err .= "<br>" . substr($result[r_error],$len);

                //print "Status: $result[r_approved]\n";

                //print "Error: $result[r_error]\n";

            }//end if

            else {	// success

                $cc_flag = true;

                $cc_tran = $result[r_ordernum];

                //	print "Status: $result[r_approved]\n";

                //print "Code: $result[r_code]\n";

                //print "OID: $result[r_ordernum]\n\n";

            }//end else

        }//end else



        return array("flag"=>$cc_flag, "msg"=>$cc_err, "txn"=>$cc_tran, "sta" => $status);

    }//end yourpay function



    function authorize_prior_capture($id, $type) {

        $cc_flag	= false;

        $message	= "";

        $txn		= 0;

        $status		= "C";



        $this->set_creditcard($id);

// Comment below line when CURL is activated properly

//return array("flag"=>true, "msg"=>$message, "txn"=>$txn, "sta" => $status);



        require_once "settings.class.php";

        //$arrSettings	= settings::select();
        $settingsObj = new settings();
        $arrSettings	= $settingsObj->select();

        if ($arrSettings['auth_demo'] == "YES")

            $flag	= false;

        else

            $flag	= true;

        //settings::set_authorize_url($flag);
        $settingsObj = new settings();
        $settingsObj->set_authorize_url($flag);

        //$authurl	= settings::get_authorize_url();
        $authurl = $settingsObj->get_authorize_url();



        if ($type == "MB") {

            $amount			= $arrSettings['membership_amount'];

            $description	= "Dollar Date Membership";

        } else if ($type == "MR") {

            $amount			= $arrSettings['membership_amount'];

            $description	= "Dollar Date Membership Renewal";

        } else if ($type == "BC") {

            $amount			= $arrSettings['background_check_amount'];

            $description	= "Dollar Date Background Check";

        } else if ($type == "IV") {

            $amount			= $arrSettings['identity_verification_amount'];

            $description	= "Dollar Date Identity Verification";

        } else if ($type == "FP") {

            $amount			= $arrSettings['featured_amount'];

            $description	= "Dollar Date Featured Profile";

        } else {

            $amount			= $this->get_product_amount($type);

            $description	= $this->get_product($type);

        }



        $x_Login				= urlencode($arrSettings['auth_loginid']);

        $x_Password				= "";//urlencode($arrSettings['auth_pass']);

        $x_tran_key				= urlencode($arrSettings['auth_txnkey']);

        $x_Merchant_Email		= urlencode($arrSettings['auth_email']);

        $x_Delim_Data			= urlencode("TRUE");

        $x_Delim_Char			= urlencode(",");

        $x_Encap_Char			= urlencode("");

        $x_Type					= urlencode("PRIOR_AUTH_CAPTURE");

        $x_ADC_Relay_Response	= urlencode("FALSE");

        if($arrSettings['auth_demo'] == "YES") {

            $x_Test_Request	= urlencode("TRUE");

        } else {

            $x_Test_Request	= urlencode("FALSE");

        }



        $x_Method				= urlencode("CC");

        $x_Amount				= urlencode($amount);



        //$x_Card_Num				= urlencode("4005550000000019");

        //$ExpDate				= (addslashes("12") . addslashes("2009"));

        //$x_Exp_Date				= urlencode($ExpDate);

        $x_card_code			= urlencode(addslashes($this->nCvv2));



        $x_ref_transid			= urlencode("508319133");

//		$x_auth_code			= urlencode("CeUxuw");

        $x_description			= urlencode($description);

        $x_dDate				= urlencode($now);

        $x_cust_id				= $id;

        $x_company				= "Dollar Date";

        $x_invid				= "";



        $fields					= "x_Version=3.1&x_Login=$x_Login&x_tran_key=$x_tran_key&

								   x_Delim_Data=$x_Delim_Data&x_Delim_Char=$x_Delim_Char&

								   x_Encap_Char=$x_Encap_Char&x_Type=$x_Type&x_Test_Request=$x_Test_Request&

								   x_Method=$x_Method&x_Amount=$x_Amount&

								   x_ADC_Relay_Response=$x_ADC_Relay_Response&

								   x_company=$x_company&x_description=$x_description&x_ref_transid=$x_ref_transid";

        if ($x_Password <> "") {

            $fields		.= "&x_Password=$x_Password";

        }



        $agent		= "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.0)";

        $ref		= $_SERVER['PHP_SELF'];



        $ch			= curl_init();

        curl_setopt($ch, CURLOPT_URL, $authurl);

        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);



        /*//for goddady server

		curl_setopt ($ch, CURLOPT_HTTPPROXYTUNNEL, TRUE);

		curl_setopt ($ch, CURLOPT_PROXYTYPE, CURLPROXY_HTTP);

		curl_setopt ($ch, CURLOPT_PROXY,"http://proxy.shr.secureserver.net:3128");

		//for goddady server*/

        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];

        switch ($details) {

            case "1":

                $cc_flag	= true;

                $txn		= $return[6];

                break;

            case "2":

                $cc_flag	= false;

                $message	= "The card has been declined";

                $message	.= "<br>" . $return[3];

                break;

            case "4":

                $cc_flag	= false;

                $message    = "The card has been held in queque for review";

                $message	.= "<br>" . $return[3];

                break;

            default:

                $cc_flag	= false;

                $message	= "Error from autorize_prio_capture";

                $message	.= "<br>" . $return[3];

                break;

        }

        return array("flag"=>$cc_flag, "msg"=>$message, "txn"=>$txn, "sta" => $status);



    }





    function testcard($id=0) {

        $message	= $this->check_payment_form();

        $cc_flag	= false;

        if ($message == "") {

            $message	= $this->store_creditcard($id);

            $array		= $this->make_payment($id, 'MB');

        }

        return $message;

    }



    function register_authorize($id=0) {

        if($_SESSION['sess_Paymode']!='PP' && $_SESSION['sess_Paymode']!='GC' && $_SESSION['sess_Paymode']!='WP' && $_SESSION['sess_Paymode']!='UP' && $_SESSION['sess_Paymode']=='CC') {

            $message	= $this->check_payment_form();

        }//end if

        else {

            $message='';

        }//end else

        $cc_flag	= false;

        if ($message == "") {

            if($_SESSION['sess_Paymode']=='PP') {

                $cc_flag	= true;

                $message	= 'Success';

                $txn		= $_SESSION['sess_TransId'];

                $status		= 'A';

            }//end if

            else if($_SESSION['sess_Paymode']=='GC') {

                $cc_flag	= true;

                $message	= 'Success';

                $txn		= $_SESSION['sess_TransId'];

                $status		= 'A';

            }//end if

            else if($_SESSION['sess_Paymode']=='WP') {

                $cc_flag	= true;

                $message	= 'Success';

                $txn		= $_SESSION['sess_TransId'];

                $status		= 'A';

            }//end if

            else {

                $message	= $this->store_creditcard($id);

                $array		= $this->make_payment($id, 'MB');

               $cc_flag	= $array['flag'];
                if($cc_flag==='FAILURE'){
                   $cc_flag =false; 
                }

                $message	= $array['msg'];

                $txn		= $array['txn'];

                $status		= $array['sta'];
                //exit;

            }//end else

            if ($cc_flag) {
//                echo "cccc",$message;
//                exit;

                $now		= date("Y-m-d H:i:s");

                $message	= $this->registration_finished($id);

                $amount		= $this->get_amount($this->get_product_id('Profile Registration'));



                //checking payment type

                switch($_SESSION['sess_register_stype']) {

                    case "CC":

                        $chck='Credit Card';

                        break;



                    case "UP":

                        $chck='Yourpay';

                        break;



                    case "WP":

                        $chck='Worldpay';

                        break;



                    case "ECHECK":

                        $chck='eCheck';

                        break;



                    case "PAYPAL":

                        $chck='PP';

                        break;



                    case "GOOGLE":

                        $chck='GC';

                        break;



                    case "GOOGLE":

                        $chck='GC';

                        break;



                }//end switch



                $sql		= "INSERT INTO ".TABLEPREFIX."payments (vMethod, vTxn_Id, dDate, nUser_Id,

											vReason, vAmountStatus, fAmount)

				               VALUES ('{$chck}', '{$txn}', '{$now}', '{$id}',

							            'Profile Registration', '{$status}', '{$amount}')";

                $res		= @mysql_query($sql, $this->dblink);

                if (!$res) {

                    $message	.= "Unable to log payment details.<br>";

                } else {

                    $payid		= @mysql_insert_id($this->dblink);

                    $prid		= $this->get_product_id('Profile Registration');

                    $message	.= $this->make_order($id, $prid, $payid);

                    //clear session value

                    $_SESSION['sess_echeck_dob']='';

                    $_SESSION['sess_register_stype']='';

                    $_SESSION['sess_Paymode']='';

                    $_SESSION['sess_TransId']='';

                }

            }

        }
//        echo "ddd",$message;
//        exit;

        return $message;



    }





    function buy_real_products($uid=0, $id=0) {

        if($_SESSION['sess_Paymode']!='PP' && $_SESSION['sess_Paymode']!='GC' && $_SESSION['sess_Paymode']!='WP') {

            $message	= $this->check_payment_form();

        }//end if

        else {

            $message='';

        }//end else

        $cc_flag	= false;



        if ($message == "") {

            if($_SESSION['sess_Paymode']=='PP') {

                $cc_flag	= true;

                $message	= 'Success';

                $txn=$_SESSION['sess_TransId'];

                $status		= true;

            }//end if

            else if($_SESSION['sess_Paymode']=='GC') {

                $cc_flag	= true;

                $message	= 'Success';

                $txn=$_SESSION['sess_TransId'];

                $status		= true;

            }//end if

            else if($_SESSION['sess_Paymode']=='WP') {

                $cc_flag	= true;

                $message	= 'Success';

                $txn=$_SESSION['sess_TransId'];

                $status		= true;

            }//end if

            else {
               
                $array		= $this->make_payment($uid, $id);
               
                $cc_flag	= $array['flag'];                
                if($cc_flag==='FAILURE'){
                   $cc_flag =false; 
                }
               
                $message	= $array['msg'];

                $txn		= $array['txn'];

                $status		= $array['sta'];
               
            }//end else           
           
            if ($cc_flag) {

                $message	= $this->buy_real_products_finished($uid, $id, $array);

            }

        }

        return $message;



    }



    function buy_real_products_finished($uid=0, $id=0, $array) {
        
        $amount		= $this->get_product_amount($id);
        $name		= $this->get_product($id);        
        //in credit buying

        if(isset($_SESSION['sess_buy_credits']) && $_SESSION['sess_buy_credits']!='') {

            $name=$_SESSION['sess_buy_credits'].' credit purchase';
            require_once "settings.class.php";
            //$arrSettings	= settings::select();
            $settingsObj = new settings();
            $arrSettings	= $settingsObj->select();
            $amount=$arrSettings['credit_value']*$_SESSION['sess_buy_credits'];
            

        }//end if

        $message	.= $this->buy_last_step_real_products($uid, $id, $array, $name, $amount);        
        return $message;

    }



    function buy_last_step_real_products($uid=0, $id=0, $array, $type='Profile Renewal', $amount=0) {



        $date		= date("Y-m-d H:i:s");

        $message	= $array['msg'];

        $txn		= $array['txn'];

        $status		= $array['sta'];

        $message	= "";
        

        if($_SESSION['sess_Paymode']=='PP' || $_SESSION['sess_Paymode']=='GC' || $_SESSION['sess_Paymode']=='WP') {

            $sql		= "INSERT INTO ".TABLEPREFIX."payments (vMethod, vTxn_Id, dDate, nUser_Id,

									vReason, vAmountStatus, fAmount)

					   VALUES ('".$_SESSION['sess_Paymode']."', '".$_SESSION['sess_TransId']."', '{$date}', '{$uid}',

								'{$type}', 'A', '{$amount}')";

        }//end if

        else {

            $sql		= "INSERT INTO ".TABLEPREFIX."payments (vMethod, vTxn_Id, dDate, nUser_Id,

									vReason, vAmountStatus, fAmount)

					   VALUES ('Credit Card', '{$txn}', '{$date}', '{$uid}',

								'{$type}', '{$status}', '{$amount}')";

        }//end else



        $res		= @mysql_query($sql, $this->dblink);

        if (!$res) {

            $message	.= "Unable to log payment details.<br>";

        } else {

            $payid		= @mysql_insert_id($this->dblink);

            $message	.= $this->make_order($uid, $id, $payid);

            if ($status == "C")

                $this->send_invoice_mail_real_products($uid, $id, $type,$amount);



        }

        return $message;

    }

    //send invoice mail to admin







    function send_invoice_mail_real_products($uid=0, $id=0, $type='Profile Renewal',$amount=0) {

        require_once "misc.class.php";

        require_once "settings.class.php";



        $type	= stripslashes($type);

        //$arrS	= settings::select();
        $settingsObj = new settings();
        $arrS	= $settingsObj->select();

        $arrU	= $this->select($uid);

        if($amount == 0)
            $amount	= $this->get_product_amount($id);



        if (!empty($arrS) AND !empty($arrU)) {

//sending invoice mail to client

            $date	= date("Y-m-d H:i:s");

            $body	= "";

            $body	= "Hi ".$row['vLogin'].","."\n\n";

            $body	.= "You have been billed the amount of $".$amount." for subscribing to  \"".$type."\"."."\n\n";

            $body	.= "by The"."\n".$arrS['sitename']." Team";

            $subject	= "Invoice of ".$type." in ".$arrS['sitename'].".";



            $from		= $arrS['adminmail'];

            $to			= $arrU['vEmail'];

            $toname		= $arrU['vLogin'];

            $fromname	= $arrS['sitename']." Team";

            $htmlbody	= '';



            $site_name	= $arrS['sitename'];

            $site_url	= $arrS['site_normal_url'];

            $site_logo	= $arrS['sitelogo'];

            $site_valid_day	=  $arrS['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 ".$arrU['vLogin']." </h2>

						<p>You have been billed an amount of $".$amount." for subscribing to  <b>".$type."</b>.

						Please click <a href='".$site_url."/login.php'>here</a> to login to ".$site_name.".</p><p>Personalized</p>

						<p>By Your <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	= $body;

            //$flag		= misc::send_mail_perfect($from, $to, $subject, $fromname, $toname, $textbody, $htmlbody);
            $miscObj = new misc();
            $flag = $miscObj->send_mail_perfect($from, $to, $subject, $fromname, $toname, $textbody, $htmlbody);



            /*

			misc::send_mail($arrU['vLogin']."<".$arrU['vEmail'].">", $body, $subject, $arrS['adminmail'], $arrS['sitename']);

            */



//sending subscription alert mail to admin

            $body	= "";

            $body	= "Hi ".$row['sitename'].","."\n\n";

            $body	.= $arrU['vLogin']." have been subscribed \"".$type."\" by paying an amount of $".$amount." on ".$date."."."\n\n";

            $body	.= "By"."\n".$arrS['sitename']." Subscription Alert Team";

            $subject = "Subscription alert: ".$type." in ".$arrS['sitename'].".";



            $from		= $arrS['adminmail'];

            $to			= $arrS['adminmail'];

            $toname		= $arrS['sitename']." Team";

            $fromname	= $arrS['sitename']." Team";

            $htmlbody	= '';

            $site_name	= $arrS['sitename'];

            $site_url	= $arrS['site_normal_url'];

            $site_logo	= $arrS['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 ".$site_name." </h2>

						  <p>".$arrU['vLogin']." have been subscribed to the product <b>".$type."</b>  by paying an amount of $".$amount." on ".$date.".Please click <a href='".$site_url."/admin/index.php'>here</a> to login to the Administrator console of ".$site_name.".</p><p>Personalized</p>

						 <p>By Your <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_mail2($basepath, $arrSearch, $arrReplace);



            $textbody	= $body;

            //$flag		= misc::send_mail_perfect($from, $to, $subject, $fromname, $toname, $textbody, $htmlbody);
            $miscObj = new misc();
            $flag = $miscObj->send_mail_perfect($from, $to, $subject, $fromname, $toname, $textbody, $htmlbody);



            /*

			misc::send_mail($arrS['sitename']."<".$arrS['adminmail'].">", $body, $subject, $arrU['vEmail'], $arrU['vLogin']);

            */

        }

    }



    function buy_product($uid=0, $id=0) {

        if($_SESSION['sess_check_validation']=='not') {

            $message="";

        }//end if

        else if($_SESSION['sess_Paymode']=='PP' || $_SESSION['sess_Paymode']=='GC' || $_SESSION['sess_Paymode']=='WP') {

            $message="";

        }//end else if

        else {

            $message	= $this->check_payment_form();

        }//end else



        $cc_flag	= false;

        if ($id == "1") {

            $type	= "MB";

        } else if ($id == "2") {

            $type	= "MR";

        } else if ($id == "4") {

            $type	= "BC";

        } else if ($id == "5") {

            $type	= "IV";

        } else if ($id == "3") {

            $type	= "FP";

        }else if ($id == "6") {
            $type	= "FM";
        }

        if ($message == "") {

            if($_SESSION['sess_Paymode']!='PP' && $_SESSION['sess_Paymode']!='GC' && $_SESSION['sess_Paymode']!='WP') {

                //checking credits exist or not

                if ($id == "2" || $id == "6") {                                      
                    //$arrSettings    = settings::select();                   
                    $settingsObj = new settings();
                    $arrSettings	= $settingsObj->select();
                    $creditValue    = $arrSettings['credit_value'];
                    $amount	    = $this->get_amount($id);
                    $creditRequired = $amount/$creditValue;
                    $totalCreditRequired = ceil($creditRequired);
                     //checking credits avilable                    
                    if($totalCreditRequired<=0){
                         $array		= $this->make_payment($uid, $type);
                    }                   
                    else {    
                        $sql_check=mysql_query("select nCredits from ".TABLEPREFIX."user where nUser_Id='{$uid}' and nCredits>='$totalCreditRequired'") or die(mysql_error());
                        if(mysql_num_rows($sql_check)>0) {
                            $creditRequired =  number_format($creditRequired,2,".","");
                            //update table with purchase credits
                            if($id == "6")
                            mysql_query("update ".TABLEPREFIX."user set nCredits=nCredits-".$creditRequired." AND premiumUser='Y' where nUser_Id='{$uid}'") or die(mysql_error());
                            else
                            mysql_query("update ".TABLEPREFIX."user set nCredits=nCredits-".$creditRequired." where nUser_Id='{$uid}'") or die(mysql_error());
                            $message	= $this->renewal_finished($uid, $id, $array);
                        }
                        else $array		= $this->make_payment($uid, $type);
                    }
                }//end if

                else {

                    $array		= $this->make_payment($uid, $type);

                }//end else

            }//end if



            if($_SESSION['sess_Paymode']=='PP') {

                $cc_flag	= true;

                $message	= 'Success';

                $txn=$_SESSION['sess_TransId'];

                $status		= true;

            }//end if

            else if($_SESSION['sess_Paymode']=='GC') {

                $cc_flag	= true;

                $message	= 'Success';

                $txn=$_SESSION['sess_TransId'];

                $status		= true;

            }//end if

            else if($_SESSION['sess_Paymode']=='WP') {

                $cc_flag	= true;

                $message	= 'Success';

                $txn=$_SESSION['sess_TransId'];

                $status		= true;

            }//end if

            else {

                $cc_flag	= $array['flag'];
                 if($cc_flag==='FAILURE'){
                   $cc_flag =false; 
                }

                $message	= $array['msg'];

                $txn		= $array['txn'];

                $status		= $array['sta'];

            }//end else

            if ($cc_flag) {

                if ($id == "2")

                    $message	= $this->renewal_finished($uid, $id, $array);

                else if ($id == "3")

                    $message	= $this->featured_finished($uid, $id, $array);

                else if ($id == "4")

                    $message	= $this->backgroundcheck_finished($uid, $id, $array);

                else if ($id == "5")

                    $message	= $this->idverify_finished($uid, $id, $array);
                else if ($id == "6")

                    $message	= $this->freemium_upgrade_finished($uid, $id, $array);

            }

        }

        return $message;

    }



    function send_invoice_mail($uid=0, $id=0, $type='Profile Renewal') {

        require_once "misc.class.php";

        require_once "settings.class.php";



        $type	= stripslashes($type);

        //$arrS	= settings::select();
        $settingsObj = new settings();
        $arrS	= $settingsObj->select();

        $arrU	= $this->select($uid);

        $amount	= $this->get_amount($id);

        if (!empty($arrS) AND !empty($arrU)) {

            $body		= "";

            $body	= "Hi ".$arrU['vLogin'].","."\n\n";

            $body	.= "You have been billed an amount of $".$amount." for for subscribing to ".$type."."."\n\n";

            $body	.= "By"."\n".$arrS['sitename']." Team";

            $subject	= "Invoice of ".$type." in ".$arrS['sitename'].".";



            $from		= $arrS['adminmail'];

            $to			= $arrU['vEmail'];

            $toname		= $arrU['vLogin'];

            $fromname	= $arrS['sitename']." Team";

            $htmlbody	= '';



            $site_name	= $arrS['sitename'];

            $site_url	= $arrS['site_normal_url'];

            $site_logo	= $arrS['sitelogo'];

            $site_valid_day	=  $arrS['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 ".$arrU['vLogin']." </h2>

						<p>You have been billed an amount of $".$amount." for subscribing to  <b>".$type."</b>.

						Please click <a href='".$site_url."/login.php'>here</a> to login to ".$site_name.".</p><p>Personalized</p>

						<p>By Your <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	= $body;

            //$flag		= misc::send_mail_perfect($from, $to, $subject, $fromname, $toname, $textbody, $htmlbody);
            $miscObj = new misc();
            $flag = $miscObj->send_mail_perfect($from, $to, $subject, $fromname, $toname, $textbody, $htmlbody);

            /*

			misc::send_mail($arrU['vLogin']."<".$arrU['vEmail'].">", $body, $subject, $arrS['adminmail'], $arrS['sitename']);

            */

        }

    }



    function buy_last_step($uid=0, $id=0, $array, $type='Profile Renewal', $amount=0) {

        $date		= date("Y-m-d H:i:s");

        $message	= $array['msg'];

        $txn		= $array['txn'];

        $status		= $array['sta'];

        $message	= "";



        if($_SESSION['sess_Paymode']=='PP' || $_SESSION['sess_Paymode']=='GC' || $_SESSION['sess_Paymode']=='WP') {

            $sql		= "INSERT INTO ".TABLEPREFIX."payments (vMethod, vTxn_Id, dDate, nUser_Id,

									vReason, vAmountStatus, fAmount)

					   VALUES ('".$_SESSION['sess_Paymode']."', '".$_SESSION['sess_TransId']."', '{$date}', '{$uid}',

								'{$type}', 'A', '{$amount}')";

        }//end if

        else {

            $sql		= "INSERT INTO ".TABLEPREFIX."payments (vMethod, vTxn_Id, dDate, nUser_Id,

										vReason, vAmountStatus, fAmount)

						   VALUES ('Credit Card', '{$txn}', '{$date}', '{$uid}',

									'{$type}', '{$status}', '{$amount}')";

        }//end else



        $res		= @mysql_query($sql, $this->dblink);

        if (!$res) {
            $message	.= "Unable to log payment details.<br>";
        } else {
            $payid		= @mysql_insert_id($this->dblink);
            $message	.= $this->make_order($uid, $id, $payid);
            if ($status == "C")
                $this->send_invoice_mail($uid, $id, $type);
        }
        return $message;

    }



    function featured_finished($uid=0, $id=0, $array) {

        $message	= "";

        $date		= date("Y-m-d H:i:s");

        $sql	= "UPDATE ".TABLEPREFIX."user

				   SET vFeatured = INSERT (vFeatured, 1, 1, 'Y')

				   WHERE nUser_Id = '{$uid}'";

        $res	= @mysql_query($sql, $this->dblink);

        if (!$res)

            $message	.= "Unable to make your account featured, please try later.<br>";

        $amount		= $this->get_amount($id);

        $message	.= $this->buy_last_step($uid, $id, $array, 'Featured Profile', $amount);

        return $message;

    }



    function backgroundcheck_finished($uid=0, $id=0, $array) {

        $message	= "";

        $date		= date("Y-m-d H:i:s");



        $arrBC		= $this->background_check();

        if (!empty($arrBC)) {

            $msg	= addslashes($arrBC['msg']);

            if ($arrBC['passed'] == "YES")

                $status	= "V";

            else

                $status	= "R";

        }



        $sql	= "UPDATE ".TABLEPREFIX."user

				   SET vBC_Verified = INSERT (vBC_Verified, 1, 1, '{$status}')

				   WHERE nUser_Id = '{$uid}'";

        $res	= @mysql_query($sql, $this->dblink);

        if (!$res) {

            $message	.= "Unable to post your account for background check, please try again later.<br>";

        } else {

            $new	= $status."N";

            $sql	= "INSERT INTO ".TABLEPREFIX."background_check (nUser_Id, vType, dDate, vStatus, vMsg)

					   VALUES ('{$uid}', 'BC', '{$date}', '{$new}', '{$msg}')";

            $res	= @mysql_query($sql, $this->dblink);

            if (!$res)

                $message	.= "Unable to post your account for background check, please try again later.<br>";

        }

        $amount		= $this->get_amount($id);

        $message	.= $this->buy_last_step($uid, $id, $array, 'Background Check', $amount);

        return $message;

    }



    function idverify_finished($uid=0, $id=0, $array) {

        $message	= "";

        $status		= "P";

        $date		= date("Y-m-d H:i:s");

        $arrBC		= $this->id_find();

        if (!empty($arrBC)) {

            $score	= $arrBC['score'];

            $msg	= addslashes($arrBC['msg']);

            if ($arrBC['passed'] == "YES")

                $status	= "V";

            else

                $status	= "R";

        }



        $sql	= "UPDATE ".TABLEPREFIX."user

				   SET vId_Varified = INSERT (vId_Varified, 1, 1, '{$status}')

				   WHERE nUser_Id = '{$uid}'";

        $res	= @mysql_query($sql, $this->dblink);

        if (!$res) {

            $message	.= "Unable to post your account for id verification, please try again later.<br>";

        } else {

            $new	= $status."N";

            $sql	= "INSERT INTO ".TABLEPREFIX."background_check (nUser_Id, vType,

									dDate, vStatus, vScore, vMsg)

					   VALUES ('{$uid}', 'ID', '{$date}', '{$new}',

								'{$score}', '{$msg}')";

            $res	= @mysql_query($sql, $this->dblink);

            if (!$res)

                $message	.= "Unable to post your account for id verification, please try again later.<br>";

        }

        $amount		= $this->get_amount($id);

        $message	.= $this->buy_last_step($uid, $id, $array, 'ID Verify', $amount);

        return $message;

    }



    function store_creditcard($id=0) {

        $message	= "";



        require_once "crypt.class.php";

        $objCrypt	= new cryptit();



        $sql		= "INSERT INTO ".TABLEPREFIX."cc (vEmail, vFirstName, vLastName,

								vCountry, vState, vCity, vAddress, vPostCode,

								vPhone, vMM, vYYYY, nNumber, vType, nCvv2, vRoutingNumber, 

								vAccountNumber, vAccountType, vBankName, vBankHolderName,

								nUser_Id)

					   VALUES ('".addslashes($this->vEmail)."', '".addslashes($this->vFirstName)."',

							'".addslashes($this->vLastName)."', '".addslashes($this->vCountry)."',

							'".addslashes($this->vState)."', '".addslashes($this->vCity)."', 

							'".addslashes($this->vAddress)."', '".addslashes($this->vPostCode)."',

							'".addslashes($this->vPhone)."',

							'".addslashes($objCrypt->encrypt_value($this->vMM, $this->ENCSEED))."',

							'".addslashes($objCrypt->encrypt_value($this->vYYYY, $this->ENCSEED))."',

							'".addslashes($objCrypt->encrypt_value($this->nNumber, $this->ENCSEED))."',

							'".addslashes($objCrypt->encrypt_value($this->vType, $this->ENCSEED))."',

							'".addslashes($objCrypt->encrypt_value($this->nCvv2, $this->ENCSEED))."',

							'".addslashes($objCrypt->encrypt_value($this->rBank, $this->ENCSEED))."',

							'".addslashes($objCrypt->encrypt_value($this->nAccountNumber, $this->ENCSEED))."',

							'".addslashes($objCrypt->encrypt_value($this->txtAccountType, $this->ENCSEED))."',

							'".addslashes($objCrypt->encrypt_value($this->txtBankName, $this->ENCSEED))."',

							'".addslashes($objCrypt->encrypt_value($this->txtBankHolderName, $this->ENCSEED))."',

							'{$id}')";

        $res		= @mysql_query($sql, $this->dblink);

        unset($objCrypt);

        if (!$res)

            $message	.= "Unable to store credit card details at this time.<br>";

        return $message;

    }



    function edit_creditcard($id=0) {

        $message	= $this->check_payment_form();

        if ($message == "") {

            require_once "crypt.class.php";

            $objCrypt	= new cryptit();



            //checking user entry already exist or not

            $check=mysql_query("select * from ".TABLEPREFIX."cc WHERE nUser_Id = '{$id}'") or die(mysql_error());

            if(mysql_num_rows($check)>0) {

                $sql		= "UPDATE ".TABLEPREFIX."cc

				           SET vEmail = '".addslashes($this->vEmail)."',

						       vFirstName = '".addslashes($this->vFirstName)."',

							   vLastName = '".addslashes($this->vLastName)."',

							   vCountry = '".addslashes($this->vCountry)."',

							   vState = '".addslashes($this->vState)."',

							   vCity = '".addslashes($this->vCity)."',

							   vAddress = '".addslashes($this->vAddress)."',

							   vPostCode = '".addslashes($this->vPostCode)."',

							   vPhone = '".addslashes($this->vPhone)."',

							   vMM = '".addslashes($objCrypt->encrypt_value($this->vMM, $this->ENCSEED))."',

							   vYYYY = '".addslashes($objCrypt->encrypt_value($this->vYYYY, $this->ENCSEED))."',

						nNumber = '".addslashes($objCrypt->encrypt_value($this->nNumber, $this->ENCSEED))."',

							   vType = '".addslashes($objCrypt->encrypt_value($this->vType, $this->ENCSEED))."',

							   nCvv2 = '".addslashes($objCrypt->encrypt_value($this->nCvv2, $this->ENCSEED))."',

							   vRoutingNumber = '".addslashes($objCrypt->encrypt_value($this->rBank, $this->ENCSEED))."',

							   vAccountNumber = '".addslashes($objCrypt->encrypt_value($this->nAccountNumber, $this->ENCSEED))."',

							   vAccountType = '".addslashes($objCrypt->encrypt_value($this->txtAccountType, $this->ENCSEED))."',

							   vBankName = '".addslashes($objCrypt->encrypt_value($this->txtBankName, $this->ENCSEED))."',

							   vBankHolderName = '".addslashes($objCrypt->encrypt_value($this->txtBankHolderName, $this->ENCSEED))."'

							   

						   WHERE nUser_Id = '{$id}'";

            }//end if

            else {

                $sql		= "insert into ".TABLEPREFIX."cc (vEmail,vFirstName,vLastName,vCountry,vState,vCity,vAddress,vPostCode,

									vPhone,vMM,vYYYY,nNumber,vType,nCvv2,vRoutingNumber,vAccountNumber,vAccountType,vBankName,vBankHolderName,nUser_Id) 

									values ('".addslashes($this->vEmail)."','".addslashes($this->vFirstName)."',

											'".addslashes($this->vLastName)."','".addslashes($this->vCountry)."',

											'".addslashes($this->vState)."','".addslashes($this->vCity)."',

											'".addslashes($this->vAddress)."','".addslashes($this->vPostCode)."',

											'".addslashes($this->vPhone)."','".addslashes($objCrypt->encrypt_value($this->vMM, $this->ENCSEED))."',

											'".addslashes($objCrypt->encrypt_value($this->vYYYY, $this->ENCSEED))."',

											'".addslashes($objCrypt->encrypt_value($this->nNumber, $this->ENCSEED))."',

											'".addslashes($objCrypt->encrypt_value($this->vType, $this->ENCSEED))."',

											'".addslashes($objCrypt->encrypt_value($this->nCvv2, $this->ENCSEED))."',

											'".addslashes($objCrypt->encrypt_value($this->rBank, $this->ENCSEED))."',

											'".addslashes($objCrypt->encrypt_value($this->nAccountNumber, $this->ENCSEED))."',

											'".addslashes($objCrypt->encrypt_value($this->txtAccountType, $this->ENCSEED))."',

											'".addslashes($objCrypt->encrypt_value($this->txtBankName, $this->ENCSEED))."',

											'".addslashes($objCrypt->encrypt_value($this->txtBankHolderName, $this->ENCSEED))."',

											'{$id}')";


            }//end else

            $res		= @mysql_query($sql, $this->dblink);

            if (!$res)

                $message	= "Unable to store credit card details at this time.<br>";

        }

        return $message;

    }



    function set_creditcard($id=0) {

        require_once "crypt.class.php";

        $objCrypt	= new cryptit();



        $array	= $this->get_creditcard($id);

        //print_r($array);

        if (empty($array)) {

            $array	= $this->select($id);

        } else {

            $array['vMM']	= addslashes($objCrypt->encrypt_value(stripslashes($array['vMM']), $this->ENCSEED));

            $array['vYYYY']	= addslashes($objCrypt->encrypt_value(stripslashes($array['vYYYY']), $this->ENCSEED));

            $array['nNumber']	= addslashes($objCrypt->encrypt_value(stripslashes($array['nNumber']), $this->ENCSEED));

            $array['vType']	= addslashes($objCrypt->encrypt_value(stripslashes($array['vType']), $this->ENCSEED));

            $array['nCvv2']	= addslashes($objCrypt->encrypt_value(stripslashes($array['nCvv2']), $this->ENCSEED));

            $array['rBank'] = addslashes($objCrypt->encrypt_value(stripslashes($array['vRoutingNumber']), $this->ENCSEED));

            $array['nAccountNumber']	= addslashes($objCrypt->encrypt_value(stripslashes($array['vAccountNumber']), $this->ENCSEED));

            $array['txtAccountType']	= addslashes($objCrypt->encrypt_value(stripslashes($array['vAccountType']), $this->ENCSEED));

            $array['txtBankName']	=  addslashes($objCrypt->encrypt_value(stripslashes($array['vBankName']), $this->ENCSEED));

            $array['txtBankHolderName']	= addslashes($objCrypt->encrypt_value(stripslashes($array['vBankHolderName']), $this->ENCSEED));

        }

        $this->set_values($array);

    }



    function get_creditcard($id=0) {

        $array	= array();

        $sql	= "SELECT * FROM ".TABLEPREFIX."cc WHERE nUser_Id = '{$id}'";

        $res	= @mysql_query($sql, $this->dblink);

        if (@mysql_num_rows($res) > 0) {

            $array	= @mysql_fetch_array($res);

        }

        return $array;

    }

    function search_profiles($arrP=array(), $flag=false,$limit='',$pagination='',$Pagesize) {

        $array		= array();
        $arraysearch	= array();
        $string		= "";
        $getSitesettings = $this->getSiteSettings();
        $search	= isset($arrP['search_profile'])	?	stripslashes(trim($arrP['search_profile']))	:	"";

        if ($flag) {

            $_SESSION['search_profile']	= "";

            $string	= "";
            $having	= "";
            $gender	= isset($arrP['vSG'])	?	$arrP['vSG']	:	"";
            $agefrom	= isset($arrP['vSAF'])	?	$arrP['vSAF']	:	"";
            $ageto	= isset($arrP['vSAT'])	?	$arrP['vSAT']	:	"";
            $photo	= isset($arrP['vSP'])	?	$arrP['vSP']	:	"";
            $county	= isset($arrP['vCounty'])	?	$arrP['vCounty']	:	"";
            $country	= isset($arrP['vCountry'])	?	$arrP['vCountry']	:	"";
            $state	= isset($arrP['vState'])	?	$arrP['vState']	:	"";

            
            
             if($getSitesettings['enable_same_sex_search']=='Y')
            {
                if($gender=='Female')
                {
                    $string	.= "U.vGender = 'Female' AND U.vDate_Preference='Male' AND ";
                }
               if($gender=='Male'){
                    $string	.= "U.vGender = 'Male'  AND U.vDate_Preference='Female' AND ";
                }
                if($gender=='Females')
                {
                    $string	.= "U.vGender = 'Female' AND U.vDate_Preference='Female' AND ";
                }
                if($gender=='Males')
                {
                    $string	.= "U.vGender = 'Male' AND U.vDate_Preference='Male' AND ";
                }
                
            }else{
                
               $string	.= "U.vGender = '".addslashes($gender)."' AND ";
               
               
            }
            
            
           // echo $string;
            
//            if ($gender <> "")
//
//                $string	.= "U.vGender = '".addslashes($gender)."' AND ";

            if ($agefrom <> "")

                $string	.= "TRUNCATE((TO_DAYS(NOW()) - TO_DAYS(U.dDob))/365, 0) >= '".addslashes($agefrom)."' AND ";

            if ($ageto <> "")

                $string	.= "TRUNCATE((TO_DAYS(NOW()) - TO_DAYS(U.dDob))/365, 0) <= '".addslashes($ageto)."' AND ";

            if ($county <> "")

                $string	.= "U.vCounty LIKE '".strtolower(addslashes($county))."%' AND ";

            if ($country <> "")

                $string	.= "U.vCountry = '".addslashes($country)."' AND ";

            if ($state <> "")

                $string	.= "U.vState = '".addslashes($state)."' AND ";

            if ($photo <> "" && $photo == "Y")

                $having	.= "HAVING COUNT( P.nPhoto_Id ) > 0 ";

            if ($string <> "")

                $string	= " WHERE ".$string." (U.vStatus LIKE 'A%' OR U.vStatus LIKE 'E%')";



            $arraysearch['search']		= $string;
            $arraysearch['vSG']			= addslashes($gender);
            $arraysearch['vSAF']		= addslashes($agefrom);
            $arraysearch['vSAT']		= addslashes($ageto);
            $arraysearch['vSP']			= addslashes($photo);
            $arraysearch['vCounty']		= addslashes($county);
            $arraysearch['vCountry']            = addslashes($country);
            $arraysearch['vState']		= addslashes($state);

            $this->arrSearch			= $arraysearch;
            $_SESSION['search_profile']	= serialize($arraysearch);

        } else {

            $string = '';
            if ($search <> "") {
                $this->arrSearch = unserialize($search);
                $string	= $this->arrSearch['search'];
            }
        }


        $string.="AND U.nUser_Id<>'".$_SESSION['user_id']."'";

        $sql	= "SELECT 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.dLast_Login_Time, U.nHeight
                  FROM ".TABLEPREFIX."user as U LEFT JOIN ".TABLEPREFIX."photos as P
                  ON U.nUser_Id = P.nUser_Id ".$string."
                  GROUP BY U.nUser_Id ".$having."
                  ORDER BY U.vFeatured DESC, U.nUser_Id DESC";

        if($pagination!='') {
            if($pagination==1) {
                $sql.=' LIMIT 0,'.$Pagesize;
            }
            elseif($pagination==-1) {
                if($limit!='')
                    $sql.=' LIMIT '.$limit;
            }
            else
                $sql.=' LIMIT '.($pagination-1)*$Pagesize.",".$Pagesize;
        }
        else {
            $sql.=' LIMIT 0,'.$Pagesize;
        }

        //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 search_profiles_matching($arrP=array(), $flag=false) {

        $array		= array();
        $arraysearch	= array();
        $string		= "";
        $getSitesettings = $this->getSiteSettings();
        $search	= isset($arrP['search_profile'])	?	stripslashes(trim($arrP['search_profile']))	:	"";

        
        
        
        if ($flag) {

            $_SESSION['search_profile']	= "";

            $string	= "";
            $having	= "";
            $gender	= isset($arrP['vSG'])	?	$arrP['vSG']	:	"";
            $agefrom	= isset($arrP['vSAF'])	?	$arrP['vSAF']	:	"";
            $ageto	= isset($arrP['vSAT'])	?	$arrP['vSAT']	:	"";
            $photo	= isset($arrP['vSP'])	?	$arrP['vSP']	:	"";
            $county	= isset($arrP['vCounty'])	?	$arrP['vCounty']	:	"";
            $country	= isset($arrP['vCountry'])	?	$arrP['vCountry']	:	"";
            $state	= isset($arrP['vState'])	?	$arrP['vState']	:	"";

            
            
             if($getSitesettings['enable_same_sex_search']=='Y')
            {
                if($arrP['vGender']=='Male' && $arrP['vDate_Preference']=='Female')
                {
                    $string	.= "U.vGender = 'Female' AND U.vDate_Preference='Male' AND ";
                }
               if($arrP['vGender']=='Female' && $arrP['vDate_Preference']=='Male'){
                    $string	.= "U.vGender = 'Male'  AND U.vDate_Preference='Female' AND ";
                }
                if($arrP['vGender']=='Female' && $arrP['vDate_Preference']=='Female')
                {
                    $string	.= "U.vGender = 'Female' AND U.vDate_Preference='Female' AND ";
                }
                if($arrP['vGender']=='Male' && $arrP['vDate_Preference']=='Male')
                {
                    $string	.= "U.vGender = 'Male' AND U.vDate_Preference='Male' AND ";
                }
                
            }else{
               if($arrP['vGender']=='Male')
                { 
               $string	.= "U.vGender = 'Female' AND ";
                }else{
                    $string	.= "U.vGender = 'Male' AND ";
                }
               
            }
            
            
            
           
            
            
           // echo $string;
            
//            if ($gender <> "")
//
//                $string	.= "U.vGender = '".addslashes($gender)."' AND ";

//            if ($agefrom <> "")
//
//                $string	.= "TRUNCATE((TO_DAYS(NOW()) - TO_DAYS(U.dDob))/365, 0) >= '".addslashes($agefrom)."' AND ";
//
//            if ($ageto <> "")
//
//                $string	.= "TRUNCATE((TO_DAYS(NOW()) - TO_DAYS(U.dDob))/365, 0) <= '".addslashes($ageto)."' AND ";

            

                $string	.= "(U.vCountry LIKE '".strtolower(addslashes($arrP['vCountry']))."' OR ";


                $string	.= "U.vState = '".addslashes($arrP['vState'])."' ) AND  ";

                
                
                
                $string	.= "(U.vBody_Type LIKE '%".addslashes($arrP['vBody_Type'])."%' OR ";

                $string	.= "U.vEye_Color LIKE '%".addslashes($arrP['vEye_Color'])."%'  OR  ";

                $string	.= "U.vBody_Art LIKE '%".addslashes($arrP['vBody_Art'])."%'  OR  ";
                
                $string	.= "U.vAstro_Sign LIKE '%".addslashes($arrP['vAstro_Sign'])."%'   OR  ";
                
                $string	.= "U.vFauvorite_Things LIKE '%".addslashes($arrP['vFauvorite_Things'])."%'  OR  ";
                
                $string	.= "U.vSports_Enjoyed LIKE '%".addslashes($arrP['vSports_Enjoyed'])."%'  OR   ";
                
                $string	.= "U.vHobbies LIKE '%".addslashes($arrP['vHobbies'])."%'  OR  ";
                
                
                $string	.= "U.vExcersise LIKE '%".addslashes($arrP['vExcersise'])."%'   OR   ";
                
                $string	.= "U.vTravel_Destination LIKE '%".addslashes($arrP['vTravel_Destination'])."%'  OR  ";
                
                $string	.= "U.vSmoking LIKE '%".addslashes($arrP['vSmoking'])."%'  OR  ";
                
                
                $string	.= "U.vDrinking LIKE '%".addslashes($arrP['vDrinking'])."%'  OR  ";
                
                
                $string	.= "U.vEthinicity LIKE '%".addslashes($arrP['vEthinicity'])."%'  OR   ";
                
                $string	.= "U.vLiving_Situation LIKE '%".addslashes($arrP['vLiving_Situation'])."%'  OR  ";
                
                $string	.= "U.tAbout_Partner LIKE '%".addslashes($arrP['tAbout_Partner'])."%' ) AND  ";
                
                 

                $having	.= "HAVING COUNT( P.nPhoto_Id ) > 0 ";
            

            if ($string <> "")

                $string	= " WHERE ".$string." U.vStatus LIKE 'A%' AND U.nUser_Id NOT IN(select nUser_Id_Hot from ".TABLEPREFIX."hot where nUser_Id = '".$_SESSION['user_id']."' ) AND U.nUser_Id NOT IN(select nUser_Id_Friend from ".TABLEPREFIX."imfriends where nUser_Id = '".$_SESSION['user_id']."'  AND vStatus='AN')";



            $arraysearch['search']		= $string;
            $arraysearch['vSG']			= addslashes($gender);
            $arraysearch['vSAF']		= addslashes($agefrom);
            $arraysearch['vSAT']		= addslashes($ageto);
            $arraysearch['vSP']			= addslashes($photo);
            $arraysearch['vCounty']		= addslashes($county);
            $arraysearch['vCountry']            = addslashes($country);
            $arraysearch['vState']		= addslashes($state);

            $this->arrSearch			= $arraysearch;
            $_SESSION['search_profile']	= serialize($arraysearch);

        } else {

            $string = '';
            if ($search <> "") {
                $this->arrSearch = unserialize($search);
                $string	= $this->arrSearch['search'];
            }
        }


        $string.="AND U.nUser_Id<>'".$_SESSION['user_id']."'";

        $sql	= "SELECT 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.dLast_Login_Time, U.nHeight
                  FROM ".TABLEPREFIX."user as U LEFT JOIN ".TABLEPREFIX."photos as P
                  ON U.nUser_Id = P.nUser_Id 

                  ".$string."    
                  GROUP BY U.nUser_Id ".$having."
                  ORDER BY U.vFeatured DESC, U.nUser_Id DESC ";

       

       // echo $sql;
        $res	= @mysql_query($sql, $this->dblink);

        $count = mysql_num_rows($res);
        
        
//         $currdate = date('Y-m-d');
//            if($_SESSION['user_id']){
//            $delsql = "DELETE FROM ".TABLEPREFIX."matching_profiles WHERE nUser_Id = '".$_SESSION['user_id']."'";
//            
//            $del	= @mysql_query($delsql, $this->dblink);
//            }
        
        
        if (@mysql_num_rows($res) > 0) {
            while ($row = @mysql_fetch_array($res)) {
                
//                $insertSql = "INSERT INTO ".TABLEPREFIX."matching_profiles (nUser_Id, profile_Id,
//
//									match_date)
//
//					   VALUES ('{$_SESSION['user_id']}', '{$row['nUser_Id']}', '{$currdate}')";
//                                           
//                                          // echo $insertSql.'<br>';
//                                           
//                          $inSql	= @mysql_query($insertSql, $this->dblink);                 
                                           
                $array['data'][]	= $row;
            }
        }

        @mysql_free_result($res);
        
        
        $array['count'] = $count;
        return $array;

    }
    
    
    function search_profiles_matching_background($arrP=array(), $flag=false) {
         if($_SESSION['user_id']){
        $array		= array();
        $arraysearch	= array();
        $string		= "";
        $getSitesettings = $this->getSiteSettings();
        $search	= isset($arrP['search_profile'])	?	stripslashes(trim($arrP['search_profile']))	:	"";

        $currdate = date('Y-m-d');
         
         
        $matchexistingquery = "SELECT * FROM ".TABLEPREFIX."matching_profiles WHERE  nUser_Id = '".$_SESSION['user_id']."' AND match_date = '$currdate' ";
       // echo "SELECT * FROM ".TABLEPREFIX."matching_profiles WHERE  nUser_Id = '".$_SESSION['user_id']."' AND match_date = '$currdate' ";
        $matchexistingqueryres	= @mysql_query($matchexistingquery, $this->dblink);

        $matchexistingquerycount = mysql_num_rows($matchexistingqueryres);
      //  echo $matchexistingquerycount;
        if(!$matchexistingquerycount){
        
        
        if ($flag) {

            $_SESSION['search_profile']	= "";

            $string	= "";
            $having	= "";
            $gender	= isset($arrP['vSG'])	?	$arrP['vSG']	:	"";
            $agefrom	= isset($arrP['vSAF'])	?	$arrP['vSAF']	:	"";
            $ageto	= isset($arrP['vSAT'])	?	$arrP['vSAT']	:	"";
            $photo	= isset($arrP['vSP'])	?	$arrP['vSP']	:	"";
            $county	= isset($arrP['vCounty'])	?	$arrP['vCounty']	:	"";
            $country	= isset($arrP['vCountry'])	?	$arrP['vCountry']	:	"";
            $state	= isset($arrP['vState'])	?	$arrP['vState']	:	"";

            
            
             if($getSitesettings['enable_same_sex_search']=='Y')
            {
                if($arrP['vGender']=='Male' && $arrP['vDate_Preference']=='Female')
                {
                    $string	.= "U.vGender = 'Female' AND U.vDate_Preference='Male' AND ";
                }
               if($arrP['vGender']=='Female' && $arrP['vDate_Preference']=='Male'){
                    $string	.= "U.vGender = 'Male'  AND U.vDate_Preference='Female' AND ";
                }
                if($arrP['vGender']=='Female' && $arrP['vDate_Preference']=='Female')
                {
                    $string	.= "U.vGender = 'Female' AND U.vDate_Preference='Female' AND ";
                }
                if($arrP['vGender']=='Male' && $arrP['vDate_Preference']=='Male')
                {
                    $string	.= "U.vGender = 'Male' AND U.vDate_Preference='Male' AND ";
                }
                
            }else{
               if($arrP['vGender']=='Male')
                { 
               $string	.= "U.vGender = 'Female' AND ";
                }else{
                    $string	.= "U.vGender = 'Male' AND ";
                }
               
            }
            
            
            
           
            
            
           // echo $string;
            
//            if ($gender <> "")
//
//                $string	.= "U.vGender = '".addslashes($gender)."' AND ";

//            if ($agefrom <> "")
//
//                $string	.= "TRUNCATE((TO_DAYS(NOW()) - TO_DAYS(U.dDob))/365, 0) >= '".addslashes($agefrom)."' AND ";
//
//            if ($ageto <> "")
//
//                $string	.= "TRUNCATE((TO_DAYS(NOW()) - TO_DAYS(U.dDob))/365, 0) <= '".addslashes($ageto)."' AND ";

            

                $string	.= "(U.vCountry LIKE '".strtolower(addslashes($arrP['vCountry']))."%' OR ";


                $string	.= "U.vState = '".addslashes($arrP['vState'])."' ) AND  ";

                
                
                
                $string	.= "(U.vBody_Type LIKE '%".addslashes($arrP['vBody_Type'])."%' OR ";

                $string	.= "U.vEye_Color LIKE '%".addslashes($arrP['vEye_Color'])."%'  OR  ";

                $string	.= "U.vBody_Art LIKE '%".addslashes($arrP['vBody_Art'])."%'  OR  ";
                
                $string	.= "U.vAstro_Sign LIKE '%".addslashes($arrP['vAstro_Sign'])."%'   OR  ";
                
                $string	.= "U.vFauvorite_Things LIKE '%".addslashes($arrP['vFauvorite_Things'])."%'  OR  ";
                
                $string	.= "U.vSports_Enjoyed LIKE '%".addslashes($arrP['vSports_Enjoyed'])."%'  OR   ";
                
                $string	.= "U.vHobbies LIKE '%".addslashes($arrP['vHobbies'])."%'  OR  ";
                
                
                $string	.= "U.vExcersise LIKE '%".addslashes($arrP['vExcersise'])."%'   OR   ";
                
                $string	.= "U.vTravel_Destination LIKE '%".addslashes($arrP['vTravel_Destination'])."%'  OR  ";
                
                $string	.= "U.vSmoking LIKE '%".addslashes($arrP['vSmoking'])."%'  OR  ";
                
                
                $string	.= "U.vDrinking LIKE '%".addslashes($arrP['vDrinking'])."%'  OR  ";
                
                
                $string	.= "U.vEthinicity LIKE '%".addslashes($arrP['vEthinicity'])."%'  OR   ";
                
                $string	.= "U.vLiving_Situation LIKE '%".addslashes($arrP['vLiving_Situation'])."%'  OR  ";
                
                $string	.= "U.tAbout_Partner LIKE '%".addslashes($arrP['tAbout_Partner'])."%' ) AND  ";
                
                 

                $having	.= "HAVING COUNT( P.nPhoto_Id ) > 0 ";
            

            if ($string <> "")

                $string	= " WHERE ".$string." U.vStatus LIKE 'A%' AND U.nUser_Id NOT IN(select nUser_Id_Hot from ".TABLEPREFIX."hot where nUser_Id = '".$_SESSION['user_id']."' ) AND U.nUser_Id NOT IN(select nUser_Id_Friend from ".TABLEPREFIX."imfriends where nUser_Id = '".$_SESSION['user_id']."'  AND vStatus='AN')";



            $arraysearch['search']		= $string;
            $arraysearch['vSG']			= addslashes($gender);
            $arraysearch['vSAF']		= addslashes($agefrom);
            $arraysearch['vSAT']		= addslashes($ageto);
            $arraysearch['vSP']			= addslashes($photo);
            $arraysearch['vCounty']		= addslashes($county);
            $arraysearch['vCountry']            = addslashes($country);
            $arraysearch['vState']		= addslashes($state);

            $this->arrSearch			= $arraysearch;
            $_SESSION['search_profile']	= serialize($arraysearch);

        } else {

            $string = '';
            if ($search <> "") {
                $this->arrSearch = unserialize($search);
                $string	= $this->arrSearch['search'];
            }
        }


        $string.="AND U.nUser_Id<>'".$_SESSION['user_id']."'";

        $sql	= "SELECT 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.dLast_Login_Time, U.nHeight
                  FROM ".TABLEPREFIX."user as U LEFT JOIN ".TABLEPREFIX."photos as P
                  ON U.nUser_Id = P.nUser_Id 

                  ".$string."    
                  GROUP BY U.nUser_Id ".$having."
                  ORDER BY U.vFeatured DESC, U.nUser_Id DESC";

       

       // echo $sql;
        $res	= @mysql_query($sql, $this->dblink);

        $count = mysql_num_rows($res);
                
         
           
           
            $delsql = "DELETE FROM ".TABLEPREFIX."matching_profiles WHERE nUser_Id = '".$_SESSION['user_id']."' AND match_date < '$currdate' ";
            
            $del	= @mysql_query($delsql, $this->dblink);
            
        
        
        if (@mysql_num_rows($res) > 0) {
            while ($row = @mysql_fetch_array($res)) {
               
                $insertSql = "INSERT INTO ".TABLEPREFIX."matching_profiles (nUser_Id, profile_Id,

									match_date)

					   VALUES ('{$_SESSION['user_id']}', '{$row['nUser_Id']}', '{$currdate}')";
                                           
                                          // echo $insertSql.'<br>';
                                           
                          $inSql	= @mysql_query($insertSql, $this->dblink);     
            
                                           
                $array['data'][]	= $row;
            }
        }

        @mysql_free_result($res);
        
        
        $array['count'] = $count;
        return $array;
        }
         }
         else{
             return '';
         }
    }
    
    
    function chatsearch($arrP=array(), $flag=false) {
        
        $array		= array();
        $arraysearch	= array();
        $string		= "";
        $getSitesettings = $this->getSiteSettings();
        $search	= isset($arrP['search_profile'])	?	stripslashes(trim($arrP['search_profile']))	:	"";

       
        
        
        if ($flag) {

            $_SESSION['search_profile']	= "";

            $string	= "";
            $having	= "";
            $gender	= isset($arrP['vSG'])	?	$arrP['vSG']	:	"";
            $agefrom	= isset($arrP['vSAF'])	?	$arrP['vSAF']	:	"";
            $ageto	= isset($arrP['vSAT'])	?	$arrP['vSAT']	:	"";
            $photo	= isset($arrP['vSP'])	?	$arrP['vSP']	:	"";
            $county	= isset($arrP['vCounty'])	?	$arrP['vCounty']	:	"";
            $country	= isset($arrP['vCountry'])	?	$arrP['vCountry']	:	"";
            $state	= isset($arrP['vState'])	?	$arrP['vState']	:	"";

            $string = '';
            
            
            if($arrP['search'])
            {
                
              $string.=" (U.vLogin LIKE '%".addslashes($arrP['search'])."%'  OR U.vEmail LIKE '%".addslashes($arrP['search'])."%' OR U.vFirstName LIKE '%".addslashes($arrP['search'])."%' 
                  OR U.vLastName LIKE '%".addslashes($arrP['search'])."%' OR CONCAT(U.vFirstName,' ',U.vLastName) LIKE '%".addslashes($arrP['search'])."%') AND ";  
            }
            
            
//             if($getSitesettings['enable_same_sex_search']=='Y')
//            {
//                if($arrP['vGender']=='Male' && $arrP['vDate_Preference']=='Female')
//                {
//                    $string	.= "U.vGender = 'Female' AND U.vDate_Preference='Male' AND ";
//                }
//               if($arrP['vGender']=='Female' && $arrP['vDate_Preference']=='Male'){
//                    $string	.= "U.vGender = 'Male'  AND U.vDate_Preference='Female' AND ";
//                }
//                if($arrP['vGender']=='Female' && $arrP['vDate_Preference']=='Female')
//                {
//                    $string	.= "U.vGender = 'Female' AND U.vDate_Preference='Female' AND ";
//                }
//                if($arrP['vGender']=='Male' && $arrP['vDate_Preference']=='Male')
//                {
//                    $string	.= "U.vGender = 'Male' AND U.vDate_Preference='Male' AND ";
//                }
//                
//            }else{
//               if($arrP['vGender']=='Male')
//                { 
//               $string	.= "U.vGender = 'Female' AND ";
//                }else{
//                    $string	.= "U.vGender = 'Male' AND ";
//                }
//               
//            }
//            
//            
//            
//           
//            
//            
//           // echo $string;
//            
////            if ($gender <> "")
////
////                $string	.= "U.vGender = '".addslashes($gender)."' AND ";
//
////            if ($agefrom <> "")
////
////                $string	.= "TRUNCATE((TO_DAYS(NOW()) - TO_DAYS(U.dDob))/365, 0) >= '".addslashes($agefrom)."' AND ";
////
////            if ($ageto <> "")
////
////                $string	.= "TRUNCATE((TO_DAYS(NOW()) - TO_DAYS(U.dDob))/365, 0) <= '".addslashes($ageto)."' AND ";
//
//            
//
//                $string	.= "(U.vCounty LIKE '".strtolower(addslashes($arrP['vCounty']))."%' OR ";
//
//
//                $string	.= "U.vState = '".addslashes($arrP['vState'])."' ) AND  ";
//
//                
//                
//                
//                $string	.= "(U.vBody_Type LIKE '".addslashes($arrP['vBody_Type'])."' OR ";
//
//                $string	.= "U.vEye_Color = '".addslashes($arrP['vEye_Color'])."'  OR  ";
//
//                $string	.= "U.vBody_Art = '".addslashes($arrP['vBody_Art'])."'  OR  ";
//                
//                $string	.= "U.vAstro_Sign = '".addslashes($arrP['vAstro_Sign'])."'  OR   ";
//                
//                $string	.= "U.vFauvorite_Things = '%".addslashes($arrP['vFauvorite_Things'])."%'  OR  ";
//                
//                $string	.= "U.vSports_Enjoyed = '%".addslashes($arrP['vSports_Enjoyed'])."%'  OR   ";
//                
//                $string	.= "U.vHobbies = '%".addslashes($arrP['vHobbies'])."%'  OR  ";
//                
//                
//                $string	.= "U.vExcersise = '%".addslashes($arrP['vExcersise'])."%'  OR   ";
//                
//                $string	.= "U.vTravel_Destination = '%".addslashes($arrP['vTravel_Destination'])."%'  OR  ";
//                
//                $string	.= "U.vSmoking = '%".addslashes($arrP['vSmoking'])."%'  OR  ";
//                
//                
//                $string	.= "U.vDrinking = '%".addslashes($arrP['vDrinking'])."%'  OR  ";
//                
//                
//                $string	.= "U.vEthinicity = '%".addslashes($arrP['vEthinicity'])."%'  OR   ";
//                
//                $string	.= "U.vLiving_Situation = '%".addslashes($arrP['vLiving_Situation'])."%'  OR  ";
//                
//                $string	.= "U.tAbout_Partner = '%".addslashes($arrP['tAbout_Partner'])."%' ) AND  ";
                
                 

                $having	.= "";
            

            if ($string <> "")

                $string	= " WHERE ".$string." (U.vStatus LIKE 'A%' OR U.vStatus LIKE 'E%')  AND U.nUser_Id NOT IN(select nUser_Id_Friend from ".TABLEPREFIX."imfriends where nUser_Id = '".$_SESSION['user_id']."' AND vStatus='AN')";



            $arraysearch['search']		= $string;
            $arraysearch['vSG']			= addslashes($gender);
            $arraysearch['vSAF']		= addslashes($agefrom);
            $arraysearch['vSAT']		= addslashes($ageto);
            $arraysearch['vSP']			= addslashes($photo);
            $arraysearch['vCounty']		= addslashes($county);
            $arraysearch['vCountry']            = addslashes($country);
            $arraysearch['vState']		= addslashes($state);

            $this->arrSearch			= $arraysearch;
            $_SESSION['search_profile']	= serialize($arraysearch);

        } else {

            $string = '';
            if ($search <> "") {
                $this->arrSearch = unserialize($search);
                $string	= $this->arrSearch['search'];
            }
        }


        $string.="AND U.nUser_Id<>'".$_SESSION['user_id']."'";

        $sql	= "SELECT U.nUser_Id, U.vLogin, U.vGender, U.vFirstName,U.vLastName, 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.dLast_Login_Time, U.nHeight
                  FROM ".TABLEPREFIX."user as U LEFT JOIN ".TABLEPREFIX."photos as P
                  ON U.nUser_Id = P.nUser_Id 
                  ".$string."    
                  GROUP BY U.nUser_Id ".$having."
                  ORDER BY U.vFeatured DESC, U.nUser_Id DESC";

       

        //echo $sql;
        $res	= @mysql_query($sql, $this->dblink);

        $count = mysql_num_rows($res);
                
         
           
           
            $delsql = "DELETE FROM ".TABLEPREFIX."matching_profiles WHERE nUser_Id = '".$_SESSION['user_id']."' AND match_date < '$currdate' ";
            
            $del	= @mysql_query($delsql, $this->dblink);
            
        
        
        if (@mysql_num_rows($res) > 0) {
            while ($row = @mysql_fetch_array($res)) {
               
                $insertSql = "INSERT INTO ".TABLEPREFIX."matching_profiles (nUser_Id, profile_Id,

									match_date)

					   VALUES ('{$_SESSION['user_id']}', '{$row['nUser_Id']}', '{$currdate}')";
                                           
                                          // echo $insertSql.'<br>';
                                           
                          $inSql	= @mysql_query($insertSql, $this->dblink);     
            
                                           
                $array['data'][]	= $row;
            }
        }

        @mysql_free_result($res);
        
        
        $array['count'] = $count;
        return $array;
        
         
        
    }
    
    
    function getUserDetails($id)
    {
        $array = array();
        $sql = "SELECT * FROM ".TABLEPREFIX."user WHERE nUser_Id = $id";
        $res	= @mysql_query($sql);
        if (@mysql_num_rows($res) > 0) {
            while ($row = @mysql_fetch_assoc($res)) {
                $array[]	= $row;
            }
        }
        
        return $array;
    }
     function getSiteSettings()
    {
        $array = array();
        $sql = "SELECT * FROM ".TABLEPREFIX."lookup";
        $res	= @mysql_query($sql);
        if (@mysql_num_rows($res) > 0) {
            while ($row = @mysql_fetch_assoc($res)) {
                $array[$row['vName']]	= $row['vValue'];
            }
        }
        
        return $array;
    }
    
     function search_profiles_api($arrP=array()) {

        $array		= array();
        $arraysearch	= array();
        $string		= "";

        $userDetails = $this->getUserDetails($arrP['user_id']);
        $getSitesettings = $this->getSiteSettings();
        //print_r($userDetails); exit;

            $string	= "";
            $having	= "";
            $gender	= isset($arrP['vSG'])	?	$arrP['vSG']	:	"";
            $agefrom	= isset($arrP['vSAF'])	?	$arrP['vSAF']	:	"";
            $ageto	= isset($arrP['vSAT'])	?	$arrP['vSAT']	:	"";
            $photo	= isset($arrP['vSP'])	?	$arrP['vSP']	:	"";
            $county	= isset($arrP['vCounty'])	?	$arrP['vCounty']	:	"";
            $country	= isset($arrP['vCountry'])	?	$arrP['vCountry']	:	"";
            $state	= isset($arrP['vState'])	?	$arrP['vState']	:	"";
            
            
            

//            if ($gender <> "")
//
//                $string	.= "U.vGender = '".addslashes($gender)."' AND ";
            
            if($getSitesettings['enable_same_sex_search']=='Y')
            {
                if($userDetails[0]['vGender']=='Female')
                {
                    $string	.= "U.vGender = 'Female' AND U.vDate_Preference='Female' AND ";
                }else{
                    $string	.= "U.vGender = 'Male' AND U.vDate_Preference='Male' AND ";
                }
                
                
            }else{
                
                if($userDetails[0]['vGender']=='Female')
                {
                    $string	.= "U.vGender = 'Male' AND ";
                }else{
                    $string	.= "U.vGender = 'Female' AND ";
                }
            }
            
//echo $userDetails[0]['vGender'].'<br>';
//
//echo $string.'<br>';
            if ($agefrom <> "")

                $string	.= "TRUNCATE((TO_DAYS(NOW()) - TO_DAYS(U.dDob))/365, 0) >= '".addslashes($agefrom)."' AND ";

            if ($ageto <> "")

                $string	.= "TRUNCATE((TO_DAYS(NOW()) - TO_DAYS(U.dDob))/365, 0) <= '".addslashes($ageto)."' AND ";

            if ($county <> "")

                $string	.= "U.vCounty LIKE '".strtolower(addslashes($county))."%' AND ";

            if ($country <> "")

                $string	.= "U.vCountry = '".addslashes($country)."' AND ";

            if ($state <> "")

                $string	.= "U.vState = '".addslashes($state)."' AND ";

            if ($photo <> "" && $photo == "Y")

                $having	.= "HAVING COUNT( P.nPhoto_Id ) > 0 ";

            if ($string <> "")

                $string	= " WHERE ".$string." (U.vStatus LIKE 'A%' OR U.vStatus LIKE 'E%')";



            $arraysearch['search']		= $string;
            $arraysearch['vSG']			= addslashes($gender);
            $arraysearch['vSAF']		= addslashes($agefrom);
            $arraysearch['vSAT']		= addslashes($ageto);
            $arraysearch['vSP']			= addslashes($photo);
            $arraysearch['vCounty']		= addslashes($county);
            $arraysearch['vCountry']            = addslashes($country);
            $arraysearch['vState']		= addslashes($state);

            $arraysearch;
           

      


        $string.="AND U.nUser_Id<>'".$arrP['user_id']."'";

        $sql	= "SELECT U.*
                  FROM ".TABLEPREFIX."user as U LEFT JOIN ".TABLEPREFIX."photos as P
                  ON U.nUser_Id = P.nUser_Id ".$string."
                  GROUP BY U.nUser_Id ".$having."
                  ORDER BY U.vFeatured DESC, U.nUser_Id DESC";
        
       

      
           
        

        
        $res	= @mysql_query($sql);

        
        
        if (@mysql_num_rows($res) > 0) {
            while ($row = @mysql_fetch_assoc($res)) {
                 /* Start- Section to get the photos of the users*/
                $photo_sql	= "SELECT vUrl FROM ".TABLEPREFIX."photos WHERE nUser_Id = '{$row['nUser_Id']}'";     
                $photo_res	= @mysql_query($photo_sql);  
                $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['profiles'][]	= $row;
            }
        }

        @mysql_free_result($res);
        $array['search'][] = $arraysearch;
        return $array;

    }
    

    function search_profiles_count($arrP=array(), $flag=false) { 

        $array		= array();
        $arraysearch	= array();
        $string		= "";
        $getSitesettings = $this->getSiteSettings();
        $search	= isset($arrP['search_profile'])	?	stripslashes(trim($arrP['search_profile']))	:	"";
        
        if ($flag) { 

            $_SESSION['search_profile']	= "";

            $string	= "";
            $having	= "";
            $gender	= isset($arrP['vSG'])	?	$arrP['vSG']	:	"";
            $agefrom	= isset($arrP['vSAF'])	?	$arrP['vSAF']	:	"";
            $ageto	= isset($arrP['vSAT'])	?	$arrP['vSAT']	:	"";
            $photo	= isset($arrP['vSP'])	?	$arrP['vSP']	:	"";
            $county	= isset($arrP['vCounty']) ?	$arrP['vCounty']:	"";
            $country	= isset($arrP['vCountry'])?	$arrP['vCountry']:	"";
            $state	= isset($arrP['vState'])  ?	$arrP['vState']	:	"";

            if($getSitesettings['enable_same_sex_search']=='Y')
            {
                if($gender=='Female')
                {
                    $string	.= "U.vGender = 'Female' AND U.vDate_Preference='Male' AND ";
                }
               if($gender=='Male'){
                    $string	.= "U.vGender = 'Male'  AND U.vDate_Preference='Female' AND ";
                }
                if($gender=='Females')
                {
                    $string	.= "U.vGender = 'Female' AND U.vDate_Preference='Female' AND ";
                }
                if($gender=='Males')
                {
                    $string	.= "U.vGender = 'Male' AND U.vDate_Preference='Male' AND ";
                }
                
            }else{
                
               $string	.= "U.vGender = '".addslashes($gender)."' AND ";
               
               
            }

//            if ($gender <> "")
//
//                $string	.= "U.vGender = '".addslashes($gender)."' AND ";

            if ($agefrom <> "")

                $string	.= "TRUNCATE((TO_DAYS(NOW()) - TO_DAYS(U.dDob))/365, 0) >= '".addslashes($agefrom)."' AND ";

            if ($ageto <> "")

                $string	.= "TRUNCATE((TO_DAYS(NOW()) - TO_DAYS(U.dDob))/365, 0) <= '".addslashes($ageto)."' AND ";

            if ($county <> "")

                $string	.= "U.vCounty LIKE '".strtolower(addslashes($county))."%' AND ";

            if ($country <> "")

                $string	.= "U.vCountry = '".addslashes($country)."' AND ";

            if ($state <> "")

                $string	.= "U.vState = '".addslashes($state)."' AND ";

            if ($photo <> "" && $photo == "Y")

                $having	.= "HAVING COUNT( P.nPhoto_Id ) > 0 ";

            if ($string <> "")

                $string	= " WHERE ".$string." (U.vStatus LIKE 'A%' OR U.vStatus LIKE 'E%') ";



            $arraysearch['search']		= $string;

            $arraysearch['vSG']			= addslashes($gender);

            $arraysearch['vSAF']		= addslashes($agefrom);

            $arraysearch['vSAT']		= addslashes($ageto);

            $arraysearch['vSP']			= addslashes($photo);

            $arraysearch['vCounty']		= addslashes($county);

            $arraysearch['vCountry']	= addslashes($country);

            $arraysearch['vState']		= addslashes($state);

            $this->arrSearch			= $arraysearch;
            $_SESSION['search_profile']	= serialize($arraysearch);

        } else {

            $string = '';
            if ($search <> "") {
                $this->arrSearch = unserialize($search);
                $string	= $this->arrSearch['search'];
            }
        }

        $string.="AND U.nUser_Id<>'".$_SESSION['user_id']."'";

        $sql	= "SELECT U.nUser_Id
                   FROM ".TABLEPREFIX."user as U LEFT JOIN ".TABLEPREFIX."photos as P
                   ON U.nUser_Id = P.nUser_Id ".$string."
                   GROUP BY U.nUser_Id ".$having."
                   ORDER BY U.vFeatured DESC, U.nUser_Id DESC";  

        $res	= @mysql_query($sql, $this->dblink);
        return mysql_num_rows($res);

    }



    function get_profile_id($name="") {

        $id		= 0;

        $sql	= "SELECT * FROM ".TABLEPREFIX."user

				   WHERE vLogin = '".addslashes($name)."' AND vStatus LIKE 'A%'";

        $res	= @mysql_query($sql, $this->dblink);

        if (@mysql_num_rows($res) > 0) {

            $row	= @mysql_fetch_array($res);

            $id		= $row['nUser_Id'];

        }

        return $id;

    }



    function is_expired($id=0) {

        $flag	= false;

        $sql	= "SELECT * FROM ".TABLEPREFIX."user WHERE vStatus LIKE 'E%' AND nUser_Id = '{$id}'";

        $res	= @mysql_query($sql);

        if (@mysql_num_rows($res) > 0) {
            $flag	= true;
        }
        return $flag;

    }
    
    function featuredText() {
        $flag	= false;
        $sql	= "SELECT vValue FROM ".TABLEPREFIX."lookup WHERE vName LIKE '%profFeatureText%'";
        $res	= @mysql_query($sql, $this->dblink);
        if (@mysql_num_rows($res) > 0) {
            $row_msg = mysql_fetch_array($res);
            return $row_msg['vValue'];
        }
        return '';
    }


    function get_amount($id=0) {

        $amount	= 0;

        require_once "settings.class.php";

        //$arrSettings	= settings::select();
        $settingsObj = new settings();
        $arrSettings	= $settingsObj->select();

        if ($id == "1") {

            $amount	= $arrSettings['membership_amount'];

        } else if ($id == "2") {

            $amount	= $arrSettings['membership_amount'];

        } else if ($id == "3") {

            $amount	= $arrSettings['featured_amount'];

        } else if ($id == "4") {

            $amount	= $arrSettings['background_check_amount'];

        } else if ($id == "5") {

            $amount	= $arrSettings['identity_verification_amount'];

        } else if ($id == "6") {
            $amount	= $arrSettings['membership_amount'];
        }

        return $amount;

    }



    function get_product_amount($id=0) {

        $amount	= 0;

        $sql	= "SELECT * FROM ".TABLEPREFIX."products WHERE nProdId = '{$id}'";

        $res	= @mysql_query($sql, $this->dblink);

        if (@mysql_num_rows($res) > 0) {

            $row	= @mysql_fetch_array($res);

            $amount	= $row['fAmount'];

        }

        return $amount;

    }



    function get_product($id=0) {

        $name	= "";

        $sql	= "SELECT * FROM ".TABLEPREFIX."products WHERE nProdId = '{$id}'";

        $res	= @mysql_query($sql, $this->dblink);

        if (@mysql_num_rows($res) > 0) {

            $row	= @mysql_fetch_array($res);

            $name	= $row['vProdName'];

        }

        return $name;

    }



    function is_featured($id=0) {

        $flag	= false;

        $sql	= "SELECT * FROM ".TABLEPREFIX."user WHERE vFeatured LIKE 'YNNN' AND nUser_Id = '{$id}'";

        $res	= @mysql_query($sql, $this->dblink);

        if (@mysql_num_rows($res) > 0) {

            $flag	= true;

        }

        return $flag;

    }



    function is_id_verfied($id=0) {

        $flag	= false;

        $sql	= "SELECT * FROM ".TABLEPREFIX."user WHERE vId_Varified LIKE 'VN' AND nUser_Id = '{$id}'";

        $res	= @mysql_query($sql, $this->dblink);

        if (@mysql_num_rows($res) > 0) {

            $flag	= true;

        }

        return $flag;

    }



    function is_background_check_verfied($id=0) {

        $flag	= false;

        $sql	= "SELECT * FROM ".TABLEPREFIX."user WHERE vBC_Verified LIKE 'VN' AND nUser_Id = '{$id}'";

        $res	= @mysql_query($sql, $this->dblink);

        if (@mysql_num_rows($res) > 0) {

            $flag	= true;

        }

        return $flag;

    }



    function get_id_verify($id=0) {

        $status	= "NN";

        $sql	= "SELECT * FROM ".TABLEPREFIX."user WHERE nUser_Id = '{$id}'";

        $res	= @mysql_query($sql, $this->dblink);

        if (@mysql_num_rows($res) > 0) {

            $row	= @mysql_fetch_array($res);

            $status	= $row['vId_Varified'];

        }

        return $status;

    }



    function get_background_check($id=0) {

        $status	= "NN";

        $sql	= "SELECT * FROM ".TABLEPREFIX."user WHERE nUser_Id = '{$id}'";

        $res	= @mysql_query($sql, $this->dblink);

        if (@mysql_num_rows($res) > 0) {

            $row	= @mysql_fetch_array($res);

            $status	= $row['vBC_Verified'];

        }

        return $status;

    }



    function get_featured_image($id=0, $path="./images/") {

        $img	= '<img src="'.$path.'featuredicon.gif" title="Featured Profile" alt="Featured Profile">';

        if (!$this->is_featured($id))

            $img	= '<img src="'.$path.'featuredicon1.gif" title="Not Featured Profile" alt="Not Featured Profile" >';

        return $img;

    }



    function get_id_verify_image($id=0, $path="./images/") {

        $img	= '<img src="'.$path.'idverify2.gif" width="34" height="35" title="ID VERIFY (NOT APPLIED)" alt="ID VERIFY (NOT APPLIED)">';

        $status	= $this->get_id_verify($id);

        if ($status == "NN") {

            $img	= '<img src="'.$path.'idverify2.gif" width="34" height="35" title="ID VERIFY (NOT APPLIED)" alt="ID VERIFY (NOT APPLIED)">';

        } else if ($status == "PN") {

            $img	= '<img src="'.$path.'idverify2.gif" width="34" height="35" title="ID VERIFY (PENDING)" alt="ID VERIFY (PENDING)">';

        } else if ($status == "VN") {

            $img	= '<img src="'.$path.'idverify.gif" width="34" height="35" title="ID VERIFY (PASSED)" alt="ID VERIFY (PASSED)">';

        } else {

            $img	= '<img src="'.$path.'idverify1.gif" width="34" height="35" title="ID VERIFY (FAILED)" alt="ID VERIFY (FAILED)">';

        }

        return $img;

    }



    function get_bgcheck_image($id=0, $path="./images/") {


        $status	= $this->get_background_check($id);
        if ($status == "VN") {

            $img	= '<img src="'.$path.'bgchek.gif" width="34" height="35" title="BACKGROUND CHECK (PASSED)" alt="BACKGROUND CHECK (PASSED)">';

        }

        return $img;

    }



    function get_image_url($rel="", $imgid="0", $gen="Male") {

        $image	= "";

        $img	= "";

        if ($imgid > 0) {

            $arrImg		= $this->get_image($imgid);

            if (!empty($arrImg)) {

                $img	= $arrImg['vUrl'];

            }

        }

        if ($gen == "Male") {

            if ($img == "") $img	= "nophoto1.gif";

            else $img = "sthumb_".$img;

        } else {

            if ($img == "") $img	= "nophoto.gif";

            else $img = "sthumb_".$img;

        }

        $image	= $rel."/".$img;

        return $image;

    }

function get_pimage_url($rel="", $imgid="0", $gen="Male") {

        $image	= "";

        $img	= "";

        if ($imgid > 0) {

            $arrImg		= $this->get_image($imgid);

            if (!empty($arrImg)) {

                $img	= $arrImg['vUrl'];

            }

        }

        if ($gen == "Male") {

            if ($img == "") $img	= "nophoto1.gif";

            else $img = "pthumb_".$img;

        } else {

            if ($img == "") $img	= "nophoto.gif";

            else $img = "pthumb_".$img;

        }

        $image	= $rel."/".$img;

        return $image;

    }

    function get_display_image($rel="", $id="0", $gen="Male") {

        $image	= "";

        $img	= "";

        if ($id > 0) {

            $arrImg		= $this->get_user_images($id);

            if (!empty($arrImg)) {

                $img	= $arrImg[0]['vUrl'];

            }

        }

        if ($gen == "Male") {

            if ($img == "") $img	= "bignophoto1.gif";

            else $img = "pthumb_".$img;

        } else {

            if ($img == "") $img	= "bignophoto.gif";

            else $img = "pthumb_".$img;

        }

        $image	= $rel."/".$img;

        return $image;

    }



    function get_full_image($rel="", $id="0", $gen="Male") {

        $image	= "";

        $img	= "";

        if ($id > 0) {

            $arrImg		= $this->get_user_images($id);

            if (!empty($arrImg)) {

                $img	= $arrImg[0]['vUrl'];

            }

        }

        if ($gen == "Male") {

            if ($img == "") $img	= "bignophoto1.gif";

        } else {

            if ($img == "") $img	= "bignophoto.gif";

        }

        $image	= $rel."/".$img;

        return $image;

    }






// CRON jobs







    function registration_alert() {

        $arrNew	= array();

        $date	= date("Y-m-d");

        $sql	= "SELECT *,TRUNCATE((TO_DAYS(NOW()) - TO_DAYS(dDob))/365, 0) as vAge

				   FROM ".TABLEPREFIX."user

		           WHERE dActive_Date = '{$date}' AND vAlertStatus LIKE 'N'

						 AND vStatus LIKE 'A%'";

        $res	= @mysql_query($sql, $this->dblink);

        if (@mysql_num_rows($res) > 0) {

            while($row = @mysql_fetch_array($res)) {

                $arrNew[]	= $row;

            }

        }



        if (!empty($arrNew)) {

            foreach ($arrNew as $key => $value) {

                $this->send_alert_to_matches($value);

                $sql	= "UPDATTE ".TABLEPREFIX."user

				           SET vAlertStatus = 'Y'

						   WHERE nUser_Id = '".$value['nUser_Id']."'";

                $res	= @mysql_query($sql, $this->dblink);

            }

        }

    }



    function send_alert_to_matches($arrNew=array()) {

        $arrMatch	= array();

        if (!empty($arrNew)) {

            $userid	= $arrNew['nUser_Id'];

            $gender	= $arrNew['vGender'];

            $userage= $arrNew['vAge'];



            $sql	= "SELECT A.nNewUser,U.*,TRUNCATE((TO_DAYS(NOW()) - TO_DAYS(U.dDob))/365, 0) as vAge

					   FROM ".TABLEPREFIX."user as U LEFT JOIN ".TABLEPREFIX."alert as A  ON U.nUser_Id = A.nUser_Id

					   WHERE A.nNewUser LIKE 'Y' AND U.vStatus LIKE 'A%' 

					         AND U.vGender NOT LIKE '{$gender}'";

            $res	= @mysql_query($sql, $this->dblink);

            if (@mysql_num_rows($res) > 0) {

                while($row = @mysql_fetch_array($res)) {

                    $arrMatch[]	= $row;

                }

            }



            if (!empty($arrMatch)) {

                $this->send_alert($arrNew, $arrMatch);

            }

        }

    }



    //partner preference match

    function partner_preference_alert() {

        $arrMatch	= array();

        $date	= date("Y-m-d");

        $sql	= "SELECT p.*,u.vLogin,u.vGender FROM ".TABLEPREFIX."partner_preferance p left join ".TABLEPREFIX."user u on

					p.nUser_Id=u.nUser_Id WHERE u.vStatus LIKE 'A%'";



        $res	= @mysql_query($sql, $this->dblink);

        if (@mysql_num_rows($res) > 0) {

            while($row = @mysql_fetch_array($res)) {

                $arrMatch[]	= $row;

            }//end while

        }//end if



        if (!empty($arrMatch)) {

            foreach ($arrMatch as $key => $value) {

                $this->send_alert_to_partner_matches($value);

            }//end foreach

        }//end if

    }//end fucntion



    function send_alert_to_partner_matches($arrMatch=array()) {

        $arrNew	= array();

        if (!empty($arrMatch)) {

            $userid	= $arrMatch['nUser_Id'];

            $gender	= $arrMatch['vGender'];



            $sql	= "SELECT *,TRUNCATE((TO_DAYS(NOW()) - TO_DAYS(dDob))/365, 0) as vAge

					   FROM ".TABLEPREFIX."user

					   WHERE vStatus LIKE 'A%' AND vBody_Type like '".$arrMatch['vBody_Type']."%'

					   AND vDrinking like '".$arrMatch['vDrinking']."%'

					   AND vSmoking like '".$arrMatch['vSmoking']."%'

					   AND vEye_Color like '".$arrMatch['vEye_Color']."%'

					   AND vHair_Color like '".$arrMatch['vHair_Color']."%'

					   AND vEthinicity like '".$arrMatch['vEthinicity']."%'

					   AND vReligion like '".$arrMatch['vRelegion']."%'

					   AND vEducation like '".$arrMatch['vEducation']."%'

					   AND vLanguages like '".$arrMatch['vLanguages']."%'

					   AND vProfession like '".$arrMatch['vProfession']."%'

					   AND vAnual_Income like '".$arrMatch['vIncome']."%'

					   AND vRealtion_Status like '".$arrMatch['vRelationship']."%'

					   AND nChildren like '".$arrMatch['vChildren']."%'

					   AND (TRUNCATE((TO_DAYS(NOW()) - TO_DAYS(dDob))/365, 0)<=".$arrMatch['nAge_High'].")

					   AND (TRUNCATE((TO_DAYS(NOW()) - TO_DAYS(dDob))/365, 0)>=".$arrMatch['nAge_Low'].")

					   AND nHeight between '".$arrMatch['nHeight_Low']."' and '".$arrMatch['nHeight_High']."'

					   AND vGender NOT LIKE '{$gender}'";



            $res	= @mysql_query($sql, $this->dblink);

            if (@mysql_num_rows($res) > 0) {

                while($row = @mysql_fetch_array($res)) {

                    $arrNew[]	= $row;

                }//end while

            }//end if



            if (!empty($arrNew)) {

                $this->send_alert($arrNew, $arrMatch);

            }//end if

        }//end if

    }//end fucntion



    function send_alert($arrNew, $arrMatch) {

        if (!empty($arrNew) AND !empty($arrMatch)) {

            require_once "settings.class.php";

            require_once "misc.class.php";

            //$arrSettings	= settings::select();
            $settingsObj = new settings();
            $arrSettings	= $settingsObj->select();

            if (!empty($arrSettings)) {

                $message	= "Hi ".$arrMatch['vLogin'].","."\n\n";

                $message	.= "A new profile which matches your preferences has been registered to the site. Here are the details: \n\n";

                $message	.= $arrNew['vLogin']." a ".$arrNew['vAge']." -year-old ".$arrNew['vGender']." from ".$arrNew['vCounty']." , ".$arrNew['vState']." , ".$arrNew['vCountry']."\n";

                $message	.= "View this profile at ".$arrSettings['site_normal_url']."/profile.php?id=".$arrNew['nUser_Id']."\n\n";

                $message	.= "by"."\n";

                $message	.= $arrSettings['sitename'];



                $from		= $arrSettings['adminmail'];

                $to			= $arrMatch['vEmail'];

                $toname		= $arrMatch['vLogin'];

                $fromname	= $arrSettings['sitename']." Team";

                $subject	= 'New Matches for You';

                $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 ".$arrMatch['vLogin']." </h2>

						<p>A new profile which matches your preferences has been registered to the site. Here are the details: <br> ".$arrNew['vLogin']." a ".$arrNew['vAge']." -year-old ".$arrNew['vGender']." from ".$arrNew['vCounty']." , ".$arrNew['vState']." , ".$arrNew['vCountry'].". <br><br>Please click <a href='".$site_url."/profile.php?id=".$arrNew['nUser_Id']."'>here</a> to view this profile.</p><p>Personalized</p>

						<p>By Your <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		= misc::send_mail_perfect($from, $to, $subject, $fromname, $toname, $textbody, $htmlbody);
                $miscObj = new misc();
                $flag = $miscObj->send_mail_perfect($from, $to, $subject, $fromname, $toname, $textbody, $htmlbody);



                /*

				$this->send_mail($arrMatch['vLogin']."<".$arrMatch['vEmail'].">", $message, "New Matches for You", $arrSettings['adminmail'], $arrSettings['sitename']);

                */

            }

        }

    }



    function get_product_type($id=0) {

        $type	= "MB";

        if ($id == "1") {

            $type	= "MB";

        } else if ($id == "2") {

            $type	= "MR";

        } else if ($id == "4") {

            $type	= "BC";

        } else if ($id == "5") {

            $type	= "IV";

        } else if ($id == "3") {

            $type	= "FP";

        }

        return $type;

    }



// below functions are not complete and not of use now

    function monthly_billing() {

        $array	= array();

        $sql	= "SELECT * FROM ".TABLEPREFIX."payments

				   WHERE vAmountStatus LIKE 'A'

				   GROUP BY nUser_Id";

        $res	= @mysql_query($sql, $this->dblink);

        if (@mysql_num_rows($res) > 0) {

            while($row = @mysql_fetch_array($res)) {

                $array[]	= $row['nUser_Id'];

            }

        }

        if (!empty($array)) {

            foreach ($array as $key => $value) {

                $this->send_monthly_bill($value);

            }

        }

    }



    function send_monthly_bill($uid=0) {

        $array	= array();

        $arrF	= array();

        $sql	= "SELECT * FROM ".TABLEPREFIX."payments as P JOIN ".TABLEPREFIX."orders as O

				   ON P.nUserId = O.nUserId

				   WHERE P.vAmountStatus LIKE 'A' AND P.nUser_Id = '{$uid}'";

        $res	= @mysql_query($sql, $this->dblink);

        if (@mysql_num_rows($res) > 0) {

            while($row = @mysql_fetch_array($res)) {

                $array[]	= $row;

            }

        }

//		return array("flag"=>$cc_flag, "msg"=>$message, "txn"=>$txn, "sta" => $status);



        if (!empty($array)) {

            foreach ($array as $key => $value) {

                $type	= $this->get_product_type($value['nProdId']);

                $array	= $this->authorize_prior_capture($value['nUser_Id'], $type);

                if ($array['flag']) {

                    $arrF[$value['nPayment_Id']] = $array;

                }

            }

        }

    }

}

?>
